Sage-Code Laboratory
index<--

Decision Statement

Decision statement is the first flow control statement we learn in C. This is very simple but also powerful. It is used to enable or disable execution of next statement depending upon a specific condition. A condition is a logical expressionthat we will explain next.

Decision Fork

In the diagram below we show the logical work-flow for decision statement. This is based on keyword "if" and it has two branches. One is the "true branch" and the other is the "false branch". It is like two branches of a river. It split the code into two blocks. After the decision is made, program will continue.

decision

Decision Diagram


Syntax description:

//brackets are optional

// single statement
if (condition) print("test");

// single block
if (condition) {
  //positive branch
  ...
}

//two branches
if (condition) {
  //positive branch
  ...
}
else {
  //negative branch
  ...
}

Example:

In the next example we use "if" keyword two times. First time will create a "branch" that print "this is expected". This branch is executed since x = 0. Second time we create a branch that will never execute since is not > 0. So the string "this is unexpected" will never be printed:

#include <stdio.h>
int main()
{
    int x = 0;
    //positive test
    if (x == 0)
    {
        printf("this is expected");
    }
    //negative test
    if (x > 0)
    {
        printf("this is unexpected");
    }
    return 0;
}

Nested Statements

Block statements can be nested. That means inside of a block statement you can create another block statement. We advice developers to reduce the number of nested levels as much as possible.

Example:

#include <stdio.h>
int main()
{
    int number1, number2;
    printf("Enter two integers: ");
    scanf("%d %d", &number1, &number2);
    if (number1 >= number2) {
        if (number1 == number2) {
        printf("Result: %d = %d",number1,number2);
      }
      else {
        printf("Result: %d > %d", number1, number2);
      }
    }
    else {
        printf("Result: %d < %d",number1, number2);
    }
    return 0;
}

Decision Ladder

You can create more than two branches using "else if" keywords. This construct is called ladder. Also known as decision chain is depicted in next diagram that looks like a stair or like a ladder:

decision

Ladder Diagram

Syntax description:

//brackets are optional
if (condition) {
  //positive branch
  ...
}
else if (condition) {
  //alternative branch
  ...
}
else if (condition) {
  //second alternative
  ...
} else
{
  //default negative
  ...
}

Selection Statement

Selection statement "switch" is a multi-path decision statement based on a variable that can have a specific value. For each value you create a single path to follow. This statement is translated by the compiler into a jump table.
switch

Switch Diagram


Syntax Pattern

switch(variable)
{
case value_1:
   //statement for case 1
break;
...
case value_n:
   //statement for case n
break;

default:
   //statement for other values
break;
}

Notes:

Rules and restrictions

Example:

#include <stdio.h>

int main () {
   char result = 'B';
   printf("enter your result:");
   scanf("%c",&result);
   switch(result) {
      case 'A' :
         printf("Congratulation, you passed!\n" );
         break;
      case 'B' :
      case 'C' :
      case 'D' :
         printf("You have passed\n" );
         break;
      case 'F' :
         printf("Sorry, you have failed\n" );
         break;
      default :
         printf("Invalid result\n" );
   }
   return 0;
}

Note:  Now you know switch statement. This statement is not available in Python but is present in many other languages similar to C language: Java, Swift, Go. In all these languages switch is very similar.

Switch Usability:

Switch is useful to create a menu. You can have options 1..9. When user press one of the option a particular branch of program is executed. This can be simulated using "if" statement but is not so readable.

The options can be also char. In this case you can have 25 options, one for each letter of he alphabet. If you use capital letters and numbers you can create a menu with maximum 70 options. This is not always readable. You can improve readability by using an enumeration type.

Enumeration

The enumeration type can be used to create a new data type representing menu options with a name for each option. This type is a discrete type so it can be used in switch statement to create one path for each element of enumeration.

Example:

#include <stdio.h>
enum option {Up, Down, Left, Right};

int main()
{
   int i;
   menu: //this is a label
   printf("0 = Up\n");
   printf("1 = Down\n");
   printf("2 = Left\n");
   printf("3 = Right\n");
   printf("select:");
   //read menu option
   scanf("%d",&i);
   printf("\n");
   switch (i) {
      case Up:    printf("up"); break;
      case Down:  printf("\n"); break;
      case Left:  printf("0 = Up\n"); break;
      case Right: printf("0 = Up\n"); break;
      default:
         printf("Invalid entry, try again\n");
         goto menu; //find label and repeat
      break;
   }
   return 0;
} 

GoTo Statement

