170 likes | 187 Views
Understand do-while loops in programming with examples. Explore nested loops for complex patterns. Practice loop rewriting and problem-solving. CS150 Introduction to Computer Science.
E N D
Announcements • Midterm on Friday, October 17th, 2003 • Quiz some time next week • Assignment 3 is due on Wednesday, October 15th, 2003 • I am almost done with your grading. I will hand it back to you today during the lab CS150 Introduction to Computer Science 1
Do While Loops do { cout << “Enter a year:” << endl; cin >> year; } while (year < 0); CS150 Introduction to Computer Science 1
When to use do while? • When loop must execute at least once • Perfect for data validation! • Post-tested loop • General format: do { statements; } while (condition is true); CS150 Introduction to Computer Science 1
Example • Write a program segment that takes as input a number between 5 and 10. Error proof the segment. CS150 Introduction to Computer Science 1
What’s the output? m = 10; do { cout << m << endl; m = m - 3; } while (m > 0) CS150 Introduction to Computer Science 1
Rewrite num = 10; while (num <= 100) { cout << num << endl; num += 10; } CS150 Introduction to Computer Science 1
Rewrite for (n = 3; n > 0; n--) cout << n << “ squared is” << n*n << endl; CS150 Introduction to Computer Science 1
Nested Loops • A loop within a loop • Can repeat multiple things within a loop • Example: Read in 10 grades for each of 20 students CS150 Introduction to Computer Science 1
Example cout << setw(12) << “i” << setw(6) << “j” << endl; for (int i = 0; i < 4; i++) { cout << “Outer” << setw(7)<< i; cout << endl; for (int j = 0; j < i; j++) { cout << “ Inner” << setw(10); cout << j << endl; } } CS150 Introduction to Computer Science 1
Example cout << " "; for (int colhead=0; colhead <10; colhead++) cout << setw(3) << colhead; cout << endl; cout << "---------------------------------" << endl; for (int row = 0; row < 10; row++) { cout << setw(3) << row ; for (int col = 0; col < 10; col++) cout << setw(3) << row*col; cout << endl; } CS150 Introduction to Computer Science 1
0 1 2 3 4 5 6 7 8 9 --------------------------------- 0 0 0 0 0 0 0 0 0 0 0 1 0 1 2 3 4 5 6 7 8 9 2 0 2 4 6 8 10 12 14 16 18 3 0 3 6 9 12 15 18 21 24 27 4 0 4 8 12 16 20 24 28 32 36 5 0 5 10 15 20 25 30 35 40 45 6 0 6 12 18 24 30 36 42 48 54 7 0 7 14 21 28 35 42 49 56 63 8 0 8 16 24 32 40 48 56 64 72 9 0 9 18 27 36 45 54 63 72 81 CS150 Introduction to Computer Science 1
What’s the Output for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) cout << “*”; cout << endl; } CS150 Introduction to Computer Science 1
* ** *** **** CS150 Introduction to Computer Science 1
What’s the Output for (int i = m; i >0; i--) { for (int j = n; j>0; j--) cout << “*”; cout << endl; } CS150 Introduction to Computer Science 1
***** ***** ***** CS150 Introduction to Computer Science 1
Problem • Write a program that outputs a rectangle of stars for any inputted width and height CS150 Introduction to Computer Science 1