If else

From Applied Science
  • An algorithm that tests if a number is odd or even:

int a;

if (a % 2 == 0) printf("The number %d is even", a);
else printf("The number %d is odd", a);

Pretty simple, just the part related to user input has been omitted. It's pretty intuitive the concept about decision making in examples such as this one.


  • A variation of the algorithm above, this time with the operators AND, OR plus ELSE IF:

int a, b, c;

if (a % 2 == 0 && b % 2 == 0) {

c = a + b;
printf("The sum of two even numbers always result in another even number: %d", c);

}

else if ((a % 2 == 0 && b % 2 != 0) || (a % 2 != 0 && b % 2 == 0)) {

c = a * b;
printf("The product of an even number and an odd number always result in another even number: %d", c);

}

else {

c = a * b;
printf("The product of two odd numbers always result in an odd number: %d", c);

}

The 'else if' decision. The pair if - else literally means "either this or that", just paths to choose from. When we want more than two paths, then we use 'else if'.

Only one case can be satisfied, the first one to be satisfied is executed, the rest is skipped. This is where some logic errors lie, if we aren't careful enough, some cases might overlap others. For example: suppose that the first conditional is "even number" and the second is "number greater than zero". If the user inputs number 4, the first conditional is satisfied before the second, the second isn't evaluated.

Every else must be "married" with an 'if', but an 'if' can be single, without an accompanying 'else'. When two or more conditionals are unrelated or mutually exclusive, many ifs can be used without an else case at the end. Be careful! In such construction the conditionals cannot overlap each other, else more than one conditional is satisfied at the same time.


  • A variation of the algorithm above, this time using nested IF statements, rather than logical operators

int a, b, c;

if (a % 2 == 0) {

if (b % 2 == 0) {

c = a + b;
printf("The sum of two even numbers always result in another even number: %d", c);

}

}

else if (b % 2 != 0) {

c = a * b;
printf("The product of two odd numbers always result in an odd number: %d", c);

}

else {

c = a * b;
printf("The product of an even number and an odd number always result in another even number: %d", c);

}

An if under another if is the same thing as using a single if with a double conditional and the '&&' operator. Be careful! If the input is 'a' is even and 'b' is odd. The first conditional is satisfied, but the second 'if' isn't. Due to the lack and accompanying 'else', nothing happens; during the execution, the 'else if' is going to be skipped, because the uppermost 'if' case has already been satisfied.

In the case of "this || that" it's not possible to write nested 'if's, because the nested 'if' case can only be satisfied if the uppermost 'if' is too.