num1
, num2
, num3
, ...,
num100
and read them in with
100 scanf()
statements.
Then we could add them up in a really huge expression like:
sum = num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 + num9 + num10 ... + num96 + num97 + num98 + num99 + num100 ;
Now in a real situation, the user of our program would likely
not always have 100 numbers to average, but would sometimes
have fewer.
That means our program needs to determine how many of the
scanf()
statements to execute and how many of the
numbers to add up.
While it's possible to do all this with a bunch of if
statement, things are really getting ridiculous.
What we'd really like to do is to be able to refer to the 1st number, then the 2nd then the 3rd and so on using one of those loops we saw in the last part. This is why nearly every programming language, including the first widely used language (FORTRAN), includes some way to have a list of items. In most languages (including C), this list mechanism is called the array. Using an array, we can solve this programming task with a program like:
#include <stdio.h> main() { int nums[100] ; int num_nums, i, sum ; printf( "How many numbers do you want to average? " ) ; scanf( "%d", &num_nums ) ; for( i = 0; i < num_nums; ++i ) { printf( "What is number %d? ", i ) ; scanf( "%d", &nums[i] ) ; } sum = 0 ; for( i = 0; i < num_nums; ++i ) sum += nums[i] ; printf( "The sum is %d, and the average is %d.\n", sum, sum / num_nums ) ; }
[]
) are used with arrays in C.
When we use them in a declaration as in the line:
int nums[100] ;
the value in the brackets indicates how big we want the array
made.
This value must be a constant number (or expression).
Often we will use a symbolic constant created with a #define
for array sizes.
sum += nums[i] ;
we're adding the ith number to sum.
nums
is here),
then we can use an array reference such as nums[i]
anywhere we could use an integer variable.
Notice how we've taken advantage of this in the scanf()
statement.
for
statement to scan
through an array.
This is a common action.
samples
.