CS 108 Computing Fundamentals Notes for Thursday, February 19, 2015.

Slides:



Advertisements
Similar presentations
Microsoft® Small Basic
Advertisements

Programming Logic and Design Eighth Edition
Computer Science 1620 Loops.
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.
Introduction to Computers and Programming Lecture 8: More Loops New York University.
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.
Summary of Loops Programming. COMP102 Prog Fundamentals I: Summary of Loops /Slide 2 Which Loop to Use? l for loop n for calculations that are repeated.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
CS 108 Computing Fundamentals Notes for Thursday, February 12, 2015.
Chapter 4: Looping. Resource: Starting Out with C++, Third Edition, Tony Gaddis 5.1 The Increment and Decrement Operators ++ and -- are operators that.
Programming Logic and Design Fifth Edition, Comprehensive
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
Programming Logic and Design Sixth Edition Chapter 5 Looping.
1 Loops. 2 Topics The while Loop Program Versatility Sentinel Values and Priming Reads Checking User Input Using a while Loop Counter-Controlled (Definite)
 Wednesday, 9/18/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/18/02  QUESTIONS?? HW #1 due today at 5!!  Today: Loops, and two new data types.
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.
CMSC 104, Lecture 171 More Loops Topics l Counter-Controlled (Definite) Repetition l Event-Controlled (Indefinite) Repetition l for Loops l do-while Loops.
Repetition Structures Repetition Structures allow you to write programs that will repeat program steps multiple times. –Also called Loops –Counter controlled.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
A loop is a repetition control structure. body - statements to be repeated control statement - decides whether another repetition needs to be made leading.
1 Chapter 9. To familiarize you with  Simple PERFORM  How PERFORM statements are used for iteration  Options available with PERFORM 2.
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.
Iteration Hussein Suleman UCT Dept of Computer Science CS115 ~ 2004.
CMSC 104, Version 9/011 More Loops Topics Counter-Controlled (Definite) Repetition Event-Controlled (Indefinite) Repetition for Loops do-while Loops Choosing.
CS 108 Computing Fundamentals Notes for Tuesday, September 22, 2015.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
H1-1 University of Washington Computer Programming I Lecture 9: Iteration © 2000 UW CSE.
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)
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CS 108 Computing Fundamentals Notes for Thursday, February 18, 2016.
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.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
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.
REPETITION CONTROL STRUCTURE
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Lecture 7: Repeating a Known Number of Times
CHAPTER 5A Loop Structure
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
CS 108 Computing Fundamental Notes for Thursday, October 5, 2017
Looping.
Arrays, For loop While loop Do while loop
Outline Altering flow of control Boolean expressions
Lesson #5 Repetition and Loops.
Iteration: Beyond the Basic PERFORM
Iteration: Beyond the Basic PERFORM
Week 6 CPS125.
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
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:

CS 108 Computing Fundamentals Notes for Thursday, February 19, 2015

Iteration (Looping) Iteration or looping is the ability to execute the same set of instructions repeatedly. Almost all loops have a starting point (or a starting situation) and a conditional component (used to decide if another pass is required or to stop). In C there are three kinds of looping statements: ­ while statements ­ do … while statements ­ for statements

While Statement A while statement checks the loop condition before the execution of the loop body. The loop body is executed as long as the loop condition is TRUE. A while statement is not always executed… testing first means loop may never be entered

While Statement Syntax : while (loop condition) { Loop Body Statement(s); } A snippet of code to demonstrate a while statement total = 0; // total of the integers between 0-5 counter = 0; // count or "track" the integers between 0-5 while (counter < 5) { total = total + counter; counter = counter +1; // counter++ works, too }

While Statement Let’s develop a program that offers the user the opportunity to pick the range of positive integers he/she wants to total (in other words, the user picks the loop’s starting point (the lower bound) and ending point (the upper bound)… the program totals all the integers between those boundaries (inclusive)). How should we proceed?

While Statement How should we proceed?  Develop an algorithm!! Don't worry about input error checking

