In this tutorial, you will learn how to print all odd numbers between 1 to 100 using a while loop conditional statement in C Programing Language. For a better understanding of this problem, we are using algorithms, examples, and Program explanations.
Required Knowledge
- C Programming Basics
- C Programming Operators
- C printf and Scanf
- While loop in C
Problem Statement
You have to write a C program that will print all the odd numbers between 1 and 100 using a while loop. This program will not take user input as our bound is already defined 1 to 100. So it should only print all the odd numbers as an output.
Example
Output:
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
Algorithm to Print All Odd Numbers
- Start the program.
- Declare a variable
num
to represent the current number, initialized to 1. - Print the header message: “Odd numbers between 1 and 100:”
- Enter the while loop with the condition
num <= 100
.- Check if the current number
num
is odd using the modulo operator (num % 2 != 0
). - If it is odd, print the value of
num
. - Increment
num
by 1.
- Check if the current number
- Exit the while loop.
- Print a new line to separate the output.
- End the program
Logic used to solve this problem
- Initialize a num variable to 1.
- Use a While loop that runs as long as the num is less than or equal to 100.
- Inside the loop, check if the num is an odd number using the modulo (%) operator.
- If the num is odd, print the number.
- Increment the num by 1 in each iteration.
- Continue the loop until the num reaches 100.
- Finish the program.
Program to print all odd number between 1 to 100
#include <stdio.h>
int main() {
int num = 1;
printf("Odd numbers between 1 and 100: ");
while (num <= 100) {
if (num % 2 != 0) {
printf("%d ", num);
}
num++;
}
printf("\n");
return 0;
}
Output
Odd numbers between 1 and 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
Program Explanation
- The program initializes a variable
num
to 1, which represents the first odd number to be printed. - The program enters a while loop with the condition
num <= 100
to iterate through numbers from 1 to 100. - Inside the while loop, it checks if
num
is an odd number. - If
num
is odd, it prints the value ofnum
on the screen. - It then increments the value of
num
by 2 since the next odd number will be 2 greater than the current one. - The loop continues until
num
exceeds the value of 100. - Once the while loop is complete, the program ends.
Conclusion
The C program successfully prints all the odd numbers between 1 and 100 using a while loop. By checking the divisibility of each number by 2, it identifies the odd numbers and prints them on a single line. I hope you really enjoyed this tutorial. Do like, share and Subscribe