0% found this document useful (0 votes)
42 views

Control Statements: Dr. Turkan Ahmed Khaleel

The document discusses various Java control structures including while, for, do-while, and switch statements. It provides examples of using each statement type to iterate through a loop with a counter variable, perform calculations, and count grades with a switch statement. The examples demonstrate the proper use of initialization, condition checking, and incrementing for counter-controlled loops as well as the execution flow of do-while versus while loops.

Uploaded by

Duaa Hussein
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Control Statements: Dr. Turkan Ahmed Khaleel

The document discusses various Java control structures including while, for, do-while, and switch statements. It provides examples of using each statement type to iterate through a loop with a counter variable, perform calculations, and count grades with a switch statement. The examples demonstrate the proper use of initialization, condition checking, and incrementing for counter-controlled loops as well as the execution flow of do-while versus while loops.

Uploaded by

Duaa Hussein
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

 Control Statements

Dr. Turkan Ahmed Khaleel


1
2

• Continue structured-programming discussion


o Introduce Java’s remaining control structures
• for, do…while, switch

• Counter-controlled repetition requires:


o Control variable (loop counter)
o Initial value of the control variable
o Increment/decrement of control variable through each loop
o Loop-continuation condition that tests for the final value of the control
variable
2
3

1 // WhileCounter
2 // Counter-controlled repetition with the while repetition statement.
3
4 public class WhileCounter
5 {
6 public static void main( String args[] )
7 {
8 int counter = 1; // declare and initialize control variable
9 Control-variable name is counter
10 while ( counter <= 10 ) // loop-continuation condition
11 { Control-variable initial value is 1
12 System.out.printf( "%d ", counter );
13 ++counter; // increment control variable by 1 Condition tests for counter’s
14 } // end while final value
15
16 System.out.println(); // output a newline
17 } // end main Increment for counter
18 } // end class WhileCounter

1 2 3 4 5 6 7 8 9 10
4

1 // ForCounter
2 // Counter-controlled repetition with the for repetition statement.
3
4 public class ForCounter
5 {
6 public static void main( String args[] )
7 {
8 // for statement header includes initialization,
9 // loop-continuation condition and increment
10 for ( int counter = 1; counter <= 10; counter++ )
11 System.out.printf( "%d ", counter );
12
13 System.out.println(); // output a newline
14 } // end main
Control-variable
15 } // end class ForCounter name is counter
1 2 3 4 5 6 7 8 9 10
Control-variable initial value is 1 Increment for counter

Condition tests for counter’s


final value
5

for statement header components.

5
6

1 // Sum
2 // Summing integers with the for statement.
3
4 public class Sum
5 {
6 public static void main( String args[] )
7 {
8 int total = 0; // initialize total
9
10 // total even integers from 2 through 20
11 for ( int number = 2; number <= 20; number += 2 )
12 total += number;
13
14 System.out.printf( "Sum is %d\n", total ); // display results
15 } // end main
16 } // end class Sum
increment number by 2 each iteration
Sum is 110
7

1 // Compound-interest
2 // calculations with for.
3
4 public class Interest
5 { Java treats floating-points as
6 public static void main( String args[] ) type double
7 {
8 double amount; // amount on deposit at end of each year
9 double principal = 1000.0; // initial amount before interest
10 double rate = 0.05; // interest rate
11
12 // display headers
13 System.out.printf( "%s%20s\n", "Year", "Amount on deposit" );
14

Second string is right justified and


displayed with a field width of 20
8

15 // calculate amount on deposit for each of ten years


16 for ( int year = 1; year <= 10; year++ )
17 {
Calculate amount with for
18 // calculate new amount for specified year
statement
19 amount = principal * Math.pow( 1.0 + rate, year );
20
21 // display the year and the amount
22 System.out.printf( "%4d%20.2f\n", year, amount );
23 } // end for
24 } // end main
25 } // end class Interest Use the comma (,) formatting flag to display
the amount with a thousands separator
Year Amount on deposit
1 1,050.00
2 1,102.50
3 1,157.63
4 1,215.51
5 1,276.28
6 1,340.10
7 1,407.10
8 1,477.46
9 1,551.33
10 1,628.89
9

