Loop Example 1: Sum from 1 to N

Similar documents
Trace call recsum(x, 3)

Trace call recsum(x, 3)

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Repetition Structures

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

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

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

COSC 122 Computer Fluency. Iteration and Arrays. Dr. Ramon Lawrence University of British Columbia Okanagan

Data Handing in Python

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

pointers + memory double x; string a; int x; main overhead int y; main overhead

CS 302: Introduction to Programming in Java. Lecture 9

Increment and the While. Class 15

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

CHAPTER 2 PROBLEM SOLVING TECHNIQUES. Mr Mohd Hatta Bin Hj Mohamed Ali Computer Programming BFC2042

In addition to the correct answer, you MUST show all your work in order to receive full credit.

Programming Paradigms: Overview to State Oriented

Question 1a) Trace of program

cs1114 REVIEW of details test closed laptop period

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

Assignment (3-6) Boolean Algebra and Logic Simplification - General Questions

WYSE Academic Challenge 2002 Computer Science Test (Sectional) SOLUTION

Overview. Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays. Initialization Searching

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

Abstract Data Types Chapter 1

CS159. Nathan Sprague. November 9, 2015

PROBLEM SOLVING WITH LOOPS. Chapter 7

CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, Good Luck!

CSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion

FORM 2 (Please put your name and form # on the scantron!!!!)

Control Structures II. Repetition (Loops)

Iteration and Arrays Dr. Abdallah Mohamed

COS 126 General Computer Science Spring Written Exam 1

Practice problems Set 2

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

QUEEN MARY, UNIVERSITY OF LONDON

Lecture 15. For-Loops

Chapter 4 The If Then Statement

ECE Digital System Design & Synthesis Exercise 1 - Logic Values, Data Types & Operators - With Answers

Java Review. Fundamentals of Computer Science

Java Coding 3. Over & over again!

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

Lesson 9: Introduction To Arrays (Updated for Java 1.5 Modifications by Mr. Dave Clausen)

CSC 222: Computer Programming II. Spring 2005

Repetition. Chapter 6

Spring Semester 13, Dr. Punch. Exam #1 (2/14), form 1 A

Lab 10: Alternate Controls

Repetition. Chapter 6

CSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion (Solutions)

CS 1110: Introduction to Computing Using Python Loop Invariants

CS115 - Module 3 - Booleans, Conditionals, and Symbols

E7 University of California, Berkeley Fall Midterm Exam 10/07/2016 version:

Solutions Manual. Data Structures and Algorithms in Java, 5th edition International Student Version. M. T. Goodrich and R.

Lecture 3 (02/06, 02/08): Condition Statements Decision, Operations & Information Technologies Robert H. Smith School of Business Spring, 2017

Introduction to Software Development (ISD) Week 3

Introduction. C provides two styles of flow control:

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Some Sample AP Computer Science A Questions - Solutions

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial:

Repetition and Loop Statements Chapter 5

CS 1110 Final, December 8th, Question Points Score Total: 100

Score score < score < score < 65 Score < 50

McGill University School of Computer Science COMP-202A Introduction to Computing 1

You ll be reading more about tools for branching in Sections 3.4, and We are skipping Sections 3.5, 3.11 and 3.13-end of chapter.

DCS/100 Procedural Programming

Testing, Debugging, and Verification

Long (LONGMATH) variables may be used the same as short variables. The syntax is the same. A few limitations apply (see below).

6.189 Exam Friday, January 11

Introduction to Python

8 Optimisation. 8.2 Machine-Independent Optimisation

Controls Structure for Repetition

COMP 111. Introduction to Computer Science and Object-Oriented Programming

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

Compsci 101 Fall 2015 Exam 1 Rubric. Problem 1 (24 points)

Full file at

Name Section: M/W T/TH Number Definition Matching (8 Points)

int a; int b = 3; for (a = 0; a < 8 b < 20; a++) {a = a + b; b = b + a;}

CS Lecture 19: Loop invariants

CS 1110 Final, December 8th, Question Points Score Total: 100

Data Structures. Lists, Tuples, Sets, Dictionaries

Search,Sort,Recursion

Spring 2013 COMP Midterm Exam Solutions March 07, 2013

Class 8 ALGORITHMS AND FLOWCHARTS. The City School

Functions with Parameters and Return Values

Decision Making -Branching. Class Incharge: S. Sasirekha

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Loops (while and for)

Term 1 Unit 1 Week 1 Worksheet: Output Solution

Variable initialization and assignment

3. Can every Do-Loop loop be written as a For-Next loop? Why or why not? 4. Name two types of files that can be opened and used in a VB program.

Loops. CSE 114, Computer Science 1 Stony Brook University

ABC basics (compilation from different articles)

5. What is a block statement? A block statement is a segment of code between {}.

Transcription:

Loop Example 1: Sum from 1 to N GIVEN: N (A positive integer) INTERMEDIATE: Count (Counter going from 1 to N) RESULT: Sum (Sum of integers 1 to N) Sum Sum1ToN(N) 1. Count 1 2. Sum 0 3. Count N? 4. Sum Sum + Count 5. Count Count + 1 1 Trace of Sum1toN(3) Instructions N Count Sum Init. 3?? 1. 1 2. 0 3. TRUE 4. 1 5. 2 3. TRUE 2 4. 3 5. 3 3. TRUE 4. 6 5. 4 3. FALSE 1

Sum from 1 to N: Variation (I) GIVENS: N (A positive integer) INTERMEDIATES: Count (Counter from N to 1) RESUTS: Sum (sum of integers from 1 to N) Sum Sum1ToN(N) Count N Sum 0 From N to 1, with intermediate counter Count > 0? Sum Sum + Count Count Count - 1 3 Sum from 1 to N: Variation (II) GIVENS: N (A positive integer) INTERMEDIATES: (none) RESUTS: Sum (sum of integers from 1 to N) Sum Sum1ToN(N) Sum 0 Attention: N (given) is modified locally only. This approach works, but can be confusing. N > 0? Sum Sum + N N Count - 1 4 2

Loop Example 2: Sum of Array Values INTERMEDIATE: Index (Array index going from 0 to N-1) RESULT: Sum (Sum of array contents) Sum SumArray(A,N) Sum 0 Index < N? Sum Sum + A[Index] 5 Loop Example 3a): Does sum of array values exceed T? N (Number of array elements) T (A threshold value) INTERMEDIATE: Sum (The sum of the array, from example 2) RESULT: Exceeds (Boolean: True if Sum > T and False otherwise) Exceeds SumLargerThanT(A,N,T) Sum SumArray(A,N) Exceeds Sum > T 6 3

