In the previous blog we saw how to print from 1 to N .In this blog we will see how to print from N to 1 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=n;i>=1;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 n to 1.
Explanation:-
We initialize the variable i as n and the test expression must be greater than or equal to 1 and then decrement the variable i by 1 .
5.Finally print the variable i by using the format specifier "%d " .
6.Stop
Screenshot:-
In the next blog we will see how to print from 1 to N by using a while loop .
0 Comments