Complementary task for topic: 3
M Nemeth · 2023-08-29 15:21:04.614221'
Arrays
Arrays
Task: Array Initialization and Access:
Write a C program that initializes an integer array with values (10,20,30,40,50) and displays the elements at specific indices (1st, 3rd, 5th elements).
Hint: The index starts with 0! the indexing operator is [] so if you have an array: Arr, Arr[0] is the first element, Arr[3] is the fourth.
The result of using the indexing operator is a variable, so Arr is for example an integer array, Arr[0] is an integer.
P.S.: indexing can be used for write, so Arr[0]=1 will overwrite the first element to 1. You do not need to use this for this task.
Solution
#include
int main() {
int numbers[] = {10, 20, 30, 40, 50}; // Initialize the array with values
printf("Array elements:\n");
printf("numbers[0]: %d\n", numbers[0]); // Display the element at index 0
printf("numbers[2]: %d\n", numbers[2]); // Display the element at index 2
printf("numbers[4]: %d\n", numbers[4]); // Display the element at index 4
return 0;
}
Explanation
In this example, the program initializes an integer array numbers with the values {10, 20, 30, 40, 50}. The size of the array is automatically determined based on the number of elements provided in the initialization list. The program then displays the elements of the array at specific indices using printf(). It accesses and prints the elements at indices 0, 2, and 4 using the syntax numbers[index], where index is the desired index of the element.