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

Similar documents
Dept. of CSE, IIT KGP

A Look Back at Arithmetic Operators: the Increment and Decrement

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

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

Iteration. CSE / ENGR 142 Programming I. Chapter 5. Motivating Loops. What s Wrong with Fahrenheit/Celsius Program? One More Type of Control Flow

Iteration. CSE / ENGR 142 Programming I. while loops. Chapter 5. Motivating Loops. Loop to Add 5 Numbers 1996 UW CSE H - 1

Sudeshna Sarkar Dept. of Computer Science & Engineering. Indian Institute of Technology Kharagpur

Programming for Engineers Iteration

Loops / Repetition Statements

REPETITION CONTROL STRUCTURE LOGO

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

Structured Programming. Dr. Mohamed Khedr Lecture 9

Lecture 10. Daily Puzzle

Control Structure: Loop

Iteration. CSE / ENGR 142 Programming I. Chapter 5. Motivating Loops. One More Type of Control Flow. What s Wrong with HW1?

Introduction. C provides two styles of flow control:

Unit 3 Decision making, Looping and Arrays

Chapter 4. Flow of Control

CPE 101 slides adapted from UW course. Overview. Chapter UW CSE H1-1. An Old Friend: Fahrenheit to Celsius. Concepts this lecture

C 101. Davide Vernizzi. April 29, 2011

3 The L oop Control Structure

Loops / Repetition Statements

Module 4: Decision-making and forming loops

MODULE 2: Branching and Looping

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

Repetition and Loop Statements Chapter 5

Repetition Structures II

Syntax of for loop is as follows: for (inite; terme; updatee) { block of statements executed if terme is true;

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

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

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

CS1100 Introduction to Programming

Computer System and programming in C

204111: Computer and Programming

Fundamentals of Computer Programming Using C

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

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

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

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

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

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

Control structures in C. Going beyond sequential

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

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Repetition, Looping. While Loop

Flow Control. CSC215 Lecture

COMP 208 Computers in Engineering

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

Computer Programming. Decision Making (2) Loops

Conditional Statement

Lecture 6. Statements

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

Why Is Repetition Needed?

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

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

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

Programming for Electrical and Computer Engineers. Loops

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

Decision Making and Loops

C: How to Program. Week /Mar/05

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

Repetition Structures

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

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

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

Functions. Arash Rafiey. September 26, 2017

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

Decision Making -Branching. Class Incharge: S. Sasirekha

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

DECISION CONTROL AND LOOPING STATEMENTS

Problem Solving and 'C' Programming

Chapter 2 - Introduction to C Programming

Prepared by: Shraddha Modi

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

Lab ACN : C++ Programming Exercises

Chapter 5: Control Structures

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

The C Programming Language Part 2. (with material from Dr. Bin Ren, William & Mary Computer Science)

Structured Program Development in C

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

One Dimension Arrays 1

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control

2/5/2018. Learn Four More Kinds of C Statements. ECE 220: Computer Systems & Programming. C s if Statement Enables Conditional Execution

Chapter 13 Control Structures

Repetition CSC 121 Fall 2014 Howard Rosenthal

M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

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

Control Statements. If Statement if statement tests a particular condition

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Looping. Arizona State University 1

Flow of Control. Selection. if statement. True and False in C False is represented by any zero value. switch

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

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

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

CS313D: ADVANCED PROGRAMMING LANGUAGE

Unit 3. Operators. School of Science and Technology INTRODUCTION

Quiz Determine the output of the following program:

Transcription:

Looping 1

Loops n Group of statements that are executed repeatedly while some condition remains true n Each execution of the group of statements is called an iteration of the loop 2

Example counter 1, sum 0 Read 5 integers and display their sum counter < 6 true input n sum sum + n false counter = counter + 1 output sum 3

Example Given an exam marks as input, display the appropriate message based on the rules below: q If marks is greater than 49, display PASS, otherwise display FAIL q However, for input outside the 0-100 range, display WRONG INPUT and prompt the user to input again until a valid input is entered 4

input m m<0 m>100 true WRONG INPUT false input m false m>49 PASS FAIL true 5

input m m<0 m>100 true WRONG INPUT false input m false m>49 PASS FAIL true 6

Looping: while statement while (expression) statement; while (expression) { Block of statements; The condition to be tested is any expression enclosed in parentheses. The expression is evaluated, and if its value is non-zero, the statement is executed. Then the expression is evaluated again and the same thing repeats. The loop terminates when the expression evaluates to 0. 7

Looping: while statement while (expression) statement; while (expression) { Block of statements; expression True statement (loop body) False 8

Looping: while statement while (expression) statement; while (expression) { Block of statements; expression True statement (loop body) False The condition to be tested is any expression enclosed in parentheses. The expression is evaluated, and if its value is non-zero, the statement is executed. Then the expression is evaluated again and the same thing repeats. The loop terminates when the expression evaluates to 0. 9

Example int i = 1, n; scanf( %d, &n); while (i <= n) { printf ( Line no : %d\n,i); i = i + 1; 10

Example int weight; scanf( %d, &weight); while ( weight > 65 ) { printf ("Go, exercise, "); printf ("then come back. \n"); printf ("Enter your weight: "); scanf ("%d", &weight); 11

Sum of first N natural numbers void main() { int N, count, sum; scanf ( %d, &N) ; sum = 0; count = 1; while (count <= N) { sum = sum + count; count = count + 1; printf ( Sum = %d\n, sum) ; 12

SUM = 1 2 + 2 2 + 3 2 + + N 2 void main() { int N, count, sum; scanf ( %d, &N) ; sum = 0; count = 1; while (count <= N) { sum = sum + count * count; count = count + 1; printf ( Sum = %d\n, sum) ; return 0; 13

Compute GCD of two numbers void main() { int A, B, temp; scanf ( %d %d, &A, &B); if (A > B) { temp = A; A = B; B = temp; while ((B % A)!= 0) { temp = B % A; B = A; A = temp; printf ( The GCD is %d, A); 12 ) 45 ( 3 36 9 ) 12 ( 1 9 3 ) 9 ( 3 Initial: A=12, B=45 Iteration 1: temp=9, B=12,A=9 Iteration 2: temp=3, B=9, A=3 B % A = 0 è GCD is 3 9 0 gcd.c 14

Double your money n Suppose your Rs 10000 is earning interest at 1% per month. How many months until you double your money? void main() { double my_money = 10000.0; int n=0; while (my_money < 20000.0) { my_money = my_money * 1.01; n++; printf ( My money will double in %d months.\n,n); 15

Maximum of positive Numbers void main() { double max = 0.0, next; printf ( Enter positive numbers, end with 0 or a negative number\n ); scanf( %lf, &next); while (next > 0) { if (next > max) max = next; scanf( %lf, &next); printf ( The maximum number is %lf\n, max) ; 16

Find the sum of digits of a number void main() { int n, sum=0; scanf ( %d, &n); while (n!= 0) { sum = sum + (n % 10); n = n / 10; printf ( The sum of digits of the number is %d \n, sum); digit-sum.c 17

Looping: for Statement n Most commonly used looping structure in C for ( expr1; expr2; expr3) statement; for ( expr1; expr2; expr3) { Block of statements; expr1 (init) : initialize parameters expr2 (test): test condition, loop continues if expression is non-0 expr3 (update): used to alter the value of the parameters after each iteration statement (body): body of loop 18

expr1 (init) expr2 (test) statement (body) True False expr3 (update) 19

Example: Computing Factorial void main () { int N, count, prod; scanf ( %d, &N) ; prod = 1; for (count = 1;count <= N; ++count) prod = prod * count; printf ( Factorial = %d\n, prod) ; 20

Computing e x series up to N terms void main () { float x, term, sum; int n, count; scanf ( %f, &x); scanf ( %d, &n); term = 1.0; sum = 0; for (count = 1; count < n; ++count) { sum += term; term *= x/count; printf ( %f\n, sum); eseries-1.c 21

Computing e x series correct up to 4 decimal places void main () { float x, term, sum; int cnt; scanf ( %f, &x) ; term = 1.0; sum = 0; for (cnt = 1; term >= 0.0001; ++cnt) { sum += term; term *= x/cnt; printf ( %f\n, sum) ; eseries-2.c 22

Equivalence of for and while for ( expr1; expr2; expr3) statement; Same as expr1; while (expr2) { statement expr3; 23

void main () { int N, count, sum; scanf ( %d, &N) ; sum = 0; count = 1; while (count <= N) { sum = sum + count; count = count + 1; printf ( %d\n, sum) ; Sum of first N Natural Numbers void main () { int N, count, sum; scanf ( %d, &N) ; sum = 0; for (count=1; count <= N; ++count) sum = sum + count; printf ( %d\n, sum) ; 24

Some observations on for n Initialization, loop-continuation test, and update can contain arithmetic expressions for ( k = x; k <= 4 * x * y; k += y / x ) n Update may be negative (decrement) for (digit = 9; digit >= 0; --digit) n If loop continuation test is initially 0 (false) Body of for structure not performed n No statement executed Program proceeds with statement after for structure 25

Looping: do-while statement do statement; while (expression); do { Block of statements; while (expression); True statement expression False 26

Example Problem: Prompt user to input month value, keep prompting until a correct value of month is given as input do { printf ( Please input month {1-12 ); scanf ( %d, &month); while ((month < 1) (month > 12)); 27

Decimal to binary conversion (prints binary in reverse order) void main() { int dec; scanf ( %d, &dec); do { printf ( %2d, (dec % 2)); dec = dec / 2; while (dec!= 0); printf ( \n ); 28

Echo characters typed on screen until end of line void main () { char echo ; do { scanf ( %c, &echo); printf ( %c,echo); while (echo!= \n ) ; 29

Specifying Infinite Loop while (1) { statements for (; ;) { statements do { statements while (1); 30

The break Statement n Break out of the loop body { can use with while, do while, for, switch does not work with if, else n Causes immediate exit from a while, do/while, for or switch structure n Program execution continues with the first statement after the structure 31

An Example void main() { int fact, i; fact = 1; i = 1; while ( i<10 ) {/* run loop break when fact >100*/ fact = fact * i; if ( fact > 100 ) { printf ("Factorial of %d above 100", i); break; /* break out of the while loop */ ++i; 32

Test if a number is prime or not void main() { int n, i=2; scanf ( %d, &n); while (i < n) { if (n % i == 0) { printf ( %d is not a prime \n, n); break; ++i; if (i == n) printf ( %d is a prime \n, n); 33

More efficient?? void main() { int n, i = 2, flag = 0; double limit; scanf ( %d, &n); limit = sqrt(n); while (i <= limit) { if (n % i == 0) { printf ( %d is not a prime \n, n); flag = 1; break; i = i + 1; if (flag == 0) printf ( %d is a prime \n, n); 34

The continue Statement n Skips the remaining statements in the body of a while, for or do/while structure Proceeds with the next iteration of the loop n while and do/while loop Loop-continuation test is evaluated immediately after the continue statement is executed n for loop expr3 is evaluated, then expr2 is evaluated 35

An Example with break and continue void main() { int fact = 1, i = 1; while (1) { fact = fact * i; ++i; if ( i <=10 ) continue; break; /* not done yet! Go to loop and perform next iteration*/ 36

Some Loop Pitfalls while (sum <= NUM) ; sum = sum+2; for (i=0; i<=num; ++i); sum = sum+i; for (i=1; i!=10; i=i+2) sum = sum+i; double x; for (x=0.0; x<2.0; x=x+0.2) printf( %.18f\n, x); 37

Nested Loops: Printing a 2-D Figure n How would you print the following diagram? * * * * * * * * * * * * * * * repeat 3 times print a row of 5 * s repeat 5 times print * 38

Nested Loops const int ROWS = 3; const int COLS = 5;... row = 1; while (row <= ROWS) { /* print a row of 5 * s */... ++row; row = 1; while (row <= ROWS) { /* print a row of 5 * s */ col = 1; while (col <= COLS) { printf ( * ); col++; printf( \n ); ++row; outer loop inner loop 39

2-D Figure: with for loop Print * * * * * * * * * * * * * * * const int ROWS = 3; const int COLS = 5;... for (row=1; row<=rows; ++row) { for (col=1; col<=cols; ++col) { printf( * ); printf( \n ); 40

Another 2-D Figure Print * * * * * * * * * * * * * * * const int ROWS = 5;... int row, col; for (row=1; row<=rows; ++row) { for (col=1; col<=row; ++col) { printf( * ); printf( \n ); 2d-figure.c 41

Yet Another One Print * * * * * * * * * * * * * * * const int ROWS = 5;... int row, col; for (row=0; row<rows; ++row) { for (col=1; col<=row; ++col) printf(" "); for (col=1; col<=rows-row; ++col) printf("* "); printf ("\n"); 42

break and continue with nested loops n For nested loops, break and continue are matched with the nearest loops (for, while, dowhile) n Example: while (i < n) { for (k=1; k < m; ++k) { if (k % i == 0) break; i = i + 1; Breaks here 43

Example void main() { int low, high, desired, i, flag = 0; scanf( %d %d %d, &low, &high, &desired); i = low; while (i < high) { for (j = i+1; j <= high; ++j) { if (j % i == desired) { flag = 1; break; Breaks here if (flag == 1) break; i = i + 1; Breaks here 44

The comma operator n Separates expressions n Syntax expr-1, expr-2,,expr-n expr-1, expr-2, are all expressions n Is itself an expression, which evaluates to the value of the last expression in the sequence n Since all but last expression values are discarded, not of much general use n But useful in for loops, by using side effects of the expressions 45

Example n We can give several expressions separated by commas in place of expr1 and expr3 in a for loop to do multiple assignments for example for (fact=1, i=1; i<=10;++ i) fact = fact * i; for (sum=0, i=1; i<=n; ++i) sum = sum + i * i; 46