In the previous example we have used goto statement. This is also know as unconditional jump statement. It is advisable to avoid this statement in C programs and use loops instead of jumps to avoid spaghetti code, considered unreadable.

Syntax:

identifier: //label
...
goto identifier; //execute jump to label

You can jump backward or forward depending on label position. Notice if you have no other control flow statement and you jump backwards the control flow becomes repetitive and the program will never terminate. 

Note: To force program termination in console, you can use Ctrl+Z.

Repetitive Statements

Work in progress. Follow me on Twitter for news.

A repetitive statement is a block of code or a statement that can be repeated several times to perform one or more tasks. We must control the number of repetitions otherwise the program will run forever. Therefore repetitive statement is sometimes called "loop".

There are 3 kind of repetitive statements in C:

  1. while: condition repetition
  2. do: post-conditional repetition
  3. for: value controlled repetition

The difference between these loops is the way we control the number of iterations. Next I will present 3 examples. You must read the comments to understand better the syntax:

Alternative: There are other two ways to repeat execution of statements or blocks in C:

  1. Using GoTo statement
  2. Using recursive functions

While Loop

The while loop will be executed as long as control condition is true and will stop when the condition become false. Remember true = 1 and false = 0. So the condition can be a logical or a numeric expression. If the condition never = 0 then we create an infinite loop.

loop

Repetition Diagram


Example:

#include <stdio.h>
int main()
{
    //control variable
    int i = 1;

    //start loop
    while (i < 4)
    {
       i = i + 1;
    }
    //end loop
    printf("i = %d", i); // expected to print 4
    return 0;
}

Do..While Loop

This loop will look very strange to you. I is designed very different than other C statements and somehow inconsistent. So pay attention to the example and read the comments below to grasp it.

do-while

do-while diagram


Example:

#include <stdio.h>
int main () {
   // control variable
   int x = 1;
   // start loop
   do {
      x = x + 1;
   } while ( x < 4 );
   // end loop
   printf("x = %d", x); // expect to print 4
   return 0;
}

The condition is specified after the block. Therefore this iteration is executed at least once regardless of condition value, unlike the previous case where the condition is evaluated before the first iteration.

For Loop

For statement is controlled by a local variable x that belong to a specified discrete range of values. In next example first value is  5 and last value is 9. Value 10 is not printed.

#include <stdio.h>
int main () {
   // start loop
   for(int x = 5; x < 10; x = a + 1 ){
      printf("x= %d\n", x);
   }
   // end loop
   return 0;
}

Note: This repetitive statement is a convenient way to have all the control into one place for easy visualization. So the for loop does the same thing as while and do except that is more compact and readable. Variable "x" is local defined but it could be declared before the loop starts. In this case it will be available after the loop end like it is for "do" and "while".

Altering the Loop

It is possible to modify the normal workflow of any repetitive statement by using two keywords: break and continue. In the diagram below we depict the concept of for loop alteration but the same apply for previous tow loops: do & while loops.

loop

For/Loop Repetition

Early exit

We ise early exit to terminate the repetition before normal ending. Usually the exit is trigger by an additional condition using statement: break. With this we "break" the normal cycle and force the loop to stop. The program will continue with next statement.

Break:

#include <stdio.h>
int main () {
   int x = 1;
   while (x < 10) {
      x++;
      if( x > 5) {
         break; // early exit
      }
   }
   printf("x = %d",x); //expected 6
   return 0;
}

Shortcut:

Sometimes it is useful to skip the rest of the block and start next iteration. This operation do not terminate the loop but jump execution back to the beginning of the loop. It can simplify the code. To make a shortcut you can use statement: continue

#include <stdio.h>
int main () {
   int x = 1;
   while (x < 10) {
      x++;
      if( x < 5) continue; // shortcut
   }
   printf("x = %d",x); //expected 10
   return 0;
}
Observe the new operator "++" that was first used in B language. This operator is equivalent to: x = x +1. It is used as increment operator to improve performance and code readability. In modern languages this is called "syntax sugar" and is considered a good thing. 

Notes:

Caution!

It is possible to declare a variable inside a loop. Then the variable is not available outside of the loop. However in my opinion this is bad practice. The variable declarations should stay outside of the loop. In the next example the result is going to be unexpected:

#include <stdio.h>
int main()
{
    for (int i = 1; i< 10; i++) {
        int j = 1;
        j++;
        printf("%d,",j);
    }
    return 0;
}

Output:

2,2,2,2,2,2,2,2,2,

Note: If you declare the variable static inside the loop then the result will be correct but still a bad practice. There is no visible advantage to declare a variable inside a loop, so don’t do this.


Read next: Input & Output