C/C++  

 

 

 

for loop

Basic synatx of the for loop is as follows :

    for(initial_condition ; in_loop_condition; counter_change)

 

basic for loop

#include <stdio.h>

 

int main()

{

    

    int i;

    for( i = 0; i < 5; i++) {

        printf("i = %d\n",i)    ;

    }

 

    return 1;

}

 

Result :---------------------------------------

    i = 0

    i = 1

    i = 2

    i = 3

    i = 4

 

loop condition and counter change

#include <stdio.h>

 

int main()

{

    

    int i;

    

    printf("Output of for( i = 0; i < 5; i++) ===\n");

    for( i = 0; i < 5; i++) {

        printf("i = %d\n",i)    ;

    }

    

    printf("\n\n");

    printf("Output of for( i = 0; i <= 5; i++) ===\n");

    for( i = 0; i <= 5; i++) {

        printf("i = %d\n",i)    ;

    }

    

    printf("\n\n");

    printf("Output of for( i = 0; i <= 5; ++i) ===\n");

    for( i = 0; i <= 5; ++i) {

        printf("i = %d\n", i);

    }

 

    return 1;

}

 

Result :---------------------------------------

    Output of for( i = 0; i < 5; i++) ===

    i = 0

    i = 1

    i = 2

    i = 3

    i = 4

     

    Output of for( i = 0; i <= 5; i++) ===

    i = 0

    i = 1

    i = 2

    i = 3

    i = 4

    i = 5

     

    Output of for( i = 0; i <= 5; ++i) ===

    i = 0

    i = 1

    i = 2

    i = 3

    i = 4

    i = 5

 

for() loop with no counter

#include <stdio.h>

 

int main()

{

    

    int i = 0;

    

    printf("Output of for( ; ; ) ===\n");

    for( ; ; ) {

        i = i + 1;

        printf("i = %d\n",i);

        

        if(i >= 5) {

            break;

        }

    }

 

    return 1;

}

 

Result :---------------------------------------

    Output of for( ; ; ) ===

    i = 1

    i = 2

    i = 3

    i = 4

    i = 5