WHAT'S NEW?
Loading...

for Loop in C Programming (With Examples)

The for loop is useful to execute a statement for a number of times. When the number of repetitions is known in advance, the use of this loop will be more efficient. Thus this loop is also known as a determinate or definite loop.
Syntax : 
     for (counter_init; condition; increment/decrement ) {
        statement(s);
     }
 
Different components in for loop
Counter Initialization: 
The counter variable is initialized using assignment statement such as i=1, j=10 and count=0, Here, the variable i, j and count are known as counter or loop-control variables whose value controls the loop execution. This expression or statement is executed only once prior to the statements within the for loop.

Condition: 
The value of counter variable is tested using test condition. if the condition is true, the body of the loop is executed; otherwise the loop is terminated and the execution continues with the statement that immediately follows the loop.
 
Update expression or increment/decrement expression: 
When the body of the loop is executed, the control is transferred back to the for statement after evaluating the last statement in the body of loop. The counter variable is updated either incremented or decremented and then only it is to be tested with test condition and same process is repeated until the condition became false.

Example 1: WAP to print the natural numbers from 1 to 100.
#include<stdio.h>
void main(){
 int i; 
 for(i=1; i<=100; i++){
  printf("%d \t",i); 
 }
 getch(); 
}
Output

Example 2: WAP to print the even numbers from 50 to 100. 

#include<stdio.h>
void main(){
 int i; 
 for(i=50; i<=100; i=i+2){
  printf("%d \t",i); 
 }
 getch(); 
}
Output

 Example 3: WAP to print the multiplication table of entered number. 
#include<stdio.h>
void main(){
 int n, i; 
 printf("Enter any number : "); 
 scanf("%d",&n); 
 for(i=1; i<=10; i++){
  printf("%d x %d = %d \n",n, i, n*i); 
 }
 getch(); 
}
Output

Example 4: WAP to ask the integer number n and calculate the sum of all natural numbers from 1 to n. 
#include<stdio.h>
void main(){
 int n, i, sum=0; 
 printf("Enter any number : "); 
 scanf("%d",&n); 
 for(i=1; i<=n; i++){
  sum = sum + i; 
 }
 printf("The Sum of Natural Numbers = %d",sum); 
 getch(); 
}
Output
Enter any number : 100
The Sum of Natural Numbers = 5050

Example 5: WAP to calculate factorial of a given number. 

#include<stdio.h>
void main(){
 int n, i, f=1; 
 printf("Enter any number : "); 
 scanf("%d",&n); 
 for(i=1; i<=n; i++){
  f=f*i;
 }
 printf("The Factorial of %d is %d",n, f); 
 getch(); 
}
Output
Enter any number : 5
The Factorial of 5 is 120

0 comments:

Post a Comment