What Is A Function - 043130
What Is A Function - 043130
A function is a block of code that performs a specific task. Functions allow you to:
In simple words:
A function takes some input (optional), does some work, and provides an output (optional).
1. Reusability: You can call a function multiple times instead of rewriting the same code.
3. Ease of debugging: Errors are easier to find and fix because the program is divided into smaller
parts.
cpp
CopyEdit
return_type function_name(parameters) {
return_type: The type of value the function gives back (e.g., int, float, void).
return: If the function produces a result, you return it using the return statement.
cpp
CopyEdit
#include <iostream>
int main() {
int x = 5, y = 10;
cout << "The sum is: " << result << endl; // Output the result
return 0;
Explanation:
int add(int a, int b): Takes two integers as input (a and b) and returns their sum.
cpp
CopyEdit
#include <iostream>
// Function definition
void printMessage() {
int main() {
printMessage();
return 0;
Explanation:
void printMessage(): The void keyword means this function doesn’t return anything.
cpp
CopyEdit
#include <iostream>
// Function definition
cout << "Hello, " << name << "!" << endl;
}
int main() {
string userName;
greet(userName);
return 0;
Explanation:
string name: The function takes a single input (name) of type string.
cpp
CopyEdit
#include <iostream>
// Function definition
}
int main() {
cout << "The product is: " << product << endl;
return 0;
Explanation:
The multiply function multiplies two integers and returns the result.
Types of Functions
1. Predefined Functions:
o These are built into C++ (e.g., cout, cin, sqrt, etc.).
2. User-Defined Functions:
o Functions you create for your own tasks (as shown above).
1. Functions must be declared before they are used. This can be done with a function prototype:
cpp
CopyEdit
cpp
CopyEdit