Download presentation
Presentation is loading. Please wait.
1
Start
2
More Loops 03/14/11 Look at geometric series example.
3
Other Loops for-loop and do-while
4
for - loop Can use while-loop for all repetition for is useful for counting
5
Example //Add first ten integers int total = 0; for (int n = 1; n <= 10; n++) total = total + n; cout << total; OUTPUT: 55
6
Syntax of for for(intialization; repetition cond; update) statement; for(intialization; repetition cond; update) { //Code of for-loop block } Initialization done upon entry. Condition must be true, check each time. Update done after each iteration, before condition is checked.
7
while vs. for int total = 0; for (int n = 1; n <= 10; n++) total = total + n; total = 0; int n=1; while (n <= 10) { total = total + n; n++ ; }
8
Other Examples Input the rainfall for the week: forrain.cpp To find a Fibonacci number. fib.cpp
9
Output Geometric Series A geometric series is defined by: a + ar + ar 2 + ar 3 +... + ar n-1 a is first term, r is common ratio, and n is number of terms. Write a function to take a, r and n then return the sum. Start with an algorithm
10
Algorithm Parameters: a, r, n term = a (1 st term is a) sum = term for(i from 2 to n) – Find ith term, term*r – Add term to sum Output sum
11
Geometric Series Program geometric.cpp Program started. Let's provide the function, using a for-loop.
12
Do-while loop do { stmts; } while (bool. expr.) Executed Once Then condition check
13
dowhile dowhile.cpp
14
What is needed? Finish for loop in countdown.cpp
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.