C++ Programming

WEEK 4 · LAB 1

Lab 1 — Loops and Relational Expressions

Use a for loop to add the integers from 1 to n.

I. Objectives

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

Open OnlineGDB ↗

III. Tasks and Requirements

Complete the TODOs in the starter code, then compare your result with the expected output. The starter is intentionally unfinished.

Task 1 — Read and run the for loop

  • Find i = 1, i <= n, and ++i. Run the program and enter 3. The starter displays Sum: 0 because the loop does not yet add i to sum.

Task 2 — Complete the loop body

  • At TODO 1, add the current value of i to sum. Keep the supplied loop condition and output statement.

Task 3 — Test the loop limits

  • Use an integer n from 0 to 10. Test 0, 1, 3, and 5; the sums should be 0, 1, 6, and 15. When n is 0, the loop body should not run.

Starter Code

Download .cpp
#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

Two Short Questions

  1. Why does the test condition use <= instead of <?
  2. How many times does the loop body run when n is 0?