Lets write a C program to print natural numbers between two user entered numbers, using for loop.
We check if the user has entered smaller number first and then the larger number. If not, we swap the numbers present in the variables min and max.
Related Read:
For Loop In C Programming Language
Assignment Operators in C
Swap 2 Numbers Using a Temporary Variable: C
C Program To Find Factorial of a Number using for Loop
#include<stdio.h> int main() { int min, max, temp, count; printf("Enter 2 positive numbers\n"); scanf("%d%d", &min, &max); if(min > max) { temp = min; min = max; max = temp; } printf("Natural numbers from %d to %d are:\n", min, max); for(count = min; count <= max; count++) { printf("%d\n", count); } return 0; }
Output 1:
Enter 2 positive numbers
10
15
Natural numbers from 10 to 15 are:
10
11
12
13
14
15
Output 2:
Enter 2 positive numbers
15
10
Natural numbers from 10 to 15 are:
10
11
12
13
14
15
We ask the user to enter 2 numbers, and store it inside variables min and max. For loop keeps iterating till min is less than or equal to max. We assign the value of min to count and keep incrementing the value of count by 1 for each iteration of the for loop. Once value of count is greater than value of max, control exits for loop.
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert