Presentation is loading. Please wait.

Presentation is loading. Please wait.

SELF STUDY. IF STATEMENTS SELECTION STRUCTURE if selection statement if … else selection statement switch selection statement.

Similar presentations


Presentation on theme: "SELF STUDY. IF STATEMENTS SELECTION STRUCTURE if selection statement if … else selection statement switch selection statement."— Presentation transcript:

1 SELF STUDY

2 IF STATEMENTS

3 SELECTION STRUCTURE if selection statement if … else selection statement switch selection statement

4 EXAMPLE Write a program that reads a student’s grade and prints “passed” if the grade is greater than or equal 60. Flowchart: Code:... if ( grade >= 60 ) System.out.print(" Passed”);...

5 5 Example: char grade=‘’ if ( score >= 90 ) grade = ‘A’; ONE-WAY SELECTION

6 EXAMPLE IF-STATEMENT: FIND ABSOLUTE VALUE import java.util.Scanner; public class If1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int a; System.out.print("Enter an integer value: "); a = in.nextInt(); // Read in an integer from keyboard System.out.print("Input value = "); System.out.println(a); if ( a < 0 ) // If-statement a = -a; // Negate a ONLY if a < 0 System.out.print("It's absolute value = "); System.out.println(a); }

7 7 TWO-WAY SELECTION  Syntax: if (expression) statement1; else statement2;  else statement must be paired with an if.

8 8 TWO-WAY SELECTION Example: boolean positive, negative; if (number >= 0 ) positive = true; else //number < 0 negative =true;

9 9 MULTIPLE SELECTION: NESTED IF Example4_23 : if ( GPA >= 2.0 ) if (GPA >= 3.9) System.out.println(“Dean Honor list”); else System.out.println(“GPA below graduation requirement”); If GPA = 3.8 what will be printed? GPA below graduation requirement

10 10 Example4_23 : (rewritten) if ( GPA >= 2.0 ) { if (GPA >= 3.9) System.out.println(“Dean Honor list”); } else System.out.println(“GPA below graduation requirement”); MULTIPLE SELECTION: NESTED IF Now, if GPA = 3.8 what will be printed?

11 public class Test { public static void main(String args[]){ int x = 30; if( x == 10 ){ System.out.print("Value of X is 10");} else if( x == 20 ){ System.out.print("Value of X is 20");} else if( x == 30 ){ System.out.print("Value of X is 30");} else{ System.out.print("This is else statement"); }

12

13 EXERCISE What is the output for the following code lines if hours=35 and hours=60: a) if (hours <= 40) System.out.println(“No overtime” ); System.out.println(“ You must work over 40 hours for overtime\n”); System.out.println(“Continue” ); B) if (hours <= 40) { cout << “No overtime” << endl; cout << "You must work over 40 hours for overtime.\n"; } cout << “Continue” << endl;


Download ppt "SELF STUDY. IF STATEMENTS SELECTION STRUCTURE if selection statement if … else selection statement switch selection statement."

Similar presentations


Ads by Google