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

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

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

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

Object Oriented Programming. Java-Lecture 1

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

ECE 161 WEEK 4 Introduction to Programing in Java

Lecture 7: Classes and Objects CS2301

Structured Program Development in C

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

Chapter 3 Structured Program Development

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

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

Introduction to Classes and Objects

Structured Program Development

Introduction to Classes and Objects

Chapter 3 Structured Program Development in C Part II

Control Statements. Musa M. Ameen Computer Engineering Dept.

Programming with Java

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

CS141 Programming Assignment #6

Control Structures (Deitel chapter 4,5)

Fundamentals of Programming Session 7

JAVA- PROGRAMMING CH2-EX1

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

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

Chapter 2 - Control Structures

Control Statements: Part 1

Introduction to Classes and Objects

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

Menu Driven Systems. While loops, menus and the switch statement. Mairead Meagher Dr. Siobhán Drohan. Produced by:

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

Supplementary Test 1

CS110D: PROGRAMMING LANGUAGE I

2.8. Decision Making: Equality and Relational Operators

Repetition CSC 121 Fall 2014 Howard Rosenthal

Midterm Examination (MTA)

Introduction to Computer Science I

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Internet & World Wide Web How to Program, 5/e by Pearson Education, Inc. All Rights Reserved.

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

In this chapter you will learn:

CS111: PROGRAMMING LANGUAGE II

Chapter 4: Control structures. Repetition

Example: Monte Carlo Simulation 1

Controls Structure for Repetition

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Chapter 2 - Control Structures

Chapter 4: Control structures

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

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

download instant at

ITERATION WEEK 4: EXMAPLES IN CLASS

Iteration statements - Loops

by Pearson Education, Inc. All Rights Reserved. 2

CS141 Programming Assignment #8

Object Oriented Programming. Java-Lecture 6 - Arrays

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

Chapter 2 - Control Structures

Lab 2: Structured Program Development in C

Activity 6: Loops. Content Learning Objectives. Process Skill Goals

Java Coding 3. Over & over again!

AP Computer Science Unit 1. Programs

Introduction to Computer Science Unit 2. Exercises

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

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

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

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Introduction to Java Applications

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

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

Arrays Pearson Education, Inc. All rights reserved.

CS110 Programming Language I. Lab 6: Multiple branching Mechanisms

COMP 202 Java in one week

Control Structures II. Repetition (Loops)

Bjarne Stroustrup. creator of C++

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

Computer Programming C++ Classes and Objects 6 th Lecture

Repetition, Looping. While Loop

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

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

Loops. Repeat after me

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

CS110: PROGRAMMING LANGUAGE I

Repetition Structures

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

C Programming for Engineers Structured Program

Introduction to Computer Programming

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Chapter 3. Selections

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.

Over and Over Again GEEN163

Mid Term Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: Sunday November 3, 2013 Total Marks: 50 Obtained Marks:

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

AP CS A Exam Review Answer Section

Program Control Flow

Program Control Flow

Fundamentals of Programming Session 25

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

Transcription:

Basic Problem solving Techniques Top Down stepwise refinement If & if.. While.. Counter controlled and sentinel controlled repetition Usage of Assignment increment & decrement operators 1

ECE 161 WEEK 7 Control Statements Part 1 9.11.05 Prof Dr. Ziya B. Güvenç Res. Asst. Barbaros Preveze IF single selection statement If we want to write a program that decides whether the student passes or not, our program has to decide for this by checking if the grade is greater than 60 or not. Thus we need the word if to decide whether the grade is greater that 60 or not. If the grade is greater than or equal to 60, print to the screen that the student passes. This sentence can easily be coded in Java programming language as seen below. if (studentgrade >= 60) System.out.println( passed ); IF. ELSE.. statement After the decision we may want to write a code print passed if the grade is greater or equal to 60 and we may want to print failed if the grade is less than 60. In this case we use if. if (studentgrade >= 60) System.out.println( passed ); System.out.println( failed ); Here the word stands for if the grade not greater or equal to. Conditional Operator System.out.println(studentGrade>=60? Passed : Failed ); The statement above is equivalent to if (studentgrade >= 60) System.out.println( passed ); System.out.println( failed ); Nested if and Nested if structure is used for blocking the part as a separated if statement that will work if and only if the if statement is not provided i.e. 2

if (studentgrade >= 90) System.out.println( AA ); if (studentgrade >= 85) System.out.println( BA ); if (studentgrade >= 75) System.out.println( BB ); if (studentgrade >= 70) System.out.println( CB ); if (studentgrade >= 60) System.out.println( CC ); System.out.println( Failed ); if (studentgrade >= 90) System.out.println( AA ); if (studentgrade >= 85) System.out.println( BA ); if (studentgrade >= 75) System.out.println( BB ); if (studentgrade >= 70) System.out.println( CB ); if (studentgrade >= 60) System.out.println( CC ); System.out.println( Failed ); Dangling Problem If (a> 2) If (b<5) System.out.println( a is greater than 2 and b is less than 5 ); System.out.println( a is greater than 2 but b is greater than or equal to 5 ); System.out.println( a is less than or equal to 2 ); 3

If (a> 2) If (b<5) System.out.println( a is greater than 2 and b is less than 5 ); System.out.println( a is greater than 2 but b is greater than or equal to 5 ); System.out.println( a is less than or equal to 2 ); Blocks If (a> 2) If (b<5) System.out.println( a is greater than 2 ); System.out.println( a is less than 5 ); } Else System.out.println( a is greater than 2 but b is greater than or equal to 5 ); System.out.println( a is greater than or equal to 2 ); Counter controlled While Repetition Statement Repetition loop Some times we want to make something until some other thing happens or stops happening. In this case we use while statement for this purpose. E.g If you have a shopping list and if you want to purchase everything in your shopping list You will write a code which says; While the shopping list is not empty,purchase the first item in the list and cross it off This way the things that you ve already purchased will not be purchased again. Or if you want to add the numbers retrieved from the user, you want the program to stop when the sum of these numbers reaches to 1000 and display the number of entries,i.e the code will be; 4

import java.util.scanner; // program uses Scanner public class Product public static void main( String args[] ) int sum; int number; int person; Scanner input = new Scanner(System.in); sum=0; person=0; System.out.println("Enter the numbers below"); while(sum<1000) number = input.nextint(); sum=sum + number; person=person + 1; } System.out.printf("The total number of users = %d,with the total of %d\n", person, sum); } // end method main Output : In this program programmer is not aware of how many entry will be entered. 5

Implementing Counter Controlled repetition in Class GradeBook import java.util.scanner; // program uses class Scanner public class GradeBook private String coursename; // name of course this GradeBook represents // constructor initializes coursename public GradeBook( String name ) coursename = name; // initializes coursename } // end constructor // method to set the course name public void setcoursename( String name ) coursename = name; // store the course name } // end method setcoursename // method to retrieve the course name public String getcoursename() return coursename; } // end method getcoursename // display a welcome message to the GradeBook user public void displaymessage() // getcoursename gets the name of the course System.out.printf( "Welcome to the grade book for\n%s!\n\n", getcoursename() ); } // end method displaymessage // determine class average based on 10 grades entered by user public void determineclassaverage() // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int total; // sum of grades entered by user int gradecounter; // number of the grade to be entered next int grade; // grade value entered by user int average; // average of grades // initialization phase total = 0; // initialize total gradecounter = 1; // initialize loop counter // processing phase 6

while ( gradecounter <= 10 ) // loop 10 times System.out.print( "Enter grade: " ); // prompt grade = input.nextint(); // read grade from user total = total + grade; // add grade to total gradecounter = gradecounter + 1; // increment counter by 1 } // end while // termination phase average = total / 10; // integer division yields integer result // display total and average of grades System.out.printf( "\ntotal of all 10 grades is %d\n", total ); System.out.printf( "Class average is %d\n", average ); } // end method determineclassaverage } // end class GradeBook public class GradeBookTest public static void main( String args[] ) // create GradeBook object mygradebook and // pass course name to constructor GradeBook mygradebook = new GradeBook( "CS101 Introduction to Java Programming" ); mygradebook.displaymessage(); // display welcome message mygradebook.determineclassaverage(); // find average of 10 grades } // end main } // end class GradeBookTest OUTPUT 7

FORMULATING ALGORITHMS: SENTINEL CONTROLLED REPITATION Assume that the user wants to calculate the average grade of any class, but the user doesn t have any idea about the number of students in the class. In this case you want to write a program which continuously retrieve inputs from the user and stops when the grade is entered as -1. if -1 is entered it will stop, calculate the average and display the result on the screen. Here -1 (which we have arbitrarily chosen) is sentinel value (flag value, dummy value, signal value) you may chose any number as sentinel value to stop the execution of the program. The program codes implementing this is given below; import java.util.scanner; // program uses class Scanner public class GradeBook private String coursename; // name of course this GradeBook represents // constructor initializes coursename public GradeBook( String name ) coursename = name; // initializes coursename } // end constructor // method to set the course name public void setcoursename( String name ) coursename = name; // store the course name } // end method setcoursename // method to retrieve the course name public String getcoursename() return coursename; } // end method getcoursename // display a welcome message to the GradeBook user public void displaymessage() // getcoursename gets the name of the course System.out.printf( "Welcome to the grade book for\n%s!\n\n", getcoursename() ); } // end method displaymessage // determine the average of an arbitrary number of grades public void determineclassaverage() // create Scanner to obtain input from command window 8

