Printing odd and even numbers using For Loop in C++


This C++ program prompts the user to enter an ending value and then displays all the even and odd numbers up to that value, along with their counts. Here's how the program works:

  • It first declares some variables, including i for the loop counter, n to store the user input, even to count the even numbers, and odd to count the odd numbers.
  • It then prompts the user to enter an ending value and reads the input using cin.
  • It then displays all the even numbers up to the input value by looping through all integers from 0 to n and checking if each one is even using the modulo operator (%). If it's even, it prints the number and increments the even counter.
  • It then displays all the odd numbers up to the input value by looping through all integers from 1 to n and checking if each one is odd using the modulo operator (%). If it's odd, it prints the number and increments the odd counter.
  • Finally, it displays the total counts of even and odd numbers.

Source Code

#include<iostream>
using namespace std;
int main()
{
    int i,n,even=0,odd=0;
    cout<<"\nEnter the Ending value:";
    cin>>n;
    cout<<"\nEven numbers:";
    for(i=0;i<=n;i++)
    {
        if(i%2==0)
        {
            cout<<"\n"<<i;
            even++;
        }
    }
    cout<<"\nOdd numbers:";
    for(i=1;i<=n;i++)
    {
        if(i%2==1)
        {
            cout<<"\n"<<i;
            odd++;
        }
    }
    cout<<"\nTotal even numbers:"<<even;
    cout<<"\nTotal odd numbers:"<<odd;
    return 0;
}
To download raw file Click Here

Output

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


Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples