Mark As Completed Discussion

Parameters and Arguments

When defining a function, you can specify one or more parameters. Parameters are like variables that are defined in the function's declaration and are used to pass values into the function. When calling a function, you can provide arguments which correspond to the parameters of the function.

Let's take a look at an example:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4// Function declaration
5int add(int a, int b);
6
7int main() {
8  int num1, num2, sum;
9
10  cout << "Enter first number: ";
11  cin >> num1;
12
13  cout << "Enter second number: ";
14  cin >> num2;
15
16  // Function call
17  sum = add(num1, num2);
18
19  // Print the sum
20  cout << "Sum: " << sum << endl;
21
22  return 0;
23}
24
25// Function definition
26int add(int a, int b) {
27  return a + b;
28}

In this example:

  • We declare a function add that takes two integer parameters a and b.
  • Inside the main function, we prompt the user to enter two numbers and store them in num1 and num2 respectively.
  • We then call the add function with the arguments num1 and num2 to calculate their sum.
  • Finally, we print the sum using the cout object.

You can run the above code to see it in action!

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment