*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Similar documents
5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Chapter 5: Loops and Files

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Looping. Arizona State University 1

Increment and the While. Class 15

Lecture 7 Tao Wang 1

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

REPETITION CONTROL STRUCTURE LOGO

LECTURE 04 MAKING DECISIONS

Object-Oriented Programming in Java

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Repetition Structures

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

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

LECTURE 5 Control Structures Part 2

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Repetition and Loop Statements Chapter 5

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

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

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

LECTURE 06 FUNCTIONS

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

Introduction. C provides two styles of flow control:

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Chapter 5: Control Structures II (Repetition)

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

Quiz Determine the output of the following program:

LECTURE 02 INTRODUCTION TO C++

C++ Programming: From Problem Analysis to Program Design, Third Edition

Control Structures of C++ Programming (2)

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

CS110D: PROGRAMMING LANGUAGE I

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Chapter 4: Loops and Files

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

A Beginner s Guide to Programming Logic, Introductory. Chapter 5 Looping

204111: Computer and Programming

Control Structures II. Repetition (Loops)

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Repetition CSC 121 Fall 2014 Howard Rosenthal

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Lecture # 6. Repetition. Review. If Else Statements Comparison Operators Boolean Expressions Nested Ifs. Switch Statements.

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Why Is Repetition Needed?

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

In this chapter you will learn:

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

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Loops and Files. of do-while loop

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

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

Chapter 4: Control structures. Repetition

Programming for Engineers Iteration

C/C++ Programming Lecture 7 Name:

Loops / Repetition Statements

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.

Structured Programming. Dr. Mohamed Khedr Lecture 9

Chapter 4: Control structures

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

CSCE 206: Structured Programming in C++

Chapter 3. More Flow of Control

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

Add Subtract Multiply Divide

Chapter 7. Additional Control Structures

Repetition Structures II

Lecture 7: General Loops (Chapter 7)

STUDENT LESSON A12 Iterations

LECTURE 11 STRUCTURED DATA

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

Chapter 3 Structured Program Development in C Part II

Repetition, Looping CS101

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Iterative Languages. Scoping

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Example of Objective Test Questions for Test 4

ECE 122. Engineering Problem Solving with Java

Computer Programming I - Unit 5 Lecture page 1 of 14

DELHI PUBLIC SCHOOL TAPI

CSCI 1061U Programming Workshop 2. C++ Basics

Chapter 5 : Repetition (pp )

Chapter 4: Loops and Files

Information Science 1

Information Science 1

Name SECTION: 12:45 2:20. True or False (12 Points)

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Transcription:

PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN ASSISTANT PROFESSOR AIR UNIVERSITY, ISLAMABAD THE INCREMENT AND DECREMENT OPERATORS ++, -- ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1; ++ can be used before (prefix) or after (postfix) a variable: ++val; val++; -- is the decrement operator. It subtracts one from a variable. val--; is the same as val = val - 1; -- can be also used before (prefix) or after (postfix) a variable: --val; val--; 2 Lecture 05 - Loops 1

THE INCREMENT AND DECREMENT OPERATORS IN PROGRAM 3 THE INCREMENT AND DECREMENT OPERATORS IN PROGRAM 4 Lecture 05 - Loops 2

PREFIX VS. POSTFIX ++ and -- operators can be used in complex statements and expressions In prefix mode (++val, --val) the operator increments or decrements, then returns the value of the variable In postfix mode (val++, val--) the operator returns the value of the variable, then increments or decrements int num, val = 12; cout << val++; // displays 12, // val is now 13; cout << ++val; // sets val to 14, // then displays it num = --val; // sets val to 13, // stores 13 in num num = val--; // stores 13 in num, // sets val to 12 5 NOTES ON INCREMENT AND DECREMENT Can be used in expressions: result = num1++ + --num2; Must be applied to something that has a location in memory. Cannot have: result = (num1 + num2)++; Can be used in relational expressions: if (++num > limit) pre- and post-operations will cause different comparisons 6 Lecture 05 - Loops 3

THE WHILE LOOP INTRODUCTION Loop: a control structure that causes a statement or statements to repeat General format of the while loop: while (expression) statement; statement; can also be a block of statements enclosed in { } while (expression) statement; expression is evaluated if true, then statement is executed, and expression is evaluated again if false, then the loop is finished and program statements following statement execute 7 THE WHILE LOOP IN PROGRAM 8 Lecture 05 - Loops 4

THE WHILE LOOP LINE 9 TO 13 9 THE WHILE LOOP 10 Lecture 05 - Loops 5

THE WHILE LOOP expression is evaluated before the loop executes. The following loop will never execute: int number = 6; while (number <= 5) { cout << "Hello\n"; number++; } 11 THE WHILE LOOP WATCH OUT FOR INFINITE LOOPS The loop must contain code to make expression become false Otherwise, the loop will have no way of stopping Such a loop is called an infinite loop, because it will repeat an infinite number of times int number = 1; while (number <= 5) { cout << "Hello\n"; } 12 Lecture 05 - Loops 6

THE WHILE LOOP INPUT VALIDATION Input validation is the process of inspecting data that is given to the program as input and determining whether it is valid. The while loop can be used to create input routines that reject invalid data, and repeat until valid data is entered. Here's the general approach, in pseudocode: Read an item of input. While the input is invalid Display an error message. Read the input again. End While 13 THE WHILE LOOP EXAMPLE cout << "Enter a number less than 10: "; cin >> number; while (number >= 10) { cout << "Invalid Entry!" << "Enter a number less than 10: "; cin >> number; } 14 Lecture 05 - Loops 7

