The for loop

The for loop consists of three elements, the initialization, the condition, and the increment. The initialization is an assignment statement that is used to set the loop control variable. The condition is a relational expression that determines when the loop stops. The increment defines how the loop control variable changes each time the loop is repeated.

#include <stdio.h>
#include <math.h>

int main(void){
 
  int x;
 
  for(x=0; x <= 20; x++){
      printf("2^%d = %.0f\n", x, pow(2, x));
  }
 
  return 0;
 
}

The loop iteration can be a decrement as well as an increment.

#include <stdio.h>

int main(void){
 
  int i;
 
  for(i=21; i>0; i--){
     printf("%d \t %d^2 = %d \t %d^3=%d\n",
        i, i, i*i, i, i*i*i);
  }
 
  return 0;
 
}

The loop can increment or decrement by values other than one.

#include <stdio.h>

int main(void){
 
 
  int i;
 
  for(i=5;i<=200;i+=5){
   printf("%-3d\t", i);
   if(i%20==0){
    putchar('\n');
   }
  }
 
  return 0;
 
}

It is possible to have two or more variables control the loop.

We can initialize multiple variables within the for statement; we use commas to separate the multiple initialization statements.

#include <stdio.h>

int main(void){
 
  int x, y;
 
  for(x=1, y=99; x<=y; x++, y--){
    printf("%2d + %2d = %d\n", x, y, x+y);
  }
 
  return 0;
 
}

Here is a quick program to copy a string that uses two loop control variables.

#include <stdio.h>
#include <string.h>

void stringCopy(char *targetString, char *sourceString);

int main(void){
 
  char string[150];
 
  stringCopy(string,
         "If mice could swim, they would float with the tide and play with the fish down by the seaside. The cats on the shore would quickly agree.");
 
  printf("string is now: %s\n", string);
 
  return 0;
 
}


void stringCopy(char *targetString, char *sourceString){
 
  int i, j;
 
  int stringLength = strlen(sourceString);
  printf("Length of the string is %d\n", stringLength);
 
  for(i=0, j=stringLength; i<=j; i++, j--){
      targetString[i] = sourceString[i];
      targetString[j] = sourceString[j];
  }
 
  targetString[stringLength+1]='';
 
}

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s