Loop Example 3b): Does sum of array values exceed T (efficient)? T (A threshold value) INTERMEDIATE: Index (Array index going from 1 to N) Sum (The sum of the array elements) RESULT: Exceeds (A Boolean: if T>Sum and otherwise) Exceeds SumLargerThanT(A,N,T) Sum 0 Index < N AND SUM T? Exceeds Sum > T Sum Sum + A[Index] 7 Loop Example 4: Count instances of K K (Value for which to count instances) INTERMEDIATES: Index (Array index going from 0 to N-1) RESULT: Count (Number of times value of K is contained in A) Count CountK(A,N,K) Count 0 Index < N? A[Index] = K? Count Count + 1 8 4

Loop Example 5a) Is K in an array? K (Value to find) INTERMEDIATES: Count (Number of times K is in array, from algorithm 4) RESULT: Found (Boolean : if K is in array and otherwise) Found FindK(A,N,K) K) Count CountK(A,N,K) Found Count > 0 9 Loop Example 5b) Is K in an array? K (Value to find) INTERMEDIATES: Index (Array index going from 1 to N) RESULT: Found (Boolean : if K is in array and otherwise) Found FindK(A,N,K) Found FALSE Index < N AND NOT Found? A[Index] = K? Found TRUE 10 5

Loop Example 6: Find K s position in an array K (Value to find) INTERMEDIATES: Index (Array index going from 1 to N) RESULT: Position (Position of K in array, or -1 if K is not contained in array) Position WhereIsK(A,N,K) Position -1 Index < N AND Position = -1? A[Index] = K? Position Index 11 Loop Example 7: Find Maximum Value in Array INTERMEDIATES: Index (Array index going from 1 to N) RESULT: Max (Maximum value contained in A) Max MaxInArray(A,N) Index 1 Max A[0] Index < N? A[Index] > Max? Max A[Index] 12 6

