0% found this document useful (0 votes)
22 views

Chapter 1

Uploaded by

Alhamdu 12
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Chapter 1

Uploaded by

Alhamdu 12
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 62

Chapter one

Function
Function

A function is a self contained block of codes or sub programs with a set


of statements that perform some specific task or coherent task when it is
called and each of which can be written more or less independently of the
others.

You can divide up your code into separate functions. How you divide up
your code among different functions is up to you, but logically the
division usually is so each function performs a specific task.
Cont…

Every C++ program has at least one function, which is main(), and all the
most trivial programs can define additional functions.

One of the best ways to tackle a problem is to start with the overall goal,
then divide this goal into several smaller tasks. You should never lose sight
of the overall goal, but think also of how individual pieces can fit together to
accomplish such a goal.

Function makes a program much easier to read, test and debug


Types of function
Built in function

Built in function are the function implicitly available in c++ programing language
to perform some common and standard tasks that includes the functions for file
access, mathematical computation, graphics, memory management etc.

Built in function can be accessed simply by including the relative header file using
#include directive and at point of function call by just writing the function name,
followed by an optional list of arguments.

Built in function are also known as library functions. We need not to declare and
define these functions as they are already written in the c++ libraries such as
iostream, cmath, time etc. we can directly call them when we need.
example

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
cout<<pow(2,5);
cout<<sqrt(9);
return 0;
}
#include <iostream>
example
#include <ctime>
using namespace std;
int main() {
// current date/time based on current system
time_t now = time(0);
// convert now to string form
char* dt = ctime(&now);
cout << "The local date and time is: " << dt << endl;
// convert now to tm struct for UTC
tm *gmtm = gmtime(&now);
dt = asctime(gmtm);
cout << "The UTC date and time is:"<< dt << endl;
}
User defined function
User defined function are custom function defined by user it self to perform as
custom task that is not available as built in, in this way user can define and
write subprogram as functions to perform a task relevant to their programs.
Function gives you way to warp up the set of statements to perform any a
specific task and give it a name, so that it can be invoked later from any where
in the program.
Cont…

 In the figure, we can see that main() calls a function named func1().
 Therefore, main() is known as the calling function and func1() is known
as the called function.
 The moment the compiler encounters a function call, the control jumps to
the statements that are a part of the called function.
 After the called function is executed, the control is returned to the calling
program.
Cont…
The main() function can call as many functions as it wants and as many
times as it wants.
For example, a function call placed within a for loop, while loop, or do–
while loop may call the same function multiple times till the condition
holds true.
Not only main(), any function can call any other function.
Function Declarations
A Function must be defined prior to use inside main() function,
otherwise this will show a compile time error as main() function is
unaware of this user-defined function, its argument list and the return
type.

 In c++, when you define a function before the main() function in your
program then it is not required to declare that function but if you are
going to provide function definition after the main() function, otherwise
this will give compilation error.
Function Declarations
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.

return_type function_name( parameter list );

e.g. int max(int num1, int num2);

Parameter names are not important in function declaration only their type is required, so
following is also valid declaration:

int max(int, int);

Function declaration is required when you define a function in one source file and you
call that function in another file. In such case you should declare the function at the top of
the file calling the function.
Function prototypes(function declaration)

To call a function it must have been declared in some earlier point of the code

An alternative way to avoid writing the whole code of a function before it can be used in
main or in some other function can be achieved by declaring just a prototype of the
function before it is used, instead of the entire definition. This declaration is shorter than
the entire definition, but significant enough for the compiler to determine its return type
and the types of its parameters.

Format: type name (argument_type1, argument_type2, ...);

The parameter enumeration does not need to include the identifiers, but only the type
specifiers. The inclusion of a name for each parameter as in the function definition is
optional in the prototype declaration.
Example:

int protofunction (int first, int second);

int protofunction (int, int);

