Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

1.

Functions
1.1. Introduction
A function is a group of program statements that work together to perform a given task. Every C++
program has at least one function called main(), and all the most trivial programs can define
additional functions. Hence, instead of writing the whole code inside the main functions divide the
tasks in different blocks. We can divide up our code into separate functions as we want depending
on the problems as we solve. How we divide up our code among different functions is as we needed,
but logically the division usually is such that each function performs a specific task. For example
when our code includes to perform all arithmetic operations (+, -, *, /, and %) then we will divided
the whole code for addition, subtraction, multiplication, division and modulus functions instead of
writing the whole code inside main() function.

A function is also known with other names like a method, a sub-routine or a procedure. When we
use functions, we will get some advantages such as:

1) Code Re-usability

By creating functions in C++, we can call it many times. So, we don't need to write the same code
again and again.

2) Code optimization

It makes the code optimized; we don't need to write much code. Suppose, we have to check 3
numbers (531, 883 and 781) whether they are prime number or not. Without using function, we
need to write the prime number logic 3 times. So, there is repetition of code. But if you use
functions, you need to write the logic only once and you can reuse it several times as you prefer.

1.2. Types of Functions


There are two types of functions in C++:

1. Library Functions (Built-in Functions): are the functions which are declared in the C++ header
files such as pow(x,y), cos(x), exp(x), etc.

2. User-defined functions: are the functions which are created by the programmer, so that he/she
can use it many times. It reduces complexity of a big program and optimizes the code.

1.3. Function Components


To create a function, we have three Components: function declaration, function definitions and
function calling.

1
1.3.1. 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. A function declaration has the following parts:

return_type function_name(data_type parameter…);

A C++ function may return any type of data except an array. The parameter list is a comma-
separated list of variable names and their associated types that receive the values of the arguments
when the function is called. A function may be without parameters, in that case the parameter list
is empty. However, even if there are no parameters, the parentheses are still required.

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. They behave like other local
variables inside the function and are created upon entry into the function and destroyed upon exit.

As shown in the following function, the parameter declarations (i.e., string firstName) occur after
the function name:
string myFunc(string firstName);

For examples, when we declare add() functions, which adds two numbers x and y, the following is
the function declaration.
int add(int x, int y);

Whereas: int, the return types which means the function returns an integer,

add is the name of the function,

int x and int y inside open and close parenthesis is the arguments or parameters of the function
add(). And also, the name x and y are the parameter names both are integer.

Note: Parameter names are not important in function declaration only their type is required, so
following is also valid declaration.
int add(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.

1.3.2. Function Definition

The general form of a C++ function definition is as follows


return_type function_name(parameter list ) {

//body of the function

}
2
A C++ function definition consists of a function header and a function body. Here are all the parts of
a function

• 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. 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 the parameter. This value is referred to as actual parameter or argument. 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 no parameters.

• Function Body − The function body contains a collection of statements that define what the
function does.

1.3.3. Calling Function (Function Invocation)

When a program calls a function, the program control is transferred to the called function. A called
function performs a defined task and when its return statement is executed or when its function
ending closing brace is reached, it returns the program control back to the main calling program. As
shown in the following syntax during calling the function, use only function name and values we
need to pass.
funcName(parameter values);

The C++ standard library provides numerous built-in functions that our program can call. For
example, function strcat() to concatenate two strings, function memcpy() to copy one memory
location to another location, function pow(x,y) to perform the x rise of y, and many more.

To call a function, we need to pass the required parameters along with the function name, and if
the function returns a value, then we can store the returned value. For example:
int addNum(int, int){
int sum = 0;
sum = x+y; return
sum;
}
main(){
int result= sum(4,8);//calling into sum()function
cout<<”sum = ”<<result;
}
In the above code, the function calling (sum(4,8))is inside the main functions and passes two
values to assign parameters x and y. Here, 4 are passed and assigned for x and 8 assigned for y. And

3
also, the function return an integer value after performing addition of the two numbers passed from
the main() function.

1.4. Scope of Variables in C++


In general, scope is defined as the extent up to which something can be worked with. In
programming also scope of a variable is defined as the extent of the program code within which the
variable can we accessed or declared or worked with. Since, the scope rules of a language are the
rules that govern whether a piece of code knows about or has access to another piece of code or
data. Each function is a discrete block of code.

A function's code is private to that function and cannot be accessed by any statement in any other
function except through a call to that function. Each function is a discrete block of code. The code
that constitutes the body of a function is hidden from the rest of the program and, unless it uses
global variables or data, it can neither affect nor be affected by other parts of the program. Stated
another way, the code and data that are defined within one function cannot interact with the code
or data defined in another function because the two functions have a different scope.

There are mainly two types of variable scopes (local and global) as discussed below:

1.4.1. Local Variables

Variables that are defined within a function are called local variables. A local variable comes into
existence when the function is entered and is destroyed upon exit. That is, local variables cannot
hold their value between function calls. The only exception to this rule is when the variable is
declared with the static storage class specifier. This causes the compiler to treat the variable as if it
were a global variable for storage purposes, but limits its scope to within the function.

Variables defined within a function or block are said to be local to those functions.

• Anything between ‘{‘and ‘}’ is said to inside a block.

• Local variables do not exist outside the block in which they are declared, i.e., they cannot be
accessed or used outside that block.

• Declaring local variables: Local variables are declared inside a block.

For examples, we declare x and y variables inside main function and declare sum variables inside
myFunc() function names as the following:
main(){
int x;//local variables inside main functions
int y;//local variable y with integer data types
}
void myFunc(){
int sum;//local variables inside myFunc() names
}
4
let us see another example;

#include<iostream>
using namespace std;
void myFunc(){
int sum;//local variables inside myFunc() names
}
main(){
int x = 10;//local variables inside main function int
y = 20; //local variable y with integer data type
sum = x + y; /*sum variable is local to myFunc() and cannot be
accessed outside this function */
cout<<”Sum = ”<<sum<<endl;
}
The above program displays an error saying “sum was not declared in this scope”. The variable sum
was declared within the function myFunc() so that it is local to that function and not visible to portion
of program outside this function.

1.4.2. Global Variable

In the program, the variable “global” is declared at the top of the program outside all of the
functions. So, it is a global variable and can be accessed or updated from anywhere in the program.
The global variables are declared outside any functions even outside the main function but we can
be accessed inside any functions including main function.

As the name suggests, Global Variables can be accessed from any part of the program.

• They are available throughout the life time of a program.

• They are declared at the top of the program outside all of the functions or blocks.

• Declaring global variables: Global variables are usually declared outside of all of the
functions and blocks, at the top of the program. They can be accessed from any portion of
the program.

#include<iostream>
using namespace std;
int age = 28; //global variables string
name = ”John”; //global variables
main(){
//body of main functions
}
In the above code we have a variable age with the integer type and name with string type global
variables. Hence, we can alter the name and age in any block of functions.

5
Unary Scope Resolution Operator ::

The :: (scope resolution) operator is used to access a global variable when there is a local variable
with same name. You can use the unary scope operator if a namespace scope or global scope name
is hidden by an explicit declaration of the same name in a block or class.

For example:

#include <iostream>
using namespace std;
int my_var = 0;

int main(void) {
int my_var = 0;
::my_var = 1; // set global my_var to 1
my_var = 2; // set local my_var to 2
cout << ::my_var << ", " << my_var;
return 0;
}

1.5. Passing Arguments


In a computer language, there are two ways that arguments can be passed to a subroutine: call by
value and call by reference. Original value is not modified in call by value but it is modified in call by
reference.

The first is known as call by value. This method copies the value of an argument into the formal
parameter of the subroutine. In this case, changes made to the parameter have no effect on the
6
argument. In call by value, value being passed to the function is locally stored by the function
parameter in stack memory location. If we 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().
void swap(int x, int y){
int temp;
Output:
temp = x;
x = 10 and y = 20
x = y;
y = temp;
}
int main(){
int x = 10, y = 20;
swap(x, y);
cout<<"x = "<<x<<" and y = "<<y<<endl;
return 0;
}
In the above program, the value of the argument to swap( ), 10, is copied into the parameter x and
20 is copied into the parameter y. When the swap of x and y are takes place, only the local variables
of x and y are modified. Remember that it is a copy of the value of the argument that is passed into
the function. What occurs inside the function has no effect on the variable used in the call. Hence,
the values of x and y didn’t change the actual values after passing into the function swap() because
of the it passed the copies not the actual values.

The second way of passing arguments is Call by reference. In this method, the address of an
argument is copied into the parameter. Inside the subroutine, the address is used to access the
actual argument used in the call. This means that changes made to the parameter affect the
argument.

Even though C++ uses call by value for passing parameters, we can create a call by reference by
passing a pointer to an argument, instead of the argument itself. Since the address of the argument
is passed to the function, code within the function can change the value of the argument outside
the function.

Pointers are passed to functions just like any other value. Of course, you need to declare the
parameters as pointer types. For example, the function swap(), which exchanges the values of the
two integer variables pointed to by its arguments. In the following code, the address of the value is
passed in the swap() function, so actual and formal arguments share the same address space. Hence,
value changed inside the swap(() 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, which
will be covered in chapter 3.

7
void swap(int *x, int *y){
int temp;
Output
temp = *x;
x = 20 and y = 10
*x = *y;
*y = temp;
}
int main(){
int x = 10, y = 20;
swap(&x, &y);//passing address value to swap()function
cout<<"x = "<<x<<" and y = "<<y<<endl;
return 0;
}

Int the above code, the actual values are passed into the function swap() and the function can alter
the actual values of x and y that found inside main() function. swap() is able to exchange the values
of the two variables pointed to by x and y because their addresses (not their values) are passed.
Thus, within the function, the contents of the variables can be accessed using standard pointer
operations, and the contents of the variables used to call the function are swapped.

Remember that swap() (or any other function that uses pointer parameters) must be called with the
addresses of the arguments.

The following tables illustrate about the difference between call bay values and call bay reference

Call by value Call by reference

A copy of the value is passed into the function An address of value is passed into the function

Changes made inside the function is limited to Changes made inside the function validate
the function only. The values of the actual outside of the function also. The values of the
parameters do not change by changing the actual parameters do change by changing the
formal parameters. formal parameters.

Actual and formal arguments are created at Actual and formal arguments are created at the
the different memory location same memory location

Table 1. Difference between call by reference and call by value.

1.5. Return Values


All functions, except those of type void, return a value. This value is specified by the return
statement. In C, if a non-void function does not explicitly return a value via a return statement, then
a garbage value is returned. In C++, a non-void function must contain a return statement that
returns a value. That is, in C++, if a function is specified as returning a value, any return statement

8
within it must have a value associated with it. However, if execution reaches the end of a non-void
function, then a garbage value is returned. Although this condition is not a syntax error, it is still a
fundamental error and should be avoided.

The general form of the return statement is:


return expression;

The expression is present only if the function is declared as returning a value. In this case, the value
of expression will become the return value of the function. We can use as many return statements
as we like within a function. However, the function will stop executing as soon as it encounters the
first return. The } that ends a function also causes the function to return. It is the same as a return
without any specified value. If this occurs within a non-void function, then the return value of the
function is undefined.
string myName(){
string name=”Ahmed”;
return name;//returning a string type
}
In the above code the first string is a returning type which means during function call it determines
the data types of the values. Since, the last line before} the name variables hold string values. Hence,
instead of string we can return any types of data like int, float, double, … as we need.

Returning values has two important uses. First, it causes an immediate exit from the function that
it is in. That is, it causes program execution to return to the calling code. Second, it may be used to
return a value. This section examines how the return statement is used.

When we write programs, our functions generally will be of three types. The first type is simply
computational. These functions are specifically designed to perform operations on their arguments
and return a value based on that operation. A computational function is a "pure" function. Examples
are the standard library functions sqrt( ) and sin( ), which compute the square root and sine of their
arguments.
#include<math.h>
main(){
int num;
cout<<”Enter any number:”;
cin>>num;
cout<<”Square root = ”<<sqrt(num);
cout<<”Sine = ”<<sin(num)<<endl;
}
In the above code, the sqrt() function return the square root of any numbers as you entered from
the keyboard. And also, the sin() function also return the sine value of the value num arguments.
Both the sqrt() and sin() functions takes only one arguments and returns a double type values.

9
The second type of function manipulates information and returns a value that simply indicates the
success or failure of that manipulation. An example is the library function fclose(), which is used to
close a file. If the close operation is successful, the function returns 0; if the operation is
unsuccessful, it returns EOF.

The last type of function has no explicit return value. In essence, the function is strictly procedural
and produces no value. An example is exit( ), which terminates a program. All functions that do not
return values should be declared as returning type void. By declaring a function as void, you keep it
from being used in an expression, thus preventing accidental misuse.

The main( ) function returns an integer to the calling process, which is generally the operating
system. Returning a value from main( ) is the equivalent of calling exit( ) with the same value. If
main( ) does not explicitly return a value, the value passed to the calling process is technically
undefined. In practice, most C++ compilers automatically return 0, but do not rely on this if
portability is a concern.

1.6. Default Parameters


A default argument is a value provided in a function declaration that is automatically assigned by
the compiler if the caller of the function doesn’t provide a value for the argument with a default
value. The idea behind default argument is simple. If a function is called by passing argument/s,
those arguments are used by the function. But if the argument/s are not passed while invoking a
function then, the default values are used. The syntax for default parameter is as follows:
return_type function_name(parameter_lists, default_parameters)
{
//function body
}
The following simple C++ example demonstrate the use of default arguments. We don’t have to
write two sum functions, only one function works by using default values for 3 rd arguments.

int sum(int x, int y, int z=0)


{
return (x + y + z);
}
int main()
{
cout << sum(10, 15, 25) << endl;
cout << sum(10, 20) << endl;
return 0;
}
Note the following default arguments key points:

• Default arguments are different from constant arguments as constant arguments can't be
changed whereas default arguments can be overwritten if required.
10
• Default arguments are overwritten when calling function provides values for them. For
example, calling of function sum(10, 15, 25) overwrites the value of z to 25.

• During calling of function, arguments from calling function to called function are copied
from left to right. Therefore, sum(10, 15, 25) will assign 10, 15 and 25 to x, y, and z.

• In the second calling function, sum (10, 20), the default value of z will be used.

• Once default value is used for an argument in function definition, all subsequent arguments
to it must have default value. It can also be stated as default arguments are assigned from
right to left. For example, the following function definition is invalid as subsequent
argument of default variable z is not default.
int sum(int x,int y=20,int z){} //error

The above code will not compile as well because we must provide the default arguments for z
after the default parameters y which means the y arguments comes after z parameters or the z
parameter should assign as default arguments.

Note: If you want a single default argument, make sure the argument is the last one.

1.7. Inline Function


The inline functions are a C++ enhancement feature to increase the execution time of a program.
Functions can be instructed to compiler to make them inline so that compiler can replace those
function definition wherever those are being called. Compiler replaces the definition of inline
functions at compile time instead of referring function definition at runtime.

NOTE- This is just a suggestion to compiler to make the function inline, if function is big (in term of
executable instruction etc.) then, compiler can ignore the “inline” request and treat the function as
normal function.

C++ programming inline function syntax as follows:


inline return_type function_name(arguments_list);

