Controlling execution iteration a lecture for the c++ Course
Download 0.75 Mb.
|
iteration7
}A summing program
// A Summing Program using a while/do Loop#include using namespace std;int main(){int sum, count ;sum = 0;count = 1;while (count <=20){sum = sum + count;count = count + 1;}cout << "The sum of the integers from 1 through 20 is ";cout << sum << endl;return 0;}The variables sum and count are accumulators. A summing program
// A Summing Program using a for loop#include using namespace std;int main(){int sum, count ;sum = 0;for (count=1; count<=20; count++)sum = sum + count;cout << "The sum of the integers from 1 through 20 is ";cout << sum << endl;return 0;}Just an average program
Just an average program
#include int main(){int n, count;float x, sum, avg;sum = 0;cout << "How many numbers? ";cin >> n;for (count=1; count<=n; count++){cout << "? ";cin >> x;sum = sum + x;}avg = sum / n;cout << "The average is " << avg << endl;return 0}Do we really need to ask the user to count? Counting is something computers do really well! Using a sentinel value#include int main(){int count;float x, sum, avg;const float EOD = -999; //end of data indicatorcount = 0;sum = 0;cout << “First number?”; cin >> x;while (x != EOD) {sum += x;count++;cout << "? "; cin >> x;}avg = sum / count;cout << "The average is " << avg << endl;return 0;}Run this program yourself to see how it works. Choosing a loop structure
Branching – emergency use only
break
// modified from the Deitel book// Using the break statement in a for structure#include using namespace std;int main(){int x;for (x=1; x<=10; x++) {if (x==5)break; //break loop only if x is 5cout << x << " ";} //end forcout << "\nBroke out of loop at x = " << x << endl;cout<< endl << endl << endl;return 0;}Example using breakContinue
// This program is modified from the Deitel book,Download 0.75 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling