Lecture 7: Branching I (if ... , if ... else ...) |
Until now, all the instructions that were put within the
program were
executed. Moreover, they were executed exactly in the order that they
were
placed. The first line of the program was executed first, then the
second,
then the third, and so on. This is not always the case. With branching
(a branch is a part of a tree) we can control the flow of the
program.
Imagine a program that specifies a number and the computer will
calculate
the square-root of the number. Taking the square-root of a negative
number
doesn't make sense (unless you are working with complex numbers, off
course),
so you would like your program to generate an error and stop when the
user
enters a negative number. You want text like
Negative numbers are not allowed! to appear on the screen. Obviously, you do not always want this text to appear on the screen; in case the user enters a positive number you just want the square-root to be calculated and appear on the screen: The square-root of 5 is 2.23607 You would like to have some way to check the number and depending on this result, execute parts of the program. |
The simplest way to have a control over the instructions that
will
be executed is with the structure if .. The full syntax
of the statement is
For condition we will
substitute
our condition and for instruction
we will put our instruction(s) that will be executed if and only if the
condition was true.
|
The normal execution of the program will resume after the block of
instructions.
In the following example, instruction3 and instruction4
will be executed, regardless of the condition (a = b).
if (a == b)
{ instruction1; instruction2; } instruction3; instruction4; |
|
Note that here the analogy with branching in trees stops. In a
tree,
the branches never meet again; once we are on a branch, it is never
again
possible to join the main trunk.
If we also want to program to do things in case the condition
is not
true we can do this with if ... else statement. The
general
form of this instruction is
example:
|
#include <stdio.h>
main()
{
double x;
double root;
printf("Give a number");
scanf("%f", &x);
if (x<0)
printf("Negative numbers
are not allowed!\n");
else
{
root = sqrt(x);
printf("The
square-root of %0.4f is %0.4f\n", x, root);
}
printf("Have a nice day\n");
}
Running the program; two examples:
Give a number
3.68 The square-root of 3.6800 is 1.9183 Have a nice day |
Give a number
-3.68 Negative numbers are not allowed! Have a nice day |