Computer Programming

Similar documents
Computer Programming

Computer Programming

Computer Programming

Computer Programming

Computer Programming

Computer Programming

Computer Programming

Computer Programming

Computer Programming

Lecture Transcript While and Do While Statements in C++

Computer Programming

Computer Programming

Computer Programming

Computer Programming

Computer Programming

Computer Programming

Computer Programming

Computer Programming

Computer Programming

Computer Programming

Computer Programming

Computer Programming

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming

Computer Programming

Computer Programming

Computer Programming

LECTURE 5 Control Structures Part 2

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

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Unit 7. 'while' Loops

Lecture 7: General Loops (Chapter 7)

CS 101 Computer Programming and utilization. Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay

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

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

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

Concepts Review. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++.

CS110D: PROGRAMMING LANGUAGE I

Arrays in C++ Instructor: Andy Abreu

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

Errata for C++ and Algorithmic Thinking for the Complete Beginner

Control Structures in Java if-else and switch

Introduction to C++ Lecture Set 2. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 1

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

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

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

Score score < score < score < 65 Score < 50

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

Computers and FORTRAN Language Fortran 95/2003. Dr. Isaac Gang Tuesday March 1, 2011 Lecture 3 notes. Topics:

Outline. For loops, nested loops and scopes. Calculate x y. For loops. Scopes. Nested loops. Algorithm: repeated multiplication x x x x

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

Introduction to Algorithms and Programming (COMP151)

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

Chapter 5: Control Structures II (Repetition)

Control Structures. A program can proceed: Sequentially Selectively (branch) - making a choice Repetitively (iteratively) - looping

Computer Programming. Dr. Deepak B Phatak Dr. Supratik Chakraborty Department of Computer Science and Engineering IIT Bombay

Add Subtract Multiply Divide

REPETITION CONTROL STRUCTURE LOGO

CSCI 111 First Midterm Exam Spring Solutions 09.05am 09.55am, Wednesday, March 14, 2018

C++ Final Exam 2017/2018

Functions! Objectives! 1E3! Topic 9! programming! n This topic should allow students to! n Read chapter 6 of the textbook now.!

Computer Department. Question (1): State whether each of the following is true or false. Question (2): Select the correct answer from the following:

CS Semester I. Quiz 1 (version A)

Arrays array array length fixed array fixed length array fixed size array Array elements and subscripting

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

CHAPTER : 9 FLOW OF CONTROL

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

2 is type double 3 auto i = 1 + 2; // evaluates to an 4 integer, so it is int. 1 auto d = 5.0; // 5.0 is a double literal, so it

CS112 Lecture: Repetition Statements

CS 101 Computer Programming and Utilization. Lecture 5, More Numerical computing (Slides courtesy Prof Ranade)

1 Memory management in C++

Practice question Answers

Increment and the While. Class 15

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

Chapter Five: Functions. by Cay Horstmann Copyright 2018 by John Wiley & Sons. All rights reserved

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

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

Computer Science II Lecture 1 Introduction and Background

Chapter 4 Computation

Chapter 01 Arrays Prepared By: Dr. Murad Magableh 2013

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

LAB 4.1 Relational Operators and the if Statement

Chapter 4. Computation. Bjarne Stroustrup.

Control Structures in Java if-else and switch

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

CS112 Lecture: Loops

Class 2: Variables and Memory. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Outline. Introduction to Programming (in C++) Introduction. First program in C++ Programming examples

In this chapter you will learn:

1. In C++, reserved words are the same as predefined identifiers. a. True

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points)

Data Types and the while Statement

CSc 10200! Introduction to Computing. Lecture 1 Edgardo Molina Fall 2013 City College of New York

EAS230: Programming for Engineers Lab 1 Fall 2004

Introduction to Programming

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Lecture 7 Tao Wang 1

7/21/10 MOTIVATION. Did you see Inception this weekend? COMP 10 EXPLORING COMPUTER SCIENCE. Lecture 6 Arrays

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

CS 105 Lecture 5 Logical Operators; Switch Statement. Wed, Feb 16, 2011, 5:11 pm

