Contact Learn C
Copy Program Share Program

Program 6:To print all the odd number till ‘N’

Program 6:
 
#include<stdio.h>
 main()
 {
 int i,n;

printf("Enter a Number to print all odd number between 0 and N \n");
 scanf("%d",&n);
 for(i=0;i<=n;i++)
 {
 if(i%2==1)
 printf("%d\n",i);
 else
 continue;
 }
 printf("\n");
 }
Explanation:
  1. Here we intialized 'i' and 'n'
  2. Then we prompted user to enter a number.
  3. After taking the number 'n' a for loop iis used to traverse from 'zero' to that number which is 'n'(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 other wise the loop continues for next iteration.(continue--refer it here).
  6. So the output here is to print all odd numbers from zero to 'n'.
In a similar way you can do it for getting all even numbers by replacing "if(i%2==0)".

 Output:

To print all the odd number till ‘N’
  

Download App and Learn when ever you want

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