08 - Conditional Statement
08 - Conditional Statement
Statements
Objectives
2
Basic Programming Constructs
3
Statements in C
4
Sequence
5
Selection/Conditional Statements
6
“if” Statement
7
Simple if-else
false true
if (condition){
//one or more statements;
}
false true
if (condition){
//one or more statements;
}else {
//one or more statements;
}
8
Example simple if example
void main()
{
int x;
printf(“Please input x: ");
scanf(“%d”, &x);
if(x > 10){
printf(”x is greater than 10");
} else {
printf(”x is smaller than or equal to 10");
}
}
9
Activity: Find maximum
• Create a program to
– Ask user to input two integers
– Find and display the larger one
10
if-else if ladder
if (condition){
//one or more statements;
}else if (condition) {
//one or more statements;
…
}else {
//one or more statements;
}
11
Example if-else if ladder
void main()
{
int x;
printf(“Enter your choice (1 - 3) : “);
scanf(“%d”, &x);
if (x == 1)
printf (“\nYour choice is one”);
else if ( x == 2)
printf (“\nYour choice is two”);
else if ( x == 3)
printf (“\nYour choice is three”);
else
printf (“\nInvalid choice“);
}
12
Activity: if-else if ladder
13
Conditional/Ternary/? : Operator
14
Example ternary operator
void main()
{
int x;
printf(“Enter a number from 1 to 10: “);
scanf(“%d”, &x);
int result = (x >= 1 && x <= 10)? 1 : 0;
if(result){
printf(“Valid input“);
}else{
printf(“Invalid input“);
}
}
15
Activity
• Make a program to
– Ask user to input two integers
– Find the larger one using Ternary operator
16
Switch Statements
17
General form of Switch statement
switch(expression){
case item1:
//one or more statements;
break;
case item2:
//one or more statements;
break;
case itemn:
//one or more statements;
break;
default:
//one or more statements;
break;
}
18
Example switch statement
void main(){
int x;
printf(“Enter a number from 0 to 3: “);
scanf(“%d”, &x);
switch(expression){
case 0:
printf(“The fan is off“);
break;
case 1:
printf(“The fan is running with speed one“);
break;
case 2:
printf(“The fan is running with speed two“);
break;
case 3:
printf(“The fan is running with speed three“);
break;
default:
printf(“Invalid input“);
break;
}
}
19
Activity: Arithmetic operators
• Make a program to
– Ask user to input two numbers
– Ask user to input one of these arithmetic operators represented
by character (‘+’, ‘-’, ‘*’, ‘/’)
– Display “invalid operator” if user inputs the wrong character
– Else, display the corresponding result
20
Activity: vowels
• Make a program to
– Ask user to input a character
– Display an error message if user inputs a non alphabet
character (check with ASCII e.g., ‘a’ < c <‘z’ for lower case
characters)
– If the character is alphabet, check if it is a vowel (‘a’, ‘e’, ‘i’, ‘o’,
‘u’) or a consonant
– Display the result
21
Summaries
22