It is identical to a function definition, except that it does not include the body
of the function itself.
Example:
void odd (int a) {
#include <iostream>
if ((a%2)!=0){
using namespace std;
cout << "Number is odd.\n";
void odd (int a);
}
int main () else
{ {
int i; cout << "Number is even.\n";
do { }
cout << "Type a number (0 to }
exit): ";
cin >> i;
odd (i);
} while (i!=0);
return 0;
Defining Function

In function definition full body of function is provided. All 0f the


statement that needs to be executed when function is invoked are written
here in function body, a function must be defined prior to use, you can
define a function as following:-

Syntax:- return_type function_name( parameter list )


{
//body of the function
}
Defining Function

A function definition in C++ programming language consists of a function header and a function
body.
Return Type: A function may return a value. The return_type is the data type of the value the
function returns.
Some functions perform the desired operations without returning a value. In this case, the
return_type is the keyword void.

Function Name: This is the actual name of the function. Function names are made up and
assigned by the programmer following the same rules that apply to naming variables. They can
contain up to 32 characters, they must begin with a letter, and they can consist of letters,
numbers, and the underscore (_) character. The function name and the parameter list together
constitute the function signature.

Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to
Cont…

The parameter list refers to the type, order, and number of the parameters of a function.

- Parameters are optional; that is, a function may contain or not parameters.

Function Body: The function body contains a collection of statements that define what
the function does.
Example:
Int add(int n1,int n2)
{
Int result;
Result=n1+n2;
Return result;
}
example
#include<iostream> cout<<result;
using namespace std; }
int max(int num1, int num2) }
{ int main()
int result; {
if (num1 > num2){ int x=5;
result = num1; int y=9;
cout<<result; max(x,y);
} }
else {
result = num2;
Calling a Function
While creating a C++ function, you give a definition of what the function has to do.
To use a function, you will have to call that function to perform the defined task.

When a program calls a function, program control is transferred to the called function.
A called function performs defined task, and when its return statement is executed or
when its function-ending closing brace is reached, it returns program control back to
the main program.

To call a function, you simply need to pass the required parameters along with
function name, and if function returns a value, then you can store returned value.

Syntax: function_name(argu1,argu2);
example
/* function declaration */
int max(int num1, int num2);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int result;
/* calling a function to get max value */
result = max(a, b);
cout<<“Max value is : “<< result ;
return 0;
}
Need of function

Dividing the program into separate well-defined functions facilitates each function to be

written and tested separately.

Understanding, coding, and testing multiple separate functions is easier than doing the

same for one big function.

When a big program is broken into comparatively smaller functions, then different

programmers working on that project can divide the workload by writing different

functions.

Like C/C++ libraries, programmers can also write their own functions and use them from

different points in the main program or any other program that needs its functionalities.
Cont…

Scope of variables
• All the variables that we intend to use in a program must have been declared with

its type specifier in an earlier point in the code.

• A variable can be either of global or local scope.

• A global variable is a variable declared in the source code, outside all functions,

while a local variable is one declared within the body of a function or a block.

• Global variables can be referred from anywhere in the code, even inside functions,

whenever it is after its declaration.

• The scope of local variables is limited to the block enclosed in braces ({}) where

they are declared.


Cont…
Example1 using global variable

#include <iostream>
using namespace std;
int g; // Global variable declaration:
int main ()
{
// Local variable declaration:
int a, b; // actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
} output: 30
example using of local variables
example using of local variables

#include<iostream>
using namespace std;

void func()
{
// this variable is local to the
// function func() and cannot be
// accessed outside this function
int age=18;
}

int main()
{
cout<<"Age is: "<<age;

return 0;
}
Cont…

Output:
Error: age was not declared in this scope

The above program displays an error saying “age was not declared in this scope”.
The variable age was declared within the function func() so it is local to that function
and not visible to portion of program outside this function. The function must be
called.
Example 2

#include<iostream>
using namespace std;

void func()
{
/* this variable is local to the
function func() and cannot be
accessed outside this function */

int age=18;
cout<<age;
}

int main()
{
cout<<"Age is: ";
func();

return 0;
}
Output: Age is: 18
Example using global variable
#include<iostream>
using namespace std;

// global variable
int num = 5;

// global variable accessed from


// within a function
void display()
{
cout<<num<<endl;
}

// main function
int main()
{
display();

// changing value of global


// variable from main function
Output:
num = 10;
display(); 5
} 10
Example
#include <iostream>
using namespace std;
void func1()
{
int x = 4;
cout << x << endl;
}
void func2()
{
int x = 5;
cout << x << endl;
}
int main()
{
func1();
func2();
return 0;
} output: 4
5
Example

#include <iostream>
using namespace std;
int multiply(int a, int b)
{
return a * b;
}
int main()
{
int x = 3, y = 5;
int z;
z = multiply( x, y );
cout << z << endl;
return 0;
} output: 15
Example

#include <iostream>
using namespace std;
int g;
int main()
{
int a = 4;
g = a * 2;
cout << g << endl;
return 0;
} output: 8
#include <iostream>
using namespace std;
int g = 10;
void func1()
{
g = 20;
cout << g << endl;
}
int main()
{
func1();
g = 30;
cout << g << endl;
return 0;
} output: 20
30
Example

#include<iostream>
using namespace std;

// global variable
int global = 5;

// main function
int main()
{
// local variable with same
// name as that of global variable

int global = 2;
cout << global << endl; output is 2
}
How to access a global variable when there is a local variable with same name?
- To solve this problem we will need to use the scope resolution operator.

#include<iostream>
using namespace std;

// Global x
int x = 0;

int main()
{
// Local x
int x = 10;
cout << "Value of global x is " << ::x;
cout<< "\nValue of local x is " << x; Output:
return 0; Value of global x is 0
Value of local x is 10
}
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of
the arguments. These variables are called the formal parameters of the function.

The formal parameters behave like other local variables inside the function and
are created upon entry into the function and destroyed upon exit. While calling a
function, there are two ways that arguments can be passed to a function:

 Function call by value

 Function call by reference


Function call by value

The call by value method of passing arguments to a function copies the actual
value of an argument into the formal parameter of the function. In this case,
changes made to the parameter inside the function have no effect on the argument.

By default, C++ programming language uses call by value method to pass


arguments. In general, this means that code within a function cannot alter the
arguments used to call the function. Consider the function swap() definition as
follows.
Example
#include<iostream> Cout<<“After swap, value of b :”<<y ;
using namespace std; }
// function definition to swap the values // function declaration
void swap(int x, int y) void swap(int x, int y);
int main ()
{ {
int temp; // local variable definition
temp = x; int a = 100;
//save the value of x int b = 200;
swap(a, b);
x = y; Cout<<“Before swap, value of a :”<< a ;
// put y into x Cout<<“Before swap, value of b :”<< b ;
y = temp; // calling a function to swap the values
// put x into y
return 0;
Cout<<“After swap, value of a :”<< x; }
Cont…

After swap, value of a : 200

After swap, value of b : 100

Before swap, value of a :100

Before swap, value of b :200

Thus actual values of a and b remain unchanged even after exchanging the values of x
and y.
Function call by reference
The call by reference method of passing arguments to a function copies the address of an
argument into the formal parameter. Inside the function, the address is used to access the
actual argument used in the call. This means that changes made to the parameter affect
the passed argument.

To pass the value by reference, argument pointers are passed to the functions just like
any other value. So accordingly you need to declare the function parameters as pointer
types as in the following function swap(), which exchanges the values of the two integer
variables pointed to by its arguments.
Cout<<“After swap, value of b :”<<*y ;
}
Example // function declaration
#include<iostream> void swap(int *x, int *y);
using namespace std; int main ()
{
// function definition // local variable definition
void swap(int *x, int *y) int a = 100;
{ int b = 200;
int temp; /* calling a function to swap the values.* &a
temp =*x; indicates pointer to a ie. address of variable a and *
//save the value of x &b indicates pointer to b ie. address of variable b.*/

*x = *y;
// put y into x swap(&a, &b);
*y = temp; Cout<<“Before swap, value of a :”<< a ;
Cout<<“Before swap, value of b :”<< b ;
// put x into y
Cout<<“After swap, value of a :”<< *x; return 0;
}
Cont…
After swap, value of a : 200

After swap, value of b : 100

Before swap, value of a : 200

Before swap, value of b : 100

Thus actual values of a and b get changed after exchanging values of


x and y.
Cont…
example //Function to add any two numbers
#include <iostream>
using namespace std;
int addition (int a, int b); //Function Declaration
int main ()
{
int z;
z = addition (5,3); //Function calling
cout << "The result is " << z;
return 0;
}
int addition (int a, int b) //Function Definition
{
int r;
r=a+b;
return (r);
}
Cont… example

#include <iostream> cout << "The first result is " << z << "\n";
using namespace std; cout << "The second result is " << subtraction (7,2) <<
int subtraction (int a, int b) "\n";
{ cout << "The third result is " << subtraction (x,y) << "\
int r; r = a-b; n";
return (r); z= 4 + subtraction (x,y);
}
cout << "The fourth result is " << z << "\n";
int main ()
return 0; }
{ int x=5, y=3, z;

z = subtraction (7,2);
OUTPUT
The first result is 5
The second result is 5
The third result is 2
The fourth result is 6
Default Values in Parameters

When declaring a function to specify a default value for each of the last
parameters. This value will be used if the corresponding argument is left
blank(empty) when calling to the function.

Use the assignment operator and a value for the arguments in the function
declaration to set default value. If a value for that parameter is not passed
when the function is called, the default value is used, but if a value is
specified this default value is ignored and the passed value is used instead.
#include <iostream>
using namespace std;
int divide (int a, int b=2)
{ int r;
r=a/b;
return (r);
}
OUTPUT:
int main (){ 6
cout << divide (12)<<endl; 5

cout << divide (20,4);


return 0;
}
Const Argument
 In C++ we can declare constant like the following

const datatype variable _name ;

 const is a reserved word and any variable declared with this keyword is can’t be modified.

 While trying to modify any constant argument the compiler gives syntax error which
detect that the argument is non-modifiable value.
eg
int Add (const int c)
{
c=c+3;// error
}
Overloaded Functions
Two different functions that have the same name but their parameter types or number
are different is said to be overloaded functions and this process is referred to as function
overloading.
For example:
#include <iostream>
using namespace std;
int operate (int a, int b)
{ return (a*b);
}
float operate (float a, float b)
{ return (a/b); }
int main () OUTPUT:
10
{ int x=5,y=2;
2.5
float n=5.0,m=2.0;
cout << operate (x,y)<< "\n";
The compiler knows which one to call in each case by examining the types passed as
arguments when the function is called. If it is called with two int’s as its arguments it
calls the function that has two int parameters in its prototype and if it is called with
two floats it will call to the one which has two float parameters in its prototype. So the
behavior of a call to operate depends on the type of the arguments passed because
the function has been overloaded.

Notice that a function cannot be overloaded only by its return type. At least one of its
parameters must have a different type
Recursive Functions

A function is said to be recursive if a statement in the body of the


function calls itself. It is useful for many tasks, like sorting or calculate
the factorial of numbers.
Example:
#include <iostream>
using namespace std;
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
else
return (1); }
int main ()
{
long number;
cout << "Please type a number: ";
cin >> number;
cout << number << "! = " << factorial (number);
return 0;
inline function

• If a function is inline, the compiler places a copy of the code of that function at each point
where the function is called at compile time.

• Any change to an inline function could require all clients of the function to be recompiled
because compiler would need to replace all the code once again otherwise it will continue
with old functionality.

• To inline a function, place the keyword inline before the function name and define the
function before any calls are made to the function. The compiler can ignore the inline
qualifier in case defined function is more than a line.
ex am p le

#include<iostream>
using namespace std;
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
// Main function for the program
int main() {
cout << "Max num is" << Max(20,10) << endl;
cout << "Max num is " << Max(0,200) << endl;
cout << "Max num is " << Max(100,1010) << endl;
return 0;
}
Storage classes
The storage class of a variable tells about which part of a program can access it
and also tells about its existence.

In C++ the storage classes are the following:


I. Automatic
II. Static
III. External
IV. Register
Automatic
A variable is defined within a function
Also known as local variable
A keyword auto is used to specify automatic variable but we can skip the word
auto also.
Cont…
The general syntax for automatic variable is :
auto datatype variable_name;

An automatic variable is created only when the function is called in which they
are defined and automatically destroyed when we return from the function.

The time period between the creation and destruction of a variable is called
lifetime.

The lifetime of automatic variable is the execution time of the function.

But if automatic variable is inside main() then that remains until main is
executing.
Cont…
 When we create automatic variable then the compiler does not initialize this. Thus it will
take an arbitrary value which maybe 0 or something else.

 But if we want to initialize we have to assign value for the variable.

Example: auto int num;

External

 External variables are also called global variables

 Defined outside of any function (i.e the variable defined in between the header of the
program and main).

 To declare external variable the keyword extern is used but we can skip.

extern datatype variable_name;


Cont…
External variable exists for the life of a program.

Takes memory space when the program begins and remain until the program ends.

If external variables are not initialized by the programmer then its initialized to 0
automatically when they are created.

Example: extern int num;

Static

A static variable has a scope of that of local variables but life time of external variables.

Initialized only once at the beginning, they are not reinitialized each time the function is
called. static datatype variable name;
Cont…
The following program demonstrates the difference between static and local variable.
void Func1(); void Func2()
void Func2();
{
int main()
{ static int m=1;
Func1();
Func1();
m++;
Func1(); cout<<“m=“<<m<<endl;
Func2();
Func2(); }
Func2();
Output
}
n=2
void Func1()
n=2
{
n=2
int n=1;
n++;
m=2
cout<<“n=“<<n<<endl
m=3
}
m=4
Cont…
The value of n is 2 in every call. Because n is automatic variable, this creates

when we call the function and destroy when we come back from the function.

In every execution the value of n is destroyed and n is created in the next calling .

But the value of m is initialized once at the first execution only.

Register

You can use the register storage class when you want to store local variables
within functions or blocks in CPU registers instead of RAM to have quick access
to these variables.
Cont…

Example: register int age;


The keyword register is used to declare a register storage class. The variables
declared using register storage class has lifespan throughout the program.
It is similar to the auto storage class. The variable is limited to the particular
block.
The only difference is that the variables declared using register storage class are
stored inside CPU registers instead of a memory. Register has faster access than
that of the main memory.
The size of the variable is depends on the size of register.
The variables declared using register storage class has no default value. These
variables are often declared at the beginning of a program
E N D
T h e

You might also like