










Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!











2
4
1 2 3 4 5 6 7 8 9 10
5
◦^ Names
counter
◦^ Declares
counter
to be an integer
◦^ Reserves space for
counter
in memory
◦^ Sets
counter
to an initial value of
^1
7
1
// code6.cpp 2
// Counter-controlled repetition with the for structure. 3
#include
using std::cout; 6
using std::endl; 7 8
// function main begins program execution 9
int main() 10
{ 11
// Initialization, repetition condition and incrementing 12
// are all included in the for structure header. 1314
for ( int counter = 1; counter <= 10; counter++ ) 15
cout << counter << endl; 1617
return 0;
// indicate successful termination
1819
} // end function main
8
10
1
// code7.cpp 2
// Summation with for. 3
#include
using std::cout; 6
using std::endl; 7 8
// function main begins program execution 9
int main() 10
{ 11
int sum = 0;
// initialize sum
1213
// sum even integers from 2 through 100 14
for ( int number = 2; number <= 100; number += 2 ) 15
sum += number;
// add number to sum
1617
cout << "Sum is " << sum << endl; // output sum 18
return 0;
// successful termination
1920
} // end function main Sum^
is^2550
11
13
24
// output table column heads 25
cout << "Year" << setw( 21 ) << "Amount on deposit" << endl; 2627
// set floating-point number format 28
cout << fixed << setprecision( 2 ); 2930
// calculate amount on deposit for each of ten years 31
for ( int year = 1; year <= 10; year++ ) { 3233
// calculate new amount for specified year 34
amount = principal * pow( 1.0 + rate, year ); 3536
// output one table row 37
cout << setw( 4 ) << year 38
<< setw( 21 ) << amount << endl; 3940
} // end for 4142
return 0;
// indicate successful termination
4344
} // end function main
14
Year^
Amount on deposit 1
2
3
4
5
6
7
8
9
10
16
1 // code11.cpp 2 // Using the break statement in a for structure. 3 #include
int x; // x declared here so it can be used after the loop 1314
// loop 10 times 15
for ( x = 1; x <= 10; x++ ) { 1617
// if x is 5, terminate loop 18
if ( x == 5 ) 19
break;
// break loop only if x is 5
2021
cout << x << " ";
// display value of x
2223
} // end for 2425
cout << "\nBroke out of loop when x became " << x << endl;
17
2627
return
0;
// indicate successful termination
2829
} // end function main 1 2
3 4 Broke
out
of^
loop
when
x^ became
5