EKT150 INTRODUCTION TO COMPUTER PROGRAMMING

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

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
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.
Loop.  While Loop  Do-while Loop  For Loop Continue Statement Conclusion Loop Loop.
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;
ITERATIVE STATEMENTS. Definition Iterative statements (loops) allow a set of instruction to be executed or performed several until condition are met.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
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.
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.
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.
Week 3.  TO PRINT NUMBERS FROM 1 TO 20  TO PRINT EVEN NUMBERS FROM 1 TO 20 2.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
ECE Application Programming
Chapter 4 – C Program Control
CSE 220 – C Programming Loops.
REPETITION CONTROL STRUCTURE
EKT120 COMPUTER PROGRAMMING
Chapter 5: Control Structures II
- Standard C Statements
Lecture 7: Repeating a Known Number of Times
Chapter 5: Control Structures II
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Chapter 4 - Program Control
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Repetition-Counter control Loop
Chapter 2.2 Control Structures (Iteration)
Chapter 5: Control Structures II
Control Structures Lecture 7.
Looping.
Arrays, For loop While loop Do while loop
MSIS 655 Advanced Business Applications Programming
- Additional C Statements
Outline Altering flow of control Boolean expressions
Structured Program
Chapter 4 - Program Control
Loops in C.
The while Looping Structure
Chapter 2.1 Repetition.
Control Statements Loops.
Program Control Topics While loop For loop Switch statement
Chapter 2.2 Control Structures (Iteration)
Chapter 6: Repetition Statements
Repetition and Loop Statements
EPSII 59:006 Spring 2004.
More Loops Topics Counter-Controlled (Definite) Repetition
Dale Roberts, Lecturer IUPUI
ECE 103 Engineering Programming Chapter 18 Iteration
Control Statements Loops.
Chapter 4 - Program Control
Based on slides created by Bjarne Stroustrup & Tony Gaddis
More Loops Topics Counter-Controlled (Definite) Repetition
Dale Roberts, Lecturer IUPUI
The while Looping Structure
The while Looping Structure
ICS103: Programming in C 5: Repetition and Loop Statements
More Loops Topics Counter-Controlled (Definite) Repetition
Presentation transcript:

EKT150 INTRODUCTION TO COMPUTER PROGRAMMING Control Structure: Repetition Dr. Nur Hafizah Ghazali hafizahghazali@unimap.edu.my

Recaps... Control Structure All programs could be written in terms of three control structures: Sequence structure Selection structure one-way selection: if if ... else switch Repetition structure

Today’s Outline Introduction to Repetition Structure (Loops) Type of loops while loops do-while loops for loops Nested loops

Why Need Loops ? Suppose we want to add five numbers and find the average. From what you have learned so far, you could proceed as follows scanf(“%f %f %f %f %f”, &fNum1, &fNum2, &fNum3, &fNum4, &fNum5); fSum = fNum1 + fNum2 + fNum3 + fNum4 + fNum5; fAverage = fNum / 5; If 100 numbers or 1000 numbers?

Repetition Structures (Loop) Used to control the flow of a program Loops are basically repetitions or iterations used to repeat a segment of code Three statements used to implement loops in C: while statement do-while statement for statement while and for statements are similar in implementation, but have different syntax The do-while statement is different do-while statement is executed at least once

1. while Repetition Structure The general form of the while statement is: while (expression) statement; To avoid an infinite loop, the loop’s body must contains statement (s) that assure the exit condition i.e. the expression in the while statement will eventually be false. while loop repeats until condition becomes false

Flowchart of a while statement

Types of while Loops There are basically three types of while loops: Counter-controlled while loop Sentinel-controlled while loop Flag-controlled while loop

Counter-Controlled while Loops Count-controlled while loop uses a loop control variable in the logical expression Control variable used to count repetitions Loop control variable should be initialized before entering the while loop, and a statement in the body of the while loop should increment/decrement the control variable Definite repetition: know how many times loop will execute

Example : Counter-Controlled while #include <stdio.h> int main() { int iCounter = 1; while ( iCounter <= 10 ) printf( "%d\n", iCounter ); ++iCounter; } return 0; Declare and initialize control variable value (or loop counter) test condition  A condition that tests for the final value of the control variable (i.e., whether looping should continue) Update control variable (increment/decrement)

Example : Counter-Controlled while #include <stdio.h> int main() { int iCounter = 1; while ( iCounter <= 10 ) printf( "%d\n", iCounter ); ++iCounter; } return 0; 1 2 3 4 5 6 7 8 9 10

Example : Counter-Controlled while Adding integers from 1 to 100 int iCount = 1; int iSum=0; while (iCount <= 100 ){ printf(“Adding %d to %d ”, iCount,iSum); iSum = iSum + iCount; printf(“ = %d”, iSum); ++iCounter; } iCounter <= 100 iSum = iSum + iCounter true false declare and initialize test condition increment