While Statement 1.Greet user 2.Ask the user to enter lower bound integer 3.Read/record the user's input for lower bound integer 4.Ask the user to enter upper bound integer greater than the lower bound 5.Read/record user’s input for upper bound integer 6.Create a place to record the "running total" and initialize to 0 7.Create a place to track progress with an "index" and initialize to 0 8.Set index to the value of the lower bound 9.Test to see if the index is less than or equal to the value of the upper bound a.If true i.Add index value to a running total ii. Add 1 to index value iii. Go to step 9 b.If false a.Go to step Display the lower bound 11.Display the upper bound 12.Display the total 13.Terminate

While Statement After you have the algorithm, use paper and a pen/pencil to test the algorithm  Chalk talk

While Statement #include // My file 1.c int main(void) { int total = 0, start_point = 0, end_point = 0, index = 0 ; printf( "\n\n This program will add a string of integers. \n" ) ; printf( "\n Enter starting integer: " ) ; scanf( "%d", &start_point ) ; printf( "\n Enter ending integer: " ) ; scanf( "%d", &end_point) ; index = start_point ; while ( index <= end_point ) { total = total + index; index = index + 1; } printf("\n The integers between %d and %d inclusive add up to %d.\n\n", start_point, end_point, total); return 0; }

While Statement Let’s develop a program that reads exam results of some number of students and then calculates the class average. (Hint: how do we handle "some number" of students?)

While Statement How should we proceed?  Develop an algorithm!!  After you try it, chalk talk

While Statement 1.Greet user 2.Prompt user to enter the total number of students 3.Read user's input number for total number of students 4.Create a place to "track" the "running total" of test scores (initialize it to 0) 5.Create a place to "track progress" with an "index" (initialize it to 0) 6.Test to see if the index value is less than or equal to the total number of students a.If test is true i.Prompt the user to enter a test score ii.Read the user’s input for test score iii.Add the user’s input to the "running total" of test scores iv.Increment the "index" value v.Go to step 6 b.If false i.Go to step 7 7.Compute the average test score (running total / number of students) 8.Display the average 9.Terminate

While Statement After you have the algorithm, use paper and a pen/pencil to test the algorithm  Chalk talk

While Statement After you have the algorithm, use paper and a pen/pencil to test the algorithm  Chalk talk  Testing the previous algorithm revealed a problem with the algorithm that required an adjustment  The next slide has the corrected algorithm

While Statement 1.Greet user 2.Prompt user to enter the total number of students 3.Read user's input number for total number of students 4.Create a place to maintain the "running total" of test scores (initialize it to 0) 5.Create a place to "track our progress" with an "index" (initialize it to 1) 6.Test to see if the index value is less than or equal to the total number of students a.If test is true i.Prompt the user to enter a test score ii.Read the user’s input for test score iii.Add the user’s input to a running total of test scores iv.Increment the index value v.Go to step 6 b.If false i.Go to step 7 7.Compute the average test score (running total / number of students) 8.Display the average 9.Terminate Now Lets Code It!!

While Statement #include // My file 2.c int main( void) { int students = 0, total = 0, index = 1, score = 0; double average = 0.0; printf( "\n Enter the number of students: " ) ; scanf( "%d", &students ) ; while ( index <= students ) { printf( "\n Enter score # %d: ", index ) ; scanf( "%d", &score) ; total = total + score ; index = index + 1 ; } average = (double) total / students; printf( "\n The class average is %5.2lf \n\n ", average ); return 0; }

Do …While Statement do…while statements check the loop condition after the execution of the loop body The loop body is executed as long as the loop condition is TRUE. A do… while statement is always executed at least once because the test occurs after the loop

Do …While Statement Syntax : do { Loop Body Statements; } while (loop condition) ; The "loop body" is executed at least once A counter may be used to keep track of how many times the loop body is executed.

Do …While Statement Let’s write a program that:  asks to user to enter and integer between 0 and 100  the program adds all the integers between the entry up to 100 (inclusive)  displays the total

Do … While Statement How should we proceed?  Develop an algorithm!!

Do …While Statement 1.Greet user 2.Prompt user to enter an integer between 0 and Read user's input 4.Create a place to maintain the "running total" (initialize it to 0) 5.Create a place to "track progress" with an "index"; initialize it to the user’s input 6. a.Add the index value to a running total b.Increment the index value c.Test to see in the index value is less than or equal to 100 d.If true, go to step 6.a e.If false, go to step 7 7.Display the total 8.Terminate

Do …While Statement # include // My file 3.c int main(void) { int index = 0, total= 0 ; printf("\n This program totals the integers between your input and 100 inclusive."); printf("\n\nEnter an integer between 0 and 100: "); scanf( "%d", &index ) ; do { total = total + index; index = index + 1; } while (index <= 100) ; printf("\n The total is: %d.\n\n", total); return 0 ; }

Practice Write a program that reads two integers (num1 and num2) and then lists the even numbers between num1 and num2 (exclusive).

While Statement 1.Greet user 2.Prompt user to enter lower bound integer 3.Read user's input for lower bound integer 4.Prompt user to enter upper bound integer 5.Read user’s input for upper bound integer 6.Track progress with an "index" (initialize it to the value of the lower bound +1) 7.Test to see if the index is less than the value of the upper bound a.If true i.Test index for "evenness" (formula: does index MOD 2 equal 0?) ii. If true 1)Display index iii.Increment index iv.Go to step 7 b.If false a.Go to step 8 8.Terminate

Practice # include //My file 4.c int main(void) { int lower = 0, higher = 0, index = 0 ; printf( "\n Enter an integer: " ); scanf( "%d", &lower ) ; printf("\n Enter a higher integer: ") ; scanf( "%d", &higher ) ; index = lower + 1; while(index < higher) { if ( index%2 == 0 ) { printf("\n %d\n", index); } index = index + 1; } printf("\n"); return 0; }

for Statements for statements have three parts (separated by ; ) : ­ Initialization part ­ Loop Condition part ­ Loop Adjustment part Syntax : for (initialization ; loop condition ; loop adjustment) { Loop Body Statements; }

for Statements Example : for ( index = 19 ; index < 40 ; index = index + 1 ) { printf("\n %d",index); } Integers between are printed. Note ­The counter initialization (index = 19). ­The conditional (index < 40). ­The loop adjustment (index = index + 1).

for Statements for statement is the best choice to be used on definite iterations (you know the number of times you want the loop to execute). If indefinite iteration is required (loop termination is based on some event or condition that is not completely predicable) then you should use either a while or a do…while loop.

Example Write a program that displays "C to Shining C!!" 5 times.

for Loop 1.Create a place to track progress with an "index" (initialize it to 1) 2.Test to see if index is less than or equal to 5 a.If true i.Display "C to Shining C" ii.Increment index iii.Go to step 2 b.If false, go to step 3 3.Terminate

Example Write a program that displays "C to Shining C!!" 5 times. #include // My file 5.c int main(void) { int index = 0 ; for (index = 1; index <= 5; index = index +1) { printf("\n C to Shining C!! \n") ; } printf("\n"); return 0; }

Definite and Indefinite Iterations Definite Iterations: ­ The number of iterations (passes through the loop) is known at the time the loop is designed ­ for loops or fixed counters/indexes are employed ­ loop condition is not influenced/updated/changed once the loop is entered Indefinite Iterations: ­ The number of iterations (passes through the loop) is unknown at the time the loop is designed ­ while or do… while loops are employed ­ loop condition is influenced/updated/changed after the loop is entered

Definite and Indefinite Iterations Example : Write a C program to calculate the numeric average of some number of test scores. How do we allow an "unknown" number of test scores to be entered?

Definite and Indefinite Iterations Example : Write a C program to calculate the numeric average of some number of test scores. One approach: the user must be prompted initially to enter a test score and them prompted a second time to confirm that additional test scores are available.

