CSS Prepare

optional · CSS study notes

II.11 Control Structures

⬆️ P-I.II. Programming Fundamentals · Question Bank · Chapter II (2016–2026)

🧠

Remember: Choose → repeat → stop at the right boundary.

Start here — what you should be able to do

  • Select if, switch, for, while or do-while appropriately.
  • Trace nested loops, break, continue and fall-through.
  • Write and test every recorded small-program pattern.

Reading order: foundation checks → full notes and examples → exam traps → self-test without notes → past-paper answers. All sections below remain part of the topic; code examples are kept in full.

Foundation checks

Loop design checklist

  1. Initial state: where does the counter/accumulator start?
  2. Condition: when is the next iteration allowed?
  3. Update: how does the loop progress?
  4. Invariant: what stays true after each iteration?
  5. Termination: why must the loop stop?

Useful boundaries: n = 0/1; first/last index; first failing condition; invalid menu choice. Switch: ordinary C/C++ case labels are constant integral/enum values, not arbitrary ranges or strings. Prime check: reject n < 2; for positive n, i <= n / i avoids the overflow risk of i <= n / i.

1. Flowchart Shape & Pseudocode for Each Structure

StructureFlowchart Shape(s)Pseudocode Form
SequenceRectangles connected top-to-bottom by plain arrows, no branchingstep1 step2 step3
Selection (if-else)Diamond (the test), with two outgoing arrows labelled Yes/No leading to separate rectanglesIF cond THEN ... ELSE ... ENDIF
Iteration (loop)Diamond (the test) with a rectangle for the body, and an arrow looping back from the body to the diamondWHILE cond DO ... ENDWHILE

If-else flowchart (textual): Decision: cond? (diamond) → Yes → Statement A (rectangle) → join | No → Statement B (rectangle) → join

While-loop flowchart (textual): Decision: cond? (diamond) → Yes → Loop body (rectangle) → arrow back up to the Decision | No → exit the loop, continue after it

Do-while flowchart (textual): Loop body (rectangle) runs first → Decision: cond? (diamond) → Yes → arrow back up to the body | No → exit — note the body sits before the diamond, which is exactly why it always runs at least once.

2. Sequential Structure

  • Statements execute strictly in the order they are written, top to bottom, one after another — the default control flow with no branching

3. Selection (Branching) Structures

  • if: executes a block only if a condition is true
  • if-else: executes one block if true, another if false
  • else if ladder: chains multiple conditions checked in order
  • switch-case: selects one branch among many based on the value of an expression
switch (grade) {
    case 'A': printf("Excellent"); break;
    case 'B': printf("Good"); break;
    default: printf("Needs improvement");
}
  • Without break, execution falls through to the next case regardless of its label — a classic exam trap
  • default is optional and can appear anywhere, but conventionally goes last

4. Iteration (Looping) Structures

LoopCondition CheckMinimum ExecutionsTypical Use
forBefore each iteration0Known/fixed number of iterations
whileBefore each iteration (pre-test)0Unknown iteration count, condition-driven
do-whileAfter each iteration (post-test)1Body must run at least once (e.g. menus)
for (int i = 0; i < 5; i++) { ... }   // init; condition; update

while (n > 0) { ... }                  // checks BEFORE running body

do { ... } while (n > 0);              // checks AFTER running body — runs at least once

5. Jump Statements

  • break: exits the nearest enclosing loop or switch immediately
  • continue: skips the rest of the current iteration and jumps to the next one (loop keeps running)
  • goto: unconditional jump to a labeled statement — generally discouraged (makes code hard to follow/"spaghetti code"), but still valid syntax and occasionally tested

6. Nested Control Structures

  • Any control structure can contain another (e.g. an if inside a for loop, a loop inside a loop) — the inner structure completes fully for each iteration/branch of the outer one
  • break/continue inside a nested loop affect only the innermost loop they're directly inside

7. 💻 Code Examples: C & C++

One program combining all three control structures — sequence, selection (switch), and iteration (for with break/continue, then do-while):

C:

#include <stdio.h>
int main(void) {
    char grade = 'B';
    switch (grade) {                 // Selection
        case 'A': printf("Excellent\n"); break;
        case 'B': printf("Good\n"); break;
        default:  printf("Needs improvement\n");
    }

    for (int i = 1; i <= 5; i++) {   // Iteration: for
        if (i == 3) continue;         // skip printing 3
        if (i == 5) break;            // stop before printing 5
        printf("%d ", i);             // prints: 1 2 4
    }
    printf("\n");

    int n = 0;
    do {                              // Iteration: do-while -- runs at least once
        printf("n=%d\n", n);
    } while (n++ < 0);                // condition is false, but body already ran once
    return 0;
}

C++:

#include <iostream>
using namespace std;
int main() {
    char grade = 'B';
    switch (grade) {
        case 'A': cout << "Excellent\n"; break;
        case 'B': cout << "Good\n"; break;
        default:  cout << "Needs improvement\n";
    }

    for (int i = 1; i <= 5; i++) {
        if (i == 3) continue;
        if (i == 5) break;
        cout << i << " ";            // prints: 1 2 4
    }
    cout << endl;

    int n = 0;
    do {
        cout << "n=" << n << endl;
    } while (n++ < 0);
    return 0;
}
  • The for loop output 1 2 4 shows continue skipping just one iteration (3) while break stops the loop entirely before 5; the do-while prints once even though its condition is false from the start

8. MCQ Traps

  • do-while always executes its body at least once, unlike while and for, which check the condition first and may execute zero times
  • Missing break in a switch causes fall-through to subsequent cases, not a compile error
  • break exits the loop/switch entirely; continue only skips to the next iteration, the loop itself keeps running
  • goto is valid C/C++ syntax but considered bad practice — it bypasses structured control flow
  • In nested loops, break only exits the innermost loop, not all enclosing loops

9. Self-Test Questions — with answers

Q1. Why does do-while execute at least once?

Answer

  • Its condition is tested after the body.
  • A reached do-while therefore enters the body once even when the first test is false.

Q2. What happens when break is omitted from a switch case?

Answer

  • Execution normally continues into the following case's statements.
  • Case labels do not re-test the expression during this fall-through.
  • A return or another control transfer can also prevent fall-through.

Q3. Distinguish break from continue.

Answer

  • break leaves the nearest enclosing loop or switch.
  • continue skips the remaining loop body and proceeds to the next iteration step.
  • In a for loop, that includes the update expression before the condition is tested again.

Q4. Give equivalent for and while loops printing 1 to 5.

Answer

  • for (int i = 1; i <= 5; ++i) cout << i << ' ';
  • Equivalent: int i = 1; while (i <= 5) { cout << i << ' '; ++i; }
  • Both print 1 2 3 4 5.

Q5. Which loop does break leave in nested loops?

Answer

  • The nearest enclosing loop, unless a nearer switch encloses the break.
  • A break directly inside the inner loop does not terminate the outer loop.

Q6. How do while and do-while flowcharts differ?

Answer

  • while: decision diamond before the body rectangle.
  • do-while: body rectangle before the decision diamond.
  • Follow the return arrow to see which point is repeated.
  1. Why does a do-while loop always execute its body at least once?
  2. What happens if a break statement is omitted from a switch case?
  3. Differentiate break from continue inside a loop.
  4. Write a for loop and an equivalent while loop that both print numbers 1 to 5.
  5. If break appears inside the inner loop of two nested for loops, which loop does it terminate?
  6. In a flowchart, how can you tell a while loop apart from a do-while loop just by looking at the position of the diamond and the rectangle?

10. 📝 Exam Practice: Prime Number Check — Logical Error Debugging

Q: Identify the logical errors in the given C++ program (declares n, checks primality) and give the correct statement(s) at the same line number.

Errors found:

LineErrorFix
1No data type declaredint n, i;
2isPrime initialized to false and never set true — always reports "not prime"bool isPrime = (n >= 2);
5Loop starts at i=1 (everything divides by 1); ++1 is invalid syntax, not an incrementfor (i=2; i<=n/2; ++i)
7n/i=0 — single = is assignment not comparison; / is division not remainderif (n%i==0)

Corrected & complete program:

#include <iostream>
using namespace std;

int main()
{
    int n, i;
    bool isPrime = true;

    cout << "Enter a positive integer.";
    if (!(cin >> n)) return 1;
    isPrime = (n >= 2);

    for (i=2; i <= n / i; ++i)
    {
        if (n%i==0)
        {
            isPrime = false;
            break;
        }
    }

    if (isPrime)
        cout << "This is a prime number";
    else
        cout << "This is not a prime number";

    return 0;
}

Optimization — checking up to √n instead of n/2:

Factor pairs always multiply to n; if both factors were greater than √n, their product would exceed n — contradiction. So at least one factor of any pair is always ≤ √n, making it a safe and much faster boundary than n/2.

for (i=2; i <= n / i; ++i)
{
    if (n%i==0) { isPrime = false; break; }
}

For positive n, i <= n / i avoids multiplying i by itself and therefore avoids that integer-overflow risk. Compute a square-root bound once if choosing a floating-point approach.

Efficiency comparison: for n=1,000,000 — the n/2 bound needs ~500,000 checks; the √n bound needs only ~1,000. This gap (O(n) vs O(√n)) is a common CS optional discussion point.

Edge case to flag: the unguarded original version misclassifies n=0 and n=1 as prime (loop never runs, isPrime stays true). A rigorous solution adds an explicit if (n==0 || n==1) isPrime = false; check upfront — a classic MCQ trap.

11. 📜 Past-Paper Questions & MCQs (CSS 2016–2026)

2016 · Paper-I · Q2(a) · 6 marks

Recall cue: Read the conversion choice; choose the matching formula; preserve floating-point division; test both branches.

Q. Write a program to input a choice for temperature conversion (Fahrenheit to Celsius or Celsius to Fahrenheit), then input the temperature and display the answer.

Answer — key points

#include <iostream>
using namespace std;
int main() {
    int choice; float t;
    cout << "1. Fahrenheit to Celsius\n2. Celsius to Fahrenheit\nEnter your choice: ";
    cin >> choice;
    if (choice == 1) {
        cout << "Enter Temperature in Fahrenheit: "; cin >> t;
        cout << "Same Temperature in Celsius: " << (t - 32) * 5 / 9;
    } else if (choice == 2) {
        cout << "Enter Temperature in Celsius: "; cin >> t;
        cout << "Same Temperature in Fahrenheit: " << t * 9 / 5 + 32;
    } else cout << "Invalid choice";
    return 0;
}
  • Check: 98°F gives (98 − 32) × 5/9 = 36.7°C.

2018 · Paper-I · Q3(a) · 5 marks

Recall cue: Read exactly five marks; accumulate; divide by five; use the paper's specified message thresholds.

Q. Write a grade average calculator. Input marks for five subjects, output the average and an appropriate message.

Answer — key points

float sum = 0, m;
for (int i = 1; i <= 5; i++) { cout << "Marks " << i << ": "; cin >> m; sum += m; }
float avg = sum / 5;
cout << "Average = " << avg << endl;
if (avg >= 80)      cout << "Well done";
else if (avg >= 60) cout << "Keep it up";
else                cout << "Better luck next time";

2018 · Paper-I · Q3(b) · 2 marks

Recall cue: Translate each clause separately; parenthesise AND groups inside OR; outside an interval uses OR.

Q. Write the conditions: (i) print hello when i is twice j, or j is smaller than k and n, or m is negative; (ii) print hello when i is not in the interval 6–9.

Answer — key points

  • (i) if (i == 2*j || (j < k && j < n) || m < 0)
  • (ii) if (i < 6 || i > 9)

2018 · Paper-I · Q3(e) · 5 marks

Recall cue: Rows get shorter: n, n−1, …, 1; each row prints ascending integers from 1.

Q. Print a triangle of increasing numbers (for n = 4: 1 2 3 4 / 1 2 3 / 1 2 / 1).

Answer — key points

for (int i = n; i >= 1; i--) {
    for (int j = 1; j <= i; j++) cout << j << " ";
    cout << endl;
}
  • The outer loop controls the row length and counts down. The inner loop prints 1 up to the row length.

2019 · Paper-I · Q3(a) · 10 marks

Recall cue: Correct each supplied line; use remainder for divisibility; start at 2; handle n < 2.

Q. Identify the logical errors in the prime-number program and give the correct statement at the same line number.

