3. CONDITIONAL STATEMENTS
• A conditional statement allows us to control whether a program segment is executed or not.
• Two constructs
• if statement
• if
• if-else
• if-else-if
• switch statement
4. THE BASIC IF STATEMENT
• Syntax
if(condition)
action
• if the condition is true then
execute the action.
• action is either a single
statement or a group of
statements within braces.
condition
action
true
false
5. CHOICE (IF)
Put multiple action statements
within braces
if (it's raining){
printf(“take umbrella”);
printf(“wear raincoat”);
}
6. ABSOLUTE VALUE
// program to read number & print its absolute value
#include <stdio.h>
main(){
int value;
printf("Enter integer: “);
scanf(“%d”,&value);
if(value < 0)
value = -value;
printf("The absolute value is %d “,value);
getch();
}
7. RELATIONAL OPERATORS
Relational operators are used to compare two values to form a
condition.
Math C Plain English
= == equals [example: if(a==b) ]
[ (a=b) means put the value of b into a ]
< < less than
<= less than or equal to
> > greater than
>= greater than or equal to
!= not equal to
9. THE BOOLEAN TYPE
• C contains a type named bool for conditions.
• A condition can have one of two values:
• true (corresponds to a non-zero value)
• false (corresponds to zero value)
• Boolean operators can be used to form more complex conditional
expressions.
• The and operator is &&
• The or operator is ||
• The not operator is !
10. THE BOOLEAN TYPE
• Truth table for "&&" (AND):
Operand1 Operand2 Operand1 &&
Operand2
true true true
true false false
false true false
false false false
11. THE BOOLEAN TYPE
• Truth table for “||" (OR):
Operand1 Operand2 Operand1 ||
Operand2
true true true
true false true
false true true
false false false
12. THE BOOLEAN TYPE
• Truth table for "!" (NOT):
Operand !Operand
true false
false true
13. A BOOLEAN TYPE
• Assignments to bool type variables
bool P = true;
bool Q = false;
bool R = true;
bool S = P && Q;
bool T = !Q || R;
bool U = !(R && !Q);
14. “IF” WITH A BLOCK OF STATEMENTS
if (aValue <= 10)
{
printf("Answer is %.2fn", aValue);
countB++;
}
15. POSITIVE OR NEGATIVE
#include <stdio.h>
main()
{
int number;
clrscr();
printf(“Enter a number”);
scanf(“%d”,&number);
if (number>0)
printf(“It is Positive”);
getch();
}
17. SYNTAX OF IF-ELSE STATEMENT
if ( condition)
statement;
else
statement;
18. IF – ELSE WITH A BLOCK OF STATEMENTS
if (aValue <= 10)
{
printf("Answer is %.2fn", aValue);
countB++;
} End if
else
{
printf("Error occurredn");
countC++;
} End else
19. TO VOTE OR NOT TO VOTE
#include<stdio.h>
main()
{
int age;
clrscr();
printf(“Enter your age”);
scanf(“%d”,&age);
if (age>=18)
printf(“You are qualified to vote”);
else
printf(“Not qualified to vote”);
getch();
}
20. POSITIVE OR NEGATIVE
#include <stdio.h>
main()
{
int number;
clrscr();
printf(“Enter a number”);
scanf(“%d”,&number);
if (number>0)
printf(“Positive number”);
else
printf(“Negative number”);
getch();
}