Print and Separate Odd and Even Numbers Using For Loop in C


written in the C programming language and is used to print all even and odd numbers between 0 and a given limit and count the total number of even and odd numbers. The program starts by including the standard input/output library (stdio.h) and then defines a main function. Within the main function, the program declares four variables: "i", "n", "even" and "odd". The variable "n" is used to store the limit entered by the user, "i" is used as a loop counter, "even" is used to count the total number of even numbers and "odd" is used to count the total number of odd numbers.

The program then prompts the user to enter the limit using the "printf" function and stores the value in the variable "n" using the "scanf" function. Next, the program uses a "for" loop with the counter variable "i" to iterate from 0 to the value of "n". Within this loop, it uses an if statement to check if the current value of "i" is even or not by using the modulus operator. If the remainder of i divided by 2 is 0, it means that the number is even. If the number is even, the program uses the "printf" function to print the number and increments the value of the "even" variable by 1. This loop will iterate from 0 to n and will check if a number is even or not, if yes it will print that number and increment the value of even by 1.

Source Code

#include<stdio.h>
int main()
{
  int i,n,even=0,odd=0;
  printf("\nEnter the Ending value:");
  scanf("%d",&n);
  printf("\nEven numbers:");
  for(i=0;i<=n;i++)
  {
    if(i%2==0)
    {
      printf("\n%d",i);
      even++;
    }
  }
  printf("\nOdd numbers:");
  for(i=1;i<=n;i++)
  {
    if(i%2==1)
    {
      printf("\n%d",i);
      odd++;
    }
  }
  printf("\nTotal even numbers:%d",even);
  printf("\nTotal odd numbers:%d",odd);
  return 0;
}
To download raw file Click Here

Output

Enter the Ending value: 8
Even numbers:
0
2
4
6
8
Odd numbers:
1
3
5
7
Total even numbers:5
Total odd numbers: 4

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C