Basics of Programming - C Arrays
Basics of Programming - C Arrays
C - Arrays
Arrays are a kind of data structure that can store a fixed-size sequential collection of elements
of the same type. An array is used to store a collection of data, but it is often more useful to
think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by an
index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
An array is a group (or collection) of same data types. For example an int array holds the
elements of int types while a float array holds the elements of float types.
1) Define 100 variables with int data type and then perform 100 scanf() operations to store the
entered values in the variables and then at last calculate the average of them.
2) Have a single integer array to store all the values, loop the array to store all the entered
values in array and later calculate the average.
Basics of Programming – C Arrays 2
Obviously the second solution, it is convenient to store same data types in one single variable
and later access them using array index.
Similarly an array can be of any data type such as double, float, short etc.
In general arr[n-1] can be used to access nth element of an array. where n is any integer
number.
For example:
int mydata[20];
mydata[0] /* first element of array mydata*/
mydata[19] /* last (20th) element of array mydata*/
avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}
Output:
number 3
20
Enter Enter number 1
10
Basics of Programming – C Arrays 4
Enter number 2
10
Enter number 4
40
Average of entered number is: 20