C++ Function with Multiple Parameters
In C++, functions can have multiple parameters, allowing you to pass multiple pieces of data to a function when it is called. Each parameter is specified with a type and a name, and the values passed during the function call are assigned to these parameters.
Syntax
The syntax of a function that accepts multiple parameters is give below:
return_type function_name(parameter_type1 parameter_name1, parameter_type2 parameter_name2, ... ) {
// Function body
}
Explanation:
return_type
: Specifies the type of value the function returns. Use void
if the function does not return anything.
function_name
: The name of the function, following C++ naming conventions.
parameter_type1 parameter_name1
, parameter_type2 parameter_name2
: Specify the type and name of each parameter. Parameters are separated by commas.
Examples for Function with Multiple Parameters
Example 1: Calculating the Product of Two Numbers
In this example, we will define a function multiply
with two integer parameters.
#include <iostream>
using namespace std;
int multiply(int a, int b) {
return a * b;
}
int main() {
int result = multiply(10, 20);
cout << "The product is: " << result << endl;
return 0;
}
The product is: 200
Explanation: The multiply
function takes two parameters, a
and b
, and returns their product. The function is called in the main
function with arguments 10
and 20
.
Example 2: Displaying a Custom Message with a Count
In this example, we will define a function displayMessage
with a string parameter and an integer parameter.
#include <iostream>
using namespace std;
void displayMessage(string message, int count) {
for (int i = 0; i < count; i++) {
cout << message << endl;
}
}
int main() {
displayMessage("Welcome to C++ programming!", 3);
return 0;
}
Welcome to C++ programming!
Welcome to C++ programming!
Welcome to C++ programming!
Explanation: The displayMessage
function takes two parameters: a string
message
and an int
count
. It prints the message to the console the number of times specified by count
.