Function Parameters

So far, we've only created functions without input. Thanks to parameters, we can provide different inputs to a function and thus influence its behavior.

We specify parameters in parentheses after the function name during its definition and use them in the function body as normal variables. We must specify the data type for each parameter. For example:

void greet(std::string name) {
    std::cout << "Hello, " << name << std::endl;
}
    
greet("Charlie"); // Prints: Hello, Charlie
greet("John"); // Prints: Hello, John

This function has one parameter: name of type std::string. When we call the function using greet("Charlie"), we store the value "Charlie" in the parameter name, which we then print. Similarly for greet("John").

A function can have multiple parameters. Let's look at an example:

void multiply(int a, int b) {
    int result = a * b;
    std::cout << result << std::endl;
}

multiply(2, 3); // Prints: 6
multiply(5, 10); // Prints: 50

This code defines a function multiply with two parameters a and b of type int. The function calculates and prints their product. It's important to realize that the order in which we write parameters in the function definition is the same order we use when calling the function. Simply put, in multiply(2, 3), 2 is substituted for a and 3 is substituted for b.

Instructions

Create a function named sum that will have two parameters x and y of type int. The function will print the sum of these two arguments.

Call this function with parameter values 3 and 4.

Call the sum function again with parameter values 10 and 15.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

4/7

Function Parameters | Start Coder