Lecture 10. Daily Puzzle

Similar documents
n Group of statements that are executed repeatedly while some condition remains true

Dept. of CSE, IIT KGP

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

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

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

Repetition and Loop Statements Chapter 5

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

Repetition Structures

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

A Look Back at Arithmetic Operators: the Increment and Decrement

Loops / Repetition Statements

Introduction. C provides two styles of flow control:

Structured Programming. Dr. Mohamed Khedr Lecture 9

Chapter 4. Flow of Control

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

DECISION CONTROL AND LOOPING STATEMENTS

Chapter 4: Control structures. Repetition

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

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

Chapter 4: Control structures

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

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

Unit 3 Decision making, Looping and Arrays

공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -CONTROL FLOW : LOOP- SPRING 2015, SEON-JU AHN, CNU EE

Module 4: Decision-making and forming loops

MODULE 2: Branching and Looping

Lecture 8. Daily Puzzle

Loops / Repetition Statements

CS110D: PROGRAMMING LANGUAGE I

Repetition Structures II

Programming for Engineers Iteration

REPETITION CONTROL STRUCTURE LOGO

Problem Solving and 'C' Programming

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

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

Decision Making and Loops

Prepared by: Shraddha Modi

CSE 130 Introduction to Programming in C Control Flow Revisited

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

Computer System and programming in C

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

CpSc 1111 Lab 9 2-D Arrays

Programming for Electrical and Computer Engineers. Loops

Flow Control. CSC215 Lecture

These are reserved words of the C language. For example int, float, if, else, for, while etc.

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

3 The L oop Control Structure

C++ PROGRAMMING SKILLS Part 2 Programming Structures

Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.

Repetition CSC 121 Fall 2014 Howard Rosenthal

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

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

(Refer Slide Time: 00:26)

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

Object-Oriented Programming in Java

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Physics 2660: Fundamentals of Scientific Computing. Lecture 5 Instructor: Prof. Chris Neu

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

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

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

CS112 Lecture: Loops

CS 106 Introduction to Computer Science I

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

Lab 2: Structured Program Development in C

Fundamentals of Computer Programming Using C

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

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

Looping. Arizona State University 1

Score score < score < score < 65 Score < 50

CHAPTER 5 FLOW OF CONTROL

Repetition, Looping. While Loop

Decision Making -Branching. Class Incharge: S. Sasirekha

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

Statements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14

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

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk

Control Statements. If Statement if statement tests a particular condition

do, while and for Constructs

Lecture 7 Tao Wang 1

Subject: PIC Chapter 2.

LECTURE 5 Control Structures Part 2

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Chapter 13 Control Structures

Copy: IF THE PROGRAM or OUTPUT is Copied, then both will have grade zero.

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013

CpSc 1111 Lab 5 Formatting and Flow Control

Course Outline Introduction to C-Programming

The Hyderabad Public School, Begumpet, Hyderabad, A.P

Note: unless otherwise stated, the questions are with reference to the C Programming Language. You may use extra sheets if need be.

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Loops and Files. of do-while loop

CS112 Lecture: Repetition Statements

Ch. 7: Control Structures

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Fundamentals of Programming Session 7

Unit 5. Decision Making and Looping. School of Science and Technology INTRODUCTION

CpSc 1111 Lab 4 Formatting and Flow Control


Day05 A. Young W. Lim Sat. Young W. Lim Day05 A Sat 1 / 14

Transcription:

Lecture 10 Daily Puzzle Imagine there is a ditch, 10 feet wide, which is far too wide to jump. Using only eight narrow planks, each no more than 9 feet long, construct a bridge across the ditch.

Daily Puzzle Announcements Assignment grading - schedule for booking appointments is open now for booking - mark deductions for missing appointment or failing to make one Assignment submission - late submissions are the same as not submitting = 0

Announcements Voting - https://studentlife.uoguelph.ca/cegc/civicengagement/get-out-and-vote - 3.6M people have voted = 14% of eligible voters. SAS students needing extra time for lab exam - contact instructor by Tuesday at 5:30 pm. - late requests cannot be accommodated. Announcements Voter turn-out, 2011 by age

Announcements Someone left their pi in care of TA last week. Owner should contact cis1500@socs.uoguelph.ca with details about where/when it was left and then can arrange for picking it up. What is a loop?

What is a loop? What is a loop? A loop allows a program to repeat a group of statements any number of times, or until some loop condition occurs. The loop body contains the statements to be repeated.

What is a loop? Commonly known as iterative or repetition statements:! for! while! do-while What is a loop? Any steps repeated? no No loop required yes Know how many times to repeat? no Use a conditional loop yes Use a counting loop

