What is function?
In C++, a function is a block of code that performs a specific task. It can
take inputs (called parameters), process them, and optionally return a
result. Functions help in organizing code, making it reusable and easier to
understand.
Syntax of function:
returnType functionName(parameter1Type parameter1, parameter2Type
parameter2,…) {
// Function body (code that performs a task)
return value;
}
What is function prototype?
A function prototype is like a "declaration" or "announcement" of the
function. It tells the compiler about the function's name, what inputs it takes
(parameters), and what it returns (return type) before the actual function is
defined. This allows you to use the function in your code even before its full
definition is written.
Syntax of Function Prototype:
returnType functionName(parameterType1, parameterType2, ...);
Example of function In C++
Why we are using functions?
1. Reusability:
If you need to perform the same task (like addition) multiple times in
your program, writing the same code over and over becomes tedious
and error-prone.
With a function, you write the logic once and reuse it wherever needed
2. Modularity:
Functions break your program into smaller, manageable pieces. Each
function performs a specific task, making your code easier to
understand and maintain.
For example, in a large program, you might have functions for addition,
subtraction, multiplication, etc. This makes the code organized.
3. Abstraction:
Functions hide the details of how a task is performed. For example,
when you call add(5, 3), you don't need to worry about how the
addition is done—you just know it works.
4. Testing and Debugging:
If a bug occurs in your program, it's easier to find and fix it if your code
is divided into functions. You can test each function individually to
ensure it works correctly.
5. Scalability:
As your program grows, functions make it easier to add new features
or modify existing ones without breaking the entire program