Program to print ODD numbers from 1 to N using while loop
#include <stdio.h>
int main()
{
//loop counter declaration
int number;
//variable to store limit /N
int n;
//assign initial value
//from where we want to print the numbers
number=1;
//input value of N
printf("Enter the value of N: ");
scanf("%d",&n);
//print statement
printf("Odd Numbers from 1 to %d:\n",n);
//while loop, that will print numbers
while(number<=n)
{
//Here is the condition to check ODD number
if(number%2 != 0)
printf("%d ",number);
// increasing loop counter by 1
number++;
}
return 0;
}
Output
Run(1)
Enter the value of N: 10
Odd Numbers from 1 to 10:
1 3 5 7 9
Run(2)
Enter the value of N: 100
Odd Numbers from 1 to 100:
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31
33 35 37 39 41 43 45 47 49 51 53 55 57 59
61 63 65 67 69 71 73 75 77 79 81 83 85 87
89 91 93 95 97 99
Another way to print ODD numbers from 1 to N
Since, we know that ODD numbers starts from 1 and ODD numbers are those numbers which are not divisible by 2. So, we can run a loop from 1 to N by increasing the value of loop counter by 2.
Consider the given code...
//initialising the number by 1
number=1;
//print statement
printf("Odd Numbers from 1 to %d:\n",n);
//while loop, that will print numbers
while(number<=n)
{
//print the number
printf("%d ",number);
//increase the value of number by 2
number+=2;
}
Program to print ODD numbers from 1 to N using while loop
Output
Another way to print ODD numbers from 1 to N
Since, we know that ODD numbers starts from 1 and ODD numbers are those numbers which are not divisible by 2. So, we can run a loop from 1 to N by increasing the value of loop counter by 2.
Consider the given code...
need an explanation for this answer? contact us directly to get an explanation for this answer