9 Functions
9 Functions
in C++
Function?
● Also known as procedure or subroutine in other programming
languages.
● A function is a group of statements that together perform a task.
● A function can be called many times.
● A function is a block of code that only runs when it is called.
Why do we need function?
● Reduce code redundancy.
○ If functionality is performed at multiple places in software, then rather than
writing the same code, again and again, it can create a function and call it
everywhere.
● Reusability
○ They can be executed many times, can call a function whenever it needs.
○ It can be executed in different parts of the program to display the line
repeatedly.
● Less Programming Time
○ A program may be made up of many functions, which are written as
independent programs.
○ Different programmers can work on different functions simultaneously,
which saves a lot of time in the long run.
Functions
Built-in
User-defined
Example:
void addition(){
int total = 0;
int x = 10;
int y = 20;
total = x + y;
Example:
int addition(){
int total = 0;
int x = 10;
int y = 20;
total = x + y;
return total;
}
With Parameter/s - No Return Type
Syntax:
void functionName (dataType parameter1,
dataType parameter2){
//function implementation
}
Example:
void addition(int x, int y){
int total = 0;
total = x + y;
Example:
int addition(int x, int y){
int total = 0;
total = x + y;
return total;
}
Calling the Function
Syntax:
variable= function_name(argument1, argument1, …, argumentN);
Prototyping a Function
● While writing a program, function cannot be used without specifying its type or
without telling the compiler about it.
● Therefore, before calling a function, it must be either declared or defined.
● Thus, declaring a function before calling a function is called function
declaration or prototype which tells the compiler that at some point of the
program we will use the function of the name specified in the prototype.
Syntax:
returnType functionName(dataType, dataType, … );
OR
returnType functionName(dataType parameter1, dataType parameter2, … );
Thank You !!!