Control Structures Lecture 7.

Slides:



Advertisements
Similar presentations
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
Advertisements

CS201 - Repetition loops.
1 Lecture 11:Control Structures II (Repetition) (cont.) Introduction to Computer Science Spring 2006.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter 4 Control Structure: Loop Knowledge: Understand the various concepts of loop control structure Skill: Be able to develop a program involving loop.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
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.
C++ Programming Lecture 6 Control Structure II (Repetition) By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (for) Outline 4.1Introduction 4.2The.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
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;
Introduction to Programming Lecture 7: Repeating Statements.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
PGT C Programming1 Week 4 – Repetition Structures / Loops.
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.
© 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.
Week 3.  TO PRINT NUMBERS FROM 1 TO 20  TO PRINT EVEN NUMBERS FROM 1 TO 20 2.
Chapter 3 Structured Program Development in C Part II C How to Program, 8/e, GE © 2016 Pearson Education, Ltd. All rights reserved.1.
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
ECE Application Programming
Chapter 4 – C Program Control
REPETITION CONTROL STRUCTURE
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Chapter 4 C Program Control Part I
Lecture 7: Repeating a Known Number of Times
Chapter 5: Control Structures II
Chapter 4 - Program Control
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
CS1010 Programming Methodology
Repetition-Counter control Loop
Ch 7: JavaScript Control Statements I.
Iteration statement while do-while
Lecture 07 More Repetition Richard Gesick.
2008/10/22: Lecture 12 CMSC 104, Section 0101 John Y. Park
Lecture 4B More Repetition Richard Gesick
Chapter 13 Control Structures
Looping.
Programming Fundamentals Lecture #6 Program Control
TOPIC 4: REPETITION CONTROL STRUCTURE
How to develop a program?
Structured Program Development in C
2008/10/22: Lecture 12 CMSC 104, Section 0101 John Y. Park
Chapter 4 - Program Control
Exam 1 Date: Feb. 2nd, 2015 during class time (50 minutes) Coverage
Loops in C.
Chapter 2.1 Repetition.
Repetition and Loop Statements
UMBC CMSC 104 – Section 01, Fall 2016
EPSII 59:006 Spring 2004.
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
Chapter 4 - Program Control
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
ICS103: Programming in C 5: Repetition and Loop Statements
More Loops Topics Counter-Controlled (Definite) Repetition
Presentation transcript:

Control Structures Lecture 7

Outline Control Structures Repetiton structure While Do while For

Repetition Example: Write a program that read 3 integer and compute average It is easy. 3 scanf, an addition, a division and, a printf Example: Write a program that read 3000 integer and compute average  ?? 3000 scanf !!! Example: Write a program that read n integer and compute average N??? scanf Repetition in algorithms

Repetition: counter controlled When we know the number of iteration Average of 10 number Initialize counter  0 Initialize other variables While (counter < number of loop repetition) do something (e.g. read input, take sum) counter  counter + 1

Repetition: counter controlled Consider the following problem statement: A class of ten 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.

Repetition: sentinel controlled When we do NOT know the number of iteration But we know, when loop terminates E.g. Average of arbitrary positive numbers ending with <0 Get first input  n While (n is not sentinel) do something (sum, …) get the next input  n if (there is not any valid input) then S1 else S2

Repetition: sentinel controlled Consider the following problem: Develop a class averaging program that will process an arbitrary number of grades each time the program is run. One way to solve this problem is to use a special value called a sentinel value (also called a signal value, a dummy value, or a flag value) to indicate “end of data entry.”

Repetition: sentinel controlled The user types in grades until all legitimate grades have been entered. The user then types the sentinel value to indicate that the last grade has been entered. Clearly, the sentinel value must be chosen so that it cannot be confused with an acceptable input value.

Repetition: sentinel controlled

Repetition Repetition is performed by loops Don’t loop to infinity Put all statements to repeat in a loop Don’t loop to infinity Stop the repetition Based on some conditions (counter, sentinel) C has 3 statements for loops while statement do-while statement for statement

Repetition Structure A loop tests a condition, and if the condition exists, it performs an action. Then it tests the condition again. If the condition still exists, the action is repeated. This continues until the condition no longer exists x < y? Process A YES

Repetition Essentials A loop is a group of instructions the computer executes repeatedly while some loop-continuation condition remains true. We have discussed two means of repetition: Counter-controlled repetition Sentinel-controlled repetition Counter-controlled repetition is sometimes called definite repetition because we know in advance exactly how many times the loop will be executed. Sentinel-controlled repetition is sometimes called indefinite repetition because it’s not known in advance how many times the loop will be executed.

Counter-Controlled Repetition In counter-controlled repetition, a control variable is used to count the number of repetitions. Counter-controlled repetition requires: The initial value of the control variable. The increment (or decrement) by which the control variable is modified each time through the loop. The condition that tests for the final value of the control variable (i.e., whether looping should continue).

Sentinel-Controlled Repetition Sentinel values are used to control repetition when: The precise number of repetitions is not known in advance, and The loop includes statements that obtain data each time the loop is performed. The sentinel is entered after all regular data items have been supplied to the program. Sentinels must be distinct from regular data items.

While statement while ( <expression> ) <statements>

#include <stdio.h> برنامه ای بنویسید که عدد n را از کاربر بگیرد و اعداد 0 تا n را چاپ کند. int main(void){ int n, number; number = 0; printf("Enter n: "); scanf("%d", &n); while(number <= n){ printf("%d \n", number++; number); } return 0; number = -1; while(++number <= n) printf("%d \n", number); }

#include <stdio.h> int main(void){ int negative_num, positive_num; int number; negative_num = positive_num = 0; printf("Enter Zero to stop \n"); printf("Enter next number: "); scanf("%d", &number); while(number != 0){ if(number > 0) positive_num++; else negative_num++; printf("Enter next number: "); scanf("%d", &number); } printf("The number of positive numbers printf("The number of negative numbers return 0; = %d\n", positive_num); = %d\n", negative_num); }

Another Example Consider a program segment designed to find the first power of 3 larger than 100. When the following while repetition statement finishes executing, product will contain the desired answer: product = 3; while ( product <= 100 ) { product = 3 * product; } /* end while */

Do-while statement do <statements> while (<expression>);

#include <stdio.h> int main(void){ int n; double number, sum; printf("Enter n > 0: "); scanf("%d", &n); if(n < 1){printf("wrong input"); return sum = 0; number = 0.0; do{ number++; sum += number / (number + 1.0); }while(number < n); -1;} printf("sum = %f\n", sum); return 0; }

#include <stdio.h> int main(void){ int negative_num=0, positive_num=0; int number; printf("Enter Zero to stop \n"); do{ printf("Enter next number: "); scanf("%d", &number); if(number > 0) positive_num++; else if(number < 0) negative_num++; }while(number != 0); printf("The number of positive printf("The number of negative return 0; numbers numbers = %d\n", positive_num); = %d\n", negative_num); }

for(<expression1>;<expression2>; <expression3>) <statements>

int x, sum, i; sum = 0; for (i = 1; i < 6; i++) { scanf(“%d”,&x); counter ← 1, sum ← 0 int x, sum, i; sum = 0; for (i = 1; i < 6; i++) { scanf(“%d”,&x); sum = sum + x; } counter < 6 false true input n sum ← sum + n counter++ printf(“%d”,sum); output sum 23

for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); ??? Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num _ 24

for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num _ 25

for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num _ 26

for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 _ 27

for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); 2 Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 _ 28

for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); 2 Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 _ 29

for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); 2 Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 2 _ 30

for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 2 _ 31

for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 2 _ 32

for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 2 3 _ 33

for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); 4 Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 2 3 _ 34

for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); 4 Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 2 3 _ 35

for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); 4 Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”); num 1 2 3 have come to exit_ 36

#include <stdio.h> int main(void){ int grade, count, i; double average, sum; sum = 0; printf("Enter the number of students: "); scanf("%d", &count); for(i = 0; i < count; i++){ printf("Enter the grade of %d-th student: scanf("%d", &grade); sum += grade; } average = sum / count; ", (i + 1)); printf("The average of your class is %0.3f\n", return 0; average); }

#include <stdio.h> int main(void){ int n, number; printf("Enter n: "); scanf("%d", &n); <= n; number++) 0) for(number = 1; number if((number % 2) == printf("%d \n", number); return 0; }

#include <stdio.h> int main(void){ int n, number; printf("Enter n: "); scanf("%d", &n); for(number = 2; number <= n; number += 2) printf("%d \n", number); return 0; }

