Computer Programming Basics Assistant Professor Jeon, Seokhee Assistant Professor Department of Computer Engineering, Kyung Hee University, Korea.

Slides:



Advertisements
Similar presentations
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
Advertisements

Computer Science 1620 Loops.
1 10/20/08CS150 Introduction to Computer Science 1 do/while and Nested Loops Section 5.5 & 5.11.
1 10/11/06CS150 Introduction to Computer Science 1 do/while and Nested Loops.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
CS 202 Computer Science II Lab Fall 2009 October 29.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.12Recursion 3.13Example Using Recursion: The Fibonacci Series 3.14Recursion.
Chapter 5: Control Structures II (Repetition)
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand basic loop concepts: ■ pretest loops and post-test loops ■ loop.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition)
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 19 Recursion.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
RECURSION.
Lecture6 Recursion function © by Pearson Education, Inc. All Rights Reserved. 1.
Lecture 8: Choosing the Correct Loop. do … while Repetition Statement Similar to the while statement Condition for repetition only tested after the body.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
CP104 Introduction to Programming Recursion 2 Lecture 29 __ 1 Recursive Function for gcd Recursive formula for the greatest common divisor of m and n,
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
1 Loops. 2 Topics The while Loop Program Versatility Sentinel Values and Priming Reads Checking User Input Using a while Loop Counter-Controlled (Definite)
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
PROBLEM SOLVING WITH LOOPS Chapter 7. Concept of Repetition Structure Logic It is a computer task, that is used for Repeating a series of instructions.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
1 Objectives ❏ To understand basic loop concepts: ■ pretest loops and post-test loops ■ loop initialization and updating ■ event and counter controlled.
CMSC 104, Lecture 171 More Loops Topics l Counter-Controlled (Definite) Repetition l Event-Controlled (Indefinite) Repetition l for Loops l do-while Loops.
CMSC 104, Version 9/011 More Loops Topics Counter-Controlled (Definite) Repetition Event-Controlled (Indefinite) Repetition for Loops do-while Loops Choosing.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Concepts of Algorithms CSC-244 Unit 5 and 6 Recursion Shahid Iqbal Lone Computer College Qassim University K.S.A.
A Brief Introduction to Recursion. Recursion Recursive methods … –methods that call themselves! –They can only solve a base case –So, you divide a problem.
CSCI 125 & 161 Lecture 12 Martin van Bommel. Prime Numbers Prime number is one whose only divisors are the number 1 and itself Therefore, number is prime.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
1 Chapter 2 Algorithm Analysis Reading: Chapter 2.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
Maitrayee Mukerji. Factorial For any positive integer n, its factorial is n! is: n! = 1 * 2 * 3 * 4* ….* (n-1) * n 0! = 1 1 ! = 1 2! = 1 * 2 = 2 5! =
Computer C programming Chapter 3. CHAPTER 3 Program Looping –The for Statement –Nested for Loops –for Loop Variants –The while Statement –The do Statement.
C++ Programming: CS102 LOOP. Not everything that can be counted counts, and not every thing that counts can be counted. −Albert Einstein Who can control.
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
Program Development and Design Using C++, Third Edition
Introduction to Computer Programming
Recursion The programs discussed so far have been structured as functions that invoke one another in a disciplined manner For some problems it is useful.
Introduction to C++ Programming Language
REPETITION CONTROL STRUCTURE
C++ Programming: CS150 For.
Chapter 2.2 Control Structures (Iteration)
Programming Fundamentals
Control Structures - Repetition
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Repetition and Loop Statements
Chapter 6 Repetition Objectives ❏ To understand basic loop concepts:
Recursion Chapter 18.
Chapter 2.2 Control Structures (Iteration)
Let’s all Repeat Together
Presentation transcript:

Computer Programming Basics Assistant Professor Jeon, Seokhee Assistant Professor Department of Computer Engineering, Kyung Hee University, Korea

CHAPTER 6 Repetition

Why Do We Need Repetition? Sometimes we want to do things more than once. –E.g., Calculate the grades of 160 students –E.g., Calculate the sum of 1~100 How? 1.Cut and paste the codes 160 times? 2.cout << ……+100 << endl; ?? 3.Then, what about summing up 1~10000?

Concept of Loop Loop: The real power of computers!

Stopping the Loop

Question: When to Check Loop-End Condition?

Two Different Strategies for Starting Exercise

Minimum Number of Iterations in Two Loops

Loop Initialization and Updating

Initialization and Updating for Exercise

Question: When to Stop a Loop? Counter-Controlled Loop –Know how many times to loop when a loop begins –E.g., do the summing calculation 100 times. Event-Controlled Loop –Don’t know how many times, but knows how world will be when done –E.g., end the exercise when energy runs out

Event-Controlled Loop Concept

Counter-Controlled Loop Concept

Loops in C++ Usually used for event- controlled loop Usually used for counter- controlled loop

The while Statement

The Compound while Statement

Examples of while Loop

Heating System Control Example

Enter an integer: Your number is: The number of digits is: 5 The sum of the digits is: 15

The for Statement

A for loop is used when your loop is to be executed a known number of times. You can do the same thing with a while loop, but the for loop is easier to read and more natural for counting loops.

The Compound for Statement

Comparing for and while Loops

Conversion from while to for Loop

int main() { int j; j = -4; while(j <= 0) { cout << j << endl; j = j + 1; } return 0; } int main() { int j; j = -4; for( ; j <= 0 ; ) { cout << j << endl; j = j + 1; } return 0; }

int main() { int j = -4; for( ; j <= 0 ; ) { cout << j << endl; j = j + 1; } return 0; } int main() { int j; for(j = -4; j <= 0 ; ) { cout << j << endl; j = j + 1; } return 0; }

Step by Step Trace int main() { int j; for(j = -4; j <= 0 ; j = j + 1) { cout << j << endl; } return 0; }

Examples! for(i = 2; i <= 6; i = i + 2) cout << i+1 << ‘\t’; for(i = 2; i != 11; i = i + 3) cout << i+1 << ‘\t’; cout << "\nPlease enter a limit: "; cin >> limit; for (i = 1; i <= limit; i++) cout << "\t" << i << endl; Please enter the limit: for (n=0,i=10;n!=I;n++,i--) cout << n <<"\t" << i << endl;

Compound Interest

Nested for Loop

Sun Mon Tue Wed Thu Fri Sat

Format of the do…while Statement

while vs. do … while Print nothing because the i<0 is checked prior to the cout Print 1. cout is executed at least once Before checking the i<0

Other Statements Related to Looping

break Statement for(…;…;…) or while(…) { … break; … } … Terminate the loop and execution jumps to here Unconditional loop exit

break in Nested Loop

continue Statement Skip the rest of the loop body without exiting the loop

break vs. continue Result: Adam Result: Adam

break and continue Examples

continue Statement Example

Recursion A repetitive process in which a function calls itself E.g., type fun(…) { if(…) fun(…) else return …; }

Recursion Example Factorial – Conventional Formula factorial(n) = –if n is 0, then 1 –If n > 0, then n*(n-1)*(n-2)*…3*2*1 E.g., factorial(4) = 4 * 3 * 2 * 1 = 24

Recursion Example Factorial – Recursive Formula factorial(n) = –if n is 0, then 1 –If n > 0, then n*(Factorial(n-1)) E.g., factorial(4) = 4*factorial(3) = … = 24

Factorial (3) Recursively

Calling a Recursive Function

Recursion Example Fibonacci Numbers

Fibonacci Numbers -Better Algorithm Let's consider all the recursive calls for fib(5). There's a lot of repeated work. For example, the call to fib(4) repeats the calculation of fib(3) In general, when n increases by 1, we roughly double the work; that makes about 2 n calls!

Fibonacci Numbers -Better Algorithm Don't recompute the previous two, but just write them down (or remember them). k is the place we've come so far in writing out the series. When k reaches n, we're done. int helpFib(int n, int k, int fibk, int fibk1) { if (n == k) return fibk; else return helpFib(n, k+1, fibk+fibk1, fibk); } int fib(int n) { return helpFib(n, 1, 1, 0); }

Fibonacci Numbers -Better Algorithm fib(6) helpFib(6, 1, 1, 0) helpFib(6, 2, 1, 1) helpFib(6, 3, 2, 1) helpFib(6, 4, 3, 2) helpFib(6, 5, 5, 3) helpFib(6, 6, 8, 5) => 8 Need n iterations to compute fib(n). That is much better than 2 n.

Every recursive call must either solve part of the problem or reduce the size of the problem.

Greatest Common Devisor Brute Force Algorithm Using Recursion int tryDivisor(int m, int n, int g) { if (((m % g) == 0) && ((n % g) == 0)) return g; else return tryDivisor(m, n, g - 1); } int gcd(int m, int n) { return tryDivisor(m, n, n); // use n as our first guess } gcd(6, 4) tryDivisor(6, 4, 4) tryDivisor(6, 4, 3) tryDivisor(6, 4, 2) => 2

Greatest Common Devisor Brute Force Algorithm Using while Loop int GreatestCommonDivisor (int a, int b) { int n = min (a, b); int gcd = 1, i = 1; while (i <= n) { if (a % i == 0 && b % i == 0) gcd = i; i++; } return gcd; }

Greatest Common Devisor Euclid's Algorithm Using Recursion The idea: gcd(a,b)=gcd(b,a mod b) gcd(a,0)=a int gcd(int m, int n) { if ((m % n) == 0) return n; else return gcd(n, m % n); } gcd(468, 24) gcd(24, 12) => 12 gcd(135, 19) gcd(19, 2) gcd(2, 1) => 1

Greatest Common Devisor Euclid's Algorithm Using while Loop int GreatestCommonDivisor (int a, int b) { while (b != 0) { int r = a % b; a = b; b = r; } return a; }

Greatest Common Devisor Dijkstra's Algorithm Using Recursion The idea: If m>n, GCD(m,n) is the same as GCD(m-n,n). int gcd(int m, int n) { if(m == n) return m; else if (m > n) return gcd(m-n, n); else return gcd(m, n-m); } This does accomplish the calculation with no division. gcd(468, 24) gcd(444, 24) gcd(420, 24)... gcd(36, 24) gcd(12, 24) (Now n is bigger) gcd(12, 12) (Same) => 12

Greatest Common Devisor Dijkstra's Algorithm Using while Loop int GreatestCommonDivisor (int a, int b) { int c; while (a != b) { while (a > b) { c = a - b; a = c; } while (b > a) { c = b - a; b = c; } } return a; }

Prime Number Example A prime number is a natural number that has exactly two distinct divisors: 1 and itself. (Comment: 1 is not prime) Write a program that reads a natural number (N) and tells whether it is prime or not. Algorithm: try all potential divisors from 2 to N ‐ 1 and check whether the remainder is zero. from

Prime Number Example Observation: as soon as a divisor is found, there is no need to check divisibility with the rest of the divisors. However the algorithm tries all potential divisors from 2 to N ‐ 1. Improvement: stop the iteration when a divisor is found.

Simple Menu

Program Efficiency Consideration