C++ Function with Parameters

A function with parameters in C++ is a function that accepts inputs (called parameters) when it is called. These parameters allow you to pass information into the function, which it can then use to perform its task.

Syntax:


return_type function_name(parameter1, parameter2, ...) {
    // Code using parameters
    return value; // if the function has a return type
}

Note: parameter1, parameter2, …: These are the inputs that you provide when calling the function.

Example:


#include <iostream>
using namespace std;

// Function that takes two parameters and returns their sum
int add(int a, int b) {
    return a + b;  // Adds the two numbers and returns the result
}

int main() {
    int result = add(10, 5);  // Call function with 10 and 5 as arguments
    cout << "The sum is: " << result << endl;  // Output the result
    return 0;
}

Explanation:

  • Function name: add
  • Parameters: int a and int b (the two numbers to add)
  • Return Type: int (since the function returns the sum of two integers)
  • Function call: add(10, 5): this passes 10 and 5 as arguments to the function.