To inline a function, place the keyword inline before the function name and define the function
before any calls are made to the function. Let us perform the maximum of two numbers using inline
function.
using namespace std;
inline int Max(int x, int y) {
int max = (x>y)? x : y;
return max;
}
int main() {
int num1,num2;

11
cout<<”Enter two numbers:”;
cin>>num1>>num2;
cout<<"Max(“<<num1<<”,”<<num2<<”)="<<Max(num1,num2)<<endl;
return 0;
}
1.8. Recursive Functions
When function is called within the same function, it is known as recursion function. The function
which calls the same function, is known as recursive function. A function that calls itself, and doesn't
perform any task after function call, is known as tail recursion. In tail recursion, we generally call the
same function with return statement.
recursionfunction(){

recursionfunction(); //calling self function

In the above example, the function recursionfunction() call itself.

int factorial(int); //function prototype


int main(){
int fact,num;
cout<<"Enter any number: ";
cin>>num;
fact = factorial(num); Output
cout<<num<<” != "<<fact<<endl;
Enter any number: 4
return 0;
4! = 24
}
int factorial(int n) {
if(n<0)
return(-1); /*Wrong value*/
if(n==0)
return(1); /*Terminating condition*/
else
return(n*factorial(n-1));
}
We can perform factorial problems without recursion functions as follows;
int main() {
int i,fact=1, number;
cout<<"Enter any Number: "; Output
cin>>number; Enter any number: 6
for(i=1;i<=number;i++){ 6!=720
fact=fact*i;
}
cout<<number<<"!= "<<fact<<endl;
12
return 0;
}
Let us see another example to perform Fibonacci Series which, next number is the sum of previous
two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc. The first two numbers of fibonacci
series are 0 and 1. first let us do without recursion by using for loop as follows:
int main() {
int num1=0,num2=1,num3,i,number;
cout<<"How many elements do u have: ";
cin>>number;
cout<<num1<<" "<<num2<<" "; //printing 0 and 1
for(i=2;i<number;++i){ //loop starts from 2
num3=num1+num2; Output
cout<<num3<<" "; How many elements do u have: 8
n1=n2; n2=n3; 0 1 1 2 3 5 8 13
}
return 0;
}
And, the above code using recursion function is as follows:
void printFibonacci(int n){
static int n1=0, n2=1, n3;
if(n > 0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
cout<<n3<<" ";
printFibonacci(n-1); Output
} How many elements do u have: 8
} 0 1 1 2 3 5 8 13
int main(){
int n;
cout<<"Enter the number of elements: ";
cin>>n;
cout<<"Fibonacci Series: ";
cout<<"0 "<<"1 ";
printFibonacci(n-2); //n-2 because 2 numbers are printed
return 0;
}

13
2. Array and String

2.1. Array Introduction

Like other programming languages, array in C++ is a group of similar types of elements that have
contiguous memory location. In computer memory, array elements are stored in a sequence of
adjacent memory blocks. Since all the elements of an array are of same data type, the memory
blocks allocated to elements of an array are also of same size. Each element of an array occupies
one block of memory. The size of memory blocks allocated depends on the data type and it is
same as for different data types.

Arrays are set of elements having same data type or we can say that Arrays are collection of
elements having same name and same data type. But always remember Arrays are always start
from its index value and the index of array is start from 0 to n-1. The lowest address corresponds
to the first element and the highest address to the last element. The following picture shows the
values of array and their index in a memory stuck.

Note: An array cannot have a mixture of different data types as its elements.

Arrays may have from one to several dimensions. So, there are two types of arrays in C++
programming language.

1. Single dimensional array


2. Multi-dimensional array

2.1.1. One Dimensional Array

In a single (one) dimensional array use single angle bracket “[ ]” which is used for dimensional or
the subscript of the array that is generally used for declaring the elements of the array. The
general form for declaring a single-dimension array is:
data_type array_name[array_size];

Like other variables, arrays must be explicitly declared so that the compiler may allocate space
for them in memory. Here, type declares the base type of the array, which is the type of each

14
element in the array, and size defines how many elements the array will hold. For example, to
declare a 10-element array called number of type integer, use the following statement:
int number[10];//declaring integer types of array with 10 array
size

For Accessing the Element from the array by using the index of array values inside the angle
bracket the Subscript of the Array like this
int number[2]=10;//assign 10 to the array at index 2

The above block code will set the value of 3rd element of array. So, there is only a single bracket
then it called the Single Dimensional Array. And also, we can initialize multiple values in array
during declaration but the number of elements should be less or equal to the size of an array.
We can skip the size of an array when we initialize an array during declaration as follows:
string studentd[]={“Abebe”,”Chala”,”Hagos”} //creating and

initialize array of student

The following example sets 10 elements of array values and displays them by using for loop as
follows:
main(){
int arrayNum[10];//array declaration
cout<<”enter all array values”<<endl;
// set value to array by using for loop for each index
for(int i=0;i<10;i++){
cin>>arrayNum[i];
}
//to display all element of the array values
for(int i=0;i<sizeof(arrayNum);i++){
cout<<arrayNum[i]; //access the value of elements
}
}
In the above code the array arrayNum can occupied 10 elements of integer values at shown line
2. And set the values by using their index at shown line 6. Then the index is starting from 0 upto
size-1 (sizeof(arrayNum) which returns the size of an array at line 9 inside for loop in the second
arguments). The last statement in the above block code is for access the value of array elements
by using their index.

15
2.1.2. Multi-dimensional Array

The multidimensional array is also known as rectangular arrays in C++. It can be two dimensional
or three dimensional. In simple words multi-dimensional array means array of array. The data is
stored in tabular form (row column) which is also known as matrix.

Here is the general form of a multidimensional array declaration is:


data_type array_name[size-1][size-2]….[size-n];

For example, the following array declare a two-dimensional integer array:


int matrix[5][4];

In the above integer array matrix we create a 5 by 4 matrix which means the matrix that have 5
rows and 4 columns.

Another example, the following declaration creates a three-dimensional string array:


string matrix[3][6][2];

A) 2D Array

