GE6151 Computer Programming DECISION MAKING

DECISION MAKING

IF STATEMENTS

The if statements allows branching (decision making) depending upon the value or state of variables. This allows statements to be executed or skipped, depending upon decisions. The basic format is,

if( expression )

program statement;

Example:

if( students < 65 )

++student_count;

In the above example, the variable student_count is incremented by one only if the value of the integer variable students is less than 65.

The following program uses an if statement to validate the users input to be in the range 1-10.

Example:

#include <stdio.h>

main()

{

int number; int valid = 0; while( valid == 0 )

{

printf("Enter a number between 1 and 10 -->");

scanf("%d", &number);

/* assume number is valid */ valid = 1;

if( number < 1 )

{

printf("Number is below 1. Please re-enter\n"); valid = 0;

}

if( number > 10 )

{

printf("Number is above 10. Please re-enter\n"); valid = 0;

}

}

printf("The number is %d\n", number );

}

IF ELSE

The general format for these are,

if( condition 1 ) statement1; elseif(condition2) statement2; elseif(condition3) 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.

Example:

#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 );

}

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.

NESTED IF ELSE

/* Illustates nested if else and multiple arguments to the scanf function. */

Example:

#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; elseif(operator=='/') result=number1/number2; elseif(operator=='+') result=number1+number2; elseif(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");