Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.

Slides:



Advertisements
Similar presentations
Computer Science 1620 Loops.
Advertisements

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Chapter 3 - Structured Program Development
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 3 - Structured Program Development Outline.
Introduction to Computers and Programming Lecture 8: More Loops New York University.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control.
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.
Structured Program Development in C
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Repetition (Loops) Want to do some repetitive sequence of actions: print vertical line of *s * Corresponding program: printf(“*\n”);
* What kind of loop would I use to complete the following: A. Output all of the prime numbers that are less than 100,000 B. Output the Fibonacci sequence.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Structured Program Development Outline 2.1Introduction 2.2Algorithms 2.3Pseudo code 2.4Control Structures 2.5The If Selection Structure 2.6The If/Else.
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
C Lecture Notes 1 Structured Program Development.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
C++ Programming Lecture 6 Control Structure II (Repetition) By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Loop.  While Loop  Do-while Loop  For Loop Continue Statement Conclusion Loop Loop.
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
C Programming Lecture 7 : Control Structures. Control Structures Conditional statement : if, switch Determine a block of statements to execute depending.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Lecture 5: Stopping with a Sentinel. Using a Sentinel Problem Develop a class-averaging program that will process an arbitrary number of grades each time.
CSCI 171 Presentation 5. The while loop Executes a block as long as the condition is true general form: while (condition) { statement 1; statement 2;
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Beginning C For Engineers Fall 2005 Lecture 3: While loops, For loops, Nested loops, and Multiple Selection Section 2 – 9/14/05 Section 4 – 9/15/05 Bettina.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 6.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 3 - Structured Program Development Outline.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (while) Outline 3.7The While Repetition.
CHAPTER 4 REPETITION STRUCTURES 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 A.AlOsaimi.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
© 2006 Pearson Education Chapter 3 Part 2 More about Strings and Conditional Statements Loops (for and while) 1.
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
Chapter 4 Repetition Statements (loops)
while Repetition Structure
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Lecture 7: Repeating a Known Number of Times
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
CS1010 Programming Methodology
Control Structures Lecture 7.
Looping.
Outline Altering flow of control Boolean expressions
Chapter 3 - Structured Program Development
Chapter 3 - Structured Program Development
EPSII 59:006 Spring 2004.
Repetition Statements
Presentation transcript:

Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1

Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions C has three kinds of repetition statements: –while loop –do loop –for loop The programmer should choose the right kind of loop for the situation BBS514 Structured Programming (Yapısal Programlama)2

while Statement The most general one of these loop statements is while. while ( boolean-expression ) statement where statement can be any statement including a compound statement, an if-statement, another loop statement,... Statement is repeated as long as the condition (boolean-expression) is true. When the condition gets false, the statement is not executed anymore. If the condition never gets false  infinite loop If the condition gets immediately false  the loop will be repeated zero times. BBS514 Structured Programming (Yapısal Programlama)3

while Statement – Flow Diagram BBS514 Structured Programming (Yapısal Programlama)4 while ( condition ) statement condition statement true false

while Statement Example: int product = 2; while ( product <= 100 ) product = 2 * product; BBS514 Structured Programming (Yapısal Programlama)5 product <= 100 product = 2 * product true false

while Statement – Counter Controlled Loop Print 5 asterisk characters This loop will be repeated for 5 times (count: 0,1,...,4) count = 0; while ( count < 5 ) { printf(“*\n”); count = count + 1; } printf(“done\n”); BBS514 Structured Programming (Yapısal Programlama)6 * * * * * done

while Statement – Counter Controlled Loop Read & sum 5 values sum = 0; count = 0; while ( count < 5 ) { scanf(“%d”, &value); sum = sum + value; count = count + 1; } printf(“sum is %d \n”, sum); BBS514 Structured Programming (Yapısal Programlama) sum is 20

Counter-Controlled Repetition – Example Program A class of 10 students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz The algorithm Set total to zero Set grade counter to one While grade counter is less than or equal to 10 Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average BBS514 Structured Programming (Yapısal Programlama)8

Counter-Controlled Repetition – Example Program /* Class average program with counter-controlled repetition */ #include int main() { int counter, grade, total, average; /* initialization phase */ total = 0; counter = 1; /* processing phase */ while ( counter <= 10 ) { printf( "Enter grade: " ); scanf( "%d", &grade ); total = total + grade; counter = counter + 1; } /* termination phase */ average = total / 10.0; printf( "Class average is %d\n", average ); return 0; /* indicate program ended successfully */ } BBS514 Structured Programming (Yapısal Programlama)9 Enter grade: 98 Enter grade: 76 Enter grade: 71 Enter grade: 87 Enter grade: 83 Enter grade: 90 Enter grade: 57 Enter grade: 79 Enter grade: 82 Enter grade: 94 Class average is 81

Infinite Loops The body of a while loop eventually must make the condition false If not, it is called an infinite loop, which will execute until the user interrupts the program This is a common logical error You should always double check the logic of a program to ensure that your loops will terminate normally int count = 1; while (count <= 25){ printf(“%d \n”, count); count = count - 1; } BBS514 Structured Programming (Yapısal Programlama)10

Infinite Loops i = 1; while ( i != 50 ) { printf(“%d\n”,i); i = i + 2; } printf(“done”); scanf(“%d”, &i); while ( i != 1 ) { if ( i % 2 == 0) i = i / 2; else i = 3 * i + 1; } printf(“done”); BBS514 Structured Programming (Yapısal Programlama)11 Sometimes, it is difficult to check loop terminating condition.

Sentinel-Controlled Loops What happens if we don’t know how many times a loop will run. Ex: a loop which reads the scores of the students in an exam and find the average of the scores; –we don’t know the number of students. –How are we going to stop the loops?  use a sentinel-value We choose a sentinel-value which can not be a score (e.g. –1) We read the scores until this sentinel-value has been entered. When this sentinel-value has been read, we stop the loop. BBS514 Structured Programming (Yapısal Programlama)12

Sentinel-Controlled Loops Problem becomes: Develop a class-averaging program that will process an arbitrary number of grades each time the program is run. –Unknown number of students –How will the program know to end? Use sentinel value –Also called signal value, dummy value, or flag value –Indicates “end of data entry.” –Loop ends when user inputs the sentinel value –Sentinel value chosen so it cannot be confused with a regular input (such as -1 in this case) BBS514 Structured Programming (Yapısal Programlama)13

/* Class average program with sentinel-controlled repetition */ #include int main() { float average; int counter, grade, total; /* initialization phase */ total = 0; counter = 0; /* processing phase */ printf( "Enter grade, -1 to end: " ); scanf( "%d", &grade ); while ( grade != -1 ) { total = total + grade; counter = counter + 1; printf( "Enter grade, -1 to end: " ); scanf( "%d", &grade ); } /* termination phase */ if ( counter != 0 ) { average = ( float ) total / counter; printf( "Class average is %.2f", average ); } else printf( "No grades were entered\n" ); return 0; /* indicate program ended successfully */ } BBS514 Structured Programming (Yapısal Programlama)14 Enter grade, -1 to end: 75 Enter grade, -1 to end: 94 Enter grade, -1 to end: 97 Enter grade, -1 to end: 88 Enter grade, -1 to end: 70 Enter grade, -1 to end: 64 Enter grade, -1 to end: 83 Enter grade, -1 to end: 89 Enter grade, -1 to end: -1 Class average is 82.50

for Statement Another loop statement in C is for-statement. for-statement is more suitable for counter-controlled loops. for ( initialization ; condition ; increment ) statement which is equivalent to initialization ; while ( condition ){ statement ; increment ; } BBS514 Structured Programming (Yapısal Programlama)15

for Statement – Flow Diagram BBS514 Structured Programming (Yapısal Programlama)16 initialization statement increment condition false true for ( initialization ; condition ; increment ) statement

for Statement Example: for(counter = 1; counter <= 10; counter++ ) printf( "%d\n", counter ); –Prints the integers from one to ten Initialization and increment –Can be comma-separated lists –Example: for (i = 0, j = 0; j + i <= 10; j++, i++) printf( "%d\n", j + i ); BBS514 Structured Programming (Yapısal Programlama)17 No semicolon ( ; ) after last expression

for statement -- Example int i;int sum = 0; for (i=1; i<=20; i++)  i = 1; sum = sum + i;while (i<=20) { sum = sum + i; i++; } --- int i; int sum = 0; for (i=100; i>=1; i--)  i = 100; sum = sum + i;while (i>=1) { sum = sum + i; i++; } BBS514 Structured Programming (Yapısal Programlama)18

for statement -- Example int i, j; int count=0; for (i=1, j=10; i<j; i++, j--)  count is 5 count++; int i, j; int count=0; i=1; j=10; for (; i<j; ) { count++; i++; j--; } BBS514 Structured Programming (Yapısal Programlama)19

The do / while Repetition Structure The do / while repetition structure –Similar to the while structure –Condition for repetition tested after the body of the loop is performed All actions are performed at least once –Format: do { statement; } while ( condition ); BBS514 Structured Programming (Yapısal Programlama)20

do-while statement – Flow Diagram BBS514 Structured Programming (Yapısal Programlama)21 statement condition false true

do-while statement – Example /*Using the do/while repetition structure */ #include int main() { int counter = 1; do { printf( "%d ", counter ); counter = counter + 1; } while ( counter <= 10 ); return 0; } Program Output: BBS514 Structured Programming (Yapısal Programlama)

Nested Loops When a loop body includes another loop construct this is called a nested loop. In a nested loop structure the inner loop is executed from the beginning every time the body of the outer loop is executed. Example 1: value = 0; for (i=1; i<=10; i=i+1) for (j=1; j<=5; j=j+1) value = value + 1; How many times the inner loop is executed?  value is 10*5=50 BBS514 Structured Programming (Yapısal Programlama)23

Nested Loops Example 2: value = 0; for (i=1; i<=10; i=i+1) for (j=1; j<=i; j=j+1) value = value + 1; How many times the inner loop is executed?  value is =55 BBS514 Structured Programming (Yapısal Programlama)24

Nested Loops - Printing a triangle Write a program to draw a triangle like the following: (The number of lines is an input) * ** *** **** ***** We can use a nested for-loop: for (i=1; i<=num_lines; ++i){ for (j=1; j<=i; ++j) printf("*"); printf("\n"); } BBS514 Structured Programming (Yapısal Programlama)25

Nested Loops – Example2 a triangle shape (1 st line contains 1 star, 2 nd line contains 3 star,..., nth line contains 2n-1 stars) *for (i=1; i<=n; i++) { // for each line *** for (j=1; j<=(n-i); j++) ***** printf(“ ”);. for (j=1; j<=(2*i-1); j++). printf(“*”); ***.....*** printf(“\n”); } BBS514 Structured Programming (Yapısal Programlama)26

Nested Loops – Example3 /* This program reads numbers until the user enters a negative number. For each number read, it prints the number and the summation of all values between 1 and the given number. */ int main() { int num, count, total = 0; printf( "Enter a value or a negative number to end: " ); scanf( "%d", &num ); while ( num >= 0 ) { for (count = 1; count <= num; count++) total = total + count; printf(“%5d%5d”,num, total); printf( "Enter a value or a negative number to end:"); scanf( "%d", &num ); total = 0; } return 0; } BBS514 Structured Programming (Yapısal Programlama)27

Nested Loops – Example4 Nesting can be more than one level int sum=0; for (i=1; i<=5; i++) for (j=1; j<=5; j++) for (k=1; k<=5; k++) sum=sum+1;  sum is 125 BBS514 Structured Programming (Yapısal Programlama)28

Loop - Exercises Write a program that reads an integer N and computes N! fact = 1; for (j = 1; j <= n; j++) fact = fact * j; Write a program for finding the sum of the first n terms of the series 1 + 1/2+ 1/3 + …. float sum = 0; for (j = 1; j <= n; j++) sum = sum / j; BBS514 Structured Programming (Yapısal Programlama)29

Loop - Exercises Write a program that reads numbers until a negative number is read and prints the number of values read, the largest value, the smallest value and the range. count =0; scanf (“%d”,&num); min = max = num; while (num >= 0){ count ++; if (num < min) min = num; else if (num > max) max = num; scanf (“%d”,&num); } printf(“count:%d max:%d min:%d range:[%d.. %d]”, count,max,min,min,max); BBS514 Structured Programming (Yapısal Programlama)30

Loop - Exercises Consider the Fibonacci sequence: … Write a program to find the nth Fibonnacci number. int main () { int n, prev1=1, prev2=0, temp, j; printf(“Enter n > “); scanf(“%d”, &n); if (n==0 || n== 1) printf(“%d th Fib number is %d”, n, n); else { prev1 = 0; prev2 = 1; for (j=1; j <= n; j++) { temp = prev1 + prev2; prev2 = prev1; prev1 = temp; } printf(“%d th Fib number is %d”, n, prev1); } BBS514 Structured Programming (Yapısal Programlama)31

Loop - Exercises Write a program to test whether a given positive integer (> 1) is a prime number of not. if (n == 2) printf(“%d is prime”, n); else if (n%2 == 0) printf(“%d is NOT prime”, n); else { flag = 1; for (i = 3; i < (n/2) && flag ); i += 2) { if (n%i == 0) flag = 0; } if (flag == 1) printf(“%d is prime”, n); else printf(“%d is NOT prime”, n); } BBS514 Structured Programming (Yapısal Programlama)32