The simplest form of multidimensional array is the two-dimensional array. A two-dimensional


array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array
of size [x][y], you would write something as follows:

type arryName[x][y];

Where type can be any valid data type and arrayName will be a valid identifier. A two-
dimensional array can be considered as a table which will have x number of rows and y number
of columns. A two-dimensional array a, which contains three rows and four columns can be
shown as follows:

Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where
'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify each element
in 'a'.

16
Multidimensional arrays may be initialized by specifying bracketed values for each row. Following
is an array with 3 rows and each row has 4 columns. To initialized two-dimensional array as
follows:
int matrix[3][4]={{1,2,3,4},{4,7,9,4},{4,7,9,0}}; or

int matrix[][4]={{1,2,3,4},{4,7,9,4},{4,7,9,0}}; or

int matrix[3][4]={1,2,3,4,4,7,9,4,4,7,9,0};

As shown in the above block of code, we can eliminate the first array size like matrix[][4]
but not declare as matrix[3][] or matrix[][]. And also, the inner brace is optional
we can note used for initialization as the last block of code.

The following code get the values of two-dimensional arrays and traverse to the values
main(){
int matrix[4][3]; //2D array declaration
cout<<”enter all array values”<<endl;
//the elements of rows
for(int i=0;i<4;i++){
//the elements of columns
for(int j=0;j<3;j++){
cin>>matrix[i][j]; //set the values for each index
}
//to display all element of the array values
for(int i=0;i<4;i++){ for(int j=0;j<3;j++){
cout<<matrix[i][j]; //access the value of elements
}
}
In the above code, the outer loop iterates the same as the size of the rows and the inner loop
iterates as the number of elements in the columns. To output all the elements of a Two-
Dimensional array we can use nested for loops. We will require two for loops. One to traverse
the rows and another to traverse columns. Hence, the total size of array matrix is
rows*columns(4*3=12) or the total elements.

B) Three Dimensional Arrays

In three-dimensional arrays, adding one additional array on two-dimensional arrays which means
it is the list of two-dimensional arrays as shown in the following figure. As shown in the figure we
have three two-dimensional array that represent Array 1, Array 2 and Array 3.

17
To declare a two-dimensional integer array of size [x][y], you would write something as follows:

Initializing Three-Dimensional Array: Initialization in Three-Dimensional array is same as that of


Two-dimensional arrays. The difference is as the number of dimensions increases so the number
of nested braces will also increase.

Method 1:
int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11, 12,
13, 14, 15, 16, 17, 18, 19,20, 21, 22, 23};

Better Method:
int x[2][3][4] =
{
{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },
{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
};
Accessing elements in Three-Dimensional Arrays: Accessing elements in Three-Dimensional
Arrays is also similar to that of Two-Dimensional Arrays. The difference is we have to use three
loops instead of two loops for one additional dimension in Three-dimensional Arrays.
int main()
{
// initializing the 3-dimensional array
int x[2][3][2] = {
{ {0,1}, {2,3}, {4,5} },
{ {6,7}, {8,9}, {10,11} }
};
// traverse to each element's value for
(int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 2; ++k) {

18
cout << "Element at x[" << i << "][" << j << "]["
<< k << "] = " << x[i][j][k]<< endl;
}
}
}
return 0;
}

2.2. C++ Passing Array to Function


Arrays can be passed to a function as an argument. As shown below figures the values of an
arrays can pass into one or many functions in the programs like other times of arguments.

