C programming for loop
Loop is used in a programming language to repeat a particular code block. In this chapter you will learn to create a for loop in C programming.
The programming loop is used to repeat any code block until the condition is false. There are three types of loop in C programming
For loop-for loop
Whole loop - while loop
Do ... want to loop - do ... while loop
for loop
for loop syntax
for (initializationStatement; testExpression; updateStatement)
{
// This code will be executed
}
How does the for loop work?
initializationStatement is only executed once.
Then testExpression is executed. If false (0) is the end of the for loop. But if the value of the test expression is true then the code block for the for loop is executed and the value of updateStatement is updated.
It continues until testExpression is false.
Note: If the number of iteration is already known then the for loop is used.
When the value of testExpression is true and when it is false: the relational and logical operators page is discussed.
C for loop:
Example 1: for loop// C program for output from full number 1 to 5
#include <stdio.h>
#include <conio.h>
int main ()
{
int i;
clrscr ();
for (i = 1; i <= 5; i ++)
{
printf ("\ n% d", i);
}
getch ();
}
Output
1
2
3
4
5
Example 2: for loop
// The first n is the number of natural numbers in the calculation program.
// Positive full number 1,2,3 ... n is known as normal number.
#include <stdio.h>
int main ()
{
int num, count, sum = 0;
printf ("Enter a positive integer:");
scanf ("% d", & num);
If the value of // num is smaller than the count, the for loop ends
for (count = 1; count <= num; ++ count)
{
sum + = count;
}
printf ("Sum =% d", sum);
return 0;
}
Output
Enter a positive integer: 10
Sum = 55
Explanation of the above example
The value entered by the user is stored in the variable num. Assume, the user entered 10.
The initial value of the variable count is assigned 1 and the test expression will be evaluated. Since count <= num (1 is smaller than 10) is true, so the code block in the loop will be executed and the value of sum will be equal to 1.
Then updateStatement ++ count will be equal to count value of 2 as it is executed. Again testExpression will be executed. Since 10 to 2 is smaller, so the value of testExpression will be true and loop code block will be executed. The value of sum will be equal to 3.
This process will continue until the value of count is not reached 11 and the value of sum will be determined.
When the value of count is equal to 11, testExpression will be false because 11 is less than or equal to 11. So the end of the loop here will be done and the next code will be edited. The sum at the end of the loop will print.


0 Comments