cplusplus:repetition_examples
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revision | Next revisionBoth sides next revision | ||
cplusplus:repetition_examples [2019/02/11 17:49] – [Input validation] mithat | cplusplus:repetition_examples [2019/02/11 18:01] – [Input validation] mithat | ||
---|---|---|---|
Line 77: | Line 77: | ||
===== Input validation ===== | ===== Input validation ===== | ||
- | <file c++ simple-input-validation.cpp> | + | <file c++ simple-input-validation.cpp>// |
- | #include < | + | #include < |
- | using namespace std; | + | using namespace std; |
- | | + | int main() |
- | { | + | { |
- | const int LOWER_BOUND = 0; | + | const int LOWER_BOUND = 0; |
- | const int UPPER_BOUND = 100; | + | const int UPPER_BOUND = 100; |
- | int num; | + | int num; |
- | cout << "Enter a number between " << LOWER_BOUND | + | cout << "Enter a number between " << LOWER_BOUND |
+ | | ||
+ | cin >> num; | ||
+ | |||
+ | // Fall through loop only if input is valid. | ||
+ | while (num < LOWER_BOUND || num > UPPER_BOUND) | ||
+ | { | ||
+ | | ||
<< | << | ||
cin >> num; | cin >> num; | ||
+ | } | ||
- | // Fall through loop only if input is valid. | + | |
- | while (num < LOWER_BOUND || num > UPPER_BOUND) | + | |
- | { | + | |
- | | + | |
- | << | + | |
- | cin >> num; | + | |
- | } | + | |
- | cout << " | + | return 0; |
+ | } | ||
- | return | + | </ |
+ | |||
+ | ===== Running total ===== | ||
+ | <file c++ simple-running-total.cpp>// | ||
+ | // Total all the integers between a lower and an upper bound. | ||
+ | #include < | ||
+ | using namespace std; | ||
+ | |||
+ | int main() | ||
+ | { | ||
+ | const int LOWER_BOUND = 0; | ||
+ | const int UPPER_BOUND = 10; | ||
+ | |||
+ | int num = LOWER_BOUND; | ||
+ | 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 | ||
+ | << | ||
+ | << | ||
+ | |||
+ | return 0; | ||
+ | } | ||
+ | |||
</ | </ | ||
===== for ===== | ===== for ===== |
cplusplus/repetition_examples.txt · Last modified: 2019/02/14 21:28 by mithat