Up until now, we have been writing a program that executes the statements one by one until the defined end. The functionality of this type of program is limited since it flows in single direction. Now we will be looking at one of the most powerful programming feature - the ability to change the flow of program execution. It is achieved by establishing the truth or falsity of an
expression (condition).
Consider the following program.
#include<stdio.h>
int main()
{
int V;
printf("Enter the value of voltage, V: ");
scanf("%d", &V);
printf("The value of V is %d\n", V);
return 0;
}
The program prints the value of V which is inputted by the users. What if we want the program prints
V when the users enter a value that is more than 5 only. This means, the program has to be able to make a decision based on the user's input. C provides a decision making capability in the form of
if statement.
if is used when we want statements to be executed if an expression is TRUE. Otherwise the statements are skipped. Now, lets add an
if statement to the above program as follows.
#include<stdio.h>
int main()
{
int V;
printf("Enter the value of voltage, V: ");
scanf("%d", &V);
if(V > 5)
printf("The value of V is %d\n", V);
return 0;
}
Output
Enter the value of voltage, V: 8
The value of V is 8
if(V > 5)
printf("The value of V is %d\n", V);
V is compared with 5. If the value of V is greater than 5, the
printf() statement will be executed which prints a string on the monitor. Otherwise the
printf() will be skipped. In the example, 8 is entered by the user, thus
"The value of V is 8" is displayed.