Exercise: Repeat the Input
Array elements are often accessed with for
or while
loops. It is very natural to use int i;
as an index and access a[i]
for all values of i
from 0 to some n
, where n
is less than the number of elements of your array. For example, you can print all elements of your array:
#include <stdio.h>
int main() {
int arr[10] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
int i;
for (i = 0; i < 10; ++i) {
printf("%d\n", arr[i]);
}
return 0;
}
Take a moment to rewrite the above code with while
loop just to make sure you remember how it works.
Now, let me give you an exercise! Let me remind you that scanf
returns the number of variables it successfully read. To rephrase it in a simple way, if we have
int a, count;
count = scanf("%d", &a);
then scanf
will try to read a number into a
, and if it succeeds, count
will become 1. If it fails, it will return something else: it might be 0 if it reads something that is not a number (e.g. a letter), or EOF
(which is normally -1) if it reaches the end of the input. In any case,
while (scanf("%d", &a) == 1) {
...
}
is a nice way to read all numbers from the input.
So, here's your exercise. Let's assume the input does not have more than 1000 numbers. Read them all, and print them twice. E.g. if you have
1 2 3 4 5
as an input, your program should print
1 2 3 4 5 1 2 3 4 5
You might need to use an array to do it!
#include <stdio.h>
int main() {
/* your code here */
return 0;
}
Here are some hints for you if you are stuck. First of all, we know that there won't be more than 1000 numbers, so this is how much numbers we must be able to remember:
int values[1000];
Then, we'll need to keep reading the numbers using the while
loop with scanf
, as above, not only assigning the values to array elements, but also counting them in a separate variable, e.g. int count = 0;
and then ++count
. Finally, use the for
loop to print them all. Then print them again!
Still stuck? Feel free to ask a question!