Functions
Functions divide a program into small, focused units. A function can receive parameters, perform work, and optionally return a value.
A Function Without a Return Value
Simple greeting function
#include <iostream>
using namespace std;
void greet()
{
cout << "Welcome to C++ programming." << endl;
}
int main()
{
greet();
return 0;
}Parameters and Return Values
Reusable add function
#include <iostream>
using namespace std;
int add(int a, int b)
{
return a + b;
}
int main()
{
int result = add(5, 3);
cout << "Sum = " << result << endl;
return 0;
}Pass by Value and Pass by Reference
Pass by value gives the function a copy. Pass by reference, written with &, allows the function to update the original variable.
Pass by reference
void applyDiscount(double& price)
{
price *= 0.90;
}Practice task
Write a function named calculateArea that receives width and height and returns the rectangle area.
Lesson Summary
Organise code into reusable functions with parameters and return values.