1 Flowchart notation and loops Implementation of loops in C –while loops –do-while loops –for loops Auxiliary Statements used inside the loops –break –continue.

Slides:



Advertisements
Similar presentations
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Advertisements

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Loops – While, Do, For Repetition Statements Introduction to Arrays
CS1061: C Programming Lecture 8: Repetition A. O’Riordan, 2004.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
1 Lecture 5  More flow control structures  for  do  continue  break  switch  Structured programming  Common programming errors and tips  Readings:
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 2: Control Flow.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
Fundamentals of C and C++ Programming Control Structures and Functions.
Chapter 5 Control Structures: Loops 5.1 The while Loop The while loop is probably the most frequently used loop construct. The while loop is a conditional.
Do-while loop Syntax do statement while (loop repetition condition)
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
Chapter 5: Structured Programming
C Programming Lecture 7 : Control Structures. Control Structures Conditional statement : if, switch Determine a block of statements to execute depending.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Chapter 6: Loops Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 6 Loops.
Repetition Repetition allows you to repeat an operation or a series of operations many times. This is called looping and is one of the basic structured.
REPETITION STATEMENTS - Part1  Also called LOOP STATEMENTS OR LOOP STRUCTURES 1 C++ Statements that repeat one or more actions while some condition is.
COMP Loop Statements Yi Hong May 21, 2015.
BY ILTAF MEHDI (MCS, MCSE, CCNA)1. INSTRUCTOR: ILTAF MEHDI (MCS, MCSE, CCNA, Web Developer) BY ILTAF MEHDI (MCS, MCSE, CCNA)2 Chapter No: 04 “Loops”
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
PGT C Programming1 Week 4 – Repetition Structures / Loops.
1 Chapter 6 Loops. Iteration Statements C’s iteration statements are used to set up loops. A loop is a statement whose job is to repeatedly execute some.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 6.
The following statements are for y = -1; if ( x ) if ( x>0 ) y = 1; else y = 0; A. y= -1 x0 B. y= 0 x0 C. y= 1 x
UCT Department of Computer Science Computer Science 1015F Iteration
ECE Application Programming
Control Structures (Repetition structure) Jump Statements
Chapter 4 – C Program Control
CSE 220 – C Programming Loops.
Chapter 6: Loops.
ECE Application Programming
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
CS1010 Programming Methodology
Loops Chapter 6 Copyright © 2008 W. W. Norton & Company.
Loops Chapter 6 Copyright © 2008 W. W. Norton & Company. 1
Control Structures Lecture 7.
Looping.
- Additional C Statements
Outline Altering flow of control Boolean expressions
Chapter 4 - Program Control
Exam 1 Date: Feb. 2nd, 2015 during class time (50 minutes) Coverage
Loops in C.
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
More Loops Topics Counter-Controlled (Definite) Repetition
Dale Roberts, Lecturer IUPUI
Loops Chapter 6 Copyright © 2008 W. W. Norton & Company.
More Loops Topics Counter-Controlled (Definite) Repetition
CSC215 Lecture Control Flow.
CprE 185: Intro to Problem Solving (using C)
More Loops Topics Counter-Controlled (Definite) Repetition
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

1 Flowchart notation and loops Implementation of loops in C –while loops –do-while loops –for loops Auxiliary Statements used inside the loops –break –continue –goto Today’s Material

2 Often you would need to repeatedly execute some statements as long as a condition is true Consider computing “a n “, where “a” is a real number and “n” is an integer >= 0 –E.g., Compute 3 5 –3 5 = 3*3*3*3*3 The Need For Loops

3 Keep a running power, initialized to 1 –power = 1 (a 0 =1) Multiply power with “a”, and count the number of times we have multiplied “power” with “a” –Initially count = 0 When “count” reaches “n”, that is, when we have multiplied “power” with “a” “n” times, we are done How to compute a n?

4 1.Prompt the user and get “a” and “n” 2.Set count to 0 3.Set power to 1 /* power = a 0 = 1 */ 4.repeat while (count < n) 4.1. power = power * a; /* power = a count now */ 4.2. count++; 5.Print power Algorithm for Computing a n

5 Flowchart for Computing a n count = 0 Start power = 1 count < n? Prompt the user and get “a” and “n” Print power no End yes power *= a; count++;

6 Clearly, we need to repeatedly execute steps 4.1 and 4.2 until “count” reaches “n” That is, we need to loop around steps 4.1, 4.2 as long as a condition is true C provides 3 looping constructs –while loops –do-while loops –for loops C Looping Constructs

7 while Statement The while loop keeps repeating an action until an associated test returns false Useful when the programmer does not know in advance how many times the loop will be iterated Syntax: while(expression) { statement1; statement2;... } expression Y N statement 1 statement 2...

8 Code for Computing a n int count; int n; double a; double power; printf(“Enter a: “); scanf(“%lf”, &a); printf(“Enter n: “); scanf(“%d”, &n); count = 0; power = 1; /* power = a 0 */ while (count < n){ power *= a; count++; } /* end-while */ printf(“a^n: %lf\n”, power); count = 0 Start power = 1 count < n? Prompt the user and get “a” and “n” Print power no End yes power *= a; count++;

9 Trace of the Code for a = 3, n = 5 int count; int n; double a; double power; printf(“Enter a: “); scanf(“%lf”, &a); printf(“Enter n: “); scanf(“%d”, &n); count = 0; power = 1; while (count < n){ power *= a; count++; } /* end-while */ printf(“a^n: %lf\n”, power); 0 1 count power 3 5 a n Test: 0 < 5?  True 1 3 Test: 1 < 5?  True 2 9 Test: 2 < 5?  True 3 27 Test: 3 < 5?  True 4 81 Test: 5 < 5?  False Test: 4 < 5?  True 5 243

10 Computing a n : Alternative Code int i; int n; double a; double power; printf(“Enter a: “); scanf(“%lf”, &a); printf(“Enter n: “); scanf(“%d”, &n); i = 0; power = 1; while (i < n){ power *= a; i++; } /* end-while */ printf(“a^n is: %lf\n”, power); int i; int n; double a; double power; printf(“Enter a: “); scanf(“%lf”, &a); printf(“Enter n: “); scanf(“%d”, &n); i = 0; power = 1; while (i++ < n) power *= a; printf(“a^n is: %lf\n”, power);

11 1.Prompt the user and get “n” 2.Set i to 1 /* Iteration variable */ 3.Set sum to 0 /* Running sum */ 4.repeat while (i <= n) 4.1. sum += i; 4.2. i++; 5.Print sum Computing N

12 Flowchart and Code for Computing N int i; int n; int sum = 0; printf(“Enter n: “); scanf(“%d”, &n); i = 1; while (i<= n){ sum += i; i++; } /* end-while */ printf(“Sum is: %d\n”, sum); i = 1 Start sum = 0 i <= n? Prompt the user and get “n” Print sum no End yes sum += i; i++;

13 Trace of the Code for n=5 int i; int n; int sum = 0; printf(“Enter n: “); scanf(“%d”, &n); i = 1; while (i<= n){ sum += i; i++; } /* end-while */ printf(“Sum is: %d\n”, sum); 1 0 i sum Test: 1 <= 5?  True 2 1 Test: 2 <= 5?  True 3 3 Test: 3 <= 5?  True 4 6 Test: 4 <= 5?  True 5 10 Test: 6 <= 5?  False Test: 5 <= 5?  True n

14 Computing N: Alternative Code int i; int n; int sum = 0; printf(“Enter n: “); scanf(“%d”, &n); i = 1; while (i<= n){ sum += i; i++; } /* end-while */ printf(“Sum is: %d\n”, sum); int i; int n; int sum = 0; printf(“Enter n: “); scanf(“%d”, &n); i = 1; while (i<= n) sum += i++; printf(“Sum is: %d\n”, sum);

15 Printing a Table of Squares | i | i*i | | 1| 1| | 2| 4| | 3| 9| | 4| 16| | 5| 25| | 6| 36| We want to print a table of squares for numbers 1, 2, 3, 4,.., n for some number “n” Here is how the table should look like for n = 6

16 Code for Printing a Table of Squares int i; int n; printf(“Enter n: “); scanf(“%d”, &n); printf(“ \n”); printf(“| i | i*i |\n”); printf(“ \n”); i = 1; while (i <= n){ printf(“|%5d|%5d|\n”, i, i*i); i++; } /* end-while */ printf(“ \n”); i = 1 Start i <= n? Prompt the user and get and “n” Print bottom line of the table no End yes print (i, i*i) i++; Print the heading

17 Trace of the code for n=4 printf(“ \n”); printf(“| i | i*i |\n”); printf(“ \n”); i = 1; while (i <= n){ printf(“|%5d|%5d|\n”, i, i*i); i++; } /* end-while */ printf(“ \n”); 1 i 4 n Test: 1 <= 4?  True | i | i*i | | 1| 1| | 2| 4| | 3| 9| | 4| 16| Test: 2 <= 4?  True 3 Test: 3 <= 4?  True 4 Test: 4 <= 4?  True 5 Test: 5 <= 4?  False

