Skip to main content

Posts

Showing posts with the label for loop

Going in loops?

The next set of control statements is loop statements. C family has 3 loop statements viz for, while and do .. while for statement  for is the most compact loop statement. Often it is used when the loop is to be repeated fixed number of times. Syntax for(expr1;expr2;expr3)    statement; expr1 is initialization. expr2 is condition and expr3 is increment.  To start with expr1 is executed and next expr2 is evaluated. If expr2 is true the loop is repeated. If it is false, loop is terminated. After each iteration, expr3 is executed - which increments or decrements the control variable.   After this, again expr2 is evaluated and loop is repeated as long expr2 is true.  Now let us understand this with an example  int a; cin >> a; for ( int i = 1 ;i < 5 ;i ++ ) cout << a * i<<" "; The output of the program is  8 16 24 32  if input is 8 Here i is defined and initialized with 1. The...