Recognize the initialization, test condition, and update in a for loop.
Use the relational operator <= to control a loop.
Before the Lab
Weeks 2–3: initialize int variables, read with std::cin, print with std::cout, and use +=, ++, <=, and a for loop. Trace one loop by hand before filling in the TODO.
II. Environment
A computer with Windows, macOS, or Linux.
Use OnlineGDB in C++ mode, or the C++ environment demonstrated in class.
Save your program as lab01.cpp. Use one source file for this lab.
#include <iostream>
int main() {
int n = 0;
std::cin >> n;
int sum = 0;
for (int i = 1; i <= n; ++i) {
// TODO 1: Add i to sum.
}
std::cout << "Sum: " << sum << '\n';
return 0;
}
Expected Output
Expected output for input 3 after completing the loop body.
Sum: 6
IV. Submission
Your completed lab01.cpp source file.
One or two screenshots showing your test results.
A short answer to each question below, in English or Chinese.
Two Short Questions
Why does the test condition use <= instead of <?
How many times does the loop body run when n is 0?