do…while Repetition Statement

• do…while structure
o Similar to while structure
o Tests loop-continuation after performing body
of loop
• i.e., loop body always executes at least
once

9
10

1 //DoWhileTest
2 // do...while repetition statement.
3
4 public class DoWhileTest
Declares and initializes
5 {
6 public static void main( String args[] )
control variable counter
7 {
8 int counter = 1; // initialize counter Variable counter’s value is displayed
9
before testing counter’s final value
10 do
11 {
12 System.out.printf( "%d ", counter );
13 ++counter;
14 } while ( counter <= 10 ); // end do...while
15
16 System.out.println(); // outputs a newline
17 } // end main
18 } // end class DoWhileTest

1 2 3 4 5 6 7 8 9 10
11

• switch statement
o Used for multiple selections

11
12
1 // GradeBook
2 // GradeBook class uses switch statement to count A, B, C, D and F grades.
3 import java.util.Scanner; // program uses class Scanner
4
5 public class GradeBook
6 {
7 private String courseName; // name of course this GradeBook represents
8 private int total; // sum of grades
9 private int gradeCounter; // number of grades entered
10 private int aCount; // count of A grades
11 private int bCount; // count of B grades
12 private int cCount; // count of C grades
13 private int dCount; // count of D grades
14 private int fCount; // count of F grades
15
16 // constructor initializes courseName;
17 // int instance variables are initialized to 0 by default
18 public GradeBook( String name )
19 {
20 courseName = name; // initializes courseName
21 } // end constructor
22
23 // method to set the course name
24 public void setCourseName( String name )
25 {
26 courseName = name; // store the course name
27 } // end method setCourseName
28
13
29 // method to retrieve the course name
30 public String getCourseName()
31 {
32 return courseName;
33 } // end method getCourseName
34
35 // display a welcome message to the GradeBook user
36 public void displayMessage()
37 {
38 // getCourseName gets the name of the course
39 System.out.printf( "Welcome to the grade book for\n%s!\n\n",
40 getCourseName() );
41 } // end method displayMessage
42
43 // input arbitrary number of grades from user
44 public void inputGrades()
45 {
46 Scanner input = new Scanner( System.in );
47
48 int grade; // grade entered by user Display prompt
49
50 System.out.printf( "%s\n%s\n %s\n %s\n",
51 "Enter the integer grades in the range 0-100.",
52 "Type the end-of-file indicator to terminate input:",
53 "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
54 "On Windows type <ctrl> z then press Enter" );
55
14
56 // loop until user enters the end-of-file indicator
57 while ( input.hasNext() )
58 {
59 grade = input.nextInt(); // read grade
60 total += grade; // add grade to total Loop condition uses method hasNext to
61 ++gradeCounter; // increment numberdetermine
of gradeswhether there is more data to input
62
63 // call method to increment appropriate counter
64 incrementLetterGradeCounter( grade );
65 } // end while
66 } // end method inputGrades
67
68 // add 1 to appropriate counter for specified grade
69 public void incrementLetterGradeCounter( int numericGrade )
70 {
71 // determine which grade was entered (grade / 10 ) is controlling
72 switch ( grade / 10 ) expression
73 {
74 case 9: // grade was between 90 switch statement determines which
75 case 10: // and 100 case label to execute, depending on
76 ++aCount; // increment aCount
77 break; // necessary to exit switch
controlling expression
78
79 case 8: // grade was between 80 and 89
80 ++bCount; // increment bCount
81 break; // exit switch
82
15
83 case 7: // grade was between 70 and 79
84 ++cCount; // increment cCount
85 break; // exit switch
86
87 case 6: // grade was between 60 and 69
88 ++dCount; // increment dCount
89 break; // exit switch
90
91 default: // grade was less than 60
92 ++fCount; // increment fCount
93 break; // optional; will exit switch anyway
94 } // end switch default case for grade less than 60
95 } // end method incrementLetterGradeCounter
96
97 // display a report based on the grades entered by user
98 public void displayGradeReport()
99 {
100 System.out.println( "\nGrade Report:" );
101
102 // if user entered at least one grade...
103 if ( gradeCounter != 0 )
104 {
105 // calculate average of all grades entered
106 double average = (double) total / gradeCounter;
107
16

108 // output summary of results


109 System.out.printf( "Total of the %d grades entered is %d\n",
110 gradeCounter, total );
111 System.out.printf( "Class average is %.2f\n", average );
112 System.out.printf( "%s\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n",
113 "Number of students who received each grade:",
114 "A: ", aCount, // display number of A grades
115 "B: ", bCount, // display number of B grades
116 "C: ", cCount, // display number of C grades
117 "D: ", dCount, // display number of D grades
118 "F: ", fCount ); // display number of F grades
119 } // end if
120 else // no grades were entered, so output appropriate message
121 System.out.println( "No grades were entered" );
122 } // end method displayGradeReport
123 } // end class GradeBook
17

