Computer Programming, I. Laboratory Manual. Experiment #6. Loops

Similar documents
Loops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department

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

Computer Programming, I. Laboratory Manual. Experiment #5. Strings & Text Files Input

Computer Programming, I. Laboratory Manual. Experiment #4. Mathematical Functions & Characters

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

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

Computer Programming: C++

Loops. CSE 114, Computer Science 1 Stony Brook University

Computer Programming, I. Laboratory Manual. Final Exam Solution

Computer Programming, I. Laboratory Manual. Experiment #9. Multi-Dimensional Arrays

Problem Solving With Loops

Date: Dr. Essam Halim

Loops. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

St. Edmund Preparatory High School Brooklyn, NY

Example. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.

Assignment 2.4: Loops

REPETITION CONTROL STRUCTURE LOGO

Over and Over Again GEEN163

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Reading Input from Text File

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

Example. Write a program which generates 2 random integers and asks the user to answer the math expression.

Oct Decision Structures cont d

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Midterm Examination (MTA)

Computer Programming I - Unit 5 Lecture page 1 of 14

Computer Programming : C++

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

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

1 Short Answer (10 Points Each)

Java Coding 3. Over & over again!

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

CS141 Programming Assignment #4

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

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

Chapter 4: Control Structures I

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

CMPT 125: Lecture 4 Conditionals and Loops

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

ITERATION WEEK 4: EXMAPLES IN CLASS

Introduction to Java Applications

switch-case Statements

Computer Programming: C++

AP CS Unit 3: Control Structures Notes

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

STUDENT LESSON A12 Iterations

Eng. Mohammed S. Abdualal

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

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

Computer Programming: C++

Arithmetic Compound Assignment Operators

Repetition. Chapter 6

Introduction to Computers. Laboratory Manual. Experiment #3. Elementary Programming, II

Repetition. Chapter 6

Arrays. Eng. Mohammed Abdualal

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Building Java Programs

Introduction to Computer Science Unit 2. Notes

New York University Intro to Computer Science (CSCI-UA.101) Fall 2014 Midterm #1 Test G. Instructions:

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

Topics. Chapter 5. Equality Operators

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

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

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Repetition, Looping. While Loop

