Functions in C++
Functions in C++ are reusable blocks of code designed to perform specific tasks.
They help in breaking a program into smaller, manageable, and reusable
components, improving modularity and code readability.
1. Syntax of a Function
General Syntax:
return_type function_name(parameter_list) {
// Function body
return value; // Optional for void functions
}
Example:
int add(int a, int b) {
return a + b;
}
2. Types of Functions in C++
2.1 Built-in Functions
Functions provided by C++ standard libraries (e.g., sqrt(), pow()).
Example:
#include <cmath>
cout << sqrt(16); // Output: 4
2.2 User-Defined Functions
Functions created by the programmer to perform specific tasks.
, Example:
void greet() {
cout << "Hello, World!";
}
3. Function Components
3.1 Return Type
Specifies the type of value the function returns. Use void if the function does not
return any value.
Example:
int square(int x) {
return x * x;
}
3.2 Function Name
The name used to call the function.
Example:
int calculate() {
return 42;
}
3.3 Parameters
Variables passed to a function to provide input.
Example:
void display(int age) {
cout << "Age: " << age;
}
Functions in C++ are reusable blocks of code designed to perform specific tasks.
They help in breaking a program into smaller, manageable, and reusable
components, improving modularity and code readability.
1. Syntax of a Function
General Syntax:
return_type function_name(parameter_list) {
// Function body
return value; // Optional for void functions
}
Example:
int add(int a, int b) {
return a + b;
}
2. Types of Functions in C++
2.1 Built-in Functions
Functions provided by C++ standard libraries (e.g., sqrt(), pow()).
Example:
#include <cmath>
cout << sqrt(16); // Output: 4
2.2 User-Defined Functions
Functions created by the programmer to perform specific tasks.
, Example:
void greet() {
cout << "Hello, World!";
}
3. Function Components
3.1 Return Type
Specifies the type of value the function returns. Use void if the function does not
return any value.
Example:
int square(int x) {
return x * x;
}
3.2 Function Name
The name used to call the function.
Example:
int calculate() {
return 42;
}
3.3 Parameters
Variables passed to a function to provide input.
Example:
void display(int age) {
cout << "Age: " << age;
}