0
0
Cprogramming~20 mins

Return inside loops in C - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Return Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of return inside a for loop
What is the output of this C program?
C
#include <stdio.h>

int test() {
    for (int i = 0; i < 5; i++) {
        if (i == 2) {
            return i;
        }
    }
    return -1;
}

int main() {
    printf("%d\n", test());
    return 0;
}
A-1
B0
C4
D2
Attempts:
2 left
💡 Hint
The function returns as soon as i equals 2 inside the loop.
Predict Output
intermediate
2:00remaining
Return inside while loop behavior
What will this program print?
C
#include <stdio.h>

int count_down(int n) {
    while (n > 0) {
        if (n == 3) {
            return n;
        }
        n--;
    }
    return 0;
}

int main() {
    printf("%d\n", count_down(5));
    return 0;
}
A0
B3
C1
D5
Attempts:
2 left
💡 Hint
The function returns when n equals 3 during the countdown.
🔧 Debug
advanced
2:30remaining
Why does this function return early?
Consider this function. Why does it return 0 instead of 10?
C
#include <stdio.h>

int sum_until_five() {
    int sum = 0;
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            return 0;
        }
        sum += i;
    }
    return sum;
}

int main() {
    printf("%d\n", sum_until_five());
    return 0;
}
ABecause the loop never runs
BBecause sum is reset to 0 when i is 5
CBecause the return 0 inside the loop stops the function when i is 5
DBecause sum is returned before the loop starts
Attempts:
2 left
💡 Hint
Look at the return statement inside the loop and when it triggers.
Predict Output
advanced
2:30remaining
Return inside nested loops
What does this program print?
C
#include <stdio.h>

int nested_loop() {
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            if (i * j == 4) {
                return i + j;
            }
        }
    }
    return 0;
}

int main() {
    printf("%d\n", nested_loop());
    return 0;
}
A5
B6
C4
D0
Attempts:
2 left
💡 Hint
Find the first pair (i,j) where i*j equals 4 and return their sum.
Predict Output
expert
3:00remaining
Return inside loop with break and continue
What is the output of this program?
C
#include <stdio.h>

int tricky() {
    for (int i = 0; i < 5; i++) {
        if (i == 2) {
            continue;
        }
        if (i == 3) {
            break;
        }
        if (i == 1) {
            return i;
        }
    }
    return -1;
}

int main() {
    printf("%d\n", tricky());
    return 0;
}
A1
B-1
C0
D3
Attempts:
2 left
💡 Hint
Remember that return exits the function immediately, continue skips to next loop iteration, and break exits the loop.