Scanner input = new Scanner( System.in ); int total; // sum of grades int gradecounter; // number of grades entered int grade; // grade value double average; // number with decimal point for average // initialization phase total = 0; // initialize total gradecounter = 0; // initialize loop counter // processing phase // prompt for input and read grade from user System.out.print( "Enter grade or -1 to quit: " ); grade = input.nextint(); // loop until sentinel value read from user while ( grade!= -1 ) total = total + grade; // add grade to total gradecounter = gradecounter + 1; // increment counter // prompt for input and read next grade from user System.out.print( "Enter grade or -1 to quit: " ); grade = input.nextint(); } // end while // termination phase // if user entered at least one grade... if ( gradecounter!= 0 ) // calculate average of all grades entered average = (double) total / gradecounter; // display total and average (with two digits of precision) System.out.printf( "\ntotal of the %d grades entered is %d\n", gradecounter, total ); System.out.printf( "Class average is %.2f\n", average ); } // end if // no grades were entered, so output appropriate message System.out.println( "No grades were entered" ); } // end method determineclassaverage } // end class GradeBook 9

public class GradeBookTest public static void main( String args[] ) // create GradeBook object mygradebook and // pass course name to constructor GradeBook mygradebook = new GradeBook( "CS101 Introduction to Java Programming" ); mygradebook.displaymessage(); // display welcome message mygradebook.determineclassaverage(); // find average of grades } // end main } // end class GradeBookTest OUTPUT: NESTED CONTROL STRUCTURES While. If. Sometimes we may need these control structures one in the other (nested). Here is an example in which we need the usage of these statements in nested structure. 10

The program below retrieves 10 inputs from the user, (1 -> passed, 2 -> failed); import java.util.scanner; // class uses class Scanner public class Analysis public void processexamresults() // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); // initializing variables in declarations int passes = 0; // number of passes int failures = 0; // number of failures int studentcounter = 1; // student counter int result; // one exam result (obtains value from user) // process 10 students using counter-controlled loop while ( studentcounter <= 10 ) // prompt user for input and obtain value from user System.out.print( "Enter result (1 = pass, 2 = fail): " ); result = input.nextint(); // if... nested in while if ( result == 1 ) // if result 1, passes = passes + 1; // increment passes; // result is not 1, so failures = failures + 1; // increment failures // increment studentcounter so loop eventually terminates studentcounter = studentcounter + 1; } // end while // termination phase; prepare and display results System.out.printf( "Passed: %d\nfailed: %d\n", passes, failures ); // determine whether more than 8 students passed if ( passes > 8 ) System.out.println( "Raise Tuition" ); } // end method processexamresults } // end class Analysis 11

public class AnalysisTest public static void main( String args[] ) Analysis application = new Analysis(); // create Analysis object application.processexamresults(); // call method to process results } // end main } // end class AnalysisTest OUTPUT: Compound Assignment Operator Initially c=3, d=5, e=4, f=6, g=12 Assignment operator Sample Expression Explanation Assigns += C+=7 C=C+7 10 to C -= D-=4 D=D-4 1 to D *= E*=5 E=E*5 20 to E /= F/=3 F=F/3 2 to F %= G%=9 G=G%9 3 to G Increment and Decrement Operators Sample expression Called Explanation ++a Prefix increment Inc. by 1 then use new value a++ Postfix increment Use old value then inc. by 1 --b Prefix decrement Dec. by 1 then use new value b-- Postfix decrement Use old value then dec. by 1 12

For understanding better,lets write a program which uses these expressions public class Increment public static void main( String args[] ) int c; // demonstrate postfix increment operator c = 5; // assign 5 to c System.out.println( c ); // print 5 System.out.println( c++ ); // print 5 then postincrement System.out.println( c ); // print 6 System.out.println(); // skip a line // demonstrate prefix increment operator c = 5; // assign 5 to c System.out.println( c ); // print 5 System.out.println( ++c ); // preincrement then print 6 System.out.println( c ); // print 6 } // end main } // end class Increment OUTPUT : 13