In this article, I am going to explain one of the loops in c programming and the program to print N natural numbers using while loop in C language. In my previous article, I have explained the implementation and working of for loop. You can also use the concept of my previous program to write this program as well.
Also read: C Program to Find the Sum of First Ten Natural Numbers using For Loop
In today’s program, you will be able to print natural numbers up to any range by setting the initial and final value in the code. The code is simple and at the end of this post, you would be able to write your code in many ways. Also, watch my video where I had explained all the loops in c program.
Program to print N natural numbers using while loop
#include<stdio.h>
main()
{
int n, value;
printf("enter the range"); //n=last number
scanf("%d", &n);
value = 1; //first number
while(value<=n)
{
printf("%d ", value); //2 3 4
value++;
}
}
Value = 1 and if N = 100 then
Output: 1 2 3 4 5 6 ........ up to 100
Explanation
- In the braces of the main() function, I have started with int (integer data type) and declared two integer type variables ‘n’ and ‘value’ to store the final and initial value of numbers.
int n, value;
- In the next two lines, I have passed the message to enter range and stores that in the variable ‘n’.
printf("enter the range"); //n=last number
scanf("%d", &n);
- Next, I have stored the initial number in the variable ‘value’.
value = 1; //first number
- While loop declaration: condition passed that ‘value’ must be less or equal to ‘n’, if condition satisfies then print the number stored in ‘value’ and increase that number by one unit.
- Repeat these steps until the condition becomes false.
while(value<=n)
{
printf("%d ", value);
value++;
}
Also read: Switch Case Statements in C Programming