#include <stdio.h> // Include the standard input-output library
int main() // Change void main() to int main()
{
int array[10]; // Declare an array of size 10
int i; // Declare the loop variable
printf("Enter the elements of the array:\n");
// Loop to read 10 integers from user input
for (i = 0; i < 10; i++) {
scanf("%d", &array[i]); // Store each integer in the array
}
printf("Alternate elements of the given array:\n");
// Loop to print every alternate element from the array
for (i = 0; i < 10; i += 2) {
printf("%d\n", array[i]); // Print the element at index i
}
return 0; // Return 0 to indicate successful execution
}
Code Explanation
Include Standard Library:
#include <stdio.h>
- This line includes the standard input-output library necessary for functions like
printf
andscanf
.
- This line includes the standard input-output library necessary for functions like
Main Function:
int main()
- Defines the main function where the program execution begins. It’s standard practice to declare the return type as
int
.
- Defines the main function where the program execution begins. It’s standard practice to declare the return type as
Array Declaration:
int array[10];
- An integer array named
array
of size 10 is declared to hold 10 integers.
- An integer array named
Variable Declaration:
int i;
- A single integer variable
i
is declared to be used as a loop counter.
- A single integer variable
Prompt for User Input:
printf("Enter the elements of the array:\n");
- This line prints a message asking the user to enter the elements of the array
Input Loop:
for (i = 0; i < 10; i++) { scanf("%d", &array[i]); }
- A
for
loop runs from0
to9
, allowing the user to input 10 integers. Each integer is stored in thearray
at indexi
. Thescanf
function is used to read the input.
- A
Print Alternate Elements Prompt:
printf("Alternate elements of the given array:\n");
- This line informs the user that the program will now print alternate elements from the array
Alternate Elements Loop:
for (i = 0; i < 10; i += 2) { printf("%d\n", array[i]); }
- Another
for
loop runs from0
to9
, but incrementsi
by2
each time. This means the loop will access every second element of the array. Theprintf
function prints each of these alternate elements on a new line
- Another
Return Statement:
return 0;
- Indicates that the program has executed successfully. Returning
0
is a convention to signal successful termination.
- Indicates that the program has executed successfully. Returning
Example Input/Output
- Input: If the user enters:
10 20 30 40 50 60 70 80 90 100
- Output:
Alternate elements of the given array: 10 30 50 70 90