C program to print odd numbers from 1 to n without using if statement

Ex: Write a C program to print odd numbers between 1 to n. How to write a C program to print odd numbers between 1 to n. C program to print odd number's between 1 to n.


Input from user: 

Enter the limit: 20

Expected output:

Odd numbers between 1 to 20:

1
3
5
7
9
11
13
15
17
19






   Step by step logic to print Odd numbers between 1 to n(without using if-statement):



1. Accept limit from user store it in variable no.

2. Run for loop which iterate upto n number's. for(i=1;i<=no;i+=2)

3. We used i=1 because odd numbers starts from 1.

4.  We increment loop by two to print odd numbers.

5. Print value of i inside the for loop.




   Program to print odd number's without using if-statement:


#include<stdio.h>
int main()
{

 int i,no;

 printf("Enter the limit: ");
 scanf("%d",&no);

  printf("Odd numbers between 1 to %d\n",no);

 for(i=1;i<=no;i+=2)
 {
   printf("%d\n",i);
 }

 return 0;
}





   Program to print odd number's using if-statement:


In below Program we print odd numbers from 1 to n using if-statement.


#include<stdio.h>
int main()
{

 int i,no;

 printf("Enter the limit: ");
 scanf("%d",&no);

  printf("Odd numbers between 1 to %d\n",no);

 for(i=1;i<=no;i++)
 {
   if(i%2==1)
   printf("%d\n",i);

 }

 return 0;

}



Above program's shows the following output:




No comments:

Post a Comment

If you have any doubts, please discuss here...👇