Table of Contents
C language for statement with example
generally in programming languages, looping statements used to perform of a condition of the block of code.
C program has 3 looping statement
- for loop
- while loop
- do-while loop
here we can clearly understand for loop in C language
Syntax
for ( initializationstatement; condition; increment/dicrement ) {
statement(s);
}
How for loops works
first the initialization statements are executed only once
Then the test expression is evaluated when the test expression becomes false. The control comes out from the loop and for loop is terminated.
However, when the test expression evaluated to true, statements inside the body of for loop are executed.
finally, the updating statement(increment/decrement) is updated
then again the test expression is evaluated
This process happening on until the test expression becomes false.
For loop starts from initialization statements.
The test expression is evaluated. if the test expression is false (boolean check), the flow of control skips from the loop. for loop is terminated, but if the test expression is true codes inside in the body of for loop is executed and then update statement is updated.
program 1
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
/* for loop execution*/
for(a=10; a<20; a=a+1){
printf(“value of a is %dn”,a);
}
return 0;
}
Find factorial of the number
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i;
long factorial=1;
printf(“Enter an integer number..”);
scanf(“%d”,&n);
// show error if user enter a negetive integer
if(n<=0){
printf(“Error you must enter positive numbern”);
}
else{
for(i=1; i<=n; ++i) // single for loop
{
factorial*=i;
}
printf(“factorial of %d=%11u”,n,factorial);
}
return 0;
}
Nested for loop
program 1
#include <stdio.h>
#include <stdlib.h>
int main()
{
int row,coloum,n;
printf(“Enter the rectabgle sizen”);
scanf(“%d”,&n);
for(row=1; row<=n; row++){
for(coloum=1; coloum<=n; coloum++){
printf(“*”);
}
printf(“n”);
}
return 0;
}