User Tools

Site Tools


cplusplus:repetition_examples

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Next revisionBoth sides next revision
cplusplus:repetition_examples [2019/02/11 17:31] – [Sentinel-controlled repetition] mithatcplusplus:repetition_examples [2019/02/12 02:17] – [increment operator] mithat
Line 40: Line 40:
 </file> </file>
  
 +===== Counter-controlled repetition =====
 +<file c++ counter-controlled-repetition.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++;
 +    }
 +
 +    return 0;
 +}</file>
 ===== Sentinel-controlled repetition ===== ===== Sentinel-controlled repetition =====
  
Line 76: Line 94:
 </file> </file>
  
 +===== Input validation =====
 +<file c++ simple-input-validation.cpp>// Simple example of input validation.
 +#include <iostream>
 +using namespace std;
 +
 +int main()
 +{
 +    const int LOWER_BOUND = 0;
 +    const int UPPER_BOUND = 100;
 +    int num;
 +
 +    cout << "Enter a number between " << LOWER_BOUND 
 +         << " and " << UPPER_BOUND << ": ";
 +    cin >> num;
 +
 +    // Fall through loop only if input is valid.
 +    while (num < LOWER_BOUND || num > UPPER_BOUND)
 +    {
 +        cout << "Enter a number between " << LOWER_BOUND
 +             << " and " << UPPER_BOUND << ": ";
 +        cin >> num;
 +    }
 +
 +    cout << "Congratulations, you can follow directions." << endl;
 +
 +    return 0;
 +}
 +
 +</file>
 +
 +===== Running total =====
 +<file c++ simple-running-total.cpp>// Simple running total example.
 +// Total all the integers between a lower and an upper bound.
 +#include <iostream>
 +using namespace std;
 +
 +int main()
 +{
 +    const int LOWER_BOUND = 0;
 +    const int UPPER_BOUND = 10;
 +
 +    int num = LOWER_BOUND;  // counter
 +    int sum = 0;            // accumulator
 +
 +    while (num <= UPPER_BOUND)
 +    {
 +        sum += num;         // add the new value to the sum
 +        num++;
 +    }
 +
 +    cout << "The sum of integers from " << LOWER_BOUND
 +         << " to " << UPPER_BOUND
 +         << " is " << sum << endl;
 +
 +    return 0;
 +}
 +
 +</file>
 ===== for ===== ===== for =====
-<file c++ simple-for.cpp>// This program counts to an upper limit +<file c++ simple-for.cpp>// This program counts to an upper limit using a for structure.
-// using a for structure.+
 #include <iostream> #include <iostream>
 using namespace std; using namespace std;
cplusplus/repetition_examples.txt · Last modified: 2019/02/14 21:28 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki