Skip to main content

if

if

if … else …

if else

Simple Example

Write a program to determine whether the body temperature entered by the user can be categorized as a fever
  • Input: body temperature in celcius (C)
  • Output: “Fever”, if body temperature is more than 37o C. If not, no outputs.

Relational Operators

OperatorDescriptionExample
==Equal tox == y
!=Not equal tox != y
>Greater thanx > y
<Less thanx < y
>=Greater than or equal tox >= y
<=Less than or equal tox <= y

Logical Operators

OperatorDescriptionExample
&&Logical ANDx && y
||Logical ORx || y
!Logical NOT!x
  • Example
    x < 0 && y >= 10
    number != 2 || number > 0
    !(temperature > 37)
    !(price < 10 || price > 100)
    (width > 0 && width < 10) || (length > 20)
    

Chaining

if (condition1) {
// executed when condition1 is true
} else if (condition2) {
// executed when condition1 is false and condition2 is true
} else if (condition3) {
// executed when condition1 & 2 are false, condition3 is true
} else {
// executed when all conditions are false
}

Exercise

Exercise 1

Write a program to calculate the total user must pay for an imported item.
  • If the price of the item exceeds USD 100, then an import tax of 20% is imposed
  • Input: price of items before tax in USD
  • Output: total paid (item price plus tax)

Exercise 2

Write a program to determine whether the value entered by the user is odd or even.
  • Input: integer
  • Output: “Odd” or “Even”

Exercise 3

Write a program to determine whether the size of the baby at birth is normal or not
  • Normal baby weight at birth ranges from 2.5 to 4.5 kg and lengths between 45 and 60 cm
  • Input: baby’s weight in kg and length in cm
  • Output: whether the baby’s size is normal or not

Exercise 4

Write a program to convert grade in numbers to letters.
  • Conversion table:
    NumberLetter
    < 41E
    41 to < 56D
    56 to < 61C
    61 to < 66BC
    66 to < 76B
    76 to < 81AB
    >= 81A
  • Input: grade in number
  • Output: letter grade