Uncategorized

C Program to Print the Alternate Elements in an Array

program to find the largest of n numbers and its location in an array
#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

  1. Include Standard Library:

    #include <stdio.h>
    
    • This line includes the standard input-output library necessary for functions like printf and scanf.
  2. Main Function:

    int main()
    
    • Defines the main function where the program execution begins. It’s standard practice to declare the return type as int.
  3. Array Declaration:

    int array[10];
    
    • An integer array named array of size 10 is declared to hold 10 integers.
  4. Variable Declaration:

     
    int i;
    
    • A single integer variable i is declared to be used as a loop counter.
  5. 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
  6. Input Loop:

     
    for (i = 0; i < 10; i++) {
        scanf("%d", &array[i]);
    }
    
    • A for loop runs from 0 to 9, allowing the user to input 10 integers. Each integer is stored in the array at index i. The scanf function is used to read the input.
  7. 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
  8. Alternate Elements Loop:

     
    for (i = 0; i < 10; i += 2) {
        printf("%d\n", array[i]);
    }
    
    • Another for loop runs from 0 to 9, but increments i by 2 each time. This means the loop will access every second element of the array. The printf function prints each of these alternate elements on a new line
  9. Return Statement:

     
    return 0;
    
    • Indicates that the program has executed successfully. Returning 0 is a convention to signal successful termination.

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

Team Educate

About Author

Leave a comment

Your email address will not be published. Required fields are marked *