What is a loop? Counting loops are used when it can be determined before loop execution how many loop repetitions will be needed. What is a loop? Conditional loops are used when a loop should be repeated until a desired condition is met.

for Situations in which the number of passes through the loop is known in advance are often best dealt with using a for loop. for The general form of a for statement is for (expr1; expr2; expr3) statement;

for expr1 is used to initialize some parameter (called a control variable, or index) that controls the looping action. expr2 represents a condition that must be true for the loop to continue execution. expr3 is used to modify the value of the control variable initially assigned by expr1. code without loops Sum the first eight odd numbers: int sum = 0; sum = sum + 1; sum = sum + 3; sum = sum + 5; sum = sum + 7; sum = sum + 9; sum = sum + 11; sum = sum + 13; sum = sum + 15;

code with loops Sum the first eight odd numbers: int i, sum = 0; for (i=1; i<=15; i=i+2) sum = sum + i; for initialize loop index is the condition true? loop body modify index

for for keyword control variable i final value of control variable for which the condition is true for (i = 1; i <= n; i = i + 1) initial value of control variable increment of control variable loop-continuation condition for i=1; i <= n? loop body i = i + 1

for i = 1 i <= 4 statement 1 statement 2 statement n i = 2 i <= 4 statement 1 statement 2 statement n i = 3 i <= 4 statement 1 statement 2 statement n i = 4 i <= 4 statement 1 statement 2 statement n i = 5 i <= 4 condition false exit loop If the logical expression, expr2 is not present, it is taken as permanently true, so for (;;) { } is an infinite loop.

Theoretically if you don t know how many times a loop will repeat you COULD use an infinite loop - but it s not good programming practice. Sometimes infinite loops are caused by an unexpected behavior in some loop terminating condition. float x = 0.1; while (x!= 1.1) { printf("x = %f\n", x); x = x + 0.1; }

the loop terminating condition tests for exact equality of two floating point numbers float x = 0.1; many computers will make this test fail while (x!= 1.1) { printf("x = %f\n", x); x = x + 0.1; } Sometimes rather than an infinite loop, there is an impossible termination condition. unsigned short i; for (i = 1; i!= 0; i=i+1) { printf("%hu\n", i); }

this loop *appears* to go on forever, however - it will eventually hit the short maximum of 65535 - adding 1 will wraparound to zero, breaking the loop. unsigned short i; for (i = 1; i!= 0; i=i+1) { printf("%hu\n", i); } for The expressions: i = i + 1 i += 1 ++i i++ are all equivalent in incrementing the value of i by 1.

for The value of expr3 may increment or decrement the variable. If expr3 is negative, the loop actually counts downwards. For example: for (i = n; i >= 0; i--) statement; for The initialization, loop-continuation condition and control-variable modification can contain arithmetic expressions. For example: for (i=n; i<=n*j; i=i+1) statement;

for Vary the control variable from i to 100 in increments of 1: for (i=1; i<=100; i=i+1) Vary the control variable from 100 to i in increments of 1 (decrements of i): for (i=100; i>=1; i=i-1) for Vary the control variable for 3 to 33 in increments of 3. for (i=3; i<=33; i=i+3) Vary the control variable from 20 to 2 in steps of -2. for (i=20; i>=2; i=i-2)

for Can you change the value of the counter variable in the body of a for loop? Yes, but the practice is not recommended. for A counter variable is used to control the loop, so its value should be changed in the modification expression, not in the loop body. The following loop is correct, but would cause an infinite loop: for (k=1; k<3; k=k+1)! k=1;

for & sums Consider the equation to calculate the mean of n numbers: It involves summing up the values of xi from i=1 to n, then dividing this total sum by n. for & sums int n = 10; double sum = 0.0, mean; int num[]= {2,3,5,7,9,11,13,17,19,23}; for (i = 0; i < 10; i = i+1) sum = sum + num[i]; mean = sum / n;

nesting Loops, like decision statements can be nested. nesting Nested means that there is a loop within a loop. A nested loop is executed, essentially, from the inside out.

nesting Each loop is like a layer and has its own counter variable, its own loop expression and its own loop body. In a nested loop, for each value of the outermost counter variable, the complete inner loop will be executed once. nesting Can you deduce how many times a nested loop is executed? for (i = 1; i <= 4; i=i+1) { for (j = 1; j <= 5; j=j+2) { k = i + j; printf( i=%d, j=%d, k=%d, i, j, k); } }

