chapter-3(Functions)
chapter-3(Functions)
CHAPTER 3
Kukutla Alekhya
Objectives
Understand the concept and purpose of functions as reusable blocks of code that
perform specific tasks.
Demonstrate the ability to define and declare functions with appropriate function
signatures, including parameter lists and return types.
Understand the scope and lifetime of variables within functions, including local
variables and parameters.
Functions
Syntax :
Function defintion
return type function name(datatype parameter...)
{
//code to be executed
}
Syntax of function call
Functionname(parameters);
Function with no return type and no parameters
#include <iostream>
using namespace std;
void func()
{
cout<<”hello”<<endl;
}
int main()
{
func();
func();
func();
cout<<”the program has ended”;
}
Function with no return statement and with parameters
#include <iostream>
using namespace std;
void change(int data);
int main()
{
int data = 3;
change(data);
cout << "Value of the data is: " << data<< endl;
return 0;
}
void change(int data)
{
data = 5;
}
Value of the data is: 3
Recursion
#include<iostream>
using namespace std;
int main()
{
int factorial(int);
int fact,value;
cout<<"Enter any number: ";
cin>>value;
fact=factorial(value);
cout<<"Factorial of a number is: "<<fact<<endl;
return 0;
}
int factorial(int n)
{
if(n<0)
return(-1); /*Wrong value*/
if(n==0)
return(1); /*Terminating condition*/
else
{
return(n*factorial(n-1));
}
}
Output:
Enter any number: 5
Factorial of a number is: 120
Function with return statement and no parameters
#include <iostream>
using namespace std;
If make a function as inline, then the compiler replaces the function calling location with
the definition of the inline function at compile time.
Syntax for an inline function:
inline return_type function_name(parameters)
{
// function code
}
14