18 Another while Example int i = 0; printf(“How do you like C programming?\n”); while(i < 10){ printf(“Programming is fun!\n”); i++; } /* end-while */ Repeats 10 times (for i from 0 to 9) Prints the same message 10 times

19 Yet Another while Example int i = 20; printf(“How do you like C programming?\n”); while(i < 10){ printf(“Programming is fun!\n”); i++; } /* end-while */ Repeats 0 times (i is 20, not less than 10) Does not print any "... is fun" messages.

20 do while Statement do { statement1; statement2;... } while(expression); expression Y N statement 1 statement 2... While loop tests the loop condition at the beginning of the loop, before the first iteration begins Sometimes you want to test the loop condition at the end of the loop. In such cases do-while loops are used –This ensures that the loop body is run at least once Syntax:

21 Asking for a Password(1) Assume you want to repeatedly ask the user for the password until the user enters the password correctly /* Implementation using while */ #define PASSWORD int passwd; printf(“Enter the password: “); scanf(“%d”, &passwd); while (passwd != PASSWD){ printf(“Enter the password: “); scanf(“%d”, &passwd); } /* end-while */ printf(“Password is OK\n”); Clearly you want to ask for the password at least once! –Using a while loop, we have to repeat printf/scanf statements

22 Asking for a Password(2) Here is the same loop with do-while #define PASSWORD int passwd; do { printf(“Enter the password: “); scanf(“%d”, &passwd); } while(passwd != PASSWD); printf(“Password is OK\n”); This is cleaner compared to while loop

23 do while Example Asking for a positive integer int no; do { printf(“Enter a positive integer: “); scanf(“%d”, &no); } while(no <= 0);

24 Another do while Example char option = 'x'; do{ printf("Select an option: \n"); printf("(a) Calculate grades \n"); printf("(b) Calculate class average \n"); printf("(c) Print grades \n"); printf("(q) Quit \n"); option = getchar(); getchar(); /* Skip ‘\n’ */ if (option == 'a')... else if (option == 'b')... else if (option == 'c')... } while(option != ‘q’);

25 Another do while Example int i = 0; printf(“How do you like C programming?\n”); do { printf(“Programming is fun!\n”); i++; } while(i < 10); Repeats 10 times (for i from 0 to 9) Prints the same message 10 times

26 Yet Another do while Example int i = 20; printf(“How do you like C programming?\n”); do { printf(“Programming is fun!\n”); i++; } while(i < 10); Repeats once (for i == 20) Prints the same message once

27 What are the differences between the while and the do while statements? whiledo while Entry control structureExit control structure Loop may or may not be executedLoop is executed at least once

28 for Statement More frequently used Ideal for loops that have a “counting” variable –i.e., We need to loop a fixed number of times Is general enough to be used by other kinds of loops as well Syntax: for (initializing list; expression; altering list) { statement1; statement2;... }

29 for Statement Flowchart, and Equivalent while Statement for(initialize; check; modify) { statement1; statement2;... } modify check Y N initialize statement 1 statement 2... initialize; while(check) { statement1; statement2;... modify; }

30 Another for Example int count; for(count = 1; count <= 10; count++){ printf("%d ",count); } /* end-for */ printf("\n"); Printed output: Start count++ End Displaycount count <= 10 Y N count = 1 Problem: Print numbers from 1 to 10

31 Using for Statement for (i=0; i<N; i++) … For statement is usually the best choice for loops that “count up” (increment a variable) or “count down” (decrement a variable) Counting up from 0 to N-1 for (i=1; i<=N; i++) … Counting up from 1 to N for (i=N-1; i>=0; i--) … Counting down from N-1 to 0 for (i=N; i>=1; i--) … Counting down from N to 1

32 for Example: Compute a n power = 1; for(i=1; i<=N; i++){ power *= a; } /* end-for */ Start i++ End Displaypower i <= N Y N i = 1 power *=a; 1 1 i power 3 5 a n Test: 1 <= 5?  True 2 3 Test: 2 <= 5?  True 3 9 Test: 3 <= 5?  True 4 27 Test: 4 <= 5?  True 5 81 Test: 6 <= 5?  False Test: 5 <= 5?  True 6 243

33 Printing a Table of Squares printf(“ \n”); printf(“| i | i*i |\n”); printf(“ \n”); for (i=1; i <= n; i++){ printf(“|%5d|%5d|\n”, i, i*i); } /* end-while */ printf(“ \n”); | i | i*i | | 1| 1| | 2| 4| | 3| 9| | 4| 16| | 5| 25| | 6| 36| Output for n=6

