Download presentation
Presentation is loading. Please wait.
Published byMorgan Farmer Modified over 9 years ago
1
CS 108 Computing Fundamentals Notes for Thursday, February 19, 2015
2
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
3
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
4
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 }
5
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?
6
While Statement How should we proceed? Develop an algorithm!! Don't worry about input error checking
7
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 10 10.Display the lower bound 11.Display the upper bound 12.Display the total 13.Terminate
8
While Statement After you have the algorithm, use paper and a pen/pencil to test the algorithm Chalk talk
9
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; }
10
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?)
11
While Statement How should we proceed? Develop an algorithm!! After you try it, chalk talk
12
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
13
While Statement After you have the algorithm, use paper and a pen/pencil to test the algorithm Chalk talk
14
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
15
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!!
16
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; }
17
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
18
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.
19
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
20
Do … While Statement How should we proceed? Develop an algorithm!!
21
Do …While Statement 1.Greet user 2.Prompt user to enter an integer between 0 and 100 3.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
22
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 ; }
23
Practice Write a program that reads two integers (num1 and num2) and then lists the even numbers between num1 and num2 (exclusive).
24
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
25
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; }
26
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; }
27
for Statements Example : for ( index = 19 ; index < 40 ; index = index + 1 ) { printf("\n %d",index); } Integers between 19 - 39 are printed. Note The counter initialization (index = 19). The conditional (index < 40). The loop adjustment (index = index + 1).
28
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.
29
Example Write a program that displays "C to Shining C!!" 5 times.
30
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
31
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; }
32
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
33
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?
34
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.
35
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
36
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; }
37
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; }
38
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
39
Write a program to draw a triangle with user specified height using * to build the triangle. Example triangle with a height of 5: * ** *** **** ***** Practice
40
#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; }
41
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
42
#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; }
43
Modify the previous program so that only the greatest factor other than the input itself is displayed to the screen. Practice
44
#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; }
45
Write a program to display a "multiplication table" for numbers 1 to 12. What are the steps necessary to accomplish this? Practice
46
#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; }
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.