cs 108 computing fundamentals notes for thursday, february 19, 2015

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

Upload: morgan-farmer

Post on 03-Jan-2016

218 views

Category:

Documents


3 download

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.

Loop Condition

Loop Body

Yes

No

• 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 statementtotal = 0; // total of the integers between 0-5counter = 0; // count or "track" the integers between 0-5while (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 Statement1. Greet user2. Ask the user to enter lower bound integer3. Read/record the user's input for lower bound integer4. Ask the user to enter upper bound integer greater than the lower bound5. Read/record user’s input for upper bound integer6. Create a place to record the "running total" and initialize to 07. Create a place to track progress with an "index" and initialize to 08. Set index to the value of the lower bound9. Test to see if the index is less than or equal to the value of the upper bound

a. If truei. Add index value to a running totalii. Add 1 to index valueiii. Go to step 9

b. If falsea. Go to step 10

10. Display the lower bound11. Display the upper bound12. Display the total13. Terminate

While Statement

• After you have the algorithm, use paper and a pen/pencil to test the algorithm

Chalk talk

While Statement#include <stdio.h> // My file 1.cint 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 StatementLet’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 Statement1. Greet user2. Prompt user to enter the total number of students3. Read user's input number for total number of students4. 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 truei. Prompt the user to enter a test scoreii. Read the user’s input for test scoreiii. Add the user’s input to the "running total" of test scores iv. Increment the "index" valuev. Go to step 6

b. If falsei. Go to step 7

7. Compute the average test score (running total / number of students)8. Display the average9. 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 talkTesting the previous algorithm revealed a problem with the

algorithm that required an adjustmentThe next slide has the corrected algorithm

While Statement1. Greet user2. Prompt user to enter the total number of students3. Read user's input number for total number of students4. 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 truei. Prompt the user to enter a test scoreii. Read the user’s input for test scoreiii. Add the user’s input to a running total of test scores iv. Increment the index valuev. Go to step 6

b. If falsei. Go to step 7

7. Compute the average test score (running total / number of students)8. Display the average9. Terminate

Now Lets Code It!!

While Statement#include <stdio.h> // My file 2.cint 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.

Loop Condition

Loop Body Yes

No

• 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 Statement1. Greet user2. Prompt user to enter an integer between 0 and 1003. 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 input6.

a. Add the index value to a running totalb. Increment the index valuec. Test to see in the index value is less than or equal to 100d. If true, go to step 6.ae. If false, go to step 7

7. Display the total8. Terminate

Do …While Statement# include <stdio.h> // My file 3.cint 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 Statement1. Greet user2. Prompt user to enter lower bound integer3. Read user's input for lower bound integer4. Prompt user to enter upper bound integer5. Read user’s input for upper bound integer6. 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 truei. Test index for "evenness" (formula: does index MOD 2 equal 0?)ii. If true

1) Display indexiii. Increment indexiv. Go to step 7

b. If falsea. Go to step 8

8. Terminate

Practice# include <stdio.h> //My file 4.cint 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 19 - 39 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 Loop1. 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 truei. Display "C to Shining C"ii. Increment indexiii. Go to step 2

b. If false, go to step 33. Terminate

Example

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

#include <stdio.h> // My file 5.cint 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 Statement1. Greet user2. 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 scoreb. Record the test scorec. Add the test score to the running totald. Ask the user if he/she has another test score to enter

i. If true1) Go to step 4.a

ii. If falseiii. 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 <stdio.h> //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 <stdio.h> //My file 6a.c uses a do – while loopint 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 <stdio.h> // My file 7.cint 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 <stdio.h> // My file 8.cint 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 <stdio.h> // My file 9.cint 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 <stdio.h> // My file 10.cint 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;}