Professional Documents
Culture Documents
Lecture02 Cs1010e NUS
Lecture02 Cs1010e NUS
1 / 24
Lecture Outline
2 / 24
Algorithmic Problem Solving
3 / 24
Control Structures – Sequence
4 / 24
Control Structures – Selection
5 / 24
Control Structures – Repetition
Take exam
Fail? y
6 / 24
Boolean Values and Variables
7 / 24
Conditions – Boolean Expression
booleanAssignment
boolVar = boolExpr ;
boolExpr
true
false
boolVar
arithmeticExpr relationalOp arithmeticExpr
boolExpr logicalOp boolExpr
( boolExpr )
8 / 24
Relational Operators
9 / 24
Logical Operators
Logical operators compare conditions
Three logical operators: and (&&), or (||), not (!)
A B A && B A || B !A !B
false false false false true true
false true false true true false
true false false true false true
true true true true false false
11 / 24
Statement and Statement Block
12 / 24
Selection: if..else Statement
ifElseStatement
if ( condition ) stmtBlock
else stmtBlock
if (condition)
{
statements(s);
}
else
{
statements(s);
}
#include <stdio.h>
int main(void)
{ x>y n
int x, y, max;
printf("Enter two numbers: "); y
scanf("%d%d", &x, &y);
max = x
if (x > y)
max = x;
if (y >= x) /* if (y > x) ??? */
max = y;
y >= x n
printf("Maximum is %d\n", max);
return 0; y
}
max = y
14 / 24
Example: Maximum of two numbers
#include <stdio.h>
int main(void)
{
int x, y, max;
x>y n
printf("Enter two numbers: ");
scanf("%d%d", &x, &y); y
if (x > y)
max = x; max = x max = y
else
max = y;
printf("Maximum is %d\n", max);
return 0;
}
15 / 24
Example: BMI
16 / 24
Example: BMI
17 / 24
Example: BMI
18 / 24
Nesting if..else Statements
#include <stdio.h>
bmi ≥ 18.5 n
int main(void)
{ y
double bmi;
printf("Enter bmi: "); bmi ≤ 24.9 n
scanf("%lf", &bmi);
y
if (bmi >= 18.5)
if (bmi <= 24.9)
printf("Normal\n"); Normal Abnormal Abnormal
else
printf("Abnormal\n");
else
printf("Abnormal\n");
return 0;
}
19 / 24
Nesting if..else Statements
20 / 24
Nesting if..else Statements
#include <stdio.h>
int main(void)
{
double bmi;
n
bmi < 18.5
printf("Enter bmi: ");
scanf("%lf", &bmi); y
if (bmi < 18.5)
printf("Underweight\n"); bmi ≤ 24.9 n
else
if (bmi <= 24.9) y
printf("Normal\n");
else Underweight Normal Overweight
printf("Overweight\n");
return 0;
}
21 / 24
Nesting if..else Statements
#include <stdio.h>
int main(void)
{
double bmi; bmi ≤ 24.9 n
printf("Enter bmi: ");
scanf("%lf", &bmi); y
23 / 24
Lecture Summary
Characteristics of an algorithm
Control structures: sequence, selection and repetition
Conditions involving relational and logical operators
Selection
– if..else statement
– Nested if..else statements
24 / 24