Nested Loops
Break and Continue
Switch Statements
Output Prediction
Functions & Loops
100

Print a 2×3 grid of * using nested for loops

for(int i=0;i<2;i++){

    for(int j=0;j<3;j++){

        cout<<"*";

    }

    cout<<"\n";

}

100

Print numbers 1–5 but stop at 3 using break.

for(int i=1;i<=5;i++){

    if(i==3) break;

    cout<<i;

}


100

Write a switch that prints “Yes” for 1, “No” for 2, and “Maybe” for 3.

switch(n){

    case 1: cout<<"Yes"; break;

    case 2: cout<<"No"; break;

    case 3: cout<<"Maybe"; break;

}

100

Predict output:

int i=1;
cout<<i++<<" "<<++i;
1 3
100

Write a function print1to5() that prints numbers 1–5.

void print1to5(){

    for(int i=1;i<=5;i++) cout<<i<<"\n";

}


200

Write a nested loop to print:

1 2

3 4

int n=1;

for(int i=0;i<2;i++){

    for(int j=0;j<2;j++){

        cout<<n++<<" ";

    }

    cout<<"\n";

}


200

Print numbers 1–5 but skip 2 using continue.

for(int i=1;i<=5;i++){

    if(i==2) continue;

    cout<<i;

}

200

Predict output:

int x=2;
switch(x){
    case 1: cout<<"A"; break;
    case 2: cout<<"B";
    case 3: cout<<"C"; break;
}



BC

200

Predict output:

for(int i=0;i<3;i++){
    cout<<i<<" ";

}



0 1 2

200

Write a function sumRange(int a, int b) that returns the sum of all numbers between a and b inclusive.

int sumRange(int a,int b){

    int sum=0;

    for(int i=a;i<=b;i++) sum+=i;

    return sum;

}

300

How many times does the inner loop execute?

for(int i=1;i<=3;i++){

    for(int j=1;j<=i;j++){

        cout<<i;

    }

}


6

300

Explain in one sentence the difference between break and continue.

break exits the loop completely; continue skips the current iteration and continues with the next one.

300

A variable grade holds a character: 'A', 'B', 'C', 'D', or 'F'. Write a switch statement that prints "Pass" for 'A', 'B', or 'C', and "Fail" for 'D' or 'F'.

switch(grade){

    case 'A': case 'B': case 'C': cout<<"Pass"; break;

    case 'D': case 'F': cout<<"Fail"; break;

}

300

Predict output:

for(int i=1;i<=3;i++){
    if(i==2) {
         continue;
    }
    cout<<i;
}

13

300

Write a function that prints numbers from 1 to n but skips multiples of 3 using continue.

void skip3(int n){

    for(int i=1;i<=n;i++){

        if(i%3==0) continue;

        cout<<i<<"\n";

    }

}