Chapter 5 Repetition and Loop Statements Instructor: Alkar & Demirer.

Slides:



Advertisements
Similar presentations
CS201 - Repetition loops.
Advertisements

Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
1 CS 201 Repetition Debzani Deb. 2 Overview Loops  Endfile-Controlled loop  Nested loop  Do-While loop  Flag-Controlled loop Hand Tracing the code.
Chapter 5: Loops and Files.
1 TDBA66, VT-03, Lecture - Ch. 5 Repetition Loops are common in programming (computers can do boring things over and over again) Type of loopWhen usedC-structures.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
Chapter 5 Repetition and Loop Statements Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Unit 4 Repetition and Loops. Key Concepts Flowcharting a loop Types of loops Counter-controlled loops while statement Compound assignment operator for.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
1 ICS103 Programming in C Ch5: Repetition and Loop Statements.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Chapter 5 Repetition and Loop Statements J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
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.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
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;
1 ICS103 Programming in C Lecture 7: Repetition Structures.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Chapter 5: Repetition and Loop Statements By: Suraya Alias.
Copyright © 2012 Pearson Education, Inc. Chapter 5: 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.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
CISC105 – General Computer Science Class 4 – 06/14/2006.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
PGT C Programming1 Week 4 – Repetition Structures / Loops.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
Problem Solving and Program Design in C Chap. 5 Repetition and Loop Statement Chow-Sing Lin.
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
CHAPTER 4 REPETITION STRUCTURES 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 A.AlOsaimi.
CHAPTER 6: REPETITION AND LOOP STATEMENTS Learning outcomes  Define the concept of repetition structure.  Specify.
Chapter 4 Repetition Structures
Topic 4: Looping Statements
REPETITION CONTROL STRUCTURE
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
CHAPTER 6: REPETITION AND LOOP STATEMENTS
ICS103 Programming in C Lecture 7: Repetition Structures
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Alternate Version of STARTING OUT WITH C++ 4th Edition
Repetition and Loop Statements
Control Statements Loops.
Chapter 6: Repetition Statements
Repetition and Loop Statements
More Loops Topics Counter-Controlled (Definite) Repetition
Control Statements Loops.
More Loops Topics Counter-Controlled (Definite) Repetition
Chapter 4 Repetition Structures
ICS103: Programming in C 5: Repetition and Loop Statements
More Loops Topics Counter-Controlled (Definite) Repetition
Presentation transcript:

Chapter 5 Repetition and Loop Statements Instructor: Alkar & Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-2 Repetition in Programs In most software, the statements in the program may need to repeat for many times. –e.g., calculate the value of n!. –If n = 10000, it’s not elegant to write the code as 1*2*3*…* LoopLoop is a control structure that repeats a group of steps in a program. –Loop body –Loop body stands for the repeated statements. There are three C loop control statements: –whilefordo-while –while, for, and do-while.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-3 Flow Diagram of Loop Choice Process e.g., calculate the value of n! e.g., read the content in a file

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-4 Comparison of Loop Choices (1/2) KindWhen to UseC Structure Counting loopWe know how many loop repetitions will be needed in advance. while, for Sentinel- controlled loop Input of a list of data ended by a special value while, for Endfile- controlled loop Input of a list of data from a data file while, for

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-5 Comparison of Loop Choices (2/2) KindWhen to UseC Structure Input validation loop Repeated interactive input of a value until a desired value is entered. do-while General conditional loop Repeated processing of data until a desired condition is met. while, for

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-6 The while Statement in C The syntax of while statement in C: loop repetition condition while (loop repetition condition) statement Loop repetition conditionLoop repetition condition is the condition which controls the loop. trueThe statement is repeated as long as the loop repetition condition is true. infinite loopA loop is called an infinite loop if the loop repetition condition is always true.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-7 An Example of a while Loop Statement Loop repetition condition Loop control variable Loop control variable is the variable whose value controls loop repetition. In this example, count_emp is the loop control variable.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-8 Flowchart for a while Loop Loop repetition condition Statement

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-9 Compound Assignment Operators (1/2) The loop body usually consists of statements of the form: variable = variable op expression. –e.g., count_emp = count_emp + 1; compound assignment operatorsC provides compound assignment operators which enable a more concise notation for this kind of statements. –“variable op = expression” –“variable op = expression” is the same to “variable = variable op expression.”

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-10 Compound Assignment Operators (2/2) Simple Assignment Operators Compound Assignment Operators count_emp = count_emp + 1; count_emp += 1; time = time -1;time -= 1; product = product * item; product *= item; total = total / number; total /= number; n = n % (x+1);n %= x+1;

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-11 The for Statement in C The syntax of for statement in C: initialization expression for (initialization expression; loop repetition condition loop repetition condition; update expression update expression) statement initialization expressionThe initialization expression set the initial value of the loop control variable. loop repetition conditionThe loop repetition condition test the value of the loop control variable. update expressionThe update expression update the loop control variable.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-12 An Example of the for Loop Loop repetition condition Initialization Expression Update Expression count_emp is set to 0 initially. count_emp should not exceed the value of number_emp. count_emp is increased by one after each iteration.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-13 Increment and Decrement Operators The statements of increment and decrement are commonly used in the for loop. ++--The increment (i.e., ++) or decrement (i.e., --) operators are the frequently used operators which take only one operand. The increment/decrement operators increase or decrease the value of the single operand. i++ –e.g., for (int i = 0; i < 100; i++){ … } –The variable i increase one after each iteration.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-14 Comparison of Prefix and Postfix Increments The value of the expression (that uses the ++/-- operators) depends on the position of the operator. The value of j is increased The value of j is not increased

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-15 Sentinel-Controlled Loops Sometimes we may not know how many times the loop will repeat. sentinel valueOne way to do this is to choose a sentinel value as an end marker. sentinel value –The loop exits when the sentinel value is read. sentinel valueIf the user wish to exit the loop, he or she has to input the sentinel value. –It is similar to the “logout” function in many applications.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-16 An Example of Sentinel-Controlled while Loops If the user wish to exit the loop, he or she has to input -99.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-17 An Example of Endfile-Controlled Loops fscanffscanf is a function used to read file. EOF fscanfEOF stands for the special value of end-file returned by fscanf. This loop repeats until reading the end of the file.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-18 Nested Loops Usually used to work with two dimensional arrays (later). Nested loops consist of an outer loop with or more inner loops. Each time the outer loop is repeated, the inner loops are reentered –Their loop control expressions are reevaluated –All required iterations are performed again.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-19 Nested Loops outer loop inner loopsNested loops consist of an outer loop with one or more inner loops. e.g., for (i=1;i<=100;i++){ for(j=1;j<=50;j++){ … } The above loop will run for 100*50 iterations. Inner loop Outer loop

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-20 What is the Output? lcv1 = 0; sum = 0; while (lcv1 < 100) { lcv2 = 0; while (lcv2 < 100) { sum = sum + 1; lcv2++; } lcv1++; } printf(“Sum is %d\n”, sum); /* Output = */ Sum is 10000

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-21 What is the Output? int a=0, b=0, sum=0; for(a=0; a<6; a+=2) for(b=0; b>4; b--) sum=sum+1; printf(“%d”,sum); /* Output = */ Sum is 0

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-22 Do While statement Both the for statement and the while statement evaluate the loop condition before the first execution of the loop body. In most cases, this pretest is desirable and prevents the loop from executing when there may be no data items to process There are some situations, generally involving interactive input, when we know that a loop must execute at least one time.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-23 The do-while Statement in C The syntax of do-while statement in C: loop repetition condition do statement while (loop repetition condition); The statement is first executed. loop repetition conditionIf the loop repetition condition is true, the statement is repeated. Otherwise, the loop is exited.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-24 An Example of the do-while Loop /* Find even number input */ do{ printf(“Enter a value: ”); scanf(“%d”, &num); }while (num % 2 !=0) This loop will repeat if the user inputs odd number.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-25 Do-While Example do { printf("Enter a letter from A through E> "); scanf("%c", &letter_choice); }while (letter_choice ’E’);

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-26 Flag Controlled Loops Sometimes a loop repetition condition becomes so complex that placing the full expression in its usual spot is awkward. In many cases, the condition may be simplified by using a flag. while (flag) { …. } A flag is a type int variable used to represent whether or not a certain event has occurred. A flag has one of two values: 1 (true) and 0 (false).

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-27 Endfile-controlled loops Many library functions return helpful data as the value of the function. For example, scanf returns the number of data items it actually obtained. num = scanf(“%d%d%d”, &n1, &n2, &n3); A data file is always terminated by an endfile character (EOF) that can be detected by the scanf and fscanf functions. You can write a program that processes a list of data of any length from a file without requiring a special sentinel value at the end of the data file.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-28 #include int main(void) { FILE *inp; int sum = 0, score, input_status; inp = fopen("scores.dat", "r"); input_status = fscanf(inp, "%d", &score); while (input_status != EOF) { printf("%d ", score); sum += score; input_status = fscanf(inp, "%d", &score); } printf("\nSum of exam scores is %d\n", sum); fclose(inp); return 0; } /* Output */ Sum of exam scores is 165

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-29 What is the Output? int i, sum=0,status=0; status = scanf(“%d”,&i); while(status!=EOF) { sum+=i; status = scanf(“%d”,&i); } printf(“%d\n”, sum); /* Input = */ ctl-d /* Output = */ 12

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-30 In class work (1/2) Write a program that prompts the user to input an integer n. Draw a triangle with n levels by star symbols. For example, n = 3, * ** *** After drawing the triangle, repeat the above process until the user input a negative integer.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-31 In class work #4 (2/2) An usage scenario: Please input: 2 * ** Please input: 3 * ** *** Please input: -9 Thank you for using this program.