AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I

Similar documents
Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Basic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Welcome1.java // Fig. 2.1: Welcome1.java // Text-printing program.

Object Oriented Programming. Java-Lecture 1

Lecture 7: Classes and Objects CS2301

MEHMET YAYAN - İSMAİL HAKKI ÖZTÜRK CS101/SEC.-2 CLASS NOTES 1. March 28-30, 2007

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

2.8. Decision Making: Equality and Relational Operators

Introduction to Classes and Objects

Introduction to Classes and Objects

by Pearson Education, Inc. All Rights Reserved. 2

Control Statements: Part 1

Introduction to Classes and Objects

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CS110D: PROGRAMMING LANGUAGE I

Computer Programming C++ Classes and Objects 6 th Lecture

JAVA- PROGRAMMING CH2-EX1

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

download instant at

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

CS141 Programming Assignment #6

How to engineer a class to separate its interface from its implementation and encourage reuse.

Chapter 3 Structured Program Development

CS111: PROGRAMMING LANGUAGE II

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

In this chapter you will learn:

Introduction to Computer Science I

Programming with Java

RANDOM NUMBER GAME PROJECT

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

LEC03: Decisions and Iterations

Structured Program Development

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Chapter 2 - Control Structures

Introduction to Java Applications

Algorithms and Conditionals

Control Statements: Part Pearson Education, Inc. All rights reserved.

Arrays Pearson Education, Inc. All rights reserved.

Fundamentals of Programming Session 25

Object Oriented Programming. Java-Lecture 6 - Arrays

Chapter 3 Structured Program Development in C Part II

CS111: PROGRAMMING LANGUAGE II

Fundamentals of Programming. Lecture 6: Structured Development (part one)

Dr.Ammar Almomani. Dept. of Information Technology, Al-Huson University College, Al- Balqa Applied University. Dr. Ammar Almomani-2017-BAU Page 1

[Page 177 (continued)] a. if ( age >= 65 ); cout << "Age is greater than or equal to 65" << endl; else cout << "Age is less than 65 << endl";

This exam is open book. Each question is worth 3 points.

2.5 Another Application: Adding Integers

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Looping Subtasks. We will examine some basic algorithms that use the while and if constructs. These subtasks include

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Functions and Recursion

Control Structures: if and while A C S L E C T U R E 4

A A B U n i v e r s i t y

CS 101 Fall 2006 Midterm 3 Name: ID:

Fundamentals of Programming Session 23

Control Statements. Musa M. Ameen Computer Engineering Dept.

Introduction to Java & Fundamental Data Types

Lab 2: Structured Program Development in C

Supplementary Test 1

JavaScript: Control Statements I

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Chapter 7: Javascript: Control Statements. Background and Terminology. Background and Terminology. Background and Terminology

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

Control Structures (Deitel chapter 4,5)

CSC 1051 Data Structures and Algorithms I

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

CSIS 10A Assignment 9 Solutions

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Section 2.2 Your First Program in Java: Printing a Line of Text

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section:

Visual Basic 2010 How to Program by Pearson Education, Inc. All Rights Reserved.

Java I/O and Control Structures

Example: Monte Carlo Simulation 1

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Java Coding 3. Over & over again!

REPETITION CONTROL STRUCTURE LOGO

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Introduction to Java Applications; Input/Output and Operators

CompSci 125 Lecture 11

Lecture Transcript While and Do While Statements in C++

Multiple-Subscripted Arrays

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Chapter 2 - Control Structures

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

CS 1063 Introduction to Computer Programming Midterm Exam 2 Section 1 Sample Exam

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

Introduction to Java Applications

Chapter 5 : Repetition (pp )

Practice Midterm 1. Problem Points Score TOTAL 50

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Transcription:

AL GHURAIR UNIVERSITY College of Computing CSC 209 JAVA I week 3- Control Statements: Part I Objectives: To use the if and if...else selection statements to choose among alternative actions. To use the while repetition statement to execute statements in a program repeatedly. To use counter-controlled repetition. Examples: Example 1 if Single-Selection Statement Programs use selection statements to choose among alternative courses of action. For example, suppose that the passing grade on an exam is 60. The pseudocode statement If student's grade is greater than or equal to 60 Print "Passed" determines whether the condition "student's grade is greater than or equal to 60" is true or false. If the condition is true, "Passed" is printed, and the next pseudocode statement in order is "performed." (Remember that pseudocode is not a real programming language.) If the condition is false, the Print statement is ignored, and the next pseudocode statement in order is performed. The indentation of the second line of this selection statement is optional, but recommended, because it emphasizes the inherent structure of structured programs. The preceding pseudocode If statement may be written in Java as if ( studentgrade >= 60 ) System.out.println( "Passed" );

