Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.

Slides:



Advertisements
Similar presentations
Introduction to Programming (in C++) Subprograms: procedures and functions Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science,
Advertisements

CS1010 Programming Methodology
Computer Science 1620 Loops.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
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.
CS150 Introduction to Computer Science 1
1 CS150 Introduction to Computer Science 1 Relational Operators and the If Statement 9/22/08.
Computer Programming 1 Repetition. Computer Programming 2 Objectives Repetition structures Study while and do loops Examine for loops A practical example.
Introduction to Programming (in C++) Vectors Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
C++ Programming Language Day 1. What this course covers Day 1 – Structure of C++ program – Basic data types – Standard input, output streams – Selection.
Introduction to Programming (in C++) Introduction Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Fall 2002CMSC Discrete Structures1 Let us get into… Number Theory.
CS1101: Programming Methodology Aaron Tan.
Introduction to Programming (in C++) Data types and visibility Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. Computer Science, UPC.
Introduction to Programming (in C++) Recursion Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Introduction to Programming (in C++) Data and statements Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
MATH 224 – Discrete Mathematics
Chapter 5: Control Structures II (Repetition)
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.
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.
Reasoning with invariants Jordi Cortadella Department of Computer Science.
Prime numbers Jordi Cortadella Department of Computer Science.
Chapter 3 (Part 3): Mathematical Reasoning, Induction & Recursion  Recursive Algorithms (3.5)  Program Correctness (3.6)
© by Kenneth H. Rosen, Discrete Mathematics & its Applications, Sixth Edition, Mc Graw-Hill, 2007 Chapter 4 (Part 3): Mathematical Reasoning, Induction.
Introduction to Programming (in C++) Algorithms on sequences. Reasoning about loops: Invariants. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept.
Copyright © Cengage Learning. All rights reserved. CHAPTER 4 ELEMENTARY NUMBER THEORY AND METHODS OF PROOF.
Data Structures Chapter 1- Introduction Mohamed Mustaq.A.
Sequences Jordi Cortadella Department of Computer Science.
The Integers. The Division Algorithms A high-school question: Compute 58/17. We can write 58 as 58 = 3 (17) + 7 This forms illustrates the answer: “3.
Data structure design Jordi Cortadella Department of Computer Science.
Polynomials Jordi Cortadella Department of Computer Science.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Greatest Common Divisor Jordi Cortadella Department of Computer Science.
First steps Jordi Cortadella Department of Computer Science.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
For loops, nested loops and scopes Jordi Cortadella Department of Computer Science.
Introduction to Programming (in C++) Numerical algorithms Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
More on Efficiency Issues. Greatest Common Divisor given two numbers n and m find their greatest common divisor possible approach –find the common primes.
Chapter 4: Elementary Number Theory and Methods of Proof 4.8 Application: Algorithms 1 Begin at the beginning…and go on till you come to the end: then.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Control of flow We learned that default flow of instructions is sequential. Then, we learned how to control the flow using "if" and "switch." Now, we will.
Introduction to Programming (in C++) Multi-dimensional vectors Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Application: Algorithms Lecture 20 Section 3.8 Wed, Feb 21, 2007.
Vectors Jordi Cortadella Department of Computer Science.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 2 September 3, 2009.
Application: Algorithms Lecture 19 Section 3.8 Tue, Feb 20, 2007.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
Ch04-Number Theory and Cryptography 1. Introduction to Number Theory Number theory is about integers and their properties. We will start with the basic.
Number Theory Lecture 1 Text book: Discrete Mathematics and its Applications, 7 th Edition.
Number Theory. Introduction to Number Theory Number theory is about integers and their properties. We will start with the basic principles of divisibility,
Basic concepts of C++ Presented by Prof. Satyajit De
Jordi Cortadella, Ricard Gavaldà, Fernando Orejas
Chapter 4 (Part 3): Mathematical Reasoning, Induction & Recursion
Introduction to C++ Programming Language
REPETITION CONTROL STRUCTURE
For loops, nested loops and scopes
Programming Fundamentals
Number Theory (Chapter 7)
Introduction to C++ Programming
CS1100 Computational Engineering
Loops (iterations, repetitions)
Jordi Cortadella Department of Computer Science
Application: Algorithms
Application: Algorithms
Programming Fundamental
Presentation transcript:

Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example Assume the following specification: Input: read a number N > 0 Output: write the sequence … N (one number per line) This specification suggests some algorithm with a repetitive procedure. Introduction to Programming© Dept. CS, UPC2

