Tutorial 5.2: if else Selection Structure

Extending the if Statement
Lets revise the last session, if statement allows a statement to be executed if the condition is true. If it is false the statement will be skipped. What if we want the program to execute certain statement if the condition is false. Remember the previous program's if statement.
if (num > 0)
   printf("%d is a positive number\n", num);
The message will be displayed only when the condition is true. Lets make a few modification to the if selection structure.
if (num > 0)
   printf("%d is a positive number\n", num);
else
   printf("%d is a negative number\n", num);
As you can see we add else statment after the if statement. In the if else selection structure, the else statement will be executed when the condition is false. For example, if variable num is less than 0, the first printf() will be skipped and the second printf() will be executed. The function of if else selection is illustrated in the flowchart.


The full program and the sample output are given below. The sample output shows two different outputs for positive number and negative number.
#include <stdio.h>

int main()
{
   int num;
   printf("Enter a number between -10 and 10: ");
   scanf("%d", &num);
   if(num > 0)
      printf("%d is a positive number\n", num);
   else
      printf("%d is a negative number\n", num);
   return 0;
}
Sample output:

Enter a number between -10 and 10: 6
6 is a positive number

or

Enter a number between -10 and 10: -2
-2 is a negative number

Next: Nested if Statement

No comments:

Post a Comment