Answer — key points

  • Line 1: int n, i; (the type is missing).
  • Line 2: bool isPrime = true; (variable names cannot contain spaces, and the flag must start as true, because the loop only sets it to false).
  • Line 5: for (i = 2; i <= n / 2; ++i) (starting at 1 divides every number by 1 and always gives "not prime"; the limit should include n/2).
  • Line 7: if (n % i == 0) (use the remainder operator, not division).
  • Line 9: isPrime = false;
  • Line 13: if (isPrime && n > 1) (the name had a space, and numbers 1 or below are not prime).

2020 · Paper-I · Q2(a) · 8 marks

Recall cue: Validate binary inputs; distinguish unary NOT from binary AND/OR; show a truth-table dry run.

Q. Write a C/C++ program implementing binary logical AND, OR and NOT gates.

Answer — key points

int a, b; char g;
cout << "Gate (A=AND, O=OR, N=NOT): "; cin >> g;
if (g == 'N' || g == 'n') { cin >> a; cout << !a; }
else {
    cin >> a >> b;
    if (g == 'A' || g == 'a') cout << (a && b);
    else if (g == 'O' || g == 'o') cout << (a || b);
}

2020 · Paper-I · Q2(b) · 7 marks

Recall cue: Clarify value ceiling versus term count; update two previous terms; handle the input range and integer limits.

Q. Input a number and print the Fibonacci series up to it.

Answer — key points

int n;
if (!(cin >> n) || n < 0) return 1;
long long a = 0, b = 1;  // wide enough for sums while a <= an int ceiling
while (a <= n) {
    cout << a << " ";
    long long c = a + b; a = b; b = c;
}
  • Each term is the sum of the previous two (0, 1, 1, 2, 3, 5 …).

2020 · Paper-I · Q4(c) · 4 marks

Recall cue: Use a lookup for small numbers and tens; split hundreds; state the supported range; handle quit and invalid input.

Q. Convert numbers into words (123 → one hundred and twenty three), continuing until the user types quit.

Answer — key points

