Functions in C++


A function is a set of statements that take input, perform specific calculations, and produce results.
The idea is to put repeated or repeated work together and do the job so that instead of writing the same code over and over again for different input, we can call it to work.
The most common method of operation is:

Return_type function_name ([arg1_type arg1_name, ...]) {code}

Example:

Below is a simple C / C ++ program to show the functions.

# include <iostream> using namespace std; int sum (int x, int y) { return(x+y); } int main () { int a= 10, b = 20; cout <<sum(a,b); return 0; }

OUTPUT:

string type

Why do we need functions?

Functions help us reduce coding. When work is done in multiple locations on software, instead of writing the same code repeatedly, we create a function and call it everywhere. This also helps to save as we have to change in one place when we make future changes in performance.
Functions turn the code into mode. Think of a large file with many rows of codes. It is much easier to read and use the code when broken down into tasks.
Functions provide output. For example, we can use library functions without worrying about internal functioning.