Contact Learn C
Copy Program Share Program

Program 106:To separate even and odd numbers in an array

Program 106:
#include<stdio.h>
main()
{
int i,size;
printf("Enter size of array\n");
scanf("%d",&size);
int a[size];
printf("Enter numbers to separate even and odd\n");
for(i=0;i<size;i++)
{
    scanf("%d",&a[i]);
}
printf("Even numbers are:\n");
for(i=0;i<size;i++)
{
    if(a[i]>=0)
    {
        if(a[i]%2==0)
        {
            printf("%d\n",a[i]);
        }
    
    }
}

printf("Odd numbers are:\n");
for(i=0;i<size;i++)
{
    if(a[i]>=0)
    {
        if(a[i]%2==1)
        {
            printf("%d\n",a[i]);
        }
    
    }
}
    
}
Explanation:

  1. The program starts with initializing
    • size→ To store size of array
    • i Temporary variable
    • a→ To store  array elements
  2. printf("Enter size of array\n");
    scanf("%d",&size);
    int a[size];
    printf("Enter numbers to separate even and odd\n");
    for(i=0;i<size;i++)
    {
        scanf("%d",&a[i]);
    }
    Taking array size and array elements from user
  3. Main Logic goes here:
    for(i=0;i<size;i++)
    {
        if(a[i]>=0)
        {
            if(a[i]%2==0)
            {
                printf("%d\n",a[i]);
            }
        
        }
    }
    
    printf("Odd numbers are:\n");
    for(i=0;i<size;i++)
    {
        if(a[i]>=0)
        {
            if(a[i]%2==1)
            {
                printf("%d\n",a[i]);
            }
        
        }
    }
  4. Lets take array size as 5 and array's element be 35,30,54,21,8.
    • First Loop:
      • for(i=0;i<size;i++)
        {
            if(a[i]>=0)
            {
                if(a[i]%2==0)
                {
                    printf("%d\n",a[i]);
                }
            
            }
        }
      • By now I hope you understood Loop Concepts and I am proceeding further.Here We are traversing from 1st element of array till the last element element.
      • Now we are checking if a[i] >0 i.e whether the number at position 'i' is greater than zero or not just to avoid 0's to print.If it is greater than zero then we are checking if it is even or not, using a[i]%2==0 which is used to identify even numbers.
      • Now this loop checks all array elements from number 35 to 8(i.e 35,30,54,21,8)
      • So first  35 will be checked whether it is  even or not since it is not even it won't be printed as output under Even Numbers and next 30 will be checked and since it is even number it is printed and so on for all numbers
      • So only 30,54,8 are printed as Even Numbers
    • Second Loop
      • This loop is same as above ones but the difference is we are using
      • if(a[i]%2==1)
      • which is used to detect Odd Numbers and we are filtering even from Odd numbers.
      • So 35 and 21 are printed under Odd Numbers


Output:

To separate even and odd numbers in an array
 

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide