Control flow of statement:
You have already known that execution of a C program will start from main function (more specifically- from the opening curly brace followed by int main). You may face a situation where you have to break the conventional sequence of execution.Controlling the execution sequence of statements is called Control flow of statement.
Explanation: Suppose you want to print “Evil company corrupts good morals” 10 times. You may write code as follows:
#include<stdio.h> int main() { printf("Evil company corrupts good morals\n"); printf("Evil company corrupts good morals\n"); printf("Evil company corrupts good morals\n"); printf("Evil company corrupts good morals\n"); printf("Evil company corrupts good morals\n"); printf("Evil company corrupts good morals\n"); printf("Evil company corrupts good morals\n"); printf("Evil company corrupts good morals\n"); printf("Evil company corrupts good morals\n"); printf("Evil company corrupts good morals\n"); return 0; }
OUTPUT
Evil company corrupts good morals
Evil company corrupts good morals
Evil company corrupts good morals
Evil company corrupts good morals
Evil company corrupts good morals
Evil company corrupts good morals
Evil company corrupts good morals
Evil company corrupts good morals
Evil company corrupts good morals
Evil company corrupts good morals
Now if there is a trick to repeat
printf("Evil company corrupts good morals\n");
this line 10 times it will be more efficient. Fortunately there are some trick to do this. In C program it is called loop. Loop can repeat a statement or a block of statements. There are three looping system in C program: for loop,while loop, do while loop. Now we do the above program with for loop:
#include<stdio.h> int main() { int i; for(i=0;i<10;i++) { printf("Evil company corrupts good morals\n"); } return 0; }
OUTPUT
Evil company corrupts good morals
Evil company corrupts good morals
Evil company corrupts good morals
Evil company corrupts good morals
Evil company corrupts good morals
Evil company corrupts good morals
Evil company corrupts good morals
Evil company corrupts good morals
Evil company corrupts good morals
Evil company corrupts good morals
NOTE:
Here we simply show how a for loop can reduced 10 line code into one line. Next section we will discuss all flow control of statement such as for loop, while loop, do while loop, if, else if, else, switch case etc with explanation.
Next Previous