0
0
C++programming~15 mins

Passing parameters by reference in C++ - Mini Project: Build & Apply

Choose your learning style9 modes available
Passing parameters by reference
📖 Scenario: Imagine you have a simple program that needs to update a number by doubling it. Instead of returning the new value, you want the original number to change directly when you call a function.
🎯 Goal: Build a C++ program that uses a function to double a number by passing the number by reference. This means the function will change the original number directly.
📋 What You'll Learn
Create an integer variable named num with the value 10.
Create a function named doubleValue that takes an integer parameter by reference.
Inside doubleValue, multiply the parameter by 2.
Call doubleValue with num as the argument.
Print the value of num after the function call.
💡 Why This Matters
🌍 Real World
Passing parameters by reference is useful when you want functions to modify data directly, such as updating settings, counters, or large data structures without copying them.
💼 Career
Understanding parameter passing is important for writing efficient and clear C++ code, which is a key skill in software development, game programming, and systems programming.
Progress0 / 4 steps
1
Create the initial variable
Create an integer variable called num and set it to 10.
C++
Need a hint?

Use int num = 10; to create the variable.

2
Create the function with reference parameter
Create a function named doubleValue that takes an int parameter by reference named value. Inside the function, multiply value by 2.
C++
Need a hint?

Use int& value to pass the parameter by reference.

3
Call the function with the variable
Inside main(), call the function doubleValue with the variable num as the argument.
C++
Need a hint?

Call the function by writing doubleValue(num); inside main().

4
Print the updated value
Add a std::cout statement inside main() to print the value of num after calling doubleValue. The output should be exactly 20.
C++
Need a hint?

Use std::cout << num << std::endl; to print the value.