int j = 0, sum = 0; for (j = 3; j <= 79; j++) { sum = sum + j; System.out.println(sum); //Show the progress as we iterate thru the loop.

Elementary Programming

CMPS 11 Introduction to Programming Midterm 1 Review Problems

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Question: Total Points: Score:

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

CompSci 125 Lecture 11

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

++x vs. x++ We will use these notations very often.

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

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Conditional Execution


Chapter 2 ELEMENTARY PROGRAMMING

Programming with Java

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

CS Computers & Programming I Review_01 Dr. H. Assadipour

AP Programming - Chapter 6 Lecture

Eng. Mohammed Abdualal

Chapter Goals. Contents LOOPS

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

Course Outline. Introduction to java

Question: Total Points: Score:

Iteration statements - Loops

STUDENT LESSON A7 Simple I/O

Building Java Programs

Transcription:

Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #6 Loops

What is Loop? A loop can be used to tell a program to execute statements repeatedly. Java provides a powerful construct called a loop that controls how many times an operation or a sequence of operations is to be performed in succession. Java provides three types of loop statements: while loops, do-while loops, and for loops. The while Loop A while loop executes statements repeatedly while the condition is true. The syntax for the while loop is: while (loop-continuation-condition) { // Loop body Statement(s); And the flowchart for while loop is: Here is an example that uses while loop to print a statement one hundred times to the console. int count = 0; while (count < 100) { // <-- the condition System.out.println("Welcome to Java!"); //loop body count++; 2

Note that The loop-continuation-condition must always appear inside the parentheses. The braces enclosing the loop body can be omitted only if the loop body contains one statement. Ex: Consider the following algorithm to generate a sequence of numbers. 1. Start with an integer n. 2. If n is even, divide by 2. If n is odd, multiply by 3 and add 1. 3. Repeat this process with the new value of n, terminating when n = 1. Write a program to reads a positive integer n and generates a sequence of numbers until 1. int n = input.nextint(); while (n > 1) { System.out.print(n + " "); if (n % 2 == 0) n /= 2; else n = n * 3 + 1; System.out.println(n); Ex: Write a program that reads a line of text and uses indexof method to determine the number of a specific letter in the text. Uppercase and lowercase letters should be counted together. System.out.println("Enter the text: "); String text = input.nextline().tolowercase(); System.out.print("Enter the letter: "); char letter = input.next().charat(0); int counter = 0; int lastindexfound = text.indexof(letter); while (lastindexfound!= -1) { counter++; lastindexfound = text.indexof(letter, lastindexfound + 1); System.out.println(counter + " Times."); 3

break Statement You can use break in a loop to immediately terminate the loop. Ex: Write a program that asks the user to type a positive integer. When the user types a negative value the program writes 'ERROR' and asks for another value. When the user types 0 that means that the last value has been typed and the program must write the average of the positive integers. If the number of typed values is zero the program writes 'NO AVERAGE'. int n, sum = 0, count = 0; while (true) { System.out.print("Enter a positive number: "); n = input.nextint(); if (n == 0) { break; else if (n < 0) { System.out.println("Error! try again"); else { sum += n; count++; if (count > 0) System.out.println("Average is: " + (sum * 1.0 / count)); else System.out.println("No Average"); The do-while Loop A do-while loop is the same as a while loop except that it executes the loop body first and then checks the loop continuation condition. The do-while loop is a variation of the while loop. Its syntax is: do { // Loop body; Statement(s); while (loop-continuation-condition); 4

Note the semicolon after the condition. And the flowchart for do-while loop is: Ex: Re-write the previous example using do-while loop. int n, sum = 0, count = 0; do { System.out.print("Enter a positive number: "); n = input.nextint(); if (n < 0) { System.out.println("Error! try again"); else if (n > 0) { sum += n; count++; while (n!= 0); if (count > 0) System.out.println("Average is: " + (sum * 1.0 / count)); else System.out.println("No Average"); Note that we didn t need to use break statement. 5

The for Loop The syntax of a for loop is: for (initial-action; loop-continuation-condition; action-aftereach-iteration) { // Loop body Statement(s); And the flowchart of for loop is: Ex: Write a program that counts how many uppercase letters exist in a given string. String line = input.nextline(); int counter = 0; for (int i = 0; i < line.length(); i++) { if (Character.isUpperCase(line.charAt(i))) counter++; System.out.println(counter); 6

continue Statement You can use continue in a loop to terminate the current iteration of a loop. Ex: Write a program that prints all numbers between 0 and 100, except that which divide by 7. for (int i = 0; i <= 100; i++) { if (i % 7 == 0) continue; System.out.println(i); Note: In IntelliJ IDEA you can use the template to write for loop quickly. Type fori then press TAB. Lab Work Ex1: Write a program that prompts the user to enter an integer and displays a rectangle as follows: System.out.println("Enter a number: "); int num = input.nextint(); for (int i = 1; i <= num; i++) { for (int j = 1; j <= i; j++) { System.out.print(j + " "); System.out.println(); 7

Ex2: Write a program that asks the user to type 10 integers and prints the smallest value. int n = input.nextint(); int min = n; for (int i = 0; i < 9; i++) { n = input.nextint(); if (n < min) min = n; System.out.println("The smallest number is: " + min); Ex3: Write a program to read a file contains unknown number of lines, each line contains exactly two integers A and B separated by a space. For each line, print the sum of both numbers, in the following format: Line #N: S Where N is the line number, and S is the sum of two numbers in that line. Here is a sample input: And here is a sample output: Line #1: 9 Line #2: 54 Line #3: 158 Line #4: 92 Hint: input.hasnext() method returns true if this scanner has another token in its input. 8

Scanner input = new Scanner(new File("input.txt")); int a, b, line = 1; while (input.hasnext()) { a = input.nextint(); b = input.nextint(); System.out.println("Line #" + line + ": " + (a + b)); line++; Homework 1. Write a program that prompts the user to enter a string and displays the characters at odd positions. Sample Input Hello World! Welcome to Java Sample Output HloWrd Wloet aa 2. The following loop uses while syntax. Convert it to use for syntax. int x; Scanner sc = new Scanner(System.in); x = sc.nextint(); while (x!= 10) { System.out.println(x + "\t"); x = sc.nextint(); 3. What is the output of the following code for (int x = 1; x <= 5; x++) { for (int y = 1; y <= x; y++) System.out.print(x + "\t"); 4. Write a program that reads integers, finds the largest of them, and counts its occurrences. Assume that the input ends with number 0. Suppose that you entered 3 5 2 5 5 5 0; the program finds that the largest is 5 and the occurrence count for 5 is 4. Good Luck 9