In the previous blog we saw how to find the greatest number from the three numbers .In this blog we will see how to print from 1 to N integers using a for loop .
What is a Loop?:-
A loop is a programming construct that repeats a block of code until the specified condition is satisfied.
There are three types of loops in C programming:
- for loop
- while loop
- do...while loop
For Loop:-
for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of loop
}
Working:-
Only one instance of the initialization statement is run.The test expression is then assessed. The for loop is terminated if the test statement evaluates to false.
If the test expression is true, however, statements inside the for loop's body are executed, and the update expression is updated.
The test expression is examined once more.
This procedure is repeated until the test expression is found to be false. The loop ends when the test expression is false.
Code:-
#include<stdio.h>
int main()
{
int i, n;
printf("Enter a number ");
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
printf("%d ",i);
}
}
Algorithm:-
1.Start
2.Declare two integer variables i and n of type int .
3.Use a scanf statement to get the input of the number (n) by using the format specifier "%d" .
4.Run a for loop from 1 to n.
Explanation:-
We initialize the variable i as 1 and the test expression must be less than or equal to n and then increment the variable i by 1 .
5.Finally print the variable i by using the format specifier "%d " .
6.Stop
Screenshot:-
1.Code Screenshot:-
2.Output Screenshot:-
In the next blog we will see how to print from N to 1 by using a for loop .
0 Comments