Transcription:

Computer Programming Dr. Deepak B Phatak Dr. Supratik Chakraborty Department of Computer Science and Engineering Session: Iteration Idioms: Motivation Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 1

Quick Recap of Relevant Topics Structure of a simple C++ program Sequential execution of statements Conditional execution of statements Programming to solve simple problems 2 Dr. Deepak B. Phatak & Dr. Supratik Chakraborty,

Overview of This Lecture Need for iteration in programming Convenience Necessity Intuitive programming Generic iteration construct Iteration constructs in C++ 3 Dr. Deepak B. Phatak & Dr. Supratik Chakraborty,

A Simple Problem Read quiz 1 marks of ten CS101 students and print their sum, average, maximum and minimum Can we solve using what we ve learnt so far? assignment statements, input/output statements arithmetic expressions sequential and conditional execution of statements Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 4

Overall Strategy Maintain running sum, max and min (aggregates) Initialize aggregates Read input 1 and update aggregates Read input 2 and update aggregates Read input 10 and update aggregates Compute average as sum/10 Output sum, average, max, min Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 5

A Simple Flowchart Initialize aggregates Ask for input 9 Read input 9 Update aggregates Ask for input 1 Read input 1 Update aggregates Ask for input 3 Read input 3 Update aggregates Ask for input 10 Read input 10 Update aggregates Ask for input 2 Read input 2 Update aggregates Ask for input 4 Read input 4 Update aggregates average = sum/10 Output average, sum, min, max Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 6

