< Prev
Next >



For Loop in C





C provides us a powerful loop through which we could execute statements in a loop(again and again), until the boolean condition of the loop returns true. This loop is known as for loop and it has three segments -





There can even be a for loop with missing initialization part or boolean condition part in its declaration. But, in order to make this for loop work prroperly, we will have to use break statement at the right time. Let's see an example.

/* C - for loop example */

#include<stdio.h>

int main() /*main method starts*/
{

for(int counter = 0;; )
{
	if(counter<5)
	{
		printf("counter = %d \n", counter);
		counter++;
	}
	else
		break;	/* In this case, break statement makes the for loop work */

return 0;
} 

}/* main method ends and program ends too */


Output


counter = 0
counter = 1
counter = 2
counter = 3
counter = 4


Note : If you remove the break statement from our last program, the program gets hanged. Hence, the use of break statement is utmost important when we have left off the initialization part or boolean condition part of for loop.


Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter




< Prev
Next >
< Nested If Else Statement
Do-While Loop>
Please subscribe our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
C++ and Python

Ad2