Loop Example 8a): Find Position of Maximum Value in Array INTERMEDIATES: Index (Array index going from 1 to N) Max (Maximum value contained in A) RESULTS: Position (Position of Maximum value contained in A) Position MaxPosInArray(A,N) Max MaxInArray(A,N) Position -1 Index < NAND Position = -1? A[Index] = Max? Position Index 13 Loop Example 8b): Find Position of Maximum Value in Array INTERMEDIATES: Max (Maximum in array from example 7) RESULT: Position (Position of Maximum value contained in A) Position MaxPosInArray(A,N) Max MaxInArray(A,N) Position WhereIsK(A,N,Max) 14 7

Loop Example 8c): Find Position of Maximum Value in Array INTERMEDIATES: Index (Array index going from 1 to N) Max (Maximum value contained in A) RESULTS: Position (Position of Maximum value contained in A) Position MaxPosInArray(A,N) Index 1 Max A[0] Position 0 Index < N? A[Index] > Max? Max A[Index] Position Index 15 Loop Example 9): Determine if array contains duplicate values N (Number of array elements) INTERMEDIATES: CheckIndex DupIndex (Array index for current element) (Array index for duplicate checking of current element) RESULT: Duplicates (True if there are duplicates in A and otherwise) Duplicates HasDuplicates(A,N) 16 8

Loop Example 9): Determine if array contains duplicate values Duplicates False Check CheckIndex < N AND Not Duplicates? DupIndex CheckIndex + 1 DupIndex < N AND Not Duplicates? CheckIndex CheckIndex + 1 A[CheckIndex] = A[DupIndex]? Duplicates True DupIndex DupIndex + 1 17 Creating an Array Create an array containing the integers 1 to N in reverse order. Remember the standard algorithm anarrayrefvar MakeNewArray( L ) that creates an array referenced by anarrayrefvar; the array has L positions with unknown values in them. GIVENS: N (a positive integer) RESULTS: A (an reference to an array containing N 1) INTERMEDIATES: Index (an index for A) A CreateNDownTo1( N ) A MakeNewArray(N) Index < N? A[Index] N - Index 18 9

Trace for N=3 statements N Index A initial values 3?? 1. A MakeArray(3)?,?,? 2. 0 3. Index < N? 4. A[Index] N Index 3,?,? 5. 1 3. Index < N? 4. A[Index] N Index 3,2,? 5. 2 3. Index < N? 4. A[Index] N Index 3,2,1 5. 3 3. Index < N? 19 Translate to Program import java.io.* ; class Sum1ToN public static int sum1ton (int n) // initialize counter and accumulator sum int count = 1; int sum = 0; // loop while (count <= n) sum = sum + count; count = count + 1; // return the result return(sum); 20 10

FOR loop to add 1 to N Sum 0 Count 1 Count N? Sum Sum + Count Count Count + 1 Translate: sum = 0 ; for ( count = 1; count <= n; count = count + 1 ) sum = sum + count ; 21 Translated to a Program import java.io.* ; class MaxInArray public static int maxinarray (int [] a) // DATA DICTIONARY // GIVEN: a An array of integers int max; // RESULT: The maximum in the array int n; // INTERMEDIATES: The length of array a int index; // Index into array a // Initialise n n = a.length; 22 11

Translated to a Program // ALGORITHM BODY max = a[0]; index = 1; while (index < n) if (a[index] > max) max = a[index]; else ; // do nothing index = index + 1; // update max // Return results return(max); 23 Comparing Strings What is the value of result for these examples? ea pes? Example 1: String str1 = "abcde" ; String str2 = "abcfg" ; int result = str1.compareto(str2); result is less than zero Example 2: String str1 = "abcde" ; String str2 = "ab" ; int result = str1.compareto(str2); result is greater than zero 24 12