Write a program in C to separate odd and even integers in separate arrays

Previous
Next

Solution:

  • In this approach, we take two arrays to store even and odd numbers after separation.
  • We repeat the loop from start index to end index and check the element is even or not.
  • We bi-furcated the elements of source array and store into two arrays even[] and odd[].
#include <stdio.h>
int main()
{
	int src[10], even[10], odd[10];
	int i, j=0, k=0, n;
	
	printf("Input size of array :");
	scanf("%d",&n);
	
	printf("Input elements :\n");
	for(i=0;i<n;i++)
	{
		scanf("%d",&src[i]);
	}	
	for(i=0;i<n;i++)
	{
		if (src[i]%2 == 0)
		{
			even[j] = src[i];
			j++;
		}
		else
		{
			odd[k] = src[i];
			k++;
		}
	}	
	printf("The Even elements are : \n");
	for(i=0;i<j;i++)
	{
		printf("%d\n",even[i]);
	}
	printf("\n");	
	printf("The Odd elements are :\n");
	for(i=0;i<k;i++)
	{
		printf("%d\n", odd[i]);
	}
	printf("\n");
	return 0;
}

Approach-2:

  • In this approach, we arrange even numbers of array to left side and odd elements to right side.
  • We are not taking the help of other arrays to store even and odd elements after separation.
#include <stdio.h>
int main()
{
	int src[10];
	int i, j, k, n, temp;	
	printf("Input size of array :");
	scanf("%d",&n);	
	printf("Input elements :\n");
	for(i=0;i<n;i++)
	{
		scanf("%d",&src[i]);
	}	
	i=0;
	j=n-1;
	for(i=0; i<n; i++) 
	{
		while(src[i]%2==0)
		{
			i++;
		}
		while(src[j]%2==1)
		{
			j--;
		}	
		if(i<j)
		{
			temp=src[i];
			src[i]=src[j];
			src[j]=temp;
		}
	}
	printf("Array after arrangement : \n");
	for(i=0 ; i<n ; i++)
	{
		printf("%d\n", src[i]);
	}
	printf("\n");
	return 0;
}
Previous
Next

Courses Enquiry Form