UNIT 3 Selection Structure C
UNIT 3 Selection Structure C
SELECTION STRUCTURE
Also known as a conditional structure, a selection structure is a programming feature that performs
different processes based on whether a boolean condition is true or false. Selection structures use
relational operators to test conditions. There are different types of selection structures that can be
used to achieve different outcomes.
IF-ELSE STATEMENT
Syntax:
if (condition){
statement1;
}
else{
statement2;
}
statement;
Relational operators
The relational operators are used to test the relation between two values. All relational operators
are binary operators and therefore require two operands. A relational expression returns zero when
the relation is false and a non-zero when it is true.
The logical operators are used to combine one or more relational expression. The logical operators
are:
OR : Condition is true if either one or both of the expression is true
AND : Condition is true only if both expressions are true
NOT : Changes an expression to its opposite state; true becomes false, false
becomes true
Flowchart:
Pseudocode:
Start
Input radius
if radius>0:
area = radius*radius*3.1416
Output area
else:
Output “Invalid radius”
endif
Stop
ONE-WAY SELECTION
- An if statement without the else portion
statement;;
next_statement
NESTED IF-ELSE STATEMENTS
- if-else statement can contain any valid python statement, including another if-else
- Nested if-else statement: an if-else statement completely contained within another if-
else
Nested within the if part:
if (condition2){
statement1
else{
statement2
else{
default_statement
IF-ELSE CHAIN
- if-else chain: A nested if statement occurring in the else statement clause of the outer
if-else
- If any condition is true, the corresponding statement is executed and the chain
terminates
- Final else is only executed if no conditions were true
o serves as a catch-all case
- if-else chain provides one selection from any possible alternatives
Nested within the else part:
General form of an if-else chain:
Syntax:
if (condition1){
statement1
else if (condition2){
statement2
else if (conditionn){
statementn
else
default_statement
1. Write a program that prompts the user to enter two numbers, the program then will
check and display whether the numbers are equal or not.
2. Write a program that prompts the user to enter a year, the program then will check
whether a given year is a leap year or not.
3. Write a program that prompts the user to enter one number, the program then will
check whether a given number is even or odd;
4. Write a program that accepts 3 numbers as input, the program then will display the
largest value of the 3.
5. Write a program that accepts the value of the 3 sides of a given valid triangle. The
program then will check and display if the triangle is an isosceles, scalene or
equilateral.