Functions
Functions are reusable blocks of code that perform a specific task. They allow you to break down a complex program into smaller, manageable pieces. In C++, you can define your own functions to perform custom operations.
Here's an example of a function that adds two numbers:
1#include <iostream>
2using namespace std;
3
4int customAdd(int a, int b) {
5 return a + b;
6}
7
8int main() {
9 int num1 = 5;
10 int num2 = 7;
11 int sum = customAdd(num1, num2);
12
13 cout << "The sum of " << num1 << " and " << num2 << " is: " << sum << endl;
14
15 return 0;
16}
In this example, we define a function called customAdd
that takes two integer parameters a
and b
and returns their sum. In the main
function, we call customAdd
with the values num1
and num2
and store the result in a variable called sum
. The cout
statement then prints the result to the console.
By using functions, you can modularize your code and make it more organized and easier to understand. Functions can also accept parameters and return values, allowing for greater flexibility in your program.
Next, we'll dive deeper into the different aspects of functions and explore more advanced concepts.
xxxxxxxxxx
using namespace std;
int customAdd(int a, int b) {
return a + b;
}
int main() {
int num1 = 5;
int num2 = 7;
int sum = customAdd(num1, num2);
cout << "The sum of " << num1 << " and " << num2 << " is: " << sum << endl;
return 0;
}