ICS 103: Computer Programming in C
Handout-6 Topic: Control Structures (Selection Structures)


Objective:

• To Know about relational and logical operators of C language and their use.
• To know about order of execution of relational and logical operators with others operators.
• To Know syntax and use of if, if … else, Nested if,
if … else if … else, switch Selection Statements.

Relational and Logical operators:

The most commonly used relational operators are
> for greater than
>= for greater than or equal to
< for less than
<= for less than or equal to
== for equal to
!= for not equal to

The most commonly used logical operators are

&& for binary AND
| | for binary OR
! for binary NOT

These operators are used in the expression of if statement. The expression having these operators is called Logical expression.

Operator Precedence:

Operator Precedence

! (not) , +, - , & (address of) ;
Note Above are Unary Operators which have a single operand. Ist (i.e highest)

* , /, % . IInd

+ , _ . IIIrd

< , <= , >=, > . IVth

== (equality operator), != (not equal) . Vth

&& (logical and operator ) . VIth

|| (logical OR operator ) . VIIth

= (assignment operator) . VIIIth (i.e Lowest)


Examples:

To check if the value of the integer variable x is more than 5 and less than 10 or equal to 15, we write

if ( x > 5 && x < 10 | | x == 15 )

To check if the value of the float variable a is not equal to 1.5 or less than or equal to 2.5 but more than or equal to 1.5, we write

if ( a != 1.5 | | a <= 2.5 && a >= 1.5 )

Selection Structures:

One-Way Selection Using the if-statement:

Syntax: if (expression)
Statement;

If the expression is true, then the statement is executed; otherwise the statement is ignored.

For example, let marks be an integer variable. To check the value of marks to see if it is more than 75 and print PASS if it is more than 75 we would write

if (marks > 75)
printf (“PASS\n”) ;

If marks is less than or equal to 75 then the print statement is ignored and nothing is printed.

If suppose that in addition to printing PASS we would like to add 5 bonus marks then we would write

if (marks > 75)
{
marks = marks + 5 ;
printf (“PASS\n”) ;
}

As seen above if there is more than one statement (compound statement) to be done after checking the expression result, then the statements should be enclosed between parenthesis. If there is only one statement (simple statement) to be executed after if then the parenthesis becomes optional (you can remove it). Note that there is no semi-colon at the end of the if or else statement.

Two-Way Selection Using the if…else statement:

Syntax: if (expression)
statement 1;
else
statement 2;

If the expression is true, then the statement 1 is executed; otherwise the statement 2 is executed if expression is false.

For example, to find the larger of two variables x and y and print the answer and assign the larger value to max variable and smaller value to min variable, we would write :

if ( x > y )
{
max = x ;
min = y ;
printf (“ x is BIG\n”) ;
}
else
{
max = y ;
min = x ;
printf (“ y is BIG\n”) ;
}

Check for the parenthesis used for more than one statement after if and else.


Multiple Alternative Decision Using the if ladder:

Syntax:
if ( expression 1 )
statement 1;

else if ( expression 2 )
statement 2;
.
.
else if ( expression n )
statement n;

else
statement e;

The expressions in a multiple-alternative decision are evaluated in sequence until a true condition is reached. If an expression is true, the statement following it is executed, and the rest of the multiple-alternative decision is skipped. If an expression is false, the statement following it is skipped, and the next expression is checked. If all the expressions are false, the statement e following the final else is executed.

For example, to check the value of the variable marks and print the message accordingly, we would write

if (marks >= 75)
printf (“Distinction\n”) ;
else if (marks >= 60)
printf (“Pass\n”) ;
else if (marks >= 50)
printf (“Average\n”) ;
else
printf (“Fail\n”) ;

Nested if statements:

There can be if statements inside if and else statements which can be used to implement decisions with several alternatives.

For example,

if ( x > 2.5 )
{ p = p + 1 ;
if ( x < 3.5 )
n = n + 1;
else
m = m + 1;
}
else
{
if ( x > 1.5 )
s = s + 1 ;
else
t = t + 1;
}

In the above example, if x is greater than 2.5 then 1 is added to p and it is checked if x is less than 3.5. If it is so, then 1 is added to n. If x is more than 3.5, 1 is added to m. If x is less than 2.5, the execution comes directly to the else part without doing anything to p, n, m and it is checked if x is more than 1.5. If it is so 1 is added to s else 1 is added to t.

Multiple selection using the switch statement:

Syntax:

switch (expression)
{
case value 1:
statement 1;
break ;
case value 2:
statement 2;
break ;
:
:

case value n:
statement n;
break ;
default:
statement e;
}

Here it is checked whether the value of expression matches any of the case values.

For example, to check the value of the character variable color and print the message accordingly, we write

switch (color)
{
case ‘R’:
printf (“red\n”) ; break ;
case ‘B’:
printf (“blue\n”) ; break ;
case ‘Y’:
printf (“yellow\n”) ; break ;
default:
printf (“black\n”) ; break ;
}

The single quotes ‘R’,’B’,’Y’ are used because of the color being character variable. If color is ‘R’ then red is printed and the other cases are not checked, however if color is not red then other cases are checked until a match is found. If no match is found then the default value of black is printed.


Solved Examples:

Use of Control Structures (Selection Structures)

Example#1:

/*******************************************************************
Write a program that calculates and displays the reciprocal of an integer,
both as a common fraction and a decimal fraction. A typical output line
would be :

The reciprocal of 2 is 1/2 or 0.500

The program should display a “Reciprocal undefined” message for an input
of zero.
********************************************************************/

#include<stdio.h>
void main ()
{
int number;
float reciprocal;
printf("please Enter an integer number: ");
scanf("%d",&number);
if (number>0 || number<0)
{ reciprocal = 1.0/number;
printf("\nThe reciprocal of %d is 1/%d or %0.3f",number,number,reciprocal);
}
else
printf("\nReciprocal undefined");

} // end of main

Sample Output:




Example#2:

/**************************************************************************
Write an interactive program that contains a compound if statement and that may be used to compute the area of a square (area=side2 ) or a triangle (area=base*height/2) after prompting the user to type the first character of the figure name (S or T).
**************************************************************************/

/*************************************************************************
Using If statement.

#include<stdio.h>
void main ()
{
int side, height, base, area;
char D;
printf("If you want area of a square press S or T for area of triangle :");
scanf("%c", &D);

if (D=='S')
{
printf("please input the side : ");
scanf("%d", &side);
area=side*side;
printf("The area : %d\n", area);
}
else if (D=='T')
{
printf("inter base and height of the triangle :");
scanf("%d %d", &base, &height);
area=(0.5)*base*height;
printf("The area of triangle is : %d", area);
}
else
printf("Dear !, Your choice must be either 'S' or 'T' ");

} // end of main

Sample Output:



/***************************************************************
Using Switch statement
****************************************************************/
#include<stdio.h>
void main( )
{
char choice;
double side, height, base, area;
printf("[To find the shape's area choose either 'S' for square , or 'T' for triangle] : ");
printf("\nEnter your choice to find the area : ");
scanf("%c", &choice);

switch(choice)
{
case 'S': printf("\nEnter its side: ");
scanf("%lf", &side);
area = (side * side);
printf("The area of square is %.2f unit square\n", area);
break;

case 'T' : printf("\nEnter the height and base: ");
scanf("%lf %lf", &height, &base);
area = (0.5) * height * base;
printf(" The area of triangle is %.2f unit square\n", area);
break;

default: printf("Sorry ,your choice is not included \nPlz try again ");
}

} // end of main

Sample Output:





Exercise

Trace output of following program manually (Without using Computer) :

#include<stdio.h>
main( )
{
int j, x=0;
switch(j-1)
{
case 0 :
case -1 :

x += 1;

break;

case 1:
case 2:
case 3:

x += 2;
break;

default:
x += 3;
}
printf("x = %d\n", x);

}

 

حلول نت

http://student.kfupm.edu.sa/s200372670/

Overview of C | ICS 103: Computer Programming in C | Arithmetic Expressions | Assignment, Input and Output statements | Control Structures (Repetition & Loop Statements) | Control Structures (Selection Structures) | Data Files | Recursive Functions | Simple Standard Mathematical Library Functions | Function Output Parameters Implemented with Pointers(OR Function with Output Parameter) | Function with Input Parameter | 1-D Array | 1-D Array (How to use array with function)