What is an Array?
Explore the concept of arrays in C, focusing on how to declare array variables and store multiple values under a single variable name. Understand array element indexing starting from zero and learn why arrays are preferred over individual variables for handling collections of similar data types.
We'll cover the following...
Storing multiple values
If we are to calculate and print the percentage marks obtained by 3 students, the program given below would suffice.
RUN the code below and see the output!
#include<stdio.h>
int main() {
int m1, m2, m3, per;
int i;
for (int i = 0; i < 3; i++){
printf("Enter Marks:\n");
scanf("%d%d%d", &m1, &m2, &m3);
// Calculates percentage of each student
per = (m1+m2+m3)/3;
printf("%d\n", per);
}
// Only percentage of last student is available to us
printf("Percentage of last student is %d\n", per);
}However, if we wish to arrange three percentages obtained, in ascending order, before printing them, the program is inadequate — as once control goes outside the loop, only the last student’s percentage is available in per. So we need to have a way to store three values. This can be done in two ways:
-
Create three variables, each holding one value
-
...