Lets write a simple C program to print natural numbers from 1 to N, using while loop.
Related Read:
while loop in C programming
Source Code: C Program to Print Natural Numbers from 1 to N using While loop
#include < stdio.h > int main() { int num, count = 1; printf("Enter a positive number\n"); scanf("%d", &num); printf("\nNatural numbers from %d to %d:\n", count, num); while(count <= num) { printf("%d ", count); count++; } printf("\n"); return 0; }
Output 1:
Enter a positive number
10
Natural numbers from 1 to 10:
1 2 3 4 5 6 7 8 9 10
Output 2:
Enter a positive number
14
Natural numbers from 1 to 14:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
C Program to Print Natural Numbers from 1 to N using While loop
[youtube https://www.youtube.com/watch?v=smJXa0WDOPU]
Logic To Print Natural Numbers from 1 to N using While loop
We start by assigning 1 to variable count. Now we ask the user to enter a positive number. Now while loop keeps executing until value of count is less than or equal to user entered value. Inside while loop we printout the value of count and then increment the value of count by one for each iteration of while loop.
This way we printout all the natural numbers from 1 to N.
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