Expressions in for statements Expression1 and Expression3 can be any number of expressions  for(i = 0, j = 0; i < 10; i++, j--) Expression2 at most should be a single expression  for(i = 0, j = 0; i < 10, j > -100; i++, j--) //ERROR Any expression can be empty expression for(;i<10;t++) for(;;)//infinite loop

Expressions in for statements The three expressions in the for statement are optional. One may omit expression1 if the control variable is initialized elsewhere in the program. If expression2 is omitted, C assumes that the condition is true, thus creating an infinite loop. expression3 may be omitted if the increment is calculated by statements in the body of the for statement or if no increment is needed.

for Repetition Statement The for repetition statement handles all the details of counter-controlled repetition.

Examples The following examples show methods of varying the control variable in a for statement. Vary the control variable from 1 to 100 in increments of 1. for ( i = 1; i <= 100; i++ ) Vary the control variable from 100 to 1 in increments of -1 (decrements of 1). for ( i = 100; i >= 1; i-- ) Vary the control variable from 7 to 77 in steps of 7. for ( i = 7; i <= 77; i += 7 ) Vary the control variable from 20 to 2 in steps of -2. for ( i = 20; i >= 2; i -= 2 ) Vary the control variable over the following sequence of values: 2, 5, 8, 11, 14, 17. for ( j = 2; j <= 17; j += 3 ) Vary the control variable over the following sequence of values: 44, 33, 22, 11, 0. for ( j = 44; j >= 0; j -= 11 )

Empty statements <statement> in loops can be empty while(<expression>) ; E.g., while(i++ <= n) ; for(<expression1>; <expression2>;<expression3>); E.g., for(i = 0; i < 10; printf("%d\n",i), i++) ;

Nested loops <statement> in loops can be loop itself while(<expression0>) for(<expression1>; <expression2>;<expression3>) <statements> do while(<expression>);

Nested loops example 1 A program that takes n and m and prints *** ….* (m * in each line) *** ….* … *** ….* (n lines)

#include <stdio.h> int main(void){ int i, j, n, m; printf("Enter n & scanf("%d%d", &n, m: "); &m); for(i = 0; i < n; i++){ for(j = 0; j < m; j++) printf("*"); printf("\n"); } return 0;

Nested loops example 2 A program that takes n and prints * ** *** (i * in i-th line) *** ….* (n lines)

#include <stdio.h> int main(void){ int i, j, n; printf("Enter n: "); scanf("%d", &n); i = 1; while(i <= n){ for(j = 0; j < i; j++) printf("*"); printf("\n"); i++; } return 0;

Nested loops example 3 A program that takes a number and generates the following pattern for(i= 1; i <= n; i++){ for(j= 0; j < i-1;j++) printf(" "); for(j= 1; j <= i; j++) printf("*"); printf("\n"); } for(i=n-1; i >= 1; i--){ for(j= 1; j < i; j++) for(j = 1; j <= i; j++) Input = 5 * ** *** **** *****

break statement The break and continue statements are used to alter the flow of control. The break statement, when executed in a while, for, do…while or switch statement, causes an immediate exit from that statement. Program execution continues with the next statement.

break statement Exit from loop based on some conditions do{ scanf("%d", &a); scanf("%d", &b); if(b == 0) break; res = a / b; printf("a /= %d\n", res); }while(b > 0);

break statement int i,j; for(i=1; i<6;i++){ for(j =1; j<6;j++) { printf("%d %d\n" , i,j); if(j==3) break; }

continue statement Jump to end of loop and continue repetition The continue statement, when executed in a while, for or do…while statement, skips the remaining statements in the body of that control statement and performs the next iteration of the loop. do{ scanf("%f", &a); scanf("%f", &b); if(b == 0) continue; res = a / b; printf("a / b= %f\n", res); }while(a> 0);

Which loop? When you know the number of repetition Counter-controlled loops Usually, for statements When you don’t know the number of repetitions (sentinel loop) Some condition should be check before starting loop Usually, while statement The loop should be executed at least one time Usually, do-while statement

Common bugs and avoiding them Loop should terminate E.g., in for loops, after each iteration, we should approach to the stop condition for(i = 0; i < 10; i++) //OK i--) //Bug Initialize loop control variables int i; for( ; i < 10; i++) //Bug

Common bugs and avoiding them Don’t modify for loop controller in loop body for(i = ... i--; 0; i < 10; i++){ //Bug } Take care about wrong control conditions  < vs. <=  = vs. == int b = 10; while(a = b){//it means while(true) scanf("%d",&a) … {