The while statement Syntax: while (  condition  ) statement; (the condition must return a Boolean value) Semantics: – Similar to the repetition of an if statement – The condition is evaluated: If true, the statement is executed and the control returns to the while statement again. If false, the while statement terminates. Introduction to Programming© Dept. CS, UPC3

Write the numbers 1…N // Input: read a number N > 0 // Output: write the numbers 1...N (one per line) int main() { int N; cin >> N; int i = 1; while (i <= N) { // The numbers 1..i-1 have been written cout << i << endl; i = i + 1; } Introduction to Programming© Dept. CS, UPC4

Product of two numbers //Input: read two non-negative numbers x and y //Output: write the product xy // Constraint: do not use the  operator // The algorithm calculates the sum x+x+x+…+x (y times) int main() { int x, y; cin >> x >> y; // Let x=A, y=B int p = 0; // Invariant: AB = p + xy while (y > 0) { p = p + x; y = y – 1; } cout << p << endl; } Introduction to Programming© Dept. CS, UPC5

A quick algorithm for the product Let p be the product x  y Observation – If y is even, p = (x  2)  (y/2) – If y is odd, p = x  (y-1) + x and (y-1) becomes even Example: 17  38 = 646 Introduction to Programming© Dept. CS, UPC6 xy pp

A quick algorithm for the product int main() { int x, y; cin >> x >> y; // Let x=A, y=B int p = 0; // Invariant: AB = p + xy while (y > 0) { if (y%2 == 0) { x = x2; y = y/2; } else { p = p + x; y = y – 1; } cout << p << endl; } Introduction to Programming© Dept. CS, UPC7 xyp

Why is the quick product interesting? Most computers have a multiply instruction in their machine language. The operations x  2 and y/2 can be implemented as 1-bit left and right shifts, respectively. So, the multiplication can be implemented with shift and add operations. The quick product algorithm is the basis for hardware implementations of multipliers and mimics the paper-and-pencil method learned at school (but using base 2). Introduction to Programming© Dept. CS, UPC8

Quick product in binary: example 77 x 41 = x Introduction to Programming© Dept. CS, UPC9

Counting a’s We want to read a text represented as a sequence of characters that ends with ‘.’ We want to calculate the number of occurrences of the letter ‘a’ We can assume that the text always has at least one character (the last ‘.’) Example: the text Programming in C++ is amazingly easy!. has 4 a’s Introduction to Programming© Dept. CS, UPC10

Counting a’s // Input: sequence of characters that ends with ‘.’ // Output: number of times ‘a’ appears in the // sequence int main() { char c; cin >> c; int count = 0; // Inv: count is the number of a’s in the visited // prefix of the sequence. c contains the next // non-visited character while (c != ‘.’) { if (c == ‘a’) count = count + 1; cin >> c; } cout << count << endl; } Introduction to Programming© Dept. CS, UPC11

Counting digits We want to read a non-negative integer and count the number of digits (in radix 10) in its textual representation. Examples  7 digits 156  3 digits 8  1 digit 0  1 digit (note this special case) Introduction to Programming© Dept. CS, UPC12

Counting digits // Input: a non-negative number N // Output: number of digits in N (0 has 1 digit) int main() { int N; cin >> N; int ndigits = 0; // Inv: ndigits contains the number of digits in the // tail of the number, N contains the remaining // part (head) of the number while (N > 9) { ndigits = ndigits + 1; N = N/10; // extracts one digit } cout << ndigits + 1 << endl; } Introduction to Programming© Dept. CS, UPC13

Euclid’s algorithm for gcd Properties – gcd(a,a)=a – If a > b, then gcd(a,b) = gcd(a-b,b) Example Introduction to Programming© Dept. CS, UPC14 ab gcd (114, 42)

Euclid’s algorithm for gcd // Input: read two positive numbers (a and b) // Output: write gcd(a,b) int main() { int a, b; cin >> a >> b; // Let a=A, b=B // gcd(A,B) = gcd(a,b) while (a != b) { if (a > b) a = a – b; else b = b – a; } cout << a << endl; } Introduction to Programming© Dept. CS, UPC15

Faster Euclid’s algorithm for gcd Properties – gcd(a, 0)=a – If b > 0 then gcd(a, b) = gcd(b, a mod b) Example Introduction to Programming© Dept. CS, UPC16 ab

Faster Euclid’s algorithm for gcd // Input: read two positive numbers (a and b) // Output: write gcd(a,b) int main() { int a, b; cin >> a >> b; // Let a=A, b=B // gcd(A,B) = gcd(a,b) while (b != 0) { int r = a%b; a = b; b = r; // Guarantees b < a (loop termination) } cout << a << endl; } Introduction to Programming© Dept. CS, UPC17

Efficiency of Euclid’s algorithm How many iterations will Euclid’s algorithm need to calculate gcd(a,b) in the worst case (assume a > b)? – Subtraction version: a iterations (consider gcd(1000,1)) – Modulo version:  5  d(b) iterations, where d(b) is the number of digits of b represented in base 10 (proof by Gabriel Lamé, 1844) Introduction to Programming© Dept. CS, UPC18

Solving a problem several times In many cases, we might be interested in solving the same problem for several input data. Example: calculate the gcd of several pairs of natural numbers. Introduction to Programming© Dept. CS, UPC19 Input Output

Solving a problem several times // Input: several pairs of natural numbers at the input // Output: the gcd of each pair of numbers written at the output int main() { int a, b; // Inv: the gcd of all previous pairs have been // calculated and written at the output while (cin >> a >> b) { // A new pair of numbers from the input while (b != 0) { int r = a%b; a = b; b = r; } cout << a << endl; } Introduction to Programming© Dept. CS, UPC20 Calculate gcd(a,b) and write the result into cout

Solving a problem several times // Input: several pairs of natural numbers at the input // Output: the gcd of each pair of numbers written at the output int main() { int a, b; // Inv: the gcd of all previous pairs have been // calculated and written at the output while (cin >> a >> b) { // A new pair of numbers from the input while (b != 0) { int r = a%b; a = b; b = r; } cout << a << endl; } Introduction to Programming© Dept. CS, UPC21

Prime number 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. Introduction to Programming© Dept. CS, UPC22

Prime number // Input: read a natural number N>0 // Output: write “is prime” or “is not prime” depending on // the primality of the number int main() { int N; cin >> N; int divisor = 2; bool is_prime = (N != 1); // 1 is not prime, 2 is prime, the rest enter the loop (assume prime) // is_prime is true while a divisor is not found // and becomes false as soon as the first divisor is found while (divisor < N) { if (N%divisor == 0) is_prime = false; divisor = divisor + 1; } if (is_prime) cout << “is prime” << endl; else cout << “is not prime” << endl; } Introduction to Programming© Dept. CS, UPC23

Prime number 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. Introduction to Programming© Dept. CS, UPC24

Prime number // Input: read a natural number N>0 // Output: write “is prime” or “is not prime” depending on // the primality of the number int main() { int N; cin >> N; int divisor = 2; bool is_prime = (N != 1); while (is_prime and divisor < N) { is_prime = N%divisor != 0; divisor = divisor + 1; } if (is_prime) cout << “is prime” << endl; else cout << “is not prime” << endl; } Introduction to Programming© Dept. CS, UPC25

Prime number: doing it faster If N is not prime, we can find two numbers, a and b, such that: N = a  b, with 1 < a  b <N and with the following property: a   N There is no need to find divisors up to N-1. We can stop much earlier. Note: a   N is equivalent to a 2  N Introduction to Programming© Dept. CS, UPC26

Prime number: doing it faster // Input: read a natural number N>0 // Output: write “is prime” or “is not prime” depending on // the primality of the number int main() { int N; cin >> N; int divisor = 2; bool is_prime = (N != 1); while (is_prime and divisordivisor <= N) { is_prime = N%divisor != 0; divisor = divisor + 1; } if (is_prime) cout << “is prime” << endl; else cout << “is not prime” << endl; } Introduction to Programming© Dept. CS, UPC27

Is there any real difference? Introduction to Programming© Dept. CS, UPC28 Iterations Number of bits

In real time (N= ) > time prime_slow < number is prime u 0.004s 0: % > time prime_fast < number is prime 0.004u 0.000s 0: % Introduction to Programming© Dept. CS, UPC29

The for statement Very often we encounter loops of the form: i = N; while (i <= M) { do_something; i = i + 1; } This can be rewritten as: for (i = N; i <= M; i = i + 1) { do_something; } Introduction to Programming© Dept. CS, UPC30

The for statement In general for (  S_init  ;  condition  ;  S_iter  )  S_body  ; is equivalent to: S_init; while (  condition  ) {  S_body  ;  S_iter  ; } Introduction to Programming© Dept. CS, UPC31

Writing the numbers in an interval // Input: read two integer numbers, N and M, // such that N <= M. // Output: write all the integer numbers in the // interval [N,M] int main() { int N, M; cin >> N >> M; for (int i = N; i <= M; ++i) cout << i << endl; } Introduction to Programming© Dept. CS, UPC32 Variable declared within the scope of the loop Autoincrement operator

Calculate x y // Input: read two integer numbers, x and y, such that y >= 0 // Output: write x y int main() { int x, y; cin >> x >> y; int p = 1; for (int i = 0; i < y; ++i) p = px; cout << p << endl; } Introduction to Programming© Dept. CS, UPC33

Drawing a triangle Given a number n (e.g. n = 6), we want to draw this triangle: * ** *** **** ***** ****** Introduction to Programming© Dept. CS, UPC34

Drawing a triangle // Input: read a number n > 0 // Output: write a triangle of size n int main() { int n; cin >> n; // Inv: the rows 1..i-1 have been written for (int i = 1; i <= n; ++i) { // Inv: ‘’ written j-1 times in row i for (int j = 1; j <= i; ++j) cout << ‘’; cout << endl; } Introduction to Programming© Dept. CS, UPC35

Perfect numbers A number n > 0 is perfect if it is equal to the sum of all its divisors except itself. Examples – 6 is a perfect number (1+2+3 = 6) – 12 is not a perfect number (  12) Strategy – Keep adding divisors until the sum exceeds the number or there are no more divisors. Introduction to Programming© Dept. CS, UPC36

Perfect numbers // Input: read a number n > 0 // Output: write a message indicating // whether it is perfect or not int main() { int n; cin >> n; int sum = 0, d = 1; // Inv: sum is the sum of all divisors until d-1 while (d <= n/2 and sum <= n) { if (n%d == 0) sum += d; d = d + 1; } if (sum == n) cout << “is perfect” << endl; else cout << “is not perfect” << endl; } Introduction to Programming© Dept. CS, UPC37

Perfect numbers Would the program work using the following loop condition? while (d <= n/2 and sum < n) Can we design a more efficient version without checking all the divisors until n/2? – Clue: consider the most efficient version of the program to check whether a number is prime. Introduction to Programming© Dept. CS, UPC38