Week 05 Tutorial Sample Answers
Arrays Practice
This week, we will discuss arrays, and complete a program to practice writing arrays.
Tutor Demo! (10 mins)
We have been provided the following program that intends to do the following steps but has some flaws.
- Create an integer array with at least 5 elements.
- Create a
while
loop which loops through every element of the array. - Write an
if
statement which adds 1 to each even value. Do this within thewhile
loop. - Write another while loop which goes through the array with a different iterator (i.e. if you used
i
last time, usej
) - Print out the values in the array.
// part1_arrays.c, odd_only
//
// Written by YOUR-NAME (YOUR-ZID)
// on TODAYS-DATE
//
// This program adds 1 to any odd element in an array and after prints
// all elements in the array
#include <stdio.h>
#define SIZE 5
int main(void) {
int array = {1, 2, 3, 4, 5};
int i = 0;
while (i < SIZE) {
if (array.i % 2 == 0) {
array.i += 1;
}
}
int j = 1;
while (j < SIZE) {
printf("%c ", array.j);
}
printf("\n");
return 0;
}
We will go through and debug the program so it executes as expected.
Your turn!
Copy Array
- Create an array of doubles with 3 elements, each with a non-zero value.
- Create another array of doubles with 10 elements where every element initialised to
0.0
. - Create a while loop that loops through every element of the first array.
- Copy the elements of the first array into the second array (leave 0's at the end)
Create a while loop that prints out all the elements of the second array.
Largest Character
- Create a character array with exactly 8 elements.
- Create a character variable called
largest_character
, equal to the first character of the array. - Create a while loop to loop through the character array.
- Create an if statement to check if the current character has a higher ascii value than "largest_character"
- Print out the largest character you've found.