0
0
C++programming~20 mins

Why variables are needed in C++ - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Variable Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this C++ code using variables?

Look at this C++ program. What will it print?

C++
#include <iostream>
int main() {
    int apples = 5;
    int oranges = 3;
    int total = apples + oranges;
    std::cout << "Total fruits: " << total << std::endl;
    return 0;
}
ATotal fruits: 8
BTotal fruits: 53
CCompilation error
DTotal fruits: 0
Attempts:
2 left
💡 Hint

Variables store numbers. Adding them sums their values.

🧠 Conceptual
intermediate
1:30remaining
Why do we use variables in programming?

Which of these best explains why variables are needed in programming?

ATo store and name data so it can be used and changed later
BTo make the program run faster by skipping calculations
CTo create pictures and graphics on the screen
DTo write comments inside the code
Attempts:
2 left
💡 Hint

Think about how you keep track of things in real life by giving them names.

Predict Output
advanced
2:00remaining
What happens if you reuse a variable in C++?

What will this C++ program print?

C++
#include <iostream>
int main() {
    int score = 10;
    score = score + 5;
    std::cout << "Score: " << score << std::endl;
    return 0;
}
AScore: 5
BScore: 10
CScore: 15
DCompilation error
Attempts:
2 left
💡 Hint

Adding 5 to the current score updates its value.

🧠 Conceptual
advanced
1:30remaining
What is the main benefit of using variables instead of fixed numbers?

Why is it better to use variables instead of writing numbers directly in code?

AVariables make the program use less memory
BVariables make the program run without errors always
CVariables automatically fix bugs in the code
DVariables let you change values easily without rewriting many places
Attempts:
2 left
💡 Hint

Think about changing a number in one place instead of many.

Predict Output
expert
2:30remaining
What is the value of x after this code runs?

Consider this C++ code snippet. What is the final value of x?

C++
#include <iostream>
int main() {
    int x = 2;
    int y = 3;
    x = x * y;
    y = x - y;
    x = x + y;
    std::cout << x << std::endl;
    return 0;
}
A12
B9
C15
D11
Attempts:
2 left
💡 Hint

Calculate step by step the changes to x and y.