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;

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Control Structures for Loops.
Some loop programs 1: Read in 10 integers and output their sum
CS1061: C Programming Lecture 8: Repetition A. O’Riordan, 2004.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
Repetition (Loops) Want to do some repetitive sequence of actions: print vertical line of *s * Corresponding program: printf(“*\n”);
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
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.
CS 108 Computing Fundamentals Notes for Thursday, February 19, 2015.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
1. Agenda for loop Short-handed notation How to use break and continue 2.
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
CMSC 104, Lecture 171 More Loops Topics l Counter-Controlled (Definite) Repetition l Event-Controlled (Indefinite) Repetition l for Loops l do-while Loops.
C Programming Lecture 7 : Control Structures. Control Structures Conditional statement : if, switch Determine a block of statements to execute depending.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
Repetition and Iteration ANSI-C. Repetition We need a control instruction to allows us to execute an statement or a set of statements as many times as.
ITERATIVE STATEMENTS. Definition Iterative statements (loops) allow a set of instruction to be executed or performed several until condition are met.
CMSC 104, Version 9/011 More Loops Topics Counter-Controlled (Definite) Repetition Event-Controlled (Indefinite) Repetition for Loops do-while Loops Choosing.
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.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
CSCI 171 Presentation 3. Operators Instructs C to perform some operation Assignment = Mathematical Relational Logical.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
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”
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
PGT C Programming1 Week 4 – Repetition Structures / Loops.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
IT CS 200: R EPEATATION Lect. Napat Amphaiphan. T HE ABILITY TO DO THE SAME TASK AGAIN BY AGAIN UNTIL THE CONDITION IS MET LOOP 2.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
Problem Solving and Program Design in C Chap. 5 Repetition and Loop Statement Chow-Sing Lin.
 Real numbers representation - Floating Point Notation  First C Program  Variables Declaration  Data Types in C ◦ char, short, int, long, float, double,
Module 6 – Decision Control Statements Objectives  Understands Increment/Decrement operators, Conditional and special operators in C  Understands significance.
Week 3.  TO PRINT NUMBERS FROM 1 TO 20  TO PRINT EVEN NUMBERS FROM 1 TO 20 2.
ECE Application Programming
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
ECE Application Programming
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Week 4 – Chapter 3 Repetition.
CS1010 Programming Methodology
Lecture 07 More Repetition Richard Gesick.
2008/10/22: Lecture 12 CMSC 104, Section 0101 John Y. Park
Lecture 4B More Repetition Richard Gesick
Control Structures Lecture 7.
Looping.
Outline Altering flow of control Boolean expressions
2008/10/22: Lecture 12 CMSC 104, Section 0101 John Y. Park
Chapter 8 The Loops By: Mr. Baha Hanene.
Chapter 2.1 Repetition.
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
Repetition Statements (Loops) - 2
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
The while Looping Structure
More Loops Topics Counter-Controlled (Definite) Repetition
ICS103: Programming in C 5: Repetition and Loop Statements
Week 3 – Repetition (ctd.)
More Loops Topics Counter-Controlled (Definite) Repetition
Presentation transcript:

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; … statement n; }

The While Statement Execution of a while loop Condition evaluated –If condition evaluates to false loop terminates – execution passes to first line of code outside loop –If condition evaluates to true Body of loop is executed Process is repeated from beginning

Sample While Statement int main ( ) { int count; count = 1; while (count <=20) { printf (“\n%d”, count); count ++; } return 0; }

Sample Program 5.1 #include int main( void ) { int increment = 0; int counter = 0; printf("Please enter the increment: "); scanf("%d", &increment); printf("\n\n"); while (counter < 20) { printf("%d ", counter+=increment); } return 0; }

Compare the for Loop & while int count; for (count=1; count <=20; count++) { printf (“\n%d”, count); } int count = 1; while (count <=20) { printf (“\n%d”, count); count++; }

Writing a while loop Write the C code to print the odd numbers less than 20 using a while loop void main () { int count = 1; while (count < 20) { printf (“\n%d”, count); count += 2; }

Sample Program 5.2 //Rewrite this using a while loop #include int main( void ) { int counter = 0, sign_change = 1; for (; counter < 20; counter++) { printf("%d\n", counter*sign_change); sign_change *= -1; } return 0; }

Uses of the while loop Iterating until the a flag is set indicated the process should be terminated –sentinel Iterating until the user enters valid data –data validation

The while loop and a sentinel printf (“Enter a test score (0 to finish)”); printf (“The average will be calculated”); scanf (“%d”, &score); count = 0; while (score != 0) { count += 1; total += score; printf (“Enter next score”); scanf (“%d”, &score); } //Calculate average – make sure count > 0

Sample Program 5.3 #include void main () { int count = 0, total = 0, score = 0; float average = 0; printf("Enter a test score (0 to finish)"); printf("\nThe average will be calculated"); printf("\n\nEnter first score: "); scanf ("%d", &score); while (score != 0) { total += score; printf ("Enter next score: "); scanf ("%d", &score); count += 1; } if (count) { average = (float)total / count; printf ("\nThe average score is %.2f", average); } else printf("\nNo scores entered."); }

The while loop and data validation //Allow the user to enter a number between 1 and 10 //and validate their entry printf(“Enter a number between 1 and 10: “); scanf(“%d”, &nbr); while (nbr 10) { printf(“Invalid data – please enter a number between 1 and 10); scanf(“%d”, &nbr); }

Sample program 5.4 #include void main () { int ctr = 0, nbr = 0, array[5]; printf("The program will allow the user to enter 5 integers."); printf("\nThe numbers must be between 1 and 10."); printf("\nThe sum of the numbers will then be printed."); while (ctr < 5) { printf("\n\nEnter number %d (between 1 & 10): ", ctr + 1); scanf("%d", &nbr); while (nbr 10) { printf("\nSorry, the number must be between 1 & 10."); printf("\nEnter number %d (between 1 & 10): ", ctr + 1); scanf("%d", &nbr); } array [ctr] = nbr; ctr ++; } nbr = 0; for (ctr = 0; ctr < 5; ctr++) nbr += array[ctr]; printf("\n\nThe sum is: %d", nbr); }

Sample Program 5.5 #include int main() { int option = 0; printf("1. Find the largest value"); printf("\n2. Find the smallest value"); printf("\n3. Find the average"); printf("\n\nPlease make selection: "); scanf("%d", &option); while ((option 3)) { printf("Invalid selection, please re-enter (valid values are 1, 2, and 3): "); scanf("%d", &option); } printf("\nCongratulations, you entered a valid menu option!!!"); return 0; }

The do … while loop Executes a block as long as the condition is true general form: do { statement 1; statement 2; … statement n; } while (condition);

The do … while loop Execution of a do…while loop Body of loop is executed Condition is executed –If condition evaluates to false loop terminates – execution passes to first line of code outside loop –If condition evaluates to true Process is repeated from beginning

Sample Program 5.6 #include void main ( ) { float average = 0; int count = 0; int score = 0; int total = 0; printf ("Enter a test score: "); scanf ("%d", &score); do{ total += score; count += 1; printf ("Enter next score (0 to finish): "); scanf ("%d", &score); }while (score != 0); average = (float)total/count; printf ("The average is %.2f", average); }

Sample Program 5.7 //Run the code and fix any errors //Would a while loop work better here than a do…while? #include void main ( ) { int choice = 0; printf ("1 - Add a record"); printf ("\n2 - Delete a record"); printf ("\n3 - Change a record"); printf ("\n\n Enter a selection: "); scanf("%d", &choice); do { printf("Invalid selection, please re-enter (valid values are 1, 2, and 3): "); scanf("%d", &choice); } while (choice != 1 || choice != 2 || choice != 3); printf("\nCongratulations, you entered a valid menu option!!!"); }

Comparing loops Tasks accomplished with for loop can be accomplished with while or do..while loop. For loop has initialization condition, & increment in one spot –increased readability –generally easier to work with If # repetitions cannot be determined before iterations begin, must use while

Comparing loops Top-checking loops –Condition is evaluated PRIOR to first iteration Loop may never execute for loops while loops Bottom-checking loops –Condition is not evaluated until AFTER the first iteration Guaranteed at least one iteration do…while loops

Nested loops Any loop can be nested within any other loops for within while while within for for within do … while do … while within for, within while, etc. Loops must be completely nested within each other

Example of while within for int count1; int count2; for (count1 = 1; count1 < 10; count1++){ count2 = 0; while (count2 <3){ printf (“%d”, count2); count2 ++; }

Illegally nested loops int count1, count2; for (count1 = 1; count1 < 10; count1 ++){ count2 = 1; do { printf (“%d”, count2); count2 ++; } }while (count2 < 3);