C Arrays
An array stores many values of the same type under one name. Instead of making 5 variables for 5 marks, we make one array with 5 elements.
Declare and initialize
int marks[5]; // 5 elements, no values yet
int scores[5] = {80, 65, 90, 72, 55};
int days[] = {1, 2, 3}; // size is 3 (counted automatically)
Each element has an index. The index starts from 0. So scores[0] is 80 and the last element scores[4] is 55.
#include <stdio.h>
int main(void) {
int scores[5] = {80, 65, 90, 72, 55};
printf("First: %d\n", scores[0]);
printf("Last: %d\n", scores[4]);
scores[1] = 70; // change a value
printf("Changed: %d\n", scores[1]);
return 0;
}
Output:
Output of the above program is
First: 80
Last: 55
Changed: 70
Loop over an array
#include <stdio.h>
int main(void) {
int scores[5] = {80, 65, 90, 72, 55};
int size = sizeof(scores) / sizeof(scores[0]);
int sum = 0;
for (int i = 0; i < size; i++) {
printf("scores[%d] = %d\n", i, scores[i]);
sum += scores[i];
}
printf("Total = %d, Average = %.1f\n", sum, (float)sum / size);
return 0;
}
Output:
Output of the above program is
scores[0] = 80
scores[1] = 65
scores[2] = 90
scores[3] = 72
scores[4] = 55
Total = 362, Average = 72.4
Find the largest value
#include <stdio.h>
int main(void) {
int a[] = {23, 91, 45, 67, 12};
int max = a[0];
for (int i = 1; i < 5; i++) {
if (a[i] > max) {
max = a[i];
}
}
printf("Maximum = %d\n", max);
return 0;
}
Output:
Output of the above program is
Maximum = 91
Read values from the user
#include <stdio.h>
int main(void) {
int n[3];
for (int i = 0; i < 3; i++) {
scanf("%d", &n[i]);
}
printf("You entered: %d %d %d\n", n[0], n[1], n[2]);
return 0;
}
Output:
Output of the above program is
4
8
15
You entered: 4 8 15
Note:
C does not check the array limits. Reading or writing scores[10] in an array of 5 is a bug that may crash the program or give wrong values. Always stay between 0 and size – 1.
Next: C Two Dimensional Arrays.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |