C Program to Print the Alternate Elements in an Array

«
»

This program prints the alternate elements in an array.

Problem Description

This is a C program which implements an array and prints the alternate elements of that array.

Problem Solution

1. Create an array and define its elements according to the size.
2. Using for loop, access the elements of the array, but instead of incrementing the iterator by 1, increase it by 2, so as to get alternate indexes of the array.

advertisement
Program/Source Code

Here is source code of the C Program to print the alternate elements in an array. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.

  1.  
  2.     /*
  3.      * C Program to Print the Alternate Elements in an Array
  4.      */
  5.  
  6.     #include <stdio.h>
  7.     void main()
  8.     {
  9.  
  10.         int array[10];
  11.         int i;
  12.         printf("enter the element of an array \n");
  13.         for (i = 0; i < 10; i++)
  14.             scanf("%d", &array[i]);
  15.  
  16.         printf("Alternate elements of a given array \n");
  17.         for (i = 0; i < 10; i += 2)
  18.             printf( "%d\n", array[i]) ;
  19.     }
Program Explanation

1. Declare an array of some fixed capacity, 10.
2. Define all its elements using scanf() function under for loop.
3. Now, run a for loop with an iterator i, incrementing it by 2 each time so as to get alternate alternate indexes.
4. Alternate indexes will give alternate elements of the array.
5. Print the alternative elements as well.

advertisement
Runtime Test Cases
12
23
45
57
68
73
84
97
120
125
Alternate elements of a given array
12
45
68
84
120

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Reference Books in C Programming, Data Structures and Algorithms.

advertisement

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn