280 likes | 296 Vues
Loops (while – for). Textbook Sections 5.1 and 5 . 2. From Selection to Repetition. The if statement and if/else statement allow a block of statements to be executed selectively: based on a condition cout << "Please enter a non-negative number" << endl ; cin >> inputnumber ;
E N D
Loops(while–for) Textbook Sections 5.1 and 5.2
From Selection to Repetition • The if statement and if/else statement allow a block of statements to be executed selectively: based on a condition cout << "Please enter a non-negative number" << endl; cin >> inputnumber; if (inputnumber < 0) { cout << inputnumber << " is negative. Wrong Input" << endl; } • This piece of code does not ask another input number if the number is negative. ------------------------------------------------------------------------------------------------------ • The while statement repeatedly executes a block of statements while the condition is true cout<< " Please enter a non-negative number" << endl; cin >> inputnumber; while (inputnumber < 0) { cout << inputnumber << " is negative! Try again" << endl; cin >> inputnumber; }
true true test test false false Statement list Next statement Statement list Next statement Semantics of while loop if (test) while (test) { { statement list; statement list; } }
Sum Example: why we need loops? • We want to find the sum of 10 positive values • We can write: int num1, num2, num3, num4, num5; int num6, num7, num8, num9, num10; int sum; cin >> num1 >> num2 >> num3 >> num4 >> num5; >> num6 >> num7 >> num8 >> num9 >> num10; sum = num1 + num2 + num3 + num4 + num5; sum += num6 + num7 + num8 + num9 + num10;
Sum Example (not in book) • What if we want to compute the sum of • 100 values • an undetermined number of values • What we need is a program to be able to read as many values as we want and then compute the sum • This is possible with loops • Good solution is to use loops. • Code is developed on board. See sum10nums.cpp • This type of loops are called counting loops • number of iterations is known
Another simple example • Calculate the sum of the integer numbers between 1 and 10 int sum = 0; // this program piece int i = 1; // calculates the sum of while (i <= 10) // integers between and { // including 1 and 10 sum = sum + i; i = i + 1; }
Walkthrough of the example 1 2 i 0 1 sum i<=10 true false sum=sum+i; i=i+1; cout<<sum; int sum = 0; int i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } cout << sum;
Walkthrough of the example 2 3 i 1 3 sum i<=10 true false sum=sum+i; i=i+1; cout<<sum; int sum = 0; int i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } cout << sum;
Walkthrough of the example 3 4 i 3 6 sum i<=10 true false sum=sum+i; i=i+1; cout<<sum; int sum = 0; int i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } cout << sum;
Walkthrough of the example 10 11 i 45 55 sum i<=10 true false sum=sum+i; i=i+1; cout<<sum; int sum = 0; int i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } cout << sum;
while loop syntax <initialization> while (<test>) { <statement1>; ... <statementN>; <update> }
while loop sum example • Sum of numbers from 1..10 int sum = 0; int i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } cout << sum; initialization test body statements update
Another easy example (not in book) • Read a sequence of integer numbers from keyboard and find their sum. • input should finish when user enters –1 • -1 is the sentinel value in this example • not to be added to the sum • Code is developed on board (see sumnums.cpp) • This type of loop is called conditional loop • number of iterations is not known • depends on input
Anatomy of a loop • Initialize variables used in loop body andloop test (before the loop) • No general rule. Theway of initializationandtheinitialvaluesareto be determinedaccordingtotheapplication • The loop test is evaluated before each loop iteration • NOT evaluated after each statement in the loop body • Current value of variables are used for the loop test before each iteration • The loop body must update some variables used in the loop test so that the loop eventually terminates • If loop test is always true, loop is infinite • Infinite loops must be avoided • Basic rule of designing a loop: • Initialization, loop test and update parts should be designed carefully in order to iterate the loop as many times as needed, but not one less or one more. • Unfortunately there is no straightforward rule of designing a bug-free loop • you should be able to develop those parts by understanding and analyzing the underlying problem that needs a loop
for loop syntax for (<initialization>; <test>; <update>) { <statement1>; ... <statementN>; } • Initialization, test and update parts are combined • Good for counting on an index kind of loops.
for loop syntax compared with while <initialization> while (<test>) { <statement1>; ... <statementN>; <update> } for (<initialization>; <test>; <update> ) { <statement1>; ... <statementN>; }
for loop example Rewrite the same loop: sum of numbers from 1..10 int sum = 0; int i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } int sum = 0; for (int i=1; i <= 10; i=i+1) { sum = sum + i; }
The for loop • initialization statement • executed once before the loop • test expression • boolean expression • checked each time before entering the loop body • if true execute loop body, if false terminate loop • update statement • executed after the last statement of the loop body • several statements in initialization and update are separated by comma for (len = s.length(), k=0; k < len; k+=1) • initialization and/or test and/or update parts could be missing • but semicolons are there int k = 0; for (; k < len; k+=1)
The for loop • For loops are good for counting loops (although they can be used for conditional loops) • Number of iterations known before loop begins • Example: sum of 10 input numbers • Example: print a string vertically void Vertical(string s) // post: chars of s printed vertically intlen; int k; len = s.length(); k = 0; while (k < len) { cout << s.substr(k,1) << endl; k += 1; } // for loop alternative 1 // for loop alternative 2 intlen; int k; len = s.length(); intlen; int k; for(k=0; k < len; k+= 1) for(len = s.length(), k=0; k < len; k+= 1) { cout << s.substr(k,1) << endl; { cout << s.substr(k,1) << endl; } } // for loop alternative 3 int len; int k; len = s.length(); k = 0; for(; k < len; k+= 1) { cout << s.substr(k,1) << endl; }
Example: Print a string backwards (revstring.cpp) • Determine the index of the last character of the string, and then access each character backwards • How many times should the loop iterate ? string s; int k; cout << "enter string: "; cin >> s; cout << s << " reversed is "; k = s.length() - 1; // index of last character in s while (k >= 0) { cout<< s.substr(k,1); k -= 1; } cout << endl; • What could we use instead of s.substr(k,1) ? s.at(k)
Reverse String as a function • First step, what is the prototype? string revstring(string s) // pre: s = c0c1c2…cn-1 // post: return cn-1…c2c1c0 • Second step, how do we build a new string? • Start with an empty string, "" • Add one character at each iteration using concatenation, + rev = rev + s.substr(k,1); • Use revstringto determine if a string is a palindrome
See palindrome.cpp for full program string revstring(string s) // post: returns reverse of s, that is "stab" for "bats“ { int k = s.length() – 1; string rev = ""; // start with empty string while (k >= 0) { rev = rev + s.substr(k,1); k -= 1; } return rev; } bool IsPalindrome(string word) // post: returns true if and only word is a palindrome { return (word == revstring(word)); }
Bad loops • for (inti = 10; i < 5; i++) { cout << "How many times do I print?"; } • for (inti = 10; i >= 1; i++) { cout << "How many times do I print?"; } • inti = 1; while (i < 20) { cout << "How many times do I print?"; }
Bad loops • Never executes • Never stops (infinite loops) • Example: consider the following modified code from sum10nums • What’s the problem in the loop below? What is missing? sum = 0; count = 1; while (count <= 10) { cin>> num; sum += num; } • count never reaches 10, because count is not updated in the loop
Infinite loops • Infinite loop is something that must be avoided • happens when the loop condition is always true • same loop body iterates forever • sometimes you see an output, sometimes you don’t • press Ctrl-C to stop • could be because of a wrong or missing update statement • could be because of a wrong condition; could be anotherreason
Infinite loops • What is the problem with the code below? • cannot say infinite loop, depends on input number • for example, if num is an odd number, then the loop is infinite cin >> num; int start = 0; while (start != num) { start += 2; cout << start << endl; } • How to fix? • You can check whether num is even before starting the loop. if (num % 2 == 0) { while (start != num) { start += 2; cout << start << endl; } }
Other Common Problems • Easy to iterate one more or one less times • Test each loop with the inputs that cause: • zero iterations of the loop body • one iteration of the loop body • maximum number of iterations • one less than the maximum number of iterations • Use the debugger and watch the variables.