When to pass a single-dimension array as an argument in a function, we have to declare function


formal parameter in one of following three ways and all three declaration methods produce
similar results because each tells the compiler that an integer pointer is going to be received.
return_type function_name(data_type *parameter_name);

In the above way, the prototype of a function should have the return type(like int, float double
or void which the determines the types of return values. Any name we can give to the function
as a name and as arguments use any pointer which have any type and name to accepted an array
value from the caller.

And the second way is as follows:


return_type function_name(data_type parameter_name[size]);

In the above declaration, used the any array name with a fixed size of an array as arguments and
accepts any array from caller.

And the third way is to pass an array to a function in c++ programming,


return_type function_name(data_type parameter_name[]);

19
Here, we can skip to set array size in function parameters/arguments. Now, consider the
following function, which will take an array as an argument along with another argument and
based on the passed arguments, it will return student’s mark passed through the array as follows:
void display(int marks[5]);
int main(){
int marks[5] = {88, 76, 90, 61, 69};
display(marks);
return 0;
}
void display(int m[5]){
cout << "Displaying marks: "<< endl;
for (int i = 0; i < 5; ++i){
cout << "Student "<< i + 1 <<": "<< m[i] << endl;
}
}
When an array is passed as an argument to a function, only the name of an array is used as
argument.
display[marks];

Also notice the difference while passing array as an argument rather than a variable.
void display(int m[5]);

The argument marks in the above code represents the memory address of first element of array
marks[5].

And the formal argument int m[5] in function declaration converts to int* m;. This pointer
points to the same address pointed by the array marks.

That's the reason, although the function is manipulated in the user-defined function with
different array name m[5], the original array marks is manipulated.

The following example is demonstrates passing multi-dimensional array to functions.


Multidimensional array can be passed in similar way as one-dimensional array. Consider this
example to pass two-dimensional array to a function:
void display(int n[3][2]);
int main()
{
int num[3][2] = {
{3, 4},

20
{9, 5},
{7, 1}
};
display(num);
return 0;
}
void display(int n[3][2]) {
cout << "Displaying Values: " << endl;
for(int i = 0; i < 3; ++i) {
for(int j = 0; j < 2; ++j) {
cout << n[i][j] << " ";
}
}
}
In the above program, the multi-dimensional array num is passed to the function display().
Inside, display() function, the array n (num) is traversed using a nested for loop. The
program uses two for loop to iterate over the elements inside a 2-dimensional array. If it were a
3dimensional array, you should use 3 for loops. Finally, all elements are printed onto the screen.

Note: Multidimensional array with dimension more than 2 can be passed in similar way as two-
dimensional array.

2.3. Strings
C++ string class internally uses char array to store character but all memory management,
allocation, and null termination is handled by string class itself that is why it is easy to use. The
length of the C++ string can be changed at runtime because of dynamic allocation of memory. As
string class is a container class, we can iterate over all its characters using an iterator similar to
other containers like vector, set and maps, but generally, we use a simple for loop for iterating
over the characters and index them using [] operator.

The first way of defining c++ string by using char arrays is as follows:
char myName[]=”Aster Awoke”;

The variable name myName is an array of char type and holds “Aster Awoke” collection of
characters. And in the array name we can set array size which is the size of characters plus one
(for null character.
char myName[12]=”Aster Awoke”;

In the above block code, the myName array variable holds 10 charters, 1 space and the null
character \0 is added to the end of the string automatically so totally we have 12 that why we
21
have set array size 12. And also, we can declare and assign in another way as follows the above
code:
char myName[12]={‘A’,’s’,’t’,’e’,’r’,’ ‘,’A’,’w’,’o’,’k’,’e’,’\0’};

Or

char myName[]={‘A’,’s’,’t’,’e’,’r’,’ ‘,’A’,’w’,’o’,’k’,’e’,’\0’};

The above to block codes are holds sequences of characters and can traverse by using their index
to display on the screen. The following examples demonstrate to get input from users and
displays them.
#include <iostream>
using namespace std;
int main()
{
char fname[50];
char lname[40];
cout << "what your First name: ";
cin >> fname;
cout << "First name: " << fname << endl;
cout << "Last name: ";
cin >> lname;
cout << "last Name: "<<lname<<endl;
return 0;
}
In the above program, we have two char arrays fname and lname which can hold up to 50 and
30 characters respectively. But we can hold less characters for the size. To displays simply use
the name of char variables like fname and lname.

However, we have another recommended way of creating a string by using string objects. To
declare string use string as data_type to hold a sequence of characters. And it stored texts instead
of a single character.
string var_name=”sequence of character”;
To use strings, must include an additional header file in the source code, the <string> library:
#include<iostream>
#include<string> //include a string library
And also,A string variable contains a collection of characters surrounded by double quotes:
string myName=”Aster Awoke”;

22
In the above code, creating a string variable name myName and assign a value Aster awoke
to the created string variable. Since, to display the variable values simply by using cout c++
outstream objects as follows:
cout<<”Muscian name:”<<myName;

For string objects,we can get any texts/strings from users/keyboard and can be displays on the
screen as follows:
#include<iostream>
#include<string>
using namespace std;
main(){
string name="Aster Awoke";
cout<<name<<endl;
cout<<"Please enter your name:";
cin>>name;
cout<<name<<end
l
}
In the above program, the first line is the directive to use for cin and cout objects of c++
programs so it includes the libraries, and at line 2 we include the string libraries for accessing
string objects. At line 5, the statement is creating a string variable that holds any text/string and
assign it a value is called “Aster Awoke” and at line 6 and 9, the statements are displays the
string values. At line 8, the statement is used for getting any string/text value from
users/keyboard by using cin objects.

2.3.1. String Concatenation

To concatenate two or more string together by using + operator (concatenation operator) and
the process is called concatenation.
string3 = string1 + string2;

//the + sign not used as addition operator as concatenation.

Here, the + operator used between strings to add them together to make a new string. In the
above example string3 holds the combination of string1 and string2.
main(){
string fname, lname;
cout<<”Enter first name: ”

23
cin>>fname;
cout<<”Enter last name: ”
cin>>lname;
string fullname = fname + lname;//concatenation performed
cout<<”Full name: ”<<fullname<<endl;
}
In the above code, the string name fullname assign to it the concatenate of two string fname
and lname. So, it holds the string of first name and last name together.

2.3.2. String Length

A string in C++ is actually an object, which contain functions that can perform certain operations
on strings. For example, the length of a string can be found with the length()function. To
know the number of characters in a string as follows:
string_name.length();

Any string name followed by length methods returns the length of a string or the number of
characters hold the string. For example, to displays length of our name that gets from
users/keyboard as follows:
String name;
cout<<”What is your name:”
cin>>name;
cout<<”My name: ”<<name<<” has “<<name.length()<<” characters”;
In the above code the string name is name and declare at the first line and accept values from
user at 3rd lines then the last line displays the accepted string values and its length.

2.3.3. Access Strings

From the string we can access the individual character by refering their index inside opening and
closing square bracket [].
string_name[index_number];
The index number starting from 0 and ending n-1 where n is the number of characters that holds
the string. The first character is referring by index 0 and the second character referring by index
1 and so on. For example, when we display the first character from our name as follows:
String ourName; cout<<”what is your name:”;
cin>>ourName;
cout<<”The first letter of our name is “<<ourName[0]<<endl;

24
In the above code, in the last statement ourName[0] return the first letter that accepted from
the users for example when you enter “Abebe” and it returns only the first character ‘A’. And
also, returns the second ourName[1] letter ‘b’, ourName[2]return the 3rd letter ‘e’.

2.3.4. Change String Characters

In string we change the characters by using index numbers like accessing the values of string
characters. To change the value of a specific character in a string, refer to the index number, and
use single quotes:

string_name[index_number]=’character’;
To replace any characters from a string by another character, first access the existing character
from the string by using its index and assign to it any characters by using assignment operator
(=). The next example shows how to change any character from a string by another character.
string_name[index_number]=’character’;
The following example shows replace the second and 4th character by another name for Hello
world string.

string mySytring=”Hello world”;


cout<<”before change:<<mystring<<endl;
mystring[1]=’o’;
mystring[3]=’i’;
cout<<”changed string=”<<mystring<<endl;

25

You might also like