Example : Counter-Controlled while Adding integers from 1 to 100 int iCount = 1; int iSum=0; while (iCount <= 100 ){ printf(“Adding %d to %d ”, iCount,iSum); iSum = iSum + iCount; printf(“ = %d”, iSum); ++iCounter; } iCounter <= 100 iSum = iSum + iCounter true false Adding 1 to 0 = 1 Adding 2 to 1 = 3 Adding 3 to 2 = 5 … Adding 100 to 4950 = 5050 declare and initialize test condition increment

Sentinel-Controlled while Loops An event-controlled while loop may use a special data value, sentinel, in conjunction with the logical expression to signal the loop exit. Sentinel value indicates "end of data“ As long as the sentinel value does not meet the logical expression (specified data value), the loop is executed Used when the number of repetitions is unknown and loop needs to input value repeatedly for each iteration

Example: Sentinel-Controlled while Adding multiple numbers int iNumber; //declaration control variable int iSum = 0; int iCount = 0; printf("To stop enter -999. Enter numbers : " ); scanf("%d",&iNumber);//read control variable value before enter loop while (iNumber != -999) // test condition { iSum = iSum + iNumber; //find sum of numbers entered iCount++;//counting numbers entered (increment of control variables) scanf("%d", &iNumber); //Read again control variable value } printf("\nThe sum of %d numbers is %d", iCount, iSum);

Example: Sentinel-Controlled while Adding multiple numbers int iNumber; //declaration control variable int iSum = 0; int iCount = 0; printf("To stop enter -999. Enter numbers : " ); scanf("%d",&iNumber);//read control variable value before enter loop while (iNumber != -999) // test condition { iSum = iSum + iNumber; //find sum of numbers entered iCount++;//counting numbers entered (increment of control variables) scanf("%d", &iNumber); //Read again control variable value } printf("\nThe sum of %d numbers is %d", iCount, iSum); To stop enter -999. Enter numbers : 4 To stop enter -999. Enter numbers : 900 To stop enter -999. Enter numbers : 1600 To stop enter -999. Enter numbers : -999 The sum of 3 numbers is 2504

Example: Sentinel-Controlled while Evaluating grade points char cChoice; float fGradePt=0; printf(“Do want to begin? y-yes n-no: ”); scanf(“%c”, &cChoice); while ( cChoice == ‘y’) { printf(“\nEnter grade point: ”); scanf(“%f”, &fGradePt); if(fGradePt > 2.0) printf(“\nPass\n”); else printf(“\n Fail \n”); printf(“Continue? y-yes n-no: ”); } declare control variable read control variable test condition read again

Example: Sentinel-Controlled while Evaluating grade points char cChoice; float fGradePt=0; printf(“Do want to begin? y-yes n-no: ”); scanf(“%c”, &cChoice); while ( cChoice == ‘y’) { printf(“\nEnter grade point: ”); scanf(“%f”, &fGradePt); if(fGradePt > 2.0) printf(“\nPass\n”); else printf(“\n Fail \n”); printf(“Continue? y-yes n-no: ”); } declare control variable read control variable test condition Do you want to begin? y-yes n-no : y Enter grade point : 2.5 Pass Continue? y-yes n-no: y Enter grade point : 1.9 Fail Continue? Y-yes n-no: n read again

Flag-Controlled while Loops A flag is a boolean variable (only can be set to true or false) If a flag is used in a while loop to control the loop execution, then the while loop is referred to as a flag-controlled while loop Hence, the end-of-file-controlled while loop is a special case of a flag-controlled while loop Loop exit when expression is evaluated to false

Example : Flag-Controlled while Adding multiple numbers bool proceed; // used to control the while loop int sum; // the sum of the numbers read int number; // the number read sum = 0; // initialize the sum proceed = true; // initialize the boolean variable done while ( proceed ) // while proceed is true { scanf(“%d”,&number); // read next number if ( number > 0 ) // sum number if positive sum = sum + number; // sum the number else proceed = false; // terminate the loop } printf(“Sum is %d \n”,sum);

Example : Flag-Controlled while Adding multiple numbers bool proceed; // used to control the while loop int sum; // the sum of the numbers read int number; // the number read sum = 0; // initialize the sum proceed = true; // initialize the boolean variable done while ( proceed ) // while proceed is true { scanf(“%d”,&number); // read next number if ( number > 0 ) // sum number if positive sum = sum + number; // sum the number else proceed = false; // terminate the loop } printf(“Sum is %d \n”,sum); 100 200 300 400 Sum is 1000

2. do-while Repetition Structure Similar to the while structure Condition for repetition is tested after the body of the loop is performed at least once Expression can be written as count-controlled or sentinel-controlled Format: do { statement; } while ( condition );

Flowchart of a do-while loop action(s) true condition false

