Instructions contd
Picking instructions based on conditions
- Instructions are executed line by line
- Consider this situation
1. wake up
2. get ready
3. if it is raining
4. carry umbrella
5. if it is cold
6. carry hoodie
7. walk to work
- Solution for : Today is hot
1 -> 2 -> 3 -> 5 -> 7
- Solution for : Today is hot and raining
1 -> 2 -> 3 -> 4 -> 5 -> 7
- This in world of programming is referred as conditionals
- For conditionals we need conditional operators
- == equals
- != not equals
>greater than<less than>=greater than or equals to<=less than or equals- and
- or
- not
Problem 1: Kid needs to say if the number is even or odd
- inputs:
- number
- Outputs:
- even or odd
- instruction
Remember 10 as number (number = 10)
calculate number % 2 and remember as remainder (remainder = number % 2)
if remainder == 0 say even
else say odd
Problem: Kid needs to findout the grades given the average
-
Grades

-
inputs
- average
- Output:
- Grade
- Instructions
Remember 82 as average
if 90 <= average <= 100
say A
else if 80 <= average <= 89
say B
else if 70 <= average <= 79
say C
else if 60 <= average <= 69
say D
else if 0 <= average <= 59
say F
else
say invalid average
loops
- Examples
keep charging your phone till battery is 100% charged
do 5 pushups
- Consider this situation:
1. start at 9:00 AM
2. until 5 PM
1. accept customer request
2. if request is deposit:
3. collect cash
4. else if request is withdra:
5. give cash
3. counter closed
- Loops give ability to repeat instructions till some condition is met
- We have 3 customers arrived between 9 to 5
1 -> 2 -> 3 -> 4 -> 5 -> 2 -> 3 -> 4 -> 6 -> 7 -> 2 -> 3 -> 4 -> 5 -> 2 -> 8
Problem 1:
- sum of all even numbers between 1 and 10
- inputs:
- min = 1
- max = 10
- output:
- 30
- instructions
Remember 1 as min
Remember 10 as max
Remember 0 as sum
until min <= max:
if min % 2 == 0 then
calculate sum + min and remember as sum (sum = sum + min)
min = min + 1
say sum
- sum of digits
number = 123
sum = 0
until number > 0
remainder = number % 10
number = number // 10
sum = sum + remainder
say sum
- Exercise: Find if the number is prime or not
