Download presentation
Presentation is loading. Please wait.
Published byShawn Johnston Modified over 5 years ago
1
if-else if (condition) { statements1 } else { statements2
if within else if (condition1) { statements1 } 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 >= 0) && (hour < 12)) { System.out.println(“Good Morning!”); } else if ((hour >= 12) && (hour < 18)) { System.out.println(“Good Afternoon!”); else if ((hour >=18) && (hour < 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; circle=1; rectangle=2; radius=5; distance=6; shape=1; if (shape==circle) { if (radius >= distance) System.out.println("Point is enclosed in the circle"); else System.out.println("Point is not enclosed in the circle"); } else System.out.println("Shape is not 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 < 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 < 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 <= 100) { y += n; n++; } System.out.println(“Sum of the first ” + (n-1) + “ natural numbers is ” + y);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.