1 // GradeBookTest
2 // Create GradeBook object, input grades and display grade report.
3
4 public class GradeBookTest
5 {
6 public static void main( String args[] )
7 {
8 // create GradeBook object myGradeBook and
9 // pass course name to constructor Call GradeBook public
10 GradeBook myGradeBook = new GradeBook(
11 "Java Programming" );
methods to count grades
12
13 myGradeBook.displayMessage(); // display welcome message
14 myGradeBook.inputGrades(); // read grades from user
15 myGradeBook.displayGradeReport(); // display report based on grades
16 } // end main
17 } // end class GradeBookTest
18

Welcome to the grade book for


Java Programming!

Enter the integer grades in the range 0-100.


Type the end-of-file indicator to terminate input:
On UNIX/Linux/Mac OS X type <ctrl> d then press Enter
On Windows type <ctrl> z then press Enter
99
92
45
57
63
71
76
85
90
100
^Z

Grade Report:
Total of the 10 grades entered is 778
Class average is 77.80
Number of students who received each grade:
A: 4
B: 1
C: 2
D: 1
F: 2
19

• break/continue
o Alter flow of control
• break statement
o Causes immediate exit from control structure
• Used in while, for, do…while or switch statements
• continue statement
o Skips remaining statements in loop body
o Proceeds to next iteration
• Used in while, for or do…while statements

19
20

1 // BreakTest
2 // break statement exiting a for statement.
3 public class BreakTest
4 {
5 public static void main( String args[] )
6 {
Loop 10 times
7 Exit
int count; // control variable also used after for
loop statement
terminates (break)
8
9 for ( count = 1; count <= 10; count++ ) // loop
when count equals 5
10 times
10 {
11 if ( count == 5 ) // if count is 5,
12 break; // terminate loop
13
14 System.out.printf( "%d ", count );
15 } // end for
16
17 System.out.printf( "\nBroke out of loop at count = %d\n", count );
18 } // end main
19 } // end class BreakTest

1 2 3 4
Broke out of loop at count = 5
21

1 // ContinueTest
2 // continue statement terminating an iteration of a for statement.
3 public class ContinueTest
4 {
Loop 10 times
5 public static void main( String args[] )
6 {
7 for ( int count = 1; count <= 10; count++ ) // Skip
loop line 12 and proceed to
10 times
8 { line 7 when count equals 5
9 if ( count == 5 ) // if count is 5,
10 continue; // skip remaining code in loop
11
12 System.out.printf( "%d ", count );
13 } // end for
14
15 System.out.println( "\nUsed continue to skip printing 5" );
16 } // end main
17 } // end class ContinueTest

1 2 3 4 6 7 8 9 10
Used continue to skip printing 5

You might also like