While Statement 1.Greet user 2.Create a way to track "number of tests" with an "index" (initialize to 1) 3.Create a way to track "running total" (initialize to 0) 4. a.Ask the user to enter a test score b.Record the test score c.Add the test score to the running total d.Ask the user if he/she has another test score to enter i. If true 1)Go to step 4.a ii.If false iii.Go to step 5 5.Calculate the average test score (formula: running total / "number of tests") 6.Display the average 7.Terminate

Indefinite Iterations #include //My file 6.c uses a while loop int main(void) { int total = 0, counter =0, score = 0 ; float average = 0.0 ; char answer = 'Y' ; printf("\n\n This program calculates a test's average grade.\n\n"); while ( (answer =='Y') || (answer=='y') ) { printf("\n Enter a test score = "); scanf("%d",&score); counter = counter + 1; total = total + score; printf("\n Are there more test scores to enter? (Y/N): "); scanf(" %c", &answer); // Notice extra space… we will discuss } average = (float) total / counter; printf("\n The average test score is: %4.2f \n\n", average); return 0; }

Indefinite Iterations #include //My file 6a.c uses a do – while loop int main(void) { int total = 0, counter =0, score = 0 ; float average = 0.0 ; char answer = ' ' ; printf("\n\n This program calculates a test's average grade.\n\n"); do { printf("\n Enter a test score = "); scanf("%d",&score); counter = counter + 1; total = total + score; printf("\n Are there more test scores to enter? (Y/N): "); scanf(" %c", &answer); // Notice extra space… we will discuss } while ( (answer =='Y') || (answer=='y') ) ; average = (float) total / counter; printf("\n The average test score is: %4.2f. \n\n", average); return 0; }

Nested Loops When the body of a loop contains another loop, these loops are called nested loops. The inner loop is always completed before the outer loop. An outer loop cannot be incremented until an inner loop has been completed. Example: minutes is an inner loop for hours: ­ The hours "counter” cannot be incremented until the minutes loop has completed 60 cycles ­ The minutes “counter” cannot be incremented until the seconds loop has completed 60 cycles ­ The days “counter” cannot be incremented until the hours loop has completed 24 cycles

Write a program to draw a triangle with user specified height using * to build the triangle. Example  triangle with a height of 5: * ** *** **** ***** Practice

#include // My file 7.c int main(void) { int height, outer, inner; printf("\n This program will print a triangle of * to the screen. \n "); printf("\n Enter the triangle's height: "); scanf("%d", &height); for (outer = 1; outer <= height; outer = outer +1) { printf("\n"); for (inner = 1; inner <= outer; inner = inner + 1) { printf("*"); } printf("\n\n\n"); return 0; }

Write a program to prompt a user to enter a positive integer and then list all factors of that positive integer. What is a "factor" and how can we test for a factor? Practice

#include // My file 8.c int main(void) { int input = 0, index = 0; printf("\n This program will determine the factors of a positive integer. \n "); printf("\n Enter a positive integer: "); scanf("%d", &input); printf("\n Integer factors of %d are: ", input); for (index = 1; index <= input; index = index + 1) { if (input%index == 0) { printf(" %d ", index); } printf("\n\n\n"); return 0; }

Modify the previous program so that only the greatest factor other than the input itself is displayed to the screen. Practice

#include // My file 9.c int main(void) // GCF is Greatest Common Factor { int input = 0, index = 0, greatest = 0; printf("\n This program determines the GCF of a positive integer. \n "); printf("\n Enter a positive integer: "); scanf("%d", &input); for (index = 1; index < input; index = index + 1) { if (input%index == 0) { greatest = index ; } printf("\n The GCF of %d other than %d is %d \n\n\n", input, input, greatest); return 0; }

Write a program to display a "multiplication table" for numbers 1 to 12. What are the steps necessary to accomplish this? Practice

#include // My file 10.c int main(void) { int outer = 0, inner = 0 ; for (outer = 1; outer <= 12; outer = outer + 1) { printf("\n"); for (inner = 1; inner <= 12; inner = inner + 1) { printf(" %5d", outer * inner); // %5d facilitates alignment } printf("\n\n\n"); return 0; }