Conditions and loops (6)

Play this article

There are some instructions to control your code, you can manage things thanks to the conditions and the loops.

Conditions

In this article we saw the boolean operators. A boolean expression always returns a value : 1 for true and 0 for false.

The if condition takes a boolean expression and execute the following code when it's true.

if (5 >= 2) {
    printf("Five is greater than two\n");
}
Five is greater than two

The condition was checked as valid, so the code was executed.

if (5 <= 2) {
    printf("Two is greater than five\n");
}

There will be no output because the condition is invalid, the code was not executed.

Also, we can create an else case.

if (false) {
    printf("This log will never be seen\n");
} else {
    printf("Hey !\n");
}
Hey !

As well as we can create else if cases.

if (0) {
    printf("1: This log will never be seen\n");
} else if (0) {
    printf("2: This log will never be seen\n");
} else if (1) {
    printf("3: Hey!\n");
} else {
    printf("4: This log will never be seen\n");
}
3: Hey !

Conditions and defensive programming

Alright, this is simple. There is a programming way that I would like to teach you. It's a part of the "defensive programming" principle.

To avoid having too many cases following an if expression, we return when the expression works.

#include <stdio.h>

int check(int a, int b) {
    if (a != b) {
        printf("a and b are different\n");
        return 1;
    }

    if (a > b) {
        printf("a is greater than b\n");
        return 1;
    }

    if (a < b) {
        printf("a is less than b\n");
        return 1;
    }

    printf("a and b are the same\n");
    return 0;
}

If you don't care about specific prints :

#include <stdio.h>

int check(int a, int b) {
    if (a != b) {
        printf("a and b are not the same\n");
        return 1;
    }

    printf("a and b are the same\n");
    return 0;
}

Loops

In programming, a loop is a way to repeat a code block while a boolean expression is true.

while (1) {
    printf("Pete and Repeat were on a boat. Pete fell out, who was left on the boat?\n");
    printf("Repeat...");  
}
Pete and Repeat were on a boat. Pete fell out, who was left on the boat?
Repeat...
Pete and Repeat were on a boat. Pete fell out, who was left on the boat?
Repeat...
...

My program won't stop ! How to stop it ?

For every running program, in your terminal you can press CTRL + c then the program will be cancelled.

In the C language, we can use two different loops :

while (<boolean expression>) {
    <?instructions...>
}
for (<set variable>; <boolean expression>; <update variable>) {
    <?instructions...>
}

And they are two keywords to manage the loop :

  • break : To stop the loop at this point
  • continue : To ignore the code below and continue the loop at this point

Loop example for arrays

#include <stdio.h>

int main(void) {
    int values[4] = {4, 2, 9, 1};

    for (int i = 0; i < 4; ++i) {
        printf("values[%i] == %i\n", i, values[i]);
    } 

    return 0;
}
values[0] == 4
values[1] == 2
values[2] == 9
values[3] == 1

We create an iterator named i. The loop lives while i is less than 4. For each round, the variable iterator is incremented by 1.

for (int i = 0; i < 4; ++i) {}

Is the same as

int i = 0;
while (i < 4) {
    ++i;
}

And

int i = 0;
while (1) {
    if (i >= 4) {
        break;
    }
    ++i;
}

Exercises

  1. Create a function telling if the parameter is odd or even
  2. Walk through an array and multiply each element by two
  3. Create a guessing program for a magic number. It takes the number from the command line parameters. We will use the int atoi(char[] string) function from <stdlib.h> to convert a string into an integer

Solutions

  1. Create a function telling if the parameter is odd or even

    void odd_or_even(int x) {
       if (x % 2 == 0) {
           printf("%i is even\n", x);
       } else {
           printf("%i is odd\n", x);
       }
    }
    
  2. Walk through an array and multiply each element by two

     int main(void) {
         int values[3] = {6, 8, 10};
         for (int i = 0; i < 3; ++i) {
             values[i] *= 2;
         }
    
         return 0;
     }
    
  3. Create a guessing program for a magic number

     #include <stdio.h>
     #include <stdlib.h>
    
     int main(int argc, char** argv) {
         int input = atoi(argv[1]);
         int magic_number = 78;
    
         if (input < magic_number) {
             printf("It's greater\n");
         } else if (input > magic_number) {
             printf("It's less\n");
         } else {
             printf("You win !\n");
         }
    
         return 0;
     }
    

    Or with the defensive programming principle :

     #include <stdio.h>
     #include <stdlib.h>
    
     int main(int argc, char** argv) {
         int input = atoi(argv[1]);
         int magic_number = 78;
    
         if (input < magic_number) {
             printf("It's greater\n");
             return 1;
         }
    
         if (input > magic_number) {
             printf("It's less\n");
             return 1;
         }
    
         printf("You win !\n");
         return 0;
     }
    

    This program is not really good. Later we will see how to ask the user a number in the command shell and we will create a loop to avoid restarting the program for each tentative. I also said we will use the int atoi(char[] string) function from <stdlib.h> to convert a string into an integer, but it's a bad function because if the string doesn't represent a number, the result will be weird. Later, we will see the right functions to use for these cases.