For loops, nested loops and scopes

Slides:



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

Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Computer Science 1620 Loops.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
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.
CS150 Introduction to Computer Science 1
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
1 10/9/06CS150 Introduction to Computer Science 1 for Loops.
Summary of Loops Programming. COMP102 Prog Fundamentals I: Summary of Loops /Slide 2 Which Loop to Use? l for loop n for calculations that are repeated.
Exercise 5.
Arrays.
Introduction to Programming (in C++) Vectors Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of 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.
Reasoning with invariants Jordi Cortadella Department of Computer Science.
Data types and their representation Jordi Cortadella Department of Computer Science.
Matrices Jordi Cortadella Department of Computer Science.
Prime numbers Jordi Cortadella Department of Computer Science.
The power of logarithmic computations Jordi Cortadella Department of Computer Science.
CS1201: Programming Language 2 Recursion By: Nouf Almunyif.
Recursion Jordi Cortadella Department of Computer Science.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Introduction to Programming (in C++) Algorithms on sequences. Reasoning about loops: Invariants. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept.
Sequences Jordi Cortadella Department of Computer Science.
Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
Looping II (for statement). CSCE 1062 Outline  for statement  Nested loops  Compound assignment operators  Increment and decrement operators.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
Sudoku Jordi Cortadella Department of Computer Science.
 Wednesday, 9/18/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/18/02  QUESTIONS?? HW #1 due today at 5!!  Today: Loops, and two new data types.
First steps Jordi Cortadella Department of Computer Science.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
For loops, nested loops and scopes Jordi Cortadella Department of Computer Science.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
Overview Go over parts of quiz? Another iteration structure for loop.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Introduction to Programming (in C++) Multi-dimensional vectors Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Vectors Jordi Cortadella Department of Computer Science.
1 2/2/05CS250 Introduction to Computer Science II Pointers.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
CS 161 Introduction to Programming and Problem Solving Chapter 17 Nested Loops Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.
Parameter passing Jordi Cortadella Department of Computer Science.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Functions Jordi Cortadella Department of Computer Science.
Introduction to Programming Lecture 12. Today’s Lecture Includes Strings ( character arrays ) Strings ( character arrays ) Algorithms using arrays Algorithms.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC530 Data Structures - LOOP 7/9/20161.
Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)
Jordi Cortadella, Ricard Gavaldà, Fernando Orejas
Reasoning with invariants
for Repetition Structures
Intro to Programming Week # 6 Repetition Structure Lecture # 10
Jordi Cortadella Department of Computer Science
Chapter 8 Repetition Statements
Counting Loops.
Cs212: DataStructures Computer Science Department Lab 3 : Recursion.
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
Let’s all Repeat Together
CS150 Introduction to Computer Science 1
INC 161 , CPE 100 Computer Programming
Jordi Cortadella Department of Computer Science
do/while Selection Structure
CS150 Introduction to Computer Science 1
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Presentation transcript:

For loops, nested loops and scopes Jordi Cortadella Department of Computer Science

Outline For loops Scopes Nested loops Introduction to Programming © Dept. CS, UPC

Calculate xy Algorithm: repeated multiplication x  x  x    x y x y times y x i p=xi 4 3 1 2 9 27 81 Introduction to Programming © Dept. CS, UPC

Calculate xy // Pre: y  0 // Returns xy int power(int x, int y) { int p = 1; int i = 0; while (i < y) { // Repeat y times p = px; i = i + 1; // p = xi } return p; } Introduction to Programming © Dept. CS, UPC

Calculate xy // Pre: y  0 // Returns xy int power(int x, int y) { int p = 1; for (int i = 0; i < y; i = i + 1) { p = px; } return p; } int i = 0; while (i < y) { p = px; i = i + 1; } Introduction to Programming © Dept. CS, UPC

Calculate xy // Pre: y  0 // Returns xy int power(int x, int y) { int p = 1; for (int i = 0; i < y; ++i) p = px; return p; } i = i + 1 int i = 0; while (i < y) { p = px; i = i + 1; } Introduction to Programming © Dept. CS, UPC

Factorial // Pre: n  0 // Returns n! int factorial(int n) { int f = 1; for (int i = 1; i <= n; ++i) f = fi; return f; } int factorial(int n) { int f = 1; for (int i = n; i > 0; --i) f = fi; return f; } Introduction to Programming © Dept. CS, UPC

Up-down sequence Write a program that reads a positive integer n and prints and up-down sequence (one number per line) Example (n=6): 1 2 3 4 5 6 5 4 3 2 1 Introduction to Programming © Dept. CS, UPC

Up-down sequence // This program reads a positive integer (n) // and prints and up-down sequence // (one number per line). // Example: 1 2 3 … n-1 n n-1 … 3 2 1 int main() { int n; cin >> n; // up sequence: 1 2 3 … n-2 n-1 n for (int i = 1; i <= n; ++i) cout << i << endl; // down sequence: n-1 n-2 … 3 2 1 for (int i = n - 1; i > 0; --i) cout << i << endl; } Same name, different variables Introduction to Programming © Dept. CS, UPC

Summary A for loop is a special type of repetitive statement with a loop counter. It is naturally used when the number of iterations is known before entering the loop. Recommendations: Declare the loop counter locally (when possible). Update the loop counter by a constant (++i, --i). Do not modify the loop counter inside the for loop. Introduction to Programming © Dept. CS, UPC

Sort three numbers Different variables // This program reads three numbers and // prints the same numbers in ascending order. int main() { int x, y, z; cin >> x >> y >> z; if (x > y) { // Swap x  y int t = x; x = y; y = t; } // We know that x  y if (y > z) { // Swap y  z int t = y; y = z; z = t; } // We know that z is the largest number if (x > y) { // Swap x  y int t = x; x = y; y = t; } // We know that x  y  z cout << x << " " << y << " " << z << endl; } 9 5 2 Different variables 5 9 2 5 2 9 2 5 9 Introduction to Programming © Dept. CS, UPC

min and max are not visible Print min and max // This program reads two numbers and prints // the minimum and the maximum (in this order). int main() { int x, y; cin >> x >> y; if (x > y) { int min = y; int max = x; } else { int min = x; int max = y; } cout << min << " " << max << endl; } Wrong! min and max are not visible Introduction to Programming © Dept. CS, UPC

Print min and max Scope for min and max // This program reads two numbers and prints // the minimum and the maximum (in this order). int main() { int x, y; cin >> x >> y; int min, max; if (x > y) { min = y; max = x; } else { min = x; max = y; } cout << min << " " << max << endl; } Scope for min and max Introduction to Programming © Dept. CS, UPC

Scopes and visibility { // a and b are not visible int a = 1, b = 20; // a and b are visible cout << a << endl; // prints 1 { // c is not visible, a and b are visible cout << a + b << endl; // prints 21 int b = 5, c = 4; // a, c and the inner b are visible, // but the outer b is not visible cout << a + b << endl; // prints 6 cout << c << endl; // prints 4 } // c is not visible cout << b << endl; // prints 20 } Introduction to Programming © Dept. CS, UPC

Summary Variables are only visible within their scope. Recommendations: Declare and use variables as locally as possible. When possible, initialize variables with their declaration. Use meaningful names (e.g., min, count, avg, …) Do not try to reuse variables: fewer variables does not imply less memory. Introduction to Programming © Dept. CS, UPC

Drawing a rectangle Write a program that reads the dimensions of a rectangle (x, y) and prints x columns and y rows of asterisks. Example (x=8, y=5):      Introduction to Programming © Dept. CS, UPC

Drawing a rectangle // Reads the dimensions (x, y) of a rectangle // and prints x columns and y rows of asterisks. int main() { int x, y; cin >> x >> y; drawRectangle(x, y); } Introduction to Programming © Dept. CS, UPC

Drawing a rectangle // Prints a rectangle with <ncols> columns and // <nrows> rows of asterisks. void drawRectangle(int ncols, int nrows) { for (int i = 0; i < nrows; ++i) { printRow(ncols); } } // Prints a row of n asterisks. void printRow(int n) { for (int i = 0; i < n; ++i) cout << ""; cout << endl; } Introduction to Programming © Dept. CS, UPC

Ordered declaration of functions void printRow(int n) { . . . } void drawRectangle(int ncols, int nrows) { . . . // uses printRow } int main() { . . . // uses drawRectangle } Introduction to Programming © Dept. CS, UPC

Drawing a rectangle: nested loops // Reads the dimensions (x, y) of a rectangle // and prints x columns and y rows of asterisks. int main() { int x, y; cin >> x >> y; for (int r = 0; r < y; ++r) { for (int c = 0; c < x; ++c) cout << ""; cout << endl; } } Print row with x asterisks Introduction to Programming © Dept. CS, UPC

Drawing a right equilateral triangle Write a program that reads an integer n and prints a right equilateral triangle with the length of the cathetus being n. Example (n=7):        Introduction to Programming © Dept. CS, UPC

Drawing a right equilateral triangle Observation: row r has r asterisks        row r Introduction to Programming © Dept. CS, UPC

Drawing a right equilateral triangle // Reads an integer n and prints a right // equilateral triangle with the length // of the cathetus being n. int main() { int n; cin >> n; for (int r = 1; r <= n; ++r) { for (int c = 0; c < ?; ++c) cout << ""; cout << endl; } } Print row r with r asterisks Introduction to Programming © Dept. CS, UPC

Drawing a right equilateral triangle // Reads an integer n and prints a right // equilateral triangle with the length // of the cathetus being n. int main() { int n; cin >> n; for (int r = 1; r <= n; ++r) { for (int c = 0; c < r; ++c) cout << ""; cout << endl; } } Introduction to Programming © Dept. CS, UPC

Exercises Draw the following shapes (for any n):    oooo oooo oooo oooo Chess board Introduction to Programming © Dept. CS, UPC

Summary Nested loops are useful when treating multi-dimensional data, e.g., rows/columns, height/width, matrices, etc. Recommendations: Use for loops if the number of iterations is known before entering the loop. Use a different local counter for each loop. Introduction to Programming © Dept. CS, UPC