DEV Community

Cognifyx
Cognifyx

Posted on

HSC ICT: How to Find the Output of a C Loop — Without Memorizing It

HSC ICT students in Bangladesh face the same problem every year: a C loop in the question paper, and they have to find the output — without a computer in front of them. Most students try to memorize outputs. That fails the moment the loop changes a little. Here is a better way: trace it, step by step.

The example:

#include <stdio.h>
int main() {
    int i, sum = 0;
    for (i = 1; i <= 10; i++) {
        sum += i;
    }
    printf("%d", sum);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

What does this print? The answer is 55 — the sum of 1 to 10.

Trace it, don't memorize it: i starts at 1, sum is 0. i=1: sum=1. i=2: sum=3. i=3: sum=6. i=4: sum=10... until i=10: sum=45+10=55. i becomes 11, condition i<=10 is false, loop stops. Two questions always answer a loop question: how many times does the loop run (here 10 times) and where does the result accumulate (here, in sum).

Common mistakes: 1) Forgetting the last value — i<=10 includes 10. 2) Confusing sum+=i with sum=i — sum+=i adds to the running total, sum=i would just overwrite it and the answer would be 10. 3) Starting sum at the wrong value — if sum is not set to 0 first, the result is garbage.

Running it beats memorizing it: when you run it, you see the output instantly — and when you change i<=10 to i<=5, you see the answer change to 15. That is how the pattern sticks.

That is what ICT Lab is built for: live HTML, C and SQL labs in the browser, a number-system converter, a logic-gate simulator, chapter quizzes and mock tests, and an AI tutor you can ask in Bangla, English or Banglish. Try the C lab free: https://ictlab.cognifyx.net/

Disclosure: ICT Lab is Cognifyx's own product.

Top comments (0)