Array basics
Victor Cionca
Integer arrays
1. Define an integer array to hold 100 numbers and initialise with the numbers from 0 to 99, so for
(i=0;i<100;i++) myarray[i] = i.
2. Print the array.
3. Write a for loop to calculate the sum of the numbers. Print the sum.
4. Write a for loop that prints all even numbers.
5. Write a for loop that prints all numbers multiple of 3 and 5. The “and” operator in C is &&.
6. Define a second array that also holds 100 numbers. Copy the first array into the second array, and
print the second array.
7. Copy the first array into the second array, in reverse order. Print the second array. Two possible
approaches:
• use two counters, one going from 0 to 100, the other from 100 to 0: int down = 99; for (int
up=0;up<100;up++) { new[up] = old[down]; down--;}
• or with a single counter: for (i=0;i<100;i++) {new[i] = old[100-1-i];}.
8. Write a for loop that find the maximum number in the array.
• declare a variable that will hold the maximum; this can be initialised with the first element in the
array
• go through the array, comparing each element with the maximum, and updating the maximum if
the element is larger.
Character arrays
In the following use getchar() to read characters from the user.
1. Read an array of 10 characters and then print the array. Use a for loop.
2. Declare an array of 100 characters. Read input from the user into the array up to the newline and store
it in the array. Print the array.
• use a while loop to read characters up to the newline
• append characters to the end of the array with a variable that keeps track of the number of
characters in the array
while (input != '\n'){
input = getchar();
myarray[end] = input;
end++;
}
1
3. Following from the code in task 2, write a for loop that prints out all the vowels in the array. You need
a longer “if” condition: if (myarray[i] == 'a' || myarray[i] == 'o' || etc. The “or” operator
in C is ||.
4. Following from the code in task 2, write a for loop that prints out all the digits in the array. A digit is
a character >= '0' && <= '9'.
5. Read input from the user into an array. Declare a second array of the exact size needed to store the
input. Copy the first array into the second, switching the case of all the letters.
• to switch the case you must first determine if the character is lower or upper case
• first find the index of the character in the corresponding case alphabet, by subtracting the start
character: if lowercase, index = mychar - 'a'
• then add the index to the start character of the other alphabet: if lowercase, mychar = 'A' +
index.
6. Read input from the user into an array of chars. Declare a second array and copy the first array into
the second, in reversed order. Use the algorithm from task 7 from the Integer section.