Example 1 – Display Array Elements
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
printf("%d ", numbers[0]);
printf("%d ", numbers[1]);
printf("%d ", numbers[2]);
printf("%d ", numbers[3]);
printf("%d", numbers[4]);
return 0;
}
Output:
10 20 30 40 50
Explanation: Each element is accessed by its index (numbers[0]
to numbers[4]
) and printed individually.
Example 2 – Sum of Array Elements
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int sum;
sum = arr[0] + arr[1] + arr[2] + arr[3] + arr[4];
printf("Sum = %d", sum);
return 0;
}
Output:
Sum = 15
Explanation: We directly add each element without a loop and store the result in sum
.
Example 3 – Display Float Array Elements
#include <stdio.h>
int main() {
float prices[4] = {12.5, 45.99, 7.25, 30.0};
printf("%f ", prices[0]);
printf("%f ", prices[1]);
printf("%f ", prices[2]);
printf("%f", prices[3]);
return 0;
}
Output:
12.500000 45.990002 7.250000 30.000000
Explanation: %f
prints float values with default six decimal places in C.
Example 4 – Sum of Float Array Elements
#include <stdio.h>
int main() {
float marks[3] = {88.5, 92.0, 75.25};
float sum;
sum = marks[0] + marks[1] + marks[2];
printf("Total Marks = %f", sum);
return 0;
}
Output:
Total Marks = 255.750000
Explanation: We directly add each float element without loops. %f
displays the sum in default float format.
Example 5 – Display Char Array Elements
#include <stdio.h>
int main() {
char vowels[5] = {'A', 'E', 'I', 'O', 'U'};
printf("%c ", vowels[0]);
printf("%c ", vowels[1]);
printf("%c ", vowels[2]);
printf("%c ", vowels[3]);
printf("%c", vowels[4]);
return 0;
}
Output:
A E I O U
Practice Statements
- Store and display three integers without loops.
- Add two integer array elements and print the result.
- Store and display three float values without loops.
- Add three float values and print the total.
- Store five vowels in a char array and print them one by one.