Example: Counter-Controlled do-while Adding integer from 1 to 10 int iCounter = 1; int iSum=0; do { printf(“Ading %d to %d =",iCounter,iSum ); iSum=iSum+iCounter; printf(“ %d\n”,iSum); } while ( ++iCounter <= 10 );  

Example: Counter-Controlled do-while Adding integer from 1 to 10 int iCounter = 1; int iSum=0; do { printf(“Adding %d to %d =",iCounter,iSum ); iSum=iSum+iCounter; printf(“ %d\n”,iSum); } while ( ++iCounter <= 10 ); Adding 1 to 0 = 1 Adding 2 to 1 = 3 Adding 3 to 2 = 5 … Adding 10 to 45 = 55  

Example: Sentinel-Controlled while Evaluating grade points char cChoice; float fGradePt=0; do { printf(“\nEnter grade point: ”); scanf(“%f”, &fGradePt); if(fGradePt > 2.0) printf(“\nPass\n”); else printf(“\n Fail \n”); printf(“Continue? y-yes n-no: ”); scanf(“%c”, &cChoice); }while( cChoice == ‘y’) declare control variable read control variable test condition

Example: Sentinel-Controlled while Evaluating grade points char cChoice; float fGradePt=0; do { printf(“\nEnter grade point: ”); scanf(“%f”, &fGradePt); if(fGradePt > 2.0) printf(“\nPass\n”); else printf(“\n Fail \n”); printf(“Continue? y-yes n-no: ”); scanf(“%c”, &cChoice); }while( cChoice == ‘y’) Enter grade point : 2.5 Pass Continue? n read control variable test condition

Infinite loop in do-while To avoid an infinite loop, the loop body must contain a statement that ultimately makes the expression false and assures exit from the loop Another example: int iLoop = 0; do { printf (“%d ”,iLoop); iLoop = iLoop + 5; } while (iLoop <= 20); The output is: 0 5 10 15 20

Comparison between while and do-while Example: Adding integers (a) iLoop = 11; while (iLoop <= 10) { printf("%d",iLoop); iLoop = iLoop + 5; } (b) iLoop = 11; do { printf("%d",iLoop); iLoop = iLoop + 5; }while (iLoop <= 10); In (a), the while loop, produces nothing In (b) the do…while loop, outputs the number 11

3. for Repetition Structure Format when using for loops for (initialization ; loop continuation test ; increment statement) Use for loops when the repetition count is known Example: Printing integer from 1 to 10 for(iCounter = 1;iCounter <= 10;iCounter++) printf("%d\n",iCounter);

3. for Repetition Structure for loops can usually be rewritten as while loops: initialization; while ( loop continuation test ) { statement; increment statement; } Initialization and increment can be comma-separated lists int iVar1, iVar2; for(iVar1=0,iVar2=0; iVar2+iVar1<=10; iVar2++,iVar1++) printf(“%d\n”,iVar2+iVar1);

Flowchart of for statement

Nested loop Loop within a loop Inner loop is performed first Example 1: for(iLoop1=1 ; iLoop1<4 ; iLoop1++) { for(iLoop2=1 ; iLoop2<5 ; iLoop2++) printf(“%d”, iLoop2); printf(“\n”); } 1234

Nested loop Example 2: Program finds and prints average of three test scores, then asks if user wants to continue do { for(iCount=0; iCount <3;iCount++) { printf(“\nEnter test marks: ”); scanf(“%d”, &iMarks); iTotal=iTotal+iMarks; } fAvg=iTotal/iCount; printf(“\nAverage:%5.2f”, fAvg); printf(“\nContinue?”); scanf(“%c”, &cChoice); }while(cChoice == ‘y’);

Nested loop Example 2: Program finds and prints average of three test scores, then asks if user wants to continue do { for(iCount=0; iCount <3;iCount++) { printf(“\nEnter test marks: ”); scanf(“%d”, &iMarks); iTotal=iTotal+iMarks; } fAvg=iTotal/iCount; printf(“\nAverage:%5.2f”, fAvg); printf(“\nContinue?”); scanf(“%c”, &cChoice); }while(cChoice == ‘y’); Enter test marks : 78 Enter test marks : 85 Enter test marks : 82 Average : 81.67 Continue? y Enter test marks : 65 Enter test marks : 73 Enter test marks : 68 Average : 68.67 Continue? n

Exercise 1 Write a C code segment using the while loop to find the sum of the first 99 positive integers 1,2,3…99. Display the resulting sum. Declare and initialize variables used.

Exercise 2 Write a C program to read characters from the keyboard until a ‘q’ character is read. Use a sentinel-controlled while loop to find the number of nonblank characters read from the keyboard

Exercise 3 Write a program that utilizes looping to print the numbers from 1 to 10 side-by-side on the same line with 3 spaces between each number

Exercise 4 Finding Error for ( x = .000001; x <= .0001; x += .000001 ) printf( "%.7f\n", x );

Exercise 5 What the following program do? #include<stdio.h> int main() { int x,y,i,j; //declare variables printf(“Enter two integers in range 1-20:”); scanf(“%d %d”,&x,&y); //read values for x,y for(i=1;i<=y;i++){ for(j=1;j<=x;j++){ printf(“@”); // display output @ } //end inner for printf(“\n”); } return 0; //indicate successful termination

Exercise 6 Write a program that sums a sequence of integers. Assume that the first integer read with scanf specifies the number of values remaining to be entered. Your program should read only one value each time scanf is executed. A typical input sequence might be 5 100 200 300 400 500 where the 5 indicates that the subsequent five values are to be summed.

End Week 4 - Loops Q & A!