if else
The general format for these are,
if( condition 1 ) statement1; else if( condition 2 ) statement2; else if( condition 3 ) statement3; else statement4;
The else clause allows action to be taken where the condition evaluates as false (zero).
The following program uses an if else statement to validate the users input to be in the range 1-10.
#include <stdio.h> main() { int number; int valid = 0; while( valid == 0 ) { printf("Enter a number between 1 and 10 -->"); scanf("%d", &number); if( number < 1 ) { printf("Number is below 1. Please re-enter\n"); valid = 0; } else if( number > 10 ) { printf("Number is above 10. Please re-enter\n"); valid = 0; } else valid = 1; } printf("The number is %d\n", number ); } Sample Program Output Enter a number between 1 and 10 --> 12 Number is above 10. Please re-enter Enter a number between 1 and 10 --> 5 The number is 5
This program is slightly different from the previous example in that an else clause is used to set the variable valid to 1. In this program, the logic should be easier to follow.
/* Illustates nested if else and multiple arguments to the scanf function. */ #include <stdio.h> main() { int invalid_operator = 0; char operator; float number1, number2, result; printf("Enter two numbers and an operator in the format\n"); printf(" number1 operator number2\n"); scanf("%f %c %f", &number1, &operator, &number2); if(operator == '*') result = number1 * number2; else if(operator == '/') result = number1 / number2; else if(operator == '+') result = number1 + number2; else if(operator == '-') result = number1 - number2; else invalid_operator = 1; if( invalid_operator != 1 ) printf("%f %c %f is %f\n", number1, operator, number2, result ); else printf("Invalid operator.\n"); } Sample Program Output Enter two numbers and an operator in the format number1 operator number2 23.2 + 12 23.2 + 12 is 35.2
The above program acts as a simple calculator.