THE WHILE LOOP IN PROGRAM 15 COUNTERS Counter: a variable that is incremented or decremented each time a loop repeats Can be used to control execution of the loop (also known as the loop control variable) Must be initialized before entering loop 16 Lecture 05 - Loops 8

COUNTER IN PROGRAM 17 THE DO-WHILE LOOP do-while: a posttest loop execute the loop, then test the expression General Format: do statement; // or block in { } while (expression); Note that a semicolon is required after (expression) 18 Lecture 05 - Loops 9

THE DO-WHILE LOOP AN EXAMPLE int x = 1; do { cout << x << endl; } while(x < 0); Although the test expression is false, this loop will execute one time because do-while is a posttest loop. 19 THE DO-WHILE LOOP IN PROGRAM 20 Lecture 05 - Loops 10

THE DO-WHILE LOOP IN PROGRAM 21 THE FOR LOOP Useful for counter-controlled loop General Format: for(initialization; test; update) statement; // or block in { } No semicolon after the update expression or after the ) 22 Lecture 05 - Loops 11

THE FOR LOOP MECHANICS for(initialization; test; update) statement; // or block in { } 1. Perform initialization 2. Evaluate test expression 1. If true, execute statement 2. If false, terminate loop execution 3. Execute update, then re-evaluate test expression 23 THE FOR LOOP 24 Lecture 05 - Loops 12

THE FOR LOOP EXAMPLE int count; for (count = 1; count <= 5; count++) cout << "Hello" << endl; 25 THE FOR LOOP FLOWCHART 26 Lecture 05 - Loops 13

THE FOR LOOP IN PROGRAM 27 THE FOR LOOP PROGRAM OUTPUT 28 Lecture 05 - Loops 14

THE FOR LOOP STEPS 29 THE FOR LOOP FLOWCHART 30 Lecture 05 - Loops 15

WHEN TO USE THE FOR LOOP In any situation that clearly requires an initialization a false condition to stop the loop an update to occur at the end of each iteration 31 THE FOR LOOP IS A PRETEST LOOP The for loop tests its test expression before each iteration, so it is a pretest loop. The following loop will never iterate: for (count = 11; count <= 10; count++) cout << "Hello" << endl; 32 Lecture 05 - Loops 16

FOR LOOP - MODIFICATIONS You can have multiple statements in the initialization expression. Separate the statements with a comma: Initialization Expression int x, y; for (x=1, y=1; x <= 5; x++) { cout << x << " plus " << y << " equals " << (x+y) << endl; } 33 FOR LOOP - MODIFICATIONS You can also have multiple statements in the test expression. Separate the statements with a comma: int x, y; for (x=1, y=1; x <= 5; x++, y++) { cout << x << " plus " << y << " equals " << (x+y) << endl; } Test Expression 34 Lecture 05 - Loops 17

FOR LOOP - MODIFICATIONS You can omit the initialization expression if it has already been done: int sum = 0, num = 1; for (; num <= 10; num++) sum += num; 35 FOR LOOP - MODIFICATIONS You can declare variables in the initialization expression: int sum = 0; for (int num = 0; num <= 10; num++) sum += num; The scope of the variable num is the for loop. 36 Lecture 05 - Loops 18

KEEPING A RUNNING TOTAL running total: accumulated sum of numbers from each repetition of loop accumulator: variable that holds running total int sum=0, num=1; // sum is the while (num <= 10) // accumulator { sum += num; num++; } cout << "Sum of numbers 1 10 is" << sum << endl; 37 KEEPING A RUNNING TOTAL FLOWCHART 38 Lecture 05 - Loops 19

KEEPING A RUNNING TOTAL IN PROGRAM 39 KEEPING A RUNNING TOTAL OUTPUT 40 Lecture 05 - Loops 20

SENTINELS sentinel: value in a list of values that indicates end of data Special value that cannot be confused with a valid value, e.g., -999 for a test score Used to terminate input when user may not know how many values will be entered 41 SENTINELS IN PROGRAM 42 Lecture 05 - Loops 21

SENTINELS OUTPUT 43 DECIDING WHICH LOOP TO USE The while loop is a conditional pretest loop Iterates as long as a certain condition exits Validating input Reading lists of data terminated by a sentinel The do-while loop is a conditional posttest loop Always iterates at least once Repeating a menu The for loop is a pretest loop Built-in expressions for initializing, testing, and updating Situations where the exact number of iterations is known 44 Lecture 05 - Loops 22

NESTED LOOPS A nested loop is a loop inside the body of another loop Inner (inside), outer (outside) loops: for (row=1; row<=3; row++) //outer for (col=1; col<=3; col++)//inner cout << row * col << endl; 45 NESTED LOOPS IN PROGRAM Inner Loop Outer Loop 46 Lecture 05 - Loops 23

NESTED LOOPS NOTES Inner loop goes through all repetitions for each repetition of outer loop Inner loop repetitions complete sooner than outer loop Total number of repetitions for inner loop is product of number of repetitions of the two loops. 47 Lecture 05 - Loops 24