Introduction to C++ Programming Language

Slides:



Advertisements
Similar presentations
Computer Science 1620 Loops.
Advertisements

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.
1 10/9/06CS150 Introduction to Computer Science 1 for Loops.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand basic loop concepts: ■ pretest loops and post-test loops ■ loop.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 19 Recursion.
Computer Programming Basics Assistant Professor Jeon, Seokhee Assistant Professor Department of Computer Engineering, Kyung Hee University, Korea.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 12 Recursion.
Lecture 8: Choosing the Correct Loop. do … while Repetition Statement Similar to the while statement Condition for repetition only tested after the body.
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.
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.
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
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.
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.
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Andy Wang Object Oriented Programming in C++ COP 3330
Introduction to Computer Programming
Chapter 19: Recursion.
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.
Chapter 4: Looping Structures LECTURER : MRS ROHANI HASSAN
Topic 6 Recursion.
REPETITION CONTROL STRUCTURE
生查子 ~ 歐陽修 去年元夜時,花市燈如晝, 月上柳梢頭,人約黃昏後; 今年元夜時,月與燈依舊, 不見去年人,淚濕春衫袖。
Chapter 5: Control Structures II (Repetition)
C++ Programming: CS150 For.
Andy Wang Object Oriented Programming in C++ COP 3330
Chapter 14: Recursion Starting Out with C++ Early Objects
Chapter 2.2 Control Structures (Iteration)
Programming Fundamentals
Control Structures - Repetition
Control Structures Lecture 7.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Chapter 4 Control structures and Loops
Repetition and Loop Statements
Chapter 6 Repetition Objectives ❏ To understand basic loop concepts:
Loops (iterations, repetitions)
Recursion Chapter 18.
Chapter 2.2 Control Structures (Iteration)
Chapter 5 Loops.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 6: Repetition Statements
UMBC CMSC 104 – Section 01, Fall 2016
Module 1-10: Recursion.
Looping III (do … while statement)
Let’s all Repeat Together
Chapter 5: Control Structures II (Repetition)
do/while Selection Structure
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
Presentation transcript:

Introduction to C++ Programming Language 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? Cut and paste the codes 160 times? cout << 1 + 2 + ……+100 << endl; ?? Then, what about summing up 1~10000?

Loop: The real power of computers! 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 Usually used for event-controlled loop

The while Statement

The Compound while Statement

Examples of while Loop

Heating System Control Example

Enter an integer: 12345 Your number is: 12345 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: 3 1 2 3 0 10 1 9 2 8 3 7 4 6 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 --- --- --- --- --- --- --- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

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 Unconditional loop exit for(…;…;…) or while(…) { … break; } Terminate the loop and execution jumps to here

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 2n 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 2n.

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 http://www.lsi.upc.edu/~jordicf/Teaching/programming/pdf4/IP03_Loops-4slides.pdf

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.

Example Program 6-27, Calculator with Menu

Program Efficiency Consideration