Download presentation
Presentation is loading. Please wait.
1
CS150 Introduction to Computer Science 1
More on Loops So far, we’ve learnt about ‘while’ loops. Today will learn about ‘for’ loops. 2/21/2019 CS150 Introduction to Computer Science 1
2
CS150 Introduction to Computer Science 1
For loops 3 main things for loops: Initialization of lcv, testing of lcv, updating lcv For loops provide a concise way to do this for (count = 0; count < 5; count++) cout << count << endl; 2/21/2019 CS150 Introduction to Computer Science 1
3
CS150 Introduction to Computer Science 1
General Format for (initialization expression; loop repetition condition; update expression) { statements; } 2/21/2019 CS150 Introduction to Computer Science 1
4
CS150 Introduction to Computer Science 1
Examples Write a for loop that outputs odd numbers less than 10 Write a program that computes the factorial of a number 2/21/2019 CS150 Introduction to Computer Science 1
5
Localized Declarations
for (int i = 0; i < n; i++) cout << i << endl; i is declared ONLY in the loop 2/21/2019 CS150 Introduction to Computer Science 1
6
Rewrite using a while loop
for (i = 5; i < 10; i+= 2) cout << i; What does this output? 2/21/2019 CS150 Introduction to Computer Science 1
7
CS150 Introduction to Computer Science 1
Formatting Output How can we generate this output? Fahrenheit Celsius 2/21/2019 CS150 Introduction to Computer Science 1
8
CS150 Introduction to Computer Science 1
The Program float F,C; F = 32.0; cout << fixed << setprecision(3); cout << "Fahrenheit "; cout << "Celsius" << endl; while (F <= 212.0) { C = (5.0/9.0)*(F - 32); cout << setw(10) << F << setw(12) << C << endl; F += 1; } You must have #include<iomanip> 2/21/2019 CS150 Introduction to Computer Science 1
9
CS150 Introduction to Computer Science 1
Programs Write a program that will print the sum of the odd integers between 1 and 50 inclusive. Write one program using a while and the other using a for loop. 2/21/2019 CS150 Introduction to Computer Science 1
10
CS150 Introduction to Computer Science 1
Program Write a program that inputs 50 numbers and outputs the largest and the smallest number 2/21/2019 CS150 Introduction to Computer Science 1
11
CS150 Introduction to Computer Science 1
Conditional Loops Loops that execute until some condition is met Includes more than counting Use while loops 2/21/2019 CS150 Introduction to Computer Science 1
12
CS150 Introduction to Computer Science 1
Program Write a flag controlled loop that continues to read pairs of integers until it reads a pair with the property that the first integer is evenly divisible by the second 2/21/2019 CS150 Introduction to Computer Science 1
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.