if...else Double-Selection Statement The if single-selection statement performs an indicated action only when the condition is true; otherwise, the action is skipped. The if...else double-selection statement allows the programmer to specify an action to perform when the condition is true and a different action when the condition is false. For example, the pseudocode statement If student's grade is greater than or equal to 60 Print "Passed" Else Print "Failed" prints "Passed" if the student's grade is greater than or equal to 60, but prints "Failed" if it is less than 60. In either case, after printing occurs, the next pseudocode statement in sequence is "performed." The preceding If...Else pseudocode statement can be written in Java as if ( grade >= 60 ) System.out.println( "Passed" ); else System.out.println( "Failed" ); Note that the body of the else is also indented. Whatever indentation convention you choose should be applied consistently throughout your programs. It is difficult to read programs that do not obey uniform spacing conventions. while Repetition Statement A repetition statement (also called a looping statement or a loop) allows the programmer to specify that a program should repeat an action while some condition remains true. The pseudocode statement While there are more items on my shopping list Purchase next item and cross it off my list describes the repetition that occurs during a shopping trip. The condition "there are more items on my shopping list" may be true or false. If it is true, then the action "Purchase next item and cross it off my list" is performed. This action will be performed repeatedly while the condition remains true. The statement(s) contained in the While repetition statement constitute the body of the While repetition statement, which may be a single statement or a block. Eventually, the condition will become false (when the last item on the shopping list has been purchased and crossed off the list). At this point, the repetition terminates, and the first statement after the repetition statement executes. As an example of Java's while repetition statement, consider a program segment designed to find the first power of 3 larger than 100. Suppose that the int variable product is initialized to 3. When the following while statement finishes executing, product contains the result: int product = 3; while ( product <= 100 ) product = 3 * product; 2 P a g e F i r a s A l S h a i k h l y h t t p : / / a g u. y o l a s i t e. c o m

When this while statement begins execution, the value of variable product is 3. Each iteration of the while statement multiplies product by 3, so product takes on the values 9, 27, 81 and 243 successively. When variable product becomes 243, the while statement condition product <= 100becomes false. This terminates the repetition, so the final value of product is 243. At this point, program execution continues with the next statement after the while statement. Counter-Controlled Repetition Consider the following problem statement: A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz. The class average is equal to the sum of the grades divided by the number of students. The algorithm for solving this problem on a computer must input each grade, keep track of the total of all grades input, perform the averaging calculation and print the result. Problem Solving Let's use pseudocode to list the actions to execute and specify the order in which they should execute. We use counter-controlled repetition to input the grades one at a time. This technique uses a variable called a counter (or control variable) to control the number of times a set of statements will execute. Counter-controlled repetition is often called definite repetition, because the number of repetitions is known before the loop begins executing. In this example, repetition terminates when the counter exceeds 10. 1 Set total to zero 2 Set grade counter to one 3 4 While grade counter is less than or equal to ten 5 Prompt the user to enter the next grade 6 Input the next grade 7 Add the grade into the total 8 Add one to the grade counter 9 10 Set the class average to the total divided by ten 11 Print the class average 3 P a g e F i r a s A l S h a i k h l y h t t p : / / a g u. y o l a s i t e. c o m

1 // GradeBook.java 2 // GradeBook class that solves class-average problem using 3 // counter-controlled repetition. 4 import java.util.scanner; // program uses class Scanner 5 6 public class GradeBook 7 { 8 private String coursename; // name of course this GradeBook represents 9 10 // constructor initializes coursename 11 public GradeBook( String name ) 12 { 13 coursename = name; // initializes coursename 14 } // end constructor 15 16 // method to set the course name 17 public void setcoursename( String name ) 18 { 19 coursename = name; // store the course name 20 } // end method setcoursename 21 22 // method to retrieve the course name 23 public String getcoursename() 24 { 25 return coursename; 26 } // end method getcoursename 27 28 // display a welcome message to the GradeBook user 29 public void displaymessage() 30 { 31 // getcoursename gets the name of the course 32 System.out.printf( "Welcome to the grade book for\n%s!\n\n", 33 getcoursename() ); 34 } // end method displaymessage 35 36 // determine class average based on 10 grades entered by user 37 public void determineclassaverage() 38 { 39 // create Scanner to obtain input from command window 40 Scanner input = new Scanner( System.in ); 41 42 int total; // sum of grades entered by user 43 int gradecounter; // number of the grade to be entered next 44 int grade; // grade value entered by user 45 int average; // average of grades 46 47 // initialization phase 48 total = 0; // initialize total 49 gradecounter = 1; // initialize loop counter 50 51 // processing phase 52 while ( gradecounter <= 10 ) // loop 10 times 53 { 54 System.out.print( "Enter grade: " ); // prompt 55 grade = input.nextint(); // input next grade 56 total = total + grade; // add grade to total 57 gradecounter = gradecounter + 1; // increment counter by 1 58 } // end while 59 4 P a g e F i r a s A l S h a i k h l y h t t p : / / a g u. y o l a s i t e. c o m

60 // termination phase 61 average = total / 10; // integer division yields integer result 62 63 // display total and average of grades 64 System.out.printf( "\ntotal of all 10 grades is %d\n", total ); 65 System.out.printf( "Class average is %d\n", average ); 66 } // end method determineclassaverage 67 68 } // end class GradeBook Class GradeBook contains a constructor (lines 11 14) that assigns a value to the class's instance variable coursename (declared in line 8). Lines 17 20, 23 26 and 29 34 declare methods setcoursename, getcoursename and displaymessage, respectively. Lines 37 66 declare method determineclassaverage, which implements the class-averaging algorithm described by the pseudocode. Line 40 declares and initializes Scanner variable input, which is used to read values entered by the user. Lines 42 45 declare local variables total, gradecounter, grade and average to be of type int. Variable grade stores the user input. Note that the declarations (in lines 42 45) appear in the body of method determinesclassaverage. Recall that variables declared in a method body are local variables and can be used only from the line of their declaration in the method to the closing right brace (}) of the method declaration. A local variable's declaration must appear before the variable is used in that method. A local variable cannot be accessed outside the method in which it is declared. In the class GradeBook, we simply read and process a set of grades. The averaging calculation is performed in method determineclassaverage using local variableswe do not preserve any information about student grades in instance variables of the class. We maintain the grades in memory using an instance variable that refers to a data structure known as an array. This allows a GradeBook object to perform various calculations on the same set of grades without requiring the user to enter the grades multiple times. 1 // GradeBookTest.java 2 // Create GradeBook object and invoke its determineclassaverage method. 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 10 GradeBook mygradebook = new GradeBook( 11 "CS101 Introduction to Java Programming" ); 12 13 mygradebook.displaymessage(); // display welcome message 14 mygradebook.determineclassaverage(); // find average of 10 grades 15 } // end main 16 17 } // end class GradeBookTest 5 P a g e F i r a s A l S h a i k h l y h t t p : / / a g u. y o l a s i t e. c o m

Welcome to the grade book for CS101 Introduction to Java Programming! Enter grade: 67 Enter grade: 78 Enter grade: 89 Enter grade: 67 Enter grade: 87 Enter grade: 98 Enter grade: 93 Enter grade: 85 Enter grade: 82 Enter grade: 100 Total of all 10 grades is 846 Class average is 84 H/W Exercise: Drivers are concerned with the mileage their automobiles get. One driver has kept track of five tankfuls times of gasoline by recording the miles driven and gallons used for each tankful. Develop a Java application that will input the miles driven and gallons used (both as integers) for each tankful. The program should calculate and display the miles per gallon obtained for each tankful and print the combined miles per gallon obtained for all tankfuls up to this point. All averaging calculations should produce floatingpoint results. Use class Scanner and Counter -controlled repetition to obtain the data from the user. Ex. miles gallons 1200 21 1250 22 1150 21 1000 20 1350 22 Average miles = 1190.0 Average gallons = 19.4 6 P a g e F i r a s A l S h a i k h l y h t t p : / / a g u. y o l a s i t e. c o m