nesting outer loop executed 4 times, i = 1, 2, 3, 4 for (i = 1; i <= 4; i=i+1) { for (j = 1; j <= 5; j=j+2) { k = i + j; printf( i=%d, j=%d, k=%d, i, j, k); } } inner loop executed 3 times, j = 1, 3, 5 TOTAL = 4 x 3 = 12 nesting! i=1, j=1, k=2! i=1, j=3, k=4! i=1, j=5, k=6! i=2, j=1, k=3! i=2, j=3, k=5! i=2, j=5, k=7! i=3, j=1, k=4! i=3, j=3, k=6! i=3, j=5, k=8! i=4, j=1, k=5! i=4, j=3, k=7! i=4, j=5, k=9 the output

nesting How to create a matrix of values? for (i = 1; i <= 10; i=i+1) { for (j = 1; j <= 10; j=j+1) printf( %d, i*10+j); printf( \n ); } outer loop does the rows nesting inner loop does the columns 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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

nesting for for for for for for for for for for for...and about another billion combinations while Situations in which the number of passes through the loop is not known in advance are often best dealt with using a while statement.

while The general form of a while statement is: while (expr) statement; where expr represents a condition that must be true for the loop to continue execution. while The statement is executed repeatedly, as long as the expression is true (i.e., as long as expr evaluates to non-zero). The cycle continues until expr becomes zero, at which point execution resumes after loop.

while The loop can be either simple or compound. while (expr) { statement1; statement2;... statementn; } while Of course, the statement must include some feature that eventually alters the value of a variable in expr, thus providing an escape mechanism from the loop. This is not done automatically (like in a for loop).

while When a loop is constructed using a while statement, the test for the continuation of the loop is carried out at the beginning of each pass. loop control variable while initial value pre-loop loop body - what the loop does i = 1;!! while (i <= 4)!! { printf( %d, i); i = i + 1;!! } loop condition - loop only activates if this is true modification of loop control variable

while initialize loop index i = 1; is the condition true? i <= 4 true loop body printf( %d, i); modify index i = i + 1; false while If a while loop s test expression is false initially, the while loop will never be activated.

while What is the meaning of while(i): while (i) statement; It means that while the variable i is not equal to 0 (is true), then the body of the loop is executed. nested while while loops, can be nested. while (expr1) { loop_body_1a while (expr2) { loop_body_2 } } loop_body_1b

for = while for(expr1; expr2; expr3) statement; is equivalent to expr1; while(expr2){ statement; expr3; } do-while When a loop is constructed using a while statement, the test for the continuation of the loop is carried out at the beginning of each pass.

do-while Sometimes however, it is desirable to have a loop where the test for continuation takes place at the end of each pass. This can be accomplished by means of a do-while loop. do-while The general form of a do-while statement is: do statement; while (expr); where expr represents a condition that must be true for the loop to continue execution.

do-while The statement is executed repeatedly, as long as expr is true. Note, however, that the statement is always executed at least once, since the test for repetition does not take place until the end of the first pass through the loop. do-while The statement can be either simple or compound, and should, of course, include some feature that eventually alters the value of the expression.

do-while do { statement 1 ; statement 2 ;... statement n ; } while (expr); do-while initialize loop index i = 1; loop body printf( %d, i); modify index i = i + 1; is the condition true? i <= 4 true false

while VS. do-while What are the differences between while and do-while loops? While loops and do-while loops are similar. while VS. do-while The difference between the two loops is that, in the while loop, the expression is tested first, and, if the expression result is false, the loop body is not executed.

while VS. do-while However, in the do-while loop, the loop body is always executed once. After that, the expression is tested; if the test result is false, the loop body is not executed again. break The break statement causes an exit from the innermost enclosing loop. The general form of a break statement is: break; It provides an early exit from for, while, and do-while loops (and the switch statement).

break while (expr) { statements break; more_statements } break implied infinite loop double x; while (1) { scanf( %lf, &x); if (x > 0.0) not the best use of break break; } // break jumps to here printf( %f\n, sqrt(x));

break double x; int true=1; while (true) { scanf( %lf, &x); if (x > 0.0) true = 0; } printf( %f\n, sqrt(x)); continue The continue statement causes the current iteration of a loop to stop and the next iteration to begin immediately. The general form of a continue statement is: continue; It applies only to loops, not to switch.

continue while (expr) { statements continue; more_statements } continue double x, sum; int count, n=10; while (count < n) { scanf( %lf, &x); if (x > -0.01 && x < 0.01) continue; count = count + 1; sum = sum + x; /* continue jumps to here to begin next iteration */ } printf( %f\n, sum);

real loop counters Because floating-point values may be approximate, controlling counting loops with floating-point variables may result in imprecise counter values and inaccurate tests for termination. Control counting loops with integer values. real loop counters Does the loop stop when count is 1.0? double count;! count = 0.0;! while (count!= 1.0)! {! count = count + 1.0/3.0;! printf( %f \n, count);! }