Selection statements

advertisement
Turbo C
1
Selection statements
Selection is used to select which statements are to be performed next based on a condition being true or
false.
Relational expressions
In the solution of many problems, different actions must be taken depending on the value of the data. The
if statement in C I used to implement such s decision structure in its simplest form – that of selecting a
statement to be executed only if a condition is satisfied.
Syntax:
if(condtion)
statement executed if condition is true
When an executing program encounters the if statement, the condition is evaluated to determine its
numerical value, which is then interpreted as either true or false. If the condition evaluates to any non-0
value (positive or negative), the condition is considered as a “true” condition and the statement following
the if is executed; otherwise this statement is not executed.
Relational Operators In C
Cristal e-College
Relational operator Meaning
Example
<
Less than
age < 30
>
Greater than
height > 6.2
<=
Less than or equal to
taxable <= 200000
>=
Greater than or equal to temp >= 98.6
==
Equal to
grade == 100
!=
Not equal to
number !=250
Tagbilaran Campus
Turbo C
2
In creating relational expressions, the relational operators must be typed exactly as given in the above
table. Thus, although the following relational expressions are all valid:
age > 40
length <= 50
temp >= 98.6
3<4
flag == done
day != 5
The following are invalid:
length =< 50
/* operator out of order*/
2.0 >> 3.3
/*invalid operator*/
flag = = done
/*spaces are not allowed*/
Relational expressions are also known as conditions.
The if and if-else Statements
The simplest C selection statement is the one-way if statement having the syntax
if ( expression )
statement;
In this construction, the statement following the if (expression ) is only executed if the expression has a
non-0 value ( a true condition ). Examples of this statement are
if ( age > 62 )
discount = .20;
if (grade > 70 )
++passTotal;
In the example above the statement following the condition contained within the parenthesis is only
executed if the relational expression is true; otherwise the statement following the condition is not
executed at all.
Cristal e-College
Tagbilaran Campus
Turbo C
3
#include <stdio.h>
main()
{
int idNum;
float miles;
printf(“ Please type in car number and mileage :” );
scanf(“ %d %f”, &idNum, &miles);
if( miles > 3000)
printf(“ Car %d is over the limit.\n”, idNum);
printf(“. . .end of program output. . .\n”);
getch();
}
Compound statements
Although only a single statement is permitted in an if statement, this statement can be a single
compound statement. A compound statement is one or more statements contained between braces as
shown below:
{
statement1;
statement2;
statement3;
}
The use of braces to enclose a set of individual statements creates a single block of statements, which
may be used anywhere in a C program in place of a single statement. The general syntax of a compound
within a one way if statement is:
Cristal e-College
Tagbilaran Campus
Turbo C
4
if (expression)
{
statement1;
statement2;
.
.
.
}
The if-else Statement
The if-else statement directs the computer to select a sequence of one or more instructions based on the
result of a comparison. The commonly used form of the if-else statement is:
if (expression)
statement1;
else
statement2;
The expression is evaluated first. If the value of the
expression is non-0, which corresponds to the expression
#include <stdio.h>
being true, statement1 is executed. If the value is 0 which
main()
{
corresponds to the expression being false the statement2
int a=0;
after the reserved word else is executed. Thus, one of the two
statements either statement1 or statement2 is always
executed depending on the value of the tested expression.
printf(“enter your age : ”);
scanf(“%i”, &a);
if(a >= 21 ){
printf(“You are an adult.\n”);
else
printf(“You are a teenager “);
printf(“end. . .”);
getch();
}
Cristal e-College
Tagbilaran Campus
Turbo C
5
The if-else Chain
Including one or more if-else statements within an if or if-else statement is referred to as nested if
statements.
if (expression1)
statement1;
else if(expression2)
statement2;
else if(expression3)
statement3;
The construction is called an if-else chain, and is used extensively in many programming problems. In
this construction, each condition is evaluated in order, and if any condition is true, the corresponding
statement is executed and all further processing of the chain stops. Thus the final else statement is only
executed if none of the previous conditions are satisfied. This serves as a default or catch-all case that is
useful for detecting an impossible or error condition.
#include <stdio.h>
main()
{
int grade=0;
printf(“enter your grade : ”);
scanf(“%i”, &grade);
if( grade >= 100 ){
printf(“Excellent.\n”);
else if(grade >= 90 )
printf(“Good job!\n “);
else if(grade >= 80 )
printf(“Fair!\n “);
else
printf(“Sorry! You failed!”);
printf(“end. . .”);
getch();
Cristal e-College
}
Tagbilaran Campus
Turbo C
6
The switch statement
A switch statement is a specialized selection statement that can be used in place of an if-else chain where
exact equality to one or more integer constants is required. Such cases occur with some regularity in realworld applications.
The main advantages of using a switch statement are to avoid using the equality operator, ==, avoids
braces needed for compound statements internal to an if-else chain, and frequently results in simpler
code. The general form of a switch statement is
switch( integer_expression)
{
case value1:
statement1;
statement2;
break;
case value2:
statement3;
statement4;
break;
case value3:
statement5;
statement6;
break;
default:
statement5;
}
In the syntax above the switch statement uses for new keywords: switch, case, default and break.
The keyword switch identifies the start of the switch statement. The integer_expression in parentheses
following this word is evaluated first. The integer value of the expression is then compared to each of the
values listed after the keyword case contained within the compound statement. A compilation error
occurs if any of these values are not integer constants or variables.
Cristal e-College
Tagbilaran Campus
Turbo C
7
The keyword case identifies the values that will be compared to the value of the switch expression. This
expression’s value is compared to each of these case values in the order that these values are listed until a
match is found. When a match occurs, execution begins with the statement immediately following the
match.
Any number of case labels may be contained within a switch statement, in any order. If the value
expression does not match any of the case values, however no statement is executed unless the keyword
default is encountered. The word default is optional and operates the same as the last else in an if-else
chain. If the value of the expression does not match any of these case values, program execution begins
with the statement following the word default.
Once an entry point has been located by the switch statement, no further case evaluations are done; this
means that unless a break statement is encountered, all statements that follow, until the closing brace of
the switch statement, will be executed. This is the reason for the break statement, which identifies the
end of a particular case and causes an immediate exit from the switch statement. Thus, just as the word
case identifies possible starting points in the compound statement, the break statement determines
termination points. If the break statements are omitted, all cases following the matching case value,
including the default case, are executed.
Cristal e-College
Tagbilaran Campus
Turbo C
#include <stdio.h>
main()
{
int choice;
float num1, num2;
printf(“please type in two numbers : ”);
scanf(“%f %f ”, &num1, &num2);
printf(“enter your code:”);
printf(“\n 1 for addition”);
printf(“\n2 for subtraction”);
printf(“\n3 for multiplication”);
scanf(“%i”, &choice);
switch( choice)
{
case 1:
printf(“the sum of the 2 numbers entered is %f”, num1+num2);
break;
case 2:
printf(“the difference of the 2 numbers entered is %f”, num1-num2);
break;
case 3:
printf(“the product of the 2 numbers entered is %f”, num1*num2);
break;
getch();
}
Cristal e-College
Tagbilaran Campus
8
Turbo C
9
When constructing a switch case statement, multiple case values can be stacked together, and the default
label is always optional.
switch (number)
{
case 1:
printf(“have a good morning!\n”);
break;
case 2:
printf(“have ahappy day!\n”);
break;
case3: case4: case5:
printf(“have a nice nice evening!\n”);
}
Assuming the choice is a character variable, the following switch statement is valid:
switch (choice)
{
case ‘a’: case ‘b’:
printf(“you enter a letter!\n”);
break;
default:
printf(“ it’s not a letter!\n);
}
Cristal e-College
Tagbilaran Campus
Download