Print the odd numbers till N

Print the odd numbers till N : In this tutorial, we are going to learn new program which is to print the odd numbers till N.

what is odd number

Any number which is divided by two and gives the remainder as 1 then that never is referred to an odd number.

How will you check number is odd?

For checking that the number is odd we perform this by a simple mathematical formula which is given as below

Suppose we are checking Number is odd or not.

Reminder = Number % 2

If in above expression Number % 2 gives the remainder 1 then Number is odd otherwise not.

Examples of odd numbers 

1, 3, 5….

Number = 5

Now check whether the number is odd or not

Reminder = 5 % 2

This expression will calculate and gives the remainder as 1.

Reminder = 1

So that Number = 5 is odd number.

In this way, using this technical we will print odd numbers till ‘N’.

Now, it’s implement program to print odd numbers.

C++ program to display odd numbers using for loop

123456789101112131415161718192021222324252627282930313233343536373839#include <iostream>using namespace std;int main(){ int no , i ; cout<<“Enter a Number\n”;cin>>no; // take input from user the ncout<<“\nodd numbers till “<<no; cout<<“\n”;// Iterate till no for(i=0;i<=no;i++){//Condition to check odd numberif(i % 2 == 1)cout<<i; //print odd numberelsecontinue; // otherwise skip}cout<<“\n”;}

Output : 

Cpp Program to print odd numbers till N
Cpp Program to print odd numbers till N

Explanation

1. First Here we internalized ‘i’ for iterate till you want to print odd number and ‘no’ is number.

2. Then we prompted the user to enter a number.

3. After taking the number ‘no’ a for loop is used to traverse from ‘zero’ to that number which is ‘no'(say 10 or 20).

4. In if we used i % 2 which is used to identify whether the given number is odd or even

0%2=0(even)

1%2=1(odd)

2%2=0(even)

3%2=1(odd)

and so on…

5. So by using modulus operator if the result is 1 then it gets printed otherwise the loop continues for next iteration.

6. So the output here is to print all odd numbers from zero to ‘no’.