cplusplus:repetition_examples
This is an old revision of the document!
Table of Contents
Control Structures: Repetition examples
while
- simple_while.cpp
// This program counts to an upper limit #include <iostream> using namespace std; int main() { const int UPPER_LIMIT = 5; int num = 1; while (num <= UPPER_LIMIT) { cout << num << endl; num = num + 1; } return 0; }
increment operator
- increment-example.cpp
// This program counts to an upper limit #include <iostream> using namespace std; int main() { int num = 10; cout << num << endl; num++; cout << num << endl; return 0; }
Sentinel-controlled repetition
- simple-sentinel.cpp
// This program calculates the squares of integers. The user // enters -999 when finished. #include <iostream> using namespace std; int main() { int num = 1; cout << "Enter an integer and I will tell you its square. " << endl; cout << "Enter -999 to quit: "; cin >> num; while (num != -999) { cout << num <<" squared is " << num * num << "." << endl << endl; cout << "Enter an integer and I will tell you its square. " << endl; cout << "Enter -999 to quit: "; cin >> num; } return 0; }
for
- simple-for.cpp
// This program counts to an upper limit // using a for structure. #include <iostream> using namespace std; int main() { const int UPPER_LIMIT = 5; int num; for (num = 1; num <=UPPER_LIMIT; num++) { cout << num << endl; } return 0; }
Nested loops
- nested-loop.cpp
// This program does some graphics with nested loops. #include <iostream> using namespace std; int main() { const int NUM_ROWS = 5; const int NUM_COLUMNS = 3; for (int row = 1; row <= NUM_ROWS; row++) { for (int column = 1; column <= NUM_COLUMNS; column++) { cout << "*"; } cout << endl; } return 0; }
cplusplus/repetition_examples.1362099913.txt.gz · Last modified: 2013/03/01 01:05 by mithat