34 Another for Example sum = 0; for(i=1; i<=N; i++){ sum += i; } Problem: Compute …+N sum=0; i=1; for(; i<=N; i++){ sum += i; } sum=0; for(i=1; i<=N;){ sum += i++; } Initialize (i=1), check(i<=N) and modify(i++) statements are all optional and can be omitted sum=0; i=1; for(; i<=N;){ sum += i++; }

35 It is possible to nest loops inside each other –Many applications require nesting of loops Example: Print the multiplication table Nested Loops | * | 1| 2| 3| 4| 5| 6| 7| 8| 9| 10| | 1| 1| 2| 3| 4| 5| 6| 7| 8| 9| 10| | 2| 2| 4| 6| 8| 10| 12| 14| 16| 18| 20| | 3| 3| 6| 9| 12| 15| 18| 21| 24| 27| 30| | 4| 4| 8| 12| 16| 20| 24| 28| 32| 36| 40| | 5| 5| 10| 15| 20| 25| 30| 35| 40| 45| 50|

36 Printing the Multiplication Table int i, j; /* Print the header */ printf(“ \n”); printf(“| * |”); for (j=1; j<=10; j++) printf(“%3d|”, j); printf(“\n \n”); /* Print the table. i goes over the rows, j over the columns */ for (i=1; i <= 10; i++){ printf(“|%3d:|“, i); /* Print 1 row of the table for i */ for (j=1; j <= 10; j++){ printf(“%3d|”, i*j); } /* end-for-inner */ printf(“\n”); } /* end-for-outer */ /* Print the bottom line of the table */ printf(“ \n”);

37 We have seen that “break” transfers the control out of switch statements Similarly, when used within loops, “break” transfers the control out of the current loop code block break & continue in loops

38 Code for Computing the sum of a series of numbers int sum = 0; int n; while (1){ /* Infinite loop */ printf("Enter an int or -1 to stop: "); scanf("%d", &n"); if (n == -1) break; /* Get out of the loop */ sum += n; } /* end-while */ printf("Sum is %d\n", sum);

39 Code for Checking if a number “n” is prime or not int d; int n; printf(“Enter an integer: “); scanf(“%d”, &n); for (d=2; d<n; d++){ if (n%d == 0) break; } /* end-for */ if (d<n) printf(“n=%d is divisible by %d\n”, n, d); else printf(“n=%d is prime\n”, n);

40 break is particularly useful if the escape point is somewhere in the middle of the loop rather than at the beginning or at the end break (cont) while (1){ printf(“Enter a number or 0 to stop: “); scanf(“%d”, &n); if (n == 0) break; printf(“n=%d, n*n*n*=%d\n”, n, n*n*n); } /* end-while */

41 break transfers the control out of the innermost enclosing code block. –Thus when you have a nested loop, break only escapes one level of nesting break (cont) while (…){ … switch(…){ … break; /* takes us out of switch to (A) */ … } (A) } (B)

42 Transfers the control to the end of the loop Note that we are still inside the loop “continue” simply skips the rest of the statements in the loop body, and moves the control to the end continue int i; int n = 0; int sum = 0; while (n<10){ scanf(“%d”, &i); if (i == 0) continue; /* takes us to (B) */ n++; sum += i; /*(B)*/ } /* end-while */

43 Transfers the control to an arbitrary point in the code designated by a label –goto is strictly discouraged as it leads to spaghetti code, which is hard to understand and maintain –But it may be useful in certain situations goto while (…){ … switch(…){ … goto loop_done; /* break won’t work here, as it takes */ … /* us out of switch only */ } /* end-switch */ } /* end-while */ loop_done:

44 Infinite Loops A loop that iterates forever while (1){ … } do{ … } while (1); How do we get out of these loops then? –Simply have a “break” somewhere within the loop for (;;;){ … } while (1){ printf(“Enter a number or 0 to stop: “); scanf(“%d”, &n); if (n == 0) break; printf(“n=%d, n*n*n*=%d\n”, n, n*n*n); } /* end-while */

45 Occasionally we may want to combine several expressions together into a single statement –This is where we use the comma operator Syntax Comma Operator expr1, expr2, …, exprN; expr1 is evaluated, its value discarded expr2 is evaluated, its value discarded … exprN is evaluated, its value becomes the value of the statement

46 Comma Operator Example (1) i=1, j=2, k=i+j; is equivalent to ((i=1), (j=2), (k=i+j)); Evaluation proceeds left to right The result of the statement is k=i+j; which is 3

47 Comma Operator Example (2) sum=0; for(i=1; i<=N; i++) sum += i; Problem: Compute …+N for(sum=0, i=1; i<=N; i++) sum += i; for(sum=0, i=1; i<=N; sum+=i, i++) ; Empty statement: Loop body is empty