WAP a program to print all odd numbers between 1 and 99.
in QBASIC
Answers
Explanation:
Skip to content
Search for:
C program to print all odd numbers from 1 to n
June 12, 2015PankajC programmingC, Loop, Program
Write a C program to print all odd numbers from 1 to n using for loop. How to print odd numbers from 1 to n using loop in C programming. Logic to print odd numbers in a given range in C programming.
Example
Input
Input upper limit: 10
Output
Odd numbers between 1 to 10:
1, 3, 5, 7, 9
Required knowledge
Basic C programming, Relational operators, If statement, For loop
Logic to print odd numbers from 1 to n using if statement
Logic to print odd numbers is similar to logic to print even numbers.
Step by step descriptive logic to print odd numbers from 1 to n.
Input upper limit to print odd number from user. Store it in some variable say N.
Run a loop from 1 to N, increment loop counter by 1 in each iteration. The loop structure should look like for(i=1; i<=N; i++).
Inside the loop body check odd condition i.e. if a number is exactly divisible by 2 then it is odd. Which is if(i % 2 != 0) then, print the value of i.
Program to print odd numbers using if statement
/**
* C program to print all Odd numbers from 1 to n
*/
#include <stdio.h>
int main()
{
int i, n;
/* Input upper limit from user */
printf("Print odd numbers till: ");
scanf("%d", &n);
printf("All odd numbers from 1 to %d are: \n", n);
/* Start loop from 1 and increment it by 1 */
for(i=1; i<=n; i++)
{
/* If 'i' is odd then print it */
if(i%2!=0)
{
printf("%d\n", i);
}
}
return 0;
}
Logic to print odd numbers from 1 to n without if statement
The above approach is not optimal approach to print odd numbers. Observe the above program for a while. You will notice that, I am unnecessarily iterating for even numbers, which is not our goal.
Step by step descriptive logic to print odd numbers without using if statement.
Input upper limit to print odd number from user. Store it in some variable say N.
Run a loop from 1 to N, increment it by 2 for each iteration. The loop structure should look like for(i=1; i<=N; i+=2).
Inside the loop body print the value of i.
Program to display odd numbers without using if statement
/**
* C program to display all odd numbers between 1 to n without using if statement
*/
#include <stdio.h>
int main()
{
int i, n;
/* Input upper limit from user */
printf("Print odd numbers till: ");
scanf("%d", &n);
printf("All odd numbers from 1 to %d are: \n", n);
/*
* Start a loop from 1, increment it by 2.
* For each repetition prints the number.
*/
for(i=1; i<=n; i+=2)
{
printf("%d\n", i);
}
return 0;
}
Note: In the above program I have used shorthand assignment operator i+=2 which is equivalent to i = i + 2.