top of page

Selection and Iteration in C

Selection

Selection is a program branch depending on a condition. The classic example of selection is the use of an if...else statement.


If...Else Syntax

If the test expression is true, the code inside the "if" body is executed and the code inside the "else" body is skipped. If the test expression is false, the opposite is true.


Iteration

Iteration, sometimes called a loop, is a repeating section of code. There are three main structures in C: a for loop, a while loop and a do while loop.


For Loop



  1. Here, i is initialised to 1.

  2. The test expression i < 11 is evaluated. Since, on the first occasion, the expression is true, the code in the body of the for loop is executed . In this case, the value of i is printed.

  3. The update statement i++ is updated. This increases the value of i by 1.

  4. The test expression is evaluated again and the code in the body of the for loop is executed.

  5. Eventually, i = 11 and the text expression is no longer true and the for loop is terminated.

While Loop



do while Loop

This loop is similar to the while loop apart from one key difference: the body of the loop is always executed at least once, even if the test expression is false.



1 view0 comments

Recent Posts

See All

Comments


bottom of page