For Loop


The for loop is another entry-controlled loop that provides a more concise loop control structure. The simplest form of the for loop is

for(initialization ; condition ; increment)
{
 //body of the loop
}

Sample Program

Program
/* Reverse number program */
#include <stdio.h>

int main() {
  int number=153, rem,rev=0;
  printf("original number : %d\n",number);
  for(number; number > 0; number/=10)
  {
   rem = number%10;
   rev = rev * 10 + rem;
  }
  printf("reverse number : %d",rev);
  return 0;
}

Additional Features of for loop

C has several capabilities for loops that are not found in other loop constructs. For example, multiple variables can be started simultaneously in the for statement. The statement is -

Sample Program

Program
#include <stdio.h>

int main() {
  int i,j;
  for(i=1, j=0; j<5; j++)
  printf("%d\n",j);
  return 0;
}

Sample Program

Program
#include <stdio.h>

int main() {
  int i,j;
  for(i=5, j=0; j<5; j++,--i)
  printf("%d %d\n",i,j);
  return 0;
}

Sample Program

Program
#include <stdio.h>

int main() {
  int i,j;
  for(i=5, j=0; j<3 && i>2; j++,--i)
  printf("%d %d\n",i,j);
  return 0;
}

Nested of for loops

Nesting of loops, one for statement within another for statement, is allowed in C. The nesting may continue up to any desired level. The loops should be property indented to enable the reader to easily determine which statements are contained within for statement.

Sample Program

Program
/* Star pattern */
#include <stdio.h>

int main() {
  for(int i=0;i<=5;i++)
  {
   for(int j=0;j<=i;j++)
   {
    printf(" * ");
   }
   printf("\n");
  }
  return 0;
}