C++ Program int main() { // Variable declarations int marks, sum, min, max; float average; // Initialization of aggregates sum = 0; average = 0; // Further code comes here return 0; Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 7

C++ Program int main() { // Variable declarations and initialization of sum and average cout << Give quiz marks of student 1: ; cin >> marks; sum = sum + marks; // Initialize min and max with first input min = marks; max = marks; // Further code comes here return 0; Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 8

C++ Program int main() { // Variable declarations and initialization of sum and average // Read marks of student 1, and update aggregates cout << Give quiz marks of student 2: ; cin >> marks; sum = sum + marks; min = (min > marks)? marks: min; max = (max < marks)? marks: max; // Further code comes here return 0; Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 9

C++ Program int main() { // Variable declarations and initialization of sum and average // Read marks of students 1 and 2, and update aggregates cout << Give quiz marks of student 3: ; cin >> marks; sum = sum + marks; min = (min > marks)? marks: min; max = (max < marks)? marks: max; // Further code comes here return 0; Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 10

C++ Program int main() { // Variable declarations and initialization of sum and average // Read marks of students1, 2 10, and update aggregates // Calculate and print aggregates average = sum/10.0; cout << Average: << average << Sum: << sum; cout << Min: << min << Max: << max << endl; return 0; Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 11

Some Observations (Almost) same instructions repeated multiple times cout << Give marks of student 3: ; cin >> marks; sum = sum + marks; min = (min > marks)? marks : min; max = (max < marks)? marks : max; Slightly different for student 1: min = marks; max = marks; Intuitively, we would like to execute (almost) the same instructions for all students Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 12

Some Observations Suppose we had a construct in C++ that allowed us to effectively say Repeat the following block of instructions a specified number of times Could we write a less repetititve C++ program to aggregate quiz 1 marks? Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 13

Another Attempt At Our C++ Program int main() { // Variable declarations and initialization of aggregates int count = 1; // Repeat the following block of code 10 times { cout << Give marks of student << count << : ; cin >> marks; sum = sum + marks; // Update min and max appropriately count = count + 1; // End of block of code to be repeated // Code for computing average and printing comes here return 0; Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 14

Another Attempt At Our C++ Program int main() { // Variable declarations and initialization of aggregates int count = 1; // Repeat the following block of code 10 times { cout << Give marks of student << count << : ; cin >> marks; sum = sum + marks; if (count == 1) { min = marks; max = marks; Updating min and max appropriately else { min = (min > marks)? marks:min; max = (max < marks)? marks: max; count = count + 1; // End of block of code to be repeated // Code for computing average and printing comes here return 0; Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 15

Another Attempt At Our C++ Program int main() { // Variable declarations and initialization of aggregates int count = 1; // Repeat the following block of code 10 times { cout << Give marks of student << count << : ; cin >> marks; Currently, only for this message sum = sum + marks; if (count == 1) { min = marks; max = marks; else { min = (min > marks)? marks:min; max = (max < marks)? marks: max; count = count + 1; Need for this? // End of block of code to be repeated // Code for computing average and printing comes here return 0; Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 16

Another Attempt At Our C++ Program int main() { // Variable declarations Compared and to initialization our earlier of aggregates program, this one is int count = 1; less repetititve, and closer to intuition // Repeat the following block of code 10 times { cout << Give marks of student << count << : ; cin >> marks; sum = sum Yet, + marks; the original problem could have been solved if (count == 1) without { min = marks; the repetition/iteration max = marks; construct else { min = (min > marks)? marks:min; max = (max < marks)? marks: max; count = count + 1; // End of block of code to be repeated // Code for computing average and printing comes here return 0; Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 17

Repetition in Programming Wasteful If you can achieve something by coding once, why code again? Potential source of bugs and inconsistencies Afterthought: Want to say Thank you after each marks is read cout << Thank you ; at 10 places What if there was a typo ( Think yoo ) at one place? Can be more dangerous than just a message being printed wrong Maintainability of large code with repetition difficult Small change in replicated code requires replicating change at several places Reuse as much code as possible, avoid repetitions consciously Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 18

More General Iteration int main() { // Variable declarations and initialization of aggregates int count = 1; // Repeat the following block of code 10 times { cout << Give marks of student << count << : ; cin >> marks; sum = sum + marks; if (count == 1) { min = marks; max = marks; else { min = (min > marks)? marks:min; max = (max < marks)? marks: max; count = count + 1; // End of block of code to be repeated // Code for computing average and printing comes here return 0; What if we want to aggregate marks of n students, where n is user specified? Number of repetitions cannot be determined when writing program Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 19

More General Iteration int main() { // Variable declarations and initialization of aggregates int count = 1; // Repeat the following block of code 10 times { cout << Give marks of student << count << : ; cin >> marks; sum = sum + marks; if (count == 1) { min = marks; max = marks; Necessity of repetition/iteration construct: else { min = (min > marks)? marks:min; max = (max < marks)? marks: max; count Problem = count + cannot 1; be solved without this // End of block of code to be repeated // Code for computing average and printing comes here return 0; What if we want to aggregate marks of n students, where n is user specified? Number of repetitions cannot be determined when writing program Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 20

More General Iteration int numstudents, count; cout << Give number of students in CS101: ; cin >> numstudents count = 1; // Repeat the following block of code while (count <= numstudents) { cout << Give marks of student << count << : ; cin >> marks; Iterate while a logical sum = sum + marks; condition is satisfied if (count == 1) { min = marks; max = marks; else { min = (min > marks)? marks:min; max = (max < marks)? marks: max; count = count + 1; // End of block of code to be repeated // Code to compute aggregates and print them Crucial: Affects logical condition for loop termination Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 21

A Generic Iteration Construct General structure of program with iteration Part of program before iteration Iteration initialization (setting up initial values, etc) Iterate/Repeat as long as a logical condition stays true { Block of statements Optional instructions to execute at end of every iteration Part of program after iteration Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 22

A Generic Iteration Construct General structure of program with iteration Part of program before iteration Iteration initialization (setting up initial values, etc) Iterate/Repeat as long as a logical condition stays true { Block of statements Optional instructions to execute at end of every iteration Part of program after iteration Loop Body Loop Condition Loop Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 23

C++ Iteration Constructs Several iteration constructs in C++ while (loopcondition) { Block of Statements to Iterate Over ; do { Block of Statements to Iterate Over while (loopcondition); for (initializationcode; loopcondition; CodeToExecuteAfterEachIteration) { Block of Statements to Iterate Over ; Details in next lecture Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 24

Summary Iteration idioms in programming Necessary in general Convenient to write intuitive code Enables code reuse, avoids pitfalls of repetition Glimpse of iteration constructs in C++ Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 25