Docsity

Notes for Iterative Statements, Counting and Conditional Loops | EECS 168, Study notes of Electrical and Electronics Engineering

Partial preview of the text

Download Notes for Iterative Statements, Counting and Conditional Loops | EECS 168 and more Study notes Electrical and Electronics Engineering in PDF only on Docsity!

Iterative Statements  The while Statement  Counting Loops  Conditional Loops  Infinite Loop Errors  The for Statement  Auto-increment and Auto-decrement Operators  The do-while Statement  Nested Loops  Common Errors  Software Engineering Tips

The while Statement  Often need to do repetitive calculations to solve problems  Computers are good at this, humans are typically bad at this  A while loop can be used to iteratively execute a block of code  Need to specify the following

  1. the code to execute before loop
  2. the Boolean condition for continuing iteration
  3. the block of code to be repeated  The program will execute block of code over and over as long as the Boolean condition remains TRUE  Code after the loop is executed when condition becomes FALSE // While loop syntax initialization code while ( Boolean expression ) { block of statements to be repeated update variables in Boolean expression }

Conditional Loops  We can vary the number of iterations based on the data values  Conditional loops process data until given situation arises  Can also be used to check for end of input or invalid data values  Need to do the following

  1. perform initialization code
  2. while condition remains TRUE the program  perform desired operations  check terminating condition again // Conditional loop example int amt = 99; int pow = 0; while (amt > 0) { cout << "amt=" << amt << " pow=" << pow << endl; amt = amt/2; pow = pow + 1; } cout << "amt=" << amt << " pow=" << pow << endl;

// Input varying loop int num; cout << "Enter a number (use -1 to end).\n"; cin >> num; while (num >= 0) { val = sqrt(num); cout << val << "squared=" << num << endl; cout << "Enter a number (use -1 to end).\n"; cin >> num; } // Calculate sum of variable number of values int count = 0; int sum = 0; int num; cout << "Enter sequence of values (use -1 to end).\n"; cin >> num; while (num >= 0) { count = count + 1; sum = sum + num; cin >> num; } // Calculate and print average if (count > 0) cout << "Average = " << sum / count << endl; else cout << "No data entered.\n";

The for Statement  The for loop provides a compact syntax for iteration  Typically used for counting loops, but can be used for any loop  Allows you to specify the following all on one line

  1. initialization statement(s)
  2. Boolean expression for continuing loop
  3. statements to be executed after loop // For loop syntax for ( initialization; Boolean expression ; increment ) { statements to be repeated } // For loop example for (int num = 0; num < 10; num = num+1) { cout << num << "cubed=" << numnumnum << endl; }

Auto-increment and Auto-decrement Operators  The ++ and – operators add or subtract one to a variable o rewrite i = i+1 as i++ o rewrite j = j-1 as j--  Similar short form combines assignment and operators o rewrite a = a + b as a += b o rewrite c = c - d as c -= d o rewrite a = a * b as a *= b o rewrite c = c / d as c /= d o rewrite a = a % b as a %= b  Produces shorter (and often faster) code // Example using compact operators int sum = 0; int product = 1; for (int count = 0; count < 13; count++) { sum += count; product *= count; } // Assign first then increment int num = 5; int val = num++; // now val is 5, num is 6 // Increment first then assign int num = 5; int val = ++num; // now nal is 6, num is 6

Nested Loops  Often necessary for one loop to include another loop  Need separate initializations, Boolean expressions, and increments  If the outer loop executes N times and the inner loop executes M times then the inner loop body is executed N x M times // Square printing example for (int height=0; height < 14; height++) { // Outer loop code for (int width=0; width < 17; width++) { // Inner loop code cout << "*"; } cout << endl; } // Factorial example for (int number = 1; number < 42; number++) { // Outer loop code int factorial = 1; for (int count = 1; count <= number; count++) { // Inner loop code factorial *= count; } cout << "Number = " << number << "Factorial = " << factorial << endl; }

Common Errors  Extra semicolon after for (..) or while (..) causes logic error  Counters (and other variables) not properly initialized  Boolean expression will never become FALSE (infinite loop)  Loop executes incorrect number of times (off by one common)  Never update for loop counter variable inside for loop  Never use same counter variable for nested loops // Incorrect nested loop example int index; for (index = 0; index < 10; index++) { for (index = 0; index < 10; index++) cout << "Result: " << 3 * index - 5 << endl; cout << "Index: " << index << endl; }

Fibonacci Example  Output the Fibonacci sequence 1, 1, 2, 3, 5, 8, 13, 21…  Invented 100s of years ago to model population growth  Do you notice the pattern?  First two values are equal to one  Following values are the sum of the previous two values

Initial Fibonacci Program //--------------------------------------------------- // Purpose: Program to print 9 Fibonacci numbers. // Solution without iteration using 9 variables. // Author: John Gauch //--------------------------------------------------- #include using namespace std; int main() { // Output first two values int num1 = 1; cout << num1 << endl; int num2 = 1; cout << num2 << endl; // Calculate and output remaining values int num3 = num1 + num2; cout << num3 << endl; int num4 = num2 + num3; cout << num4 << endl; int num5 = num3 + num4; cout << num5 << endl; int num6 = num4 + num5; cout << num6 << endl; int num7 = num5 + num6; cout << num7 << endl; int num8 = num6 + num7; cout << num8 << endl; int num9 = num7 + num8; cout << num9 << endl; return 0; }

Final Fibonacci Program //--------------------------------------------------- // Purpose: Program to print 9 Fibonacci numbers. // Solution with iteration. // Author: John Gauch //--------------------------------------------------- #include using namespace std; int main() { // Output first two values int num1 = 1; cout << num1 << endl; int num2 = 1; cout << num2 << endl; // Calculate and output remaining values using iteration int count = 3; while (count <= 9) { int num3 = num1 + num2; cout << num3 << endl; num1 = num2; num2 = num3; count = count + 1; } }