Look at this C++ program. What will it print?
#include <iostream> int main() { int apples = 5; int oranges = 3; int total = apples + oranges; std::cout << "Total fruits: " << total << std::endl; return 0; }
Variables store numbers. Adding them sums their values.
The variables apples and oranges hold numbers 5 and 3. Adding them gives 8, which is printed.
Which of these best explains why variables are needed in programming?
Think about how you keep track of things in real life by giving them names.
Variables let us store data with a name so we can use or change it anytime in the program.
What will this C++ program print?
#include <iostream> int main() { int score = 10; score = score + 5; std::cout << "Score: " << score << std::endl; return 0; }
Adding 5 to the current score updates its value.
The variable score starts at 10, then 5 is added, making it 15.
Why is it better to use variables instead of writing numbers directly in code?
Think about changing a number in one place instead of many.
Using variables means you can update a value once and the change applies everywhere the variable is used.
Consider this C++ code snippet. What is the final value of x?
#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; }
Calculate step by step the changes to x and y.
Step 1: x = 2 * 3 = 6
Step 2: y = 6 - 3 = 3
Step 3: x = 6 + 3 = 9
But wait, re-check step 3 carefully:
Actually, after step 2, y = 3, so x = 6 + 3 = 9.
Output is 9, so option B is correct.