#include <iostream>
#include <string>
using namespace std;
string ones[] = {"","one","two","three","four","five","six","seven","eight","nine","ten",
 "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
string tens[] = {"","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
string words(int n) {                 // 1..999
    string s = "";
    if (n >= 100) { s += ones[n/100] + " hundred"; n %= 100; if (n) s += " and "; }
    if (n >= 20) { s += tens[n/10]; if (n % 10) s += " " + ones[n % 10]; }
    else s += ones[n];
    return s;
}
int main() {
    string in;
    while (true) {
        cout << "Enter a number (or quit): ";
        if (!(cin >> in)) break;
        if (in == "quit") break;
        try {
            size_t used = 0;
            int n = stoi(in, &used);
            if (used != in.size() || n < 0 || n > 999) {
                cout << "Enter an integer from 0 to 999." << endl;
                continue;
            }
            cout << (n == 0 ? "zero" : words(n)) << endl;
        } catch (...) {
            cout << "Enter an integer from 0 to 999, or quit." << endl;
        }
    }
}

2021 · Paper-I · Q3(b) · 5 marks

Recall cue: For positive n, test divisors from 1 through n; print each i with n % i == 0.

Q. Write a program that outputs the factors of a number, one per line.

Answer — key points

int x; cin >> x;
for (int i = 1; i <= x; i++)
    if (x % i == 0) cout << i << endl;

2021 · Paper-I · Q3(d) · 4 marks

Recall cue: Repeatedly divide by 16; map remainders 10–15 to A–F; reverse the digits; handle zero.

Q. Write a C/C++ program to convert a decimal number to hexadecimal.

Answer — key points

int n; cin >> n;
char hex[32]; int i = 0;
if (n == 0) cout << 0;
while (n > 0) {
    int r = n % 16;
    hex[i++] = (r < 10) ? '0' + r : 'A' + (r - 10);
    n /= 16;
}
for (int j = i - 1; j >= 0; j--) cout << hex[j];
  • Remainders are read in reverse order.

2022 · Paper-I · Q2(a) · 8 marks

Recall cue: Use a void function; separate spacing and number loops; match the shown alignment.

Q. Write a function pattern(int n) that prints the right-aligned number triangle (1 / 1 2 / 1 2 3 …).

Answer — key points

void pattern(int n) {                  // return type void
    for (int i = 1; i <= n; i++) {
        for (int s = 1; s <= n - i; s++) cout << "  ";   // leading spaces
        for (int j = 1; j <= i; j++) cout << j << " ";
        cout << endl;
    }
}
  • Each missing number is replaced by two spaces, for single-digit entries. For rows containing numbers above 9, use a consistent field width (for example setw) for both spaces and values.

2024 · Paper-I · Q3(a) · 6 marks

Recall cue: Map each grade to a number; include a default case; handle letter case deliberately.

Q. Prompt for a letter grade A, B, C, D or F and display 4, 3, 2, 1 or 0.

Answer — key points

char g; cin >> g;
switch (toupper(g)) {
    case 'A': cout << 4; break;
    case 'B': cout << 3; break;
    case 'C': cout << 2; break;
    case 'D': cout << 1; break;
    case 'F': cout << 0; break;
    default:  cout << "Invalid grade";
}

2024 · Paper-I · Q3(b) · 6 marks

Recall cue: Initialise the accumulator to zero; multiply corresponding components; sum exactly n terms.

Q. Write pseudocode or C for the dot product a·b = Σ aᵢbᵢ.

Answer — key points

sum = 0
for i = 1 to n
    sum = sum + a[i] * b[i]
print sum

2024 · Paper-I · Q4(a) · 6 marks

Recall cue: Area = width × height; perimeter = 2(width + height); state units where given.

Q. Display the area and perimeter of a rectangle with width 4.5 and height 7.9.

Answer — key points

float w = 4.5, h = 7.9;
cout << "Area = " << w * h << endl;            // 35.55
cout << "Perimeter = " << 2 * (w + h) << endl; // 24.8

2024 · Paper-I · Q4(c) · 8 marks

Recall cue: Validate month; apply the 400/100/4 leap-year rule; distinguish 28/29/30/31 days.

Q. Enter a month and year and display the number of days in that month.

Answer — key points

int m, y, d;
if (!(cin >> m >> y) || m < 1 || m > 12 || y < 1) {
    cout << "Invalid month or year";
    return 1;
}
bool leap = (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
switch (m) {
    case 2: d = leap ? 29 : 28; break;
    case 4: case 6: case 9: case 11: d = 30; break;
    default: d = 31;
}
cout << "The month has " << d << " days";
  • Example: month 2, year 2024 → 29 days. Month 3, year 2015 → 31 days.

2025 · Paper-I · Q4(a) · 6 marks

Recall cue: Generate a+i×d for i=0…n−1; accumulate or use the formula; expected series sums to 75.

Q. Output the arithmetic series of n terms and its sum Sₙ = (n/2)[2a + (n−1)d], with a = 5, d = 3, n = 6.

Answer — key points

int a = 5, d = 3, n = 6;
for (int i = 0; i < n; i++) cout << a + i * d << " ";   // 5 8 11 14 17 20
cout << "\nSum = " << n * (2 * a + (n - 1) * d) / 2;      // 75

Recall check and coverage

  • Explain the three learning outcomes at the top without looking.
  • Reproduce one example or trace and test a boundary case.
  • Answer each self-test, then compare with the key.
  • Attempt each recorded past-paper task on this page.
  • Recorded written references: 2016 · Paper-I · Q2(a) · 6 marks; 2018 · Paper-I · Q3(a) · 5 marks; 2018 · Paper-I · Q3(b) · 2 marks; 2018 · Paper-I · Q3(e) · 5 marks; 2019 · Paper-I · Q3(a) · 10 marks; 2020 · Paper-I · Q2(a) · 8 marks; 2020 · Paper-I · Q2(b) · 7 marks; 2020 · Paper-I · Q4(c) · 4 marks; 2021 · Paper-I · Q3(b) · 5 marks; 2021 · Paper-I · Q3(d) · 4 marks; 2022 · Paper-I · Q2(a) · 8 marks; 2024 · Paper-I · Q3(a) · 6 marks; 2024 · Paper-I · Q3(b) · 6 marks; 2024 · Paper-I · Q4(a) · 6 marks; 2024 · Paper-I · Q4(c) · 8 marks; 2025 · Paper-I · Q4(a) · 6 marks

Evidence limit: this page preserves the question records found in your Notion notes. Disputed labels and questions not checked against original PDFs remain flagged in the Question Bank; this is not a claim of exhaustive original-paper verification.