Tutorial 4
Tutorial 4
Outline
Review on looping constructs
While loop For loop
Exercise
Looping constructs
Mainly while-loop and for-loop When we use looping constructs?
When statements are executed repeatedly until a particular condition is satisfied
N matter we know the number of iterations or not No tt k th b f it ti t
VS
total = 0; cin >> score; while (score >=0 ) { total = total + score; cin >> score; }
+ + + + +
VS
Multiple efforts to type the codes Multiple efforts to do the debugging (if there are errors) Multiple efforts to make modifications Multiple chances to make mistakes
While loop
Format
while (condition) { body }
condition
Has the value of type bool (true or false) If condition is evaluated to true, then the block body is executed
For loop
Format
for (initialization action; condition; update action) { ( ; ; p ) body }
E.g.
Nested loops
Loops can appear inside loops
while (...) { ... while (...) { ... } ... } for (...) { ... for (...) { ... } ... }
Exercise 1
Fibonacci numbers are a sequence of numbers defined by the q y following relations:
0 1 Fn F F n2 n 1
if n 0 if n 1 if n 1
Write a program fibonacci.cpp to read in a non-negative integer n and determine the n th Fibonacci number n-th number. Hints can be found in the last slide.
C:\tutorial4>fibonacci 1 1
C:\tutorial4>fibonacci 10 55
C:\tutorial4>fibonacci 46 1836311903
Exercise 2
Write a program pyramid.cpp to read in a non-negative integer non negative n, and print out a pyramid shape made of n lines of *
Submit fibonacci.cpp & pyramid.cpp to the Assignment T4 folder of the webhandin Deadline: 11:59pm Oct 7, 2011
Sample solutions will be provided after the deadline
Hints on question 1
#include <iostream> using namespace std; int main(){ // get a non-negative integer n int n; cin >> n; if (n <= 1) cout << n << endl; else { int Fn 2 = 0; // F(n-2) Fn_2 int Fn_1 = 1; // F(n-1) int Fn; // F(n) for (int i = 2; i <= n; i++){ Fn = Fn_2 + Fn_1; Fn 2 Fn 1; ... } ... } return 0; }