Lesson 5 - Conditions (branching) in the C language

C and C++ The C language Basics Conditions (branching) in the C language

In the previous lesson, More on the C type system: Data types, we discussed the C language data types in detail. We need to react somehow to different situations if we want to program something. It may be, for example, a value entered by the user, according to which we would like to change how the program runs. We metaphorically say that the program branches, and for branching we use conditions. We will pay attention to those in today's article. We're going create a program which calculates square roots, and we're going to improve our calculator.

Conditions

Conditions are written using the if keyword, which is followed by a logical expression. If the expression is true, the following statement will be executed. If it's not true, the following statement will be skipped, and the program will continue with the next statement. Let's try it out:

if (15 > 5)
        printf("True \n");
printf("The program continues here... \n");

The output:

Console application
True
The program continues here...

If the condition is true, a command which writes a text to the console will be executed. In both cases the program continues. Of course, a variable can also be part of the expression:

int a;
printf("Enter a number");
scanf("%d", &a);
if (a > 5)
        printf("The number you entered is greater than 5! \n");
printf("Thanks for the input! \n");

Let's look at the relational operators which can be used in expressions:

Meaning Operator
Equal to ==
Greater than >
Less than <
Greater than or equal to >=
Less than or equal to <=
Not equal !=
Negation !

We use the == operator for equality to avoid confusing it with a normal assignment to a variable (the = operator). If we wanted to negate an expression, we would write it in parentheses and write an exclamation mark before the actual expression within the parentheses. If you want to execute more than one command, you'd have to add the commands into a block of curly brackets:

#include <stdio.h>
#include <stdlib.h>
#include <math.h> // We have to include math.h containing a function to compute a square root

int main(int argc, char** argv) {
        int a;
        printf("Enter a number and I'll calculate its square root: \n");
        scanf("%d", &a);
        if (a > 0)
        {
                printf("The number you entered is greater than 0, so I can calculate it! \n");
                double root = sqrt(a);
                printf("The square root of %d is %lf \n", a, root);
        }
        printf("Thanks for the input \n");
        return (EXIT_SUCCESS);
}

Console application
Enter a number and I'll calculate its square root:
144
You've entered a number greater than 0, I can calculate it!
Square root of 144 is 12.000000
Thanks for the input

You may encounter times when people use a {} block even for just a single command, some programmers find it more readable.

The program retrieves a number from the user, and if it is greater than 0, it calculates a square root. We have used the math.h library, which contains plenty of useful mathematical methods. At the end of this course, we'll learn more about them. Sqrt() returns the value as a double data type. It would be nice if our program warned us if we entered a negative number. With what we know up until now, we're able to write something like this:

#include <stdio.h>
#include <stdlib.h>
#include <math.h> // We have to include math.h containing a function to compute a square root

int main(int argc, char** argv) {
        int a;
        printf("Enter some number and I'll calculate a square root: \n");
        scanf("%d", &a);
        if (a > 0)
        {
                printf("The number you entered is greater than 0, so I can calculate it! \n");
                double root = sqrt(a);
                printf("The square root of %d is %lf \n", a, root);
        }
        if (a <= 0)
                printf("I can't calculate the square root of a negative number! \n");
        printf("Thanks for the input \n");
        return (EXIT_SUCCESS);
}

We must keep the case where a == 0 in mind, and also when it is less than 0. The code can be greatly simplified using the else keyword which executes the following statement or block of statements if the condition was not true:

#include <stdio.h>
#include <stdlib.h>
#include <math.h> // We have to include math.h containing a function to compute a square root

int main(int argc, char** argv) {
        int a;
        printf("Enter some number and I'll calculate a square root: \n");
        scanf("%d", &a);
        if (a > 0)
        {
                printf("The number you entered is greater than 0, so I can calculate it! \n");
                double root = sqrt(a);
                printf("The square root of %d is %lf \n", a, root);
        }
        else
                printf("I can't calculate the square root of a negative number! \n");
        printf("Thanks for the input \n");
        return (EXIT_SUCCESS);
}

The code is much clearer now, and we don't have to make up the negating condition which could get very difficult with complex conditions. In the case of multiple commands, there would be a {} block again after the else keyword.

Else is also used when we need to set a variable from the condition up so we can't evaluate it later again. The program remembers that the condition didn't apply and it'll move on to the else branch. Let's look at an example: Consider a number whose value will be either 0 or 1, and we'll be asked to swap those values (if there is a 0, we'll put a 1 there, and the other way around). Naively, we could write a code like this:

int a = 0; // the variable is initialized with a value of 0

if (a == 0) // if the value is 0, we change its value to 1
        a = 1;
if (a == 1) // if the value is 1, we change its value to 0
        a = 0;

printf("%d", a);

It doesn't work, does it? Let's take a closer look at the program. At the very beginning, a contains value 0, the first condition is undoubtedly fulfilled and it assigns 1 into a. Well, suddenly, the second condition becomes true. What should we do? When we swap the conditions, we'll have the same problem with 1. Now, how do we solve this? You guessed it, using else!

int a = 0; // the variable is initialized with a value of 0

if (a == 0) // if the value is 0, we change its value to 1
        a = 1;
else // if the value is 1, we change its value to 0
        a = 0;

printf("%d", a);

Conditions can be composed by using two basic logical operators:

Operator C-like syntax
Logical AND &&
Logical OR ||

Let's take a look at the example:

int a;
printf("Enter a number between 10-20: \n");
scanf("%d", &a);
if ((a >= 10) && (a <= 20))
        printf("The condition has been met. \n");
else
        printf("You did it wrong. \n");

Of course operators can be combined with parentheses:

int a;
printf("Enter a number between 10-20 or 30-40: \n");
scanf("%d", &a);
if (((a >= 10) && (a <= 20)) || ((a >=30) && (a <= 40)))
        printf("The condition has been met. \n");
else
        printf("You did it wrong. \n");

Switch

Switch is a construct that allows us to relatively simplify the usage of if-else command sequences. Let's remember our calculator from the first lesson, which had read two numbers and calculated all 4 operations. Now, we want to single out an operation. Without the switch, we would write the code like this:

double a;
double b;
int option;
double result = 0.0;
printf("Welcome to our calculator \n");
printf("Enter the first number: \n");
scanf("%lf", &a);
printf("Enter the second number:");
scanf("%lf", &b);
printf("Choose one of the following operations: \n");
printf("1 - addition \n");
printf("2 - subtraction \n");
printf("3 - multiplication \n");
printf("4 - division \n");
scanf("%d", &option);
if (option == 1)
        result = a + b;
else
if (option == 2)
        result = a - b;
else
if (option == 3)
        result = a * b;
else
if (option == 4)
        result = a / b;
if ((option > 0) && (option < 5))
        printf("result: %lf", result);
else
        printf("Invalid option");
printf("Thank you for using our calculator. Press any key to end the program. \n");

Console application
Welcome to our calculator
Enter the first number:
3.14
Enter the second number:
2.72
Choose one of the following operations:
1 - addition
2 - subtraction
3 - multiplication
4 - division
2
result: 0.420000
Thank you for using our calculator. Press any key to end the program.

Notice that we've declared the variable result at the beginning, so we could later assign something to it. If we declared it during every assignment, C would not compile the code and report an error since the variable had already been declared. A variable can be declared only once. The C language is not able to tell whether a value is really assigned to the variable result. It would report an error on the line where we're printing to the console because C doesn't like the fact that the variable being printed is not guaranteed to contain a value. For this reason, we have to assign zero to the variable "result" at the beginning. Another trick is validating the user's choice. The program should still work the same even without all the "else"s (but why keep on asking if we already have a result).

Now, here's the same program using a switch:

double a;
double b;
int option;
double result = 0.0;
printf("Welcome to our calculator \n");
printf("Enter the first number: \n");
scanf("%lf", &a);
printf("Enter the second number: \n");
scanf("%lf", &b);
printf("Choose one of the following operations: \n");
printf("1 - addition \n");
printf("2 - subtraction \n");
printf("3 - multiplication \n");
printf("4 - division \n");
scanf("%d", &option);
switch (option)
{
        case 1:
                result = a + b;
                break;
        case 2:
                result = a - b;
                break;
        case 3:
                result = a * b;
                break;
        case 4:
                result = a / b;
                break;
}
if ((option > 0) && (option < 5))
        printf("result: %lf", result);
else
        printf("Invalid option");
printf("Thank you for using our calculator. Press any key to end the program. \n");

As you can see, the code is a bit clearer now. If we needed to execute multiple commands in any branch of the switch, surprisingly, we wouldn't write it into the {} block, but just under the first command. The {} block is replaced by a break command that causes a jumping out from the entire switch. Beside of case x:, the switch can also contain the default: branch, which will be executed if neither of the cases applied. It's up to you whether you use a switch or not. Generally, it's useful only for a larger amount of branches and you always could always it with if-else sequences. Don't forget about breaks. If you omit them, the program would enter the next case even the condition would not be met! Programmers used to take an advantage of this strange behavior in the past, however, today's IDEs tend to warn about this kind of usage.

That is all for today. In the next lesson, Loops in the C language, we'll take a look at arrays and loops, i.e. finish up with the absolute basics of the C language. Look forward to it :)


 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Thumbnail
All articles in this section
The C language basic constructs
Activities (6)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!