ifelse - PowerPoint PPT Presentation

About This Presentation
Title:

ifelse

Description:

class greetings { public static void main(String arg[]) { int hour = 3; ... else if ((hour = 12) && (hour 18)) { System.out.println('Good Afternoon! ... – PowerPoint PPT presentation

Number of Views:36
Avg rating:3.0/5.0
Slides: 10
Provided by: RMK
Category:
Tags: ifelse

less

Transcript and Presenter's Notes

Title: ifelse


1
if-else
  • if (condition)
  • statements1
  • else
  • statements2
  • if within else
  • if (condition1) statements1
  • else
  • if (condition2) statements2
  • statements3

2
if-else if-else if--else
  • if (condition1)
  • statements1
  • else if (condition2)
  • statements2
  • else if (condition3)
  • statements3
  • else
  • statementsn

3
Example
  • class greetings
  • public static void main(String arg)
  • int hour 3
  • if ((hour gt 0) (hour lt 12))
  • System.out.println(Good Morning!)
  • else if ((hour gt 12) (hour lt 18))
  • System.out.println(Good
    Afternoon!)
  • else if ((hour gt18) (hour lt 24))
  • System.out.println(Good
    Evening!)
  • else
  • System.out.println(Bad time!)

4
Dangling else
  • / Write comments here
  • /
  • class dangle
  • public static void main (String args)
  • int shape,circle,rectangle,radius,distance
  • circle1
  • rectangle2
  • radius5
  • distance6
  • shape1
  • if (shapecircle)
  • if (radius gt distance)
  • System.out.println("Point is enclosed in the
    circle")
  • else System.out.println("Point is not
    enclosed in the circle")

5
Loops
  • Needed in problems that require solving the same
    subproblem over and over
  • Computing the sum of the first 100 natural
    numbers and putting the result in y
  • Algorithm
  • y 1
  • y y 2
  • y y 3
  • y y 100
  • Cannot write 99 such additions use a loop

6
while
  • while (condition)
  • statements
  • Can put anything in statements
  • The entire construct is called a while loop
  • statements are executed until condition is true
  • Even before executing it the first time condition
    is evaluated
  • A while loop may not execute even once

7
Example
  • class justAnExample
  • public static void main(String arg)
  • int x 5
  • int y 0
  • while (x lt 10)
  • y--
  • x
  • System.out.println(y)

8
Example
  • class justAnExample
  • public static void main(String arg)
  • int x 15
  • int y 0
  • while (x lt 10)
  • y--
  • x
  • System.out.println(y)

9
Sum of natural numbers
  • class naturalSum
  • public static void main(String arg)
  • int n 2
  • int y 1
  • while (n lt 100)
  • y n
  • n
  • System.out.println(Sum of the first
    (n-1) natural numbers is y)
Write a Comment
User Comments (0)
About PowerShow.com