Chapter 4 (Arrays and Functions)
Chapter 4 (Arrays and Functions)
Arrays
Like other programming languages, array in C++ is a group of similar
types of elements that have contiguous memory location.
o Random Access
Let's see a simple example of C++ array, where we are going to create,
initialize and traverse array.
#include <iostream>
using namespace std;
int main()
{
int arr[]={10, 0, 20, 0, 30}; //creating and initializing array
//traversing array
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}
Output:
10
0
20
0
30
Following is an example, which will use declaration, assignment and
accessing arrays :
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
int main () {
return 0;
}
This program makes use of setw() function to format the output. When
the above code is compiled and executed, it produces the following result
−
Element Value
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
C++ Array Example: Traversal using foreach loop
We can also traverse the array elements using foreach loop. It returns
array element one by one.
#include <iostream>
using namespace std;
int main()
{
int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
//traversing array
for (int i : arr)
{
cout<<i<<"\n";
}
}
Output:
10
20
30
40
50
Example:
float number[3][10]; // 3 x 10 matrix
This defines a matrix called number that contains 3 rows and 10 columns. Each of
the 30 (3 X 10) elements is a float type. The assignment
Example:
number[0][9] = 7.2; // Row 0, column 9
stores the value 7.2 in the last element of the first row.
Each of these elements is a float array with a size of 10, which in turn forms the
rows of the two-dimensional array, number.
This means that the same rules apply to multidimensional arrays as to one-
dimensional arrays. The initialization list of a two-dimensional array thus contains
the values of the array elements, that is, the one-dimensional rows.
These two definitions are equivalent. When you initialize an array, you
can only omit the size of the first dimension. It is necessary to define any
other dimensions since they define the size of array elements.
Let's see a simple example of multidimensional array in C++ which
declares, initializes and traverse two dimensional arrays.
#include <iostream>
using namespace std;
int main()
{
int test[3][3]; //declaration of 2D array
test[0][0]=5; //initialization
test[0][1]=10;
test[1][1]=15;
test[1][2]=20;
test[2][0]=30;
test[2][2]=10;
//traversal
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
cout<< test[i][j]<<" ";
}
cout<<"\n"; //new line at each row
}
return 0;
}
Output:
5 10 0
0 15 20
30 0 10
Let's see a simple example of multidimensional array which initializes
array at the time of declaration.
#include <iostream>
using namespace std;
int main()
{
int test[3][3] =
{
{2, 5, 5},
{4, 0, 3},
{9, 1, 8} }; //declaration and initialization
//traversal
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
cout<< test[i][j]<<" ";
}
cout<<"\n"; //new line at each row
}
return 0;
}
Output:"
255
403
918
return 0;
}
C++ Functions
As we know that functions play an important role in C or C++ program
development. Dividing a program into functions is one of the major
principles of top-down, structured programming. Another advantage of
using functions is that it is possible to reduce the size of a program by
calling and using them at different places in the program.
2) Code optimization
Suppose, you have to check 3 numbers (531, 883 and 781) whether it is
prime number or not. Without using function, you need to write the prime
number logic 3 times. So, there is repetition of code.
Function Declaration
Types of functions
Broadly functions are categorized into two category:
1. Library Functions: are the functions which are declared in the C++
header files such as ceil(x), cos(x), exp(x), etc.
Syntax:-
void Function_name (void)
{
// Function Body
}
A function that takes an argument and not returns any value that type
of function is take something and return nothing type
Syntax:-
void Function_name (Parameter)
{
// Function Body
}
A function that not take any argument and return any value that type of
function is take nothing and return something type
Syntax :-
Return_type Function_name (void)
{
// Function Body
}
A function that takes an argument and return any value that type of
function is take something and return something type
Syntax :-
Return_type Function_name (Parameter)
{
// Function Body
}
int main()———————–line 1
{
addition();———————–line 2
}
int main()———————–line 1
{
int a=10,b=20;———————–line 2
addition(a,b);———————–line 3
}
int main()———————–line 1
{
int c;———————–line 2
c=addition();———————–line 3
cout<<c;————————line 4
}
int main()———————–line 1
{
int a=10,b=20 , c ; ———————–line 2
c=addition(a,b); ———————–line 3
cout<<c;————————line 4
}
Let's see the simple example of C++ function using static variable.
#include <iostream>
using namespace std;
void func()
{
static int i=0; //static variable
int j=0; //local variable
i++;
j++;
cout<<"i=" << i<<" and j=" <<j<<endl;
}
int main()
{
func();
func();
func();
}
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
Call by value and call by reference in C++
There are two ways to pass value or data to function in C language: call
by value and call by reference. Original value is not modified in call by
value but it is modified in call by reference.
Let's understand call by value and call by reference in C++ language one
by one.
In call by value, value being passed to the function is locally stored by the
function parameter in stack memory location. If you change the value of
function parameter, it is changed for the current function only. It will not
change the value of variable inside the caller method such as main().
#include <iostream>
using namespace std;
void change(int data);
int main()
{
int data = 3; data =3 (23465#)
change(data);
cout << "Value of the data is: " << data<< endl;
return 0;
}
void change(int data) data = 8(56241#)
{
data += 5;
}
Output:
Here, address of the value is passed in the function, so actual and formal
arguments share the same address space. Hence, value changed inside the
function, is reflected inside as well as outside the function.
Note: To understand the call by reference, you must have the basic
knowledge of pointers.
#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
int swap;
swap=*x;
*x=*y;
*y=swap;
}
int main()
{
int x=500, y=100;
swap(&x, &y); // passing value to function
cout<<"Value of x is: "<<x<<endl;
cout<<"Value of y is: "<<y<<endl;
return 0;
}
Output:
2 Changes made inside the function Changes made inside the function
is not reflected on other functions is reflected outside the function
also
3 Actual and formal arguments will Actual and formal arguments will
be created in different memory be created in same memory
location location
Output:
o The values passed in the default arguments are not constant. These
values can be overwritten if the value is passed to the function. If
not, the previously declared value retains.
o During the calling of function, the values are copied from left to
right.
o All the values that will be given default value will be on the right.
Example
#include<iostream>
using namespace std;
int sum(int x, int y, int z=0, int w=0) // Here there are two values in t
he default arguments
{ // Both z and w are initialised to zero
return (x + y + z + w); // return sum of all parameter values
}
int main()
{
cout << sum(10, 15) << endl; // x = 10, y = 15, z = 0, w = 0
cout << sum(10, 15, 25) << endl; // x = 10, y = 15, z = 25, w = 0
cout << sum(10, 15, 25, 30) << endl; // x = 10, y = 15, z = 25, w =
30
return 0;
}
Output
25
50
80
In the above program, we have called the sum function three times.
o Sum(10,15)
When this function is called, it reaches the definition of the sum.
There it initializes x to 10 y to 15, and the rest values are zero by
default as no value is passed. And all the values after sum give 25
as output.
o Sum(10, 15, 25)
When this function is called, x remains 10, y remains 15, the third
parameter z that is passed is initialized to 25 instead of zero. And
the last value remains 0. The sum of x, y, z, w, is 50 which is
returned as output.
o Sum(10, 15, 25, 30)
In this function call, there are four parameter values passed into the
function with x as 10, y as 15, z is 25, and w as 30. All the values
are then summed up to give 80 as the output.
Note If the function is overloaded with different data types that also
contain the default arguments, it may result in an ambiguous match,
which results in an error.
#include<iostream>
using namespace std;
int sum(int x, int y, int z=0, int w=0) // Here there are two values in the
default arguments
{ // Both z and w are initialised to zero
return (x + y + z + w); // return sum of all parameter values
}
int sum(int x, int y, float z=0, float w=0) // Here sum is overloaded wit
h two float parameter values
{ // This results in ambiguity
return (x + y + z + w);
}
int main()
{
cout << sum(10, 15) << endl; // x = 10, y = 15, z = 0, w = 0
cout << sum(10, 15, 25) << endl; // x = 10, y = 15, z = 25, w = 0
cout << sum(10, 15, 25, 30) << endl; // x = 10, y = 15, z = 25, w = 30
return 0;
}
Output
Here when we call the sum function with all the parameters(x, y, z,
w) or either any one parameter value of z or w, the compiler gets
confused about which function to execute. Thus, it creates an ambiguity
which results in the error.
Function Overloading
You can have multiple definitions for the same function name in the same
scope. The definition of the function must differ from each other by the
types and/or the number of arguments in the argument list. You cannot
overload function declarations that differ only by return type.
Following is the example where same function print() is being used to
print different data types
#include <iostream>
using namespace std;
class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
int main(void) {
printData pd;
return 0;
}
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
Output:
Here is int 10
Here is float 10.1
Here is char* ten
When the compiler shows the ambiguity error, the compiler does not run
the program.
o Type Conversion.
o Function with default arguments.
o Function with pass by reference.
o
Type Conversion:
#include<iostream>
using namespace std;
void fun(int);
void fun(float);
void fun(int i)
{
std::cout << "Value of i is : " <<i<< std::endl;
}
void fun(float j)
{
std::cout << "Value of j is : " <<j<< std::endl;
}
int main()
{
fun(12);
fun(1.2);
return 0;
}
#include<iostream>
using namespace std;
void fun(int);
void fun(int,int);
void fun(int i)
{
std::cout << "Value of i is : " <<i<< std::endl;
}
void fun(int a,int b=9)
{
std::cout << "Value of a is : " <<a<< std::endl;
std::cout << "Value of b is : " <<b<< std::endl;
}
int main()
{
fun(12);
return 0;
}
The above example shows an error "call of overloaded 'fun(int)' is
ambiguous". The fun(int a, int b=9) can be called in two ways: first is by
calling the function with one argument, i.e., fun(12) and another way is
calling the function with two arguments, i.e., fun(4,5). The fun(int i)
function is invoked with one argument. Therefore, the compiler could
not be able to select among fun(int i) and fun(int a,int b=9).
Function with pass by reference
Inline Function
Inline function is one of the important feature of C++. So, let’s first
understand why inline functions are used and what is the purpose of
inline function?
When the program executes the function call instruction the CPU stores
the memory address of the instruction following the function call, copies
the arguments of the function on the stack and finally transfers control
to the specified function. The CPU then executes the function code,
stores the function return value in a predefined memory location/register
and returns control to the calling function. This can become overhead if
the execution time of function is less than the switching time from the
caller function to called function (callee). For functions that are large
and/or perform complex tasks, the overhead of the function call is usually
insignificant compared to the amount of time the function takes to run.
However, for small, commonly-used functions, the time needed to make
the function call is often a lot more than the time needed to actually
execute the function’s code. This overhead occurs for small functions
because execution time of small function is less than the switching time.
C++ provides an inline functions to reduce the function call overhead.
Inline function is a function that is expanded in line when it is called.
When the inline function is called whole code of the inline function gets
inserted or substituted at the point of inline function call. This
substitution is performed by the C++ compiler at compile time. Inline
function may increase efficiency if it is small.
#include <iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<add(2,3);A
return 0;
}