0% found this document useful (0 votes)
10 views37 pages

Functions and Arrays in C++

Uploaded by

mayankchitra3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
10 views37 pages

Functions and Arrays in C++

Uploaded by

mayankchitra3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 37

Functions in C++ with example

BY CHAITANYA SINGH | FILED UNDER: LEARN C++

A function is block of code which is used to perform a particular task, for example
let’s say you are writing a large C++ program and in that program you want to do a
particular task several number of times, like displaying value from 1 to 10, in order to
do that you have to write few lines of code and you need to repeat these lines every
time you display values. Another way of doing this is that you write these lines inside
a function and call that function every time you want to display values. This would
make your code simple, readable and reusable.

Syntax of Function

return_type function_name (parameter_list) { //C++ Statements }


Let’s take a simple example to understand this concept.

A simple function example

#include <iostream>
#include<conio >
using namespace std; /* This function adds two integer values * and returns the result
*/
int sum(int num1, int num2)
{ int num3 = num1+num2;
return num3;
}
int main()
{ //Calling the function
clrscr();
cout<<sum(1,99);
return 0;
}
Output:

100
The same program can be written like this: Well, I am writing this program to let
you understand an important term regarding functions, which is function declaration.
Lets see the program first and then at the end of it we will discuss function
declaration, definition and calling of function.

#include <iostream>
using namespace std;
//Function declaration
int sum(int,int);

//Main function
int main()
{
clrscr();
//Calling the function
cout<<sum(1,99);
return 0;
}
/* Function is defined after the main method
*/
int sum(int num1, int num2)
{
int num3 = num1+num2;
return num3;
}
Function Declaration: You have seen that I have written the same program in two
ways, in the first program I didn’t have any function declaration and in the second
program I have function declaration at the beginning of the program. The thing is that
when you define the function before the main() function in your program then you
don’t need to do function declaration but if you are writing your function after the
main() function like we did in the second program then you need to declare the
function first, else you will get compilation error.
syntax of function declaration:
return_type function_name(parameter_list);
Note: While providing parameter_list you can avoid the parameter names, just like I
did in the above example. I have given int sum(int,int); instead of int sum(int
num1,int num2);.
Function definition: Writing the full body /code of function is known as defining a
function.
syntax of function definition:
return_type function_name(parameter_list)
{
//Statements inside function
}
Calling function: We can call the function like this:
function_name(parameters);
Now that we understood the working of function, lets see the types of function in
C++

Types of function
We have two types of function in C++:
1) Built-in functions/library functions
2) User-defined functions
1) Built-in functions
Built-in functions 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 etc. We can directly call them when we need.
Example: C++ built-in function example
Here we are using built-in function pow(x,y) which is x to the power y. This function
is declared in math header file so we have included the file in our program using
#include directive.
#include <iostream>
#include <math>
using namespace std;
int main()
{
/* Calling the built-in function
* pow(x, y) which is x to the power y
* We are directly calling this function
*/
cout<<pow(2,5);
return 0;
}
Output:
32
2) User-defined functions
We have already seen user-defined functions, the example we have given at the
beginning of this tutorial is an example of user-defined function. The functions that
we declare and write in our programs are user-defined functions. Lets see another
example of user-defined functions.
User-defined functions
#include <iostream>
#include <cmath>
using namespace std;
//Declaring the function sum
int sum(int,int);

int main(){
int x, y;
cout<<"enter first number: ";
cin>> x; 22

cout<<"enter second number: ";


cin>>y; 19

cout<<"Sum of these two :"<<sum(x,y);


return 0;
}
//Defining the function sum
int sum(int a, int b) {
int c = a+b;
return c;
}
Output:
enter first number: 22
enter second number: 19
Sum of these two :41
Why do we need functions?
• Functions help us in reducing code redundancy. If functionality is performed at
multiple places in software, then rather than writing the same code, again and
again, we create a function and call it everywhere. This also helps in
maintenance as we have to change at one place if we make future changes to the
functionality.
• Functions make code modular. Consider a big file having many lines of codes. It
becomes really simple to read and use the code if the code is divided into
functions.
• Functions provide abstraction. For example, we can use library functions
without worrying about their internal working.

A function is a group of statements that together perform a task. Every C++ program
has at least one function, which is main(), and all the most trivial programs can
define additional functions.
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 such that
each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body/code of the function.
The C++ standard library provides numerous built-in functions that your program
can call. For example, function strcat() to concatenate two strings,
function memcpy() to copy one memory location to another location and many more
functions.
A function is known with various names like a method or a sub-routine or a
procedure etc.
Defining a Function
The general form of a C++ function definition is as follows −
return_type function_name( parameter list ) { body of the function }
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.
Example
Following is the source code for a function called max(). This function takes two
parameters num1 and num2 and return the biggest of both −
// function returning the max between two numbers int max(int num1, int num2) {
// local variable declaration int result; if (num1 > num2) result = num1; else
result = num2; return result; }
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( parameter list );
For the above defined function max(), following is the function declaration −
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.
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 or invoke that function.
When a program calls a function, program control is transferred to the called
function. A called function performs defined task and when it’s 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. For
example −
#include <iostream>
using namespace std;
// function declaration
int max(int num1, int num2);
//global function declaration
int main ()
{ // local variable declaration:
int a = 100; int b = 200; int ret;
// calling a function to get max value.
ret = max(&a, &b); -actual parameters/arguments
cout << "Max value is : " << ret << endl; return 0;
}
// function returning the max between two numbers
int max(int num1, int num2) –formal arguments/parameters
{ // local variable declaration
int result;
if (num1 > num2)
result = num1;
else result = num2;
return result;
}
I kept max() function along with main() function and compiled the source code.
While running final executable, it would produce the following result −
Max value is : 200
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 −

Sr.No Call Type & Description

1 Call by Value

This method 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.

2 Call by Pointer
This method 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 argument.

3 Call by Reference
This method copies the reference of an argument into the formal parameter. Inside the function, the
reference is used to access the actual argument used in the call. This means that changes made to the
parameter affect the argument.

By default, C++ uses call by value to pass arguments. In general, this means that
code within a function cannot alter the arguments used to call the function and above
mentioned example while calling max() function used the same method.
Default Values for Parameters
When you define a function, you can specify a default value for each of the last
parameters. This value will be used if the corresponding argument is left blank when
calling to the function.
This is done by using the assignment operator and assigning values for the
arguments in the function definition. If a value for that parameter is not passed when
the function is called, the default given value is used, but if a value is specified, this
default value is ignored and the passed value is used instead. Consider the following
example −
#include <iostream>
using namespace std;
int sum(int a, int b = 20)
{ int result;
result = a + b;
return (result);
}
int main ()
{ // local variable declaration: int a = 100; int b = 200; int result;
// calling a function to add the values.
result = sum(a, b);
cout << "Total value is :" << result << endl;
// calling a function again as follows.
result = sum(a); cout << "Total value is :" << result << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total value is :300 Total value is :120

Difference between Actual and Formal Parameters :


Actual Parameters Formal Parameters

When a function is called, the values The parameter used in function


(expressions) that are passed in the definition statement which contain data
function call are called the actual type on its time of declaration is called
arguments or actual parameters. formal parameter.

These are the variables or expressions These are the variables or expressions
referenced in the parameter list of a referenced in the parameter list of a
subprogram call. subprogram specification.

Actual Parameters are the parameters Formal Parameters are the parameters
which are in calling subprogram. which are in called subprogram.
Actual Parameters Formal Parameters

There is no need to specify datatype in The datatype of the receiving value must
actual parameter. be defined.

The parameters are written in function


The parameters are written in function call definition are known as formal
are known as actual parameters. parameters.

Formal Parameters can be treated as


Actual Parameters can be constant values local variables of a function in which
or variable names. they are used in the function header.

Factorial program using loops

void main()

{int f=1,i=1,x;
cout<<”enter a number\n”;
cin>>x; 5
for(i=1;i<=x; i++)
{f=f*i;}
cout<<”factorial of “ <<x<<”=”<<f;
}

factorial of 5=120

C++ Recursion

A function that calls itself is known as a recursive function. And, this technique is
known as recursion.
What is Recursion?
The process in which a function calls itself directly or indirectly is
called recursion and the corresponding function is called as recursive
function.

Working of Recursion in C++


void recurse()
{
... .. ...
recurse();
... .. ...
}

int main()
{
... .. ...
recurse();
... .. ...
}
The figure below shows how recursion works by calling itself over and over again.

How recursion works in C++ programming


The recursion continues until some condition is met.
To prevent infinite recursion, if...else statement (or similar approach) can be used
where one branch makes the recursive call and the other doesn't.

Example 1: Factorial of a Number Using Recursion


// Factorial of n = 1*2*3*...*n

#include <iostream>
using namespace std;

int factorial(int); global declaration

int main()
{
int n, result;
cout << "Enter a non-negative number: ";
cin >> n; 4

result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}

int factorial(int n)
{
if (n > 1) {
return n * factorial(n - 1); 4*factorial(3)
3*factorial(2)
} else
{ 2*factorial(1)
return 1; 1*factorial(0)
4*3*2*1
}

}
Output
Enter a non-negative number: 4
Factorial of 4 = 24

Working of Factorial Program


How this C++ recursion program works

As we can see, the factorial() function is calling itself. However,


during each call, we have decreased the value of n by 1 . When n is
less than 1 , the factorial() function ultimately returns the output.

Advantages and Disadvantages of Recursion

Below are the pros and cons of using recursion in C++.

Advantages of C++ Recursion

• It makes our code shorter and cleaner.

• Recursion is required in problems concerning data structures and


advanced algorithms, such as Graph and Tree Traversal.

Disadvantages of C++ Recursion

• It takes a lot of stack space compared to an iterative program.

• It uses more processor time.

• It can be more difficult to debug compared to an equivalent iterative


program.

Fibonacii series
Third term= first term +second term
Third term(1)=0+1
0 1 1 2 3 5 8 13 21 34

C++ Arrays-derived datatype


C++ provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of data,
but it is often more useful to think of an array as a collection of variables of the same
type.
Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables. A specific element
in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element.
Declaring Arrays
To declare an array in C++, the programmer specifies the type of the elements and the
number of elements required by an array as follows −
type arrayName [ arraySize ]; eg int student_name[100];
2-d array- mat[2][3]=mat[r][c]
3-d array mat[2][3][4][2]
This is called a single-dimension array. The arraySize must be an integer constant
greater than zero and type can be any valid C++ data type. For example, to declare a
10-element array called balance of type double, use this statement −
double balance[10];
Initializing Arrays
You can initialize C++ array elements either one by one or using a single statement as
follows −
1. double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } can not be larger than the number of
elements that we declare for the array between square brackets [ ]. Following is an
example to assign a single element of the array −
2. If you omit the size of the array, an array is just big enough to hold the initialization
which is created. Therefore, if you write −
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
3. You will create exactly the same array as you did in the previous example.
int n[ 10 ];
float i[5];
char a[20]

for ( int i = 0; i < 10; i++ )


{
cout<<”enter the values for array n”;
cin>>n[i]; }

balance[4] = 50.0;
size of an array starts from 0 uptill n-1 terms
int n[5];
n[0]= 1st element
n[1]=2nd element
n[2]=3rd element
n[3]=4th element
n[4]=5th element
n[5]=?
The above statement assigns element number 5th in the array a value of 50.0. Array
with 4th index will be 5th, i.e., last element because all arrays have 0 as the index of
their first element which is also called base index. Following is the pictorial
representaion of the same array we discussed above −

Accessing Array Elements


An element is accessed by indexing the array name. This is done by placing the index
of the element within square brackets after the name of the array. For example −
double salary = balance[9];
The above statement will take 10th element from the array and assign the value to
salary variable. Following is an example, which will use all the above-mentioned
three concepts viz. declaration, assignment and accessing arrays −
Live Demo
#include <iostream>
using namespace std;

#include <iomanip>
using std::setw;

int main () {

int n[ 10 ]; // n is an array of 10 integers

// initialize elements of array n to 0


for ( int i = 0; i < 10; i++ ) {
n[ i ] = i + 100; // set element at location i to i + 100
}
cout << "Element" << setw( 13 ) << "Value" << endl;

// output each array element's value


for ( int j = 0; j < 10; j++ ) {
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
}

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
Arrays in C++
Arrays are important to C++ and should need lots of more detail. There are following
few important concepts, which should be clear to a C++ programmer −
Sr.No Concept & Description
1 Multi-dimensional arrays
C++ supports multidimensional arrays. The simplest form of the multidimensional array is the tw
2 Pointer to an array
You can generate a pointer to the first element of an array by simply specifying the array name, w
3 Passing arrays to functions
You can pass to the function a pointer to an array by specifying the array's name without an inde
4 Return array from functions
C++ allows a function to return an array.

void main()
{
int n[5],i;
for(i=0;i<5;i++)
{ cout<<” enter the elements of array n\n”; enter the elements of array n
12
cin>>n[i]; 14
11
2
19
}

for(i=0;i<5;i++)
{ cout<<” the elements of array n are”<<n[i]<<”\n”;
}

C++ Arrays
In this article, you will learn to work with arrays. You will learn to
declare, initialize and, access array elements in C++ programming.

In programming, one of the frequently arising problem is to handle


numerous data of same type.
Consider this situation, you are taking a survey of 100 people and
you have to store their age. Now it is not possible to create 100
variables .
In case you want to store information about 1000 people. Is it
possible to have 1000 variables like
int a,b,c,d,e,f,g,h,……upto 1000 ?

To solve this problem in C++, you can create an integer array having
100 elements.
An array is a collection of data that holds fixed number of values of
same type. For example:
int age[100];
Here, the age array can hold maximum of 100 elements of integer
type.
The size and type of arrays cannot be changed after its declaration.

What is an ARRAY?
Arrays in C/C++

An array in C or C++ is a collection of items stored at contiguous


memory locations and elements can be accessed randomly using
indices of an array. They are used to store similar type of elements as
in the data type must be the same for all elements. They can be used
to store collection of primitive data types such as int, float, double,
char, etc of any particular type. To add to it, an array in C or C++ can
store derived data types such as the structures, pointers etc. Given
below is the picturesque representation of an array.

Why do we need arrays?


We can use normal variables (v1, v2, v3, ..) when we have a small
number of objects, but if we want to store a large number of
instances, it becomes difficult to manage them with normal variables.
The idea of an array is to represent many instances in one variable.

Array declaration in C/C++:

There are various ways in which we can declare an array. It can be


done by specifying its type and size, by initializing it or both.

Array declaration by specifying size


// Array declaration by specifying size int arr1[10];
// With recent C/C++ versions, we can also
// declare an array of user specified size
int n = 10;
int arr2[n];

Array declaration by initializing elements


// Array declaration by initializing elements
int arr[] = { 10, 20, 30, 40 } // Compiler creates an array of size 4.
// above is same as "int arr[4] = {10, 20, 30, 40}"

Array declaration by specifying size and initializing elements


// Array declaration by specifying size and initializing elements
int arr[6] = { 10, 20, 30, 40 } // Compiler creates an array of size 6,
//initializes first 4 elements as specified by user and rest two elements as 0.
// above is same as "int arr[] = {10, 20, 30, 40, 0, 0}"

Advantages of an Array in C/C++:


1 Random access of elements using array index.
2 Use of less line of code as it creates a single array of multiple
elements.
3 Easy access to all the elements.
4 Traversal through the array becomes easy using a single loop.
5 Sorting becomes easy as it can be accomplished by writing less line
of code.

Disadvantages of an Array in C/C++:


1 Allows a fixed number of elements to be entered which is decided
at the time of declaration. Unlike a linked list, an array in C is
not dynamic.
2 Insertion and deletion of elements can be costly since the elements
are needed to be managed in accordance with the new memory
allocation.
Facts about Array in C/C++:
• Accessing Array Elements:
• Array elements are accessed by using an integer index. Array index
starts with 0 and goes till size of array minus 1.

How to declare an array in C++?


dataType arrayName[arraySize]; // one-dimensional array
For example,
float mark[5]; Here, we declared an array, mark, of floating-point
type and size 5. Meaning, it can hold 5 floating-point values.

Elements of an Array and How to access them?


You can access elements of an array by using indices.
Suppose you declared an array mark as above. The first element
is mark[0], second element is mark[1] and so on.

Few key notes:


• Arrays have 0 as the first index not 1. In this example, mark[0] is
the first element.
• If the size of an array is n, to access the last element, (n-1) index is
used. In this example, mark[4] is the last element.
• Suppose the starting address of mark[0] is 2120d. Then, the next
address, a[1], will be 2124d, address of a[2] will be 2128d and
so on. It's because the size of float is 4 bytes.

How to initialize an array in C++ programming?


It's possible to initialize an array during declaration. For example,
int mark[5] = {19, 10, 8, 17, 9};
Another method to initialize array during declaration:
int mark[] = {19, 10, 8, 17, 9}

Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9

How to insert and print array elements?


int mark[5] = {19, 10, 8, 17, 9}

// change 4th element to 9


mark[3] = 9;

// take input from the user and insert in third element


cin >> mark[2];

// take input from the user and insert in (i+1)th element


cin >> mark[i];

// print first element of the array


cout << mark[0];

// print ith element of the array


cout >> mark[i-1];
Example: C++ Array
C++ program to store and calculate the sum of 5 numbers
entered by the user using arrays.
#include <iostream.h>

int main()
{
int numbers[5], sum = 0;
cout << "Enter 5 numbers: ";

// Storing 5 number entered by user in an array


// Finding the sum of numbers entered
for (int i = 0; i < 5; ++i)
{
cin >> numbers[i]; numbers[0]=10,numbers[1]=20,
sum =sum+ numbers[i];0+10,10+20
}

cout << "Sum = " << sum << endl;

return 0;
}
Output
Enter 5 numbers: 3
4
5
4
2
Sum = 18

Things to remember when working with arrays in C++


Suppose you declared an array of 10 elements. Let's say,
int testArray[10];
You can use the array members from testArray[0] to testArray[9].
If you try to access array elements outside of its bound, let's say
testArray[14], the compiler may not show any error. However, this
may cause unexpected output (undefined behavior).

C++ Multidimensional Arrays


In this article, you'll learn about multi-dimensional arrays in C++.
More specifically, how to declare them, access them and use them
efficiently in your program.

In C++, you can create an array of an array known as multi-


dimensional array. For example:
int x[3][4];
Here, x is a two dimensional array. It can hold a maximum of 12
elements.
You can think this array as table with 3 rows and each row has 4

columns as shown below.

Three dimensional array also works in a similar way. For example:


float x[2][4][3];
This array x can hold a maximum of 24 elements. You can think this
example as: Each of the 2 elements can hold 4 elements, which makes
8 elements and each of those 8 elements can hold 3 elements. Hence,
total number of elements this array can hold is 24.

Multidimensional Array Initialisation


You can initialise a multidimensional array in more than one way.
Initialisation of two dimensional array
int test[2][3] = {2, 4, -5, 9, 0, 9};
Better way to initialise this array with same array elements as above.
int test[2][3] = { {2, 4, 5}, {9, 0 0}};

Initialisation of three dimensional array


int test[2][3][4] = {3, 4, 2, 3, 0, -3, 9, 11, 23, 12, 23,
2, 13, 4, 56, 3, 5, 9, 3, 5, 5, 1, 4, 9};
Better way to initialise this array with same elements as above.
int test[2][3][4] = {
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
{ {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }
};

Example 1: Two Dimensional Array


C++ Program to display all elements of an initialised two
dimensional array.
#include <iostream>
using namespace std;

int main()
{
int test[3][2] = {{2, -5},{4, 0},{9, 1}};

// Accessing two dimensional array using


// nested for loops
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 2; ++j)
{
cout<< "test[" << i << "][" << j << "] = " << test[i][j] << endl;
}
}

return 0;
}
Output
test[0][0] = 2
test[0][1] = -5
test[1][0] = 4
test[1][1] = 0
test[2][0] = 9
test[2][1] = 1

Example 2: Two Dimensional Array


C++ Program to store temperature of two different cities for a
week and display it.
#include <iostream.h>

const int CITY = 2;


const int WEEK = 7;

int main()
{
int temperature[CITY][WEEK];

cout << "Enter all temperature for a week of first city and then
second city. \n";

// Inserting the values into the temperature array


for (int i = 0; i < CITY; ++i)
{
for(int j = 0; j < WEEK; ++j)
{
cout << "City " << i + 1 << ", Day " << j + 1 << " : ";
cin >> temperature[i][j];
}
}

cout << "\n\nDisplaying Values:\n";

// Accessing the values from the temperature array


for (int i = 0; i < CITY; ++i)
{
for(int j = 0; j < WEEK; ++j)
{
cout << "City " << i + 1 << ", Day " << j + 1 << " = " <<
temperature[i][j] << endl;
}
}

return 0;
}
Output
Enter all temperature for a week of first city and then second city.
City 1, Day 1 : 32
City 1, Day 2 : 33
City 1, Day 3 : 32
City 1, Day 4 : 34
City 1, Day 5 : 35
City 1, Day 6 : 36
City 1, Day 7 : 38
City 2, Day 1 : 23
City 2, Day 2 : 24
City 2, Day 3 : 26
City 2, Day 4 : 22
City 2, Day 5 : 29
City 2, Day 6 : 27
City 2, Day 7 : 23

Displaying Values:
City 1, Day 1 = 32
City 1, Day 2 = 33
City 1, Day 3 = 32
City 1, Day 4 = 34
City 1, Day 5 = 35
City 1, Day 6 = 36
City 1, Day 7 = 38
City 2, Day 1 = 23
City 2, Day 2 = 24
City 2, Day 3 = 26
City 2, Day 4 = 22
City 2, Day 5 = 29
City 2, Day 6 = 27
City 2, Day 7 = 23

Example 3: Three Dimensional Array


C++ Program to Store value entered by user in three
dimensional array and display it.
#include <iostream>

int main()
{
// This array can store upto 12 elements (2x3x2)
int test[2][3][2];

cout << "Enter 12 values: \n";

// Inserting the values into the test array


// using 3 nested for loops.
for(int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for(int k = 0; k < 2; ++k )
{
cin >> test[i][j][k];
}
}
}

cout<<"\nDisplaying Value stored:"<<endl;

// Displaying the values with proper index.


for(int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for(int k = 0; k < 2; ++k)
{
cout << "test[" << i << "][" << j << "][" << k << "] = " <<
test[i][j][k] << endl;
}
}
}

return 0;
}
Output
Enter 12 values:
1
2
3
4
5
6
7
8
9
10
11
12

Displaying Value stored:


test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
As the number of dimension increases, the complexity also increases
tremendously although the concept is quite similar.

Example: Add Two Matrices using Multi-dimensional Arrays

#include <iostream.h>
int main()
{ int r, c, a[100][100], b[100][100], sum[100][100], i, j;
cout << "Enter number of rows (between 1 and 100): ";
cin >> r;
cout << "Enter number of columns (between 1 and 100): ";
cin >> c;
cout << endl << "Enter elements of 1st matrix: " << endl;
// Storing elements of first matrix entered by user.
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{ cout << "Enter element a" << i + 1 << j + 1 << " : ";
cin >> a[i][j]; }
//Displaying the elements of first matrix
cout<<” Display the elements of Matrix a”;
for(i = 0; i < r; i++)
{ for(j = 0; j < c; j++)
{ cout<<a[i][j] <<”\t”;
}
cout<<”\n”;
}
// Storing elements of second matrix entered by user.
cout << endl << "Enter elements of 2nd matrix: " << endl;
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{ cout << "Enter element b" << i + 1 << j + 1 << " : ";
cin >> b[i][j]; }
//Displaying the elements of second matrix
cout<<” Display the elements of Matrix b”;
for(i = 0; i < r; i++)
{ for(j = 0; j < c; j++)
{ cout<<b[i][j] <<”\t”;
}
cout<<”\n”;
}
// Adding Two matrices

for(i = 0; i < r; ++i)


for(j = 0; j < c; ++j)
sum[i][j] = a[i][j] + b[i][j];

cout << endl << "Sum of two matrix is: " << endl;
// Displaying the resultant sum matrix.
for(i = 0; i < r; ++i)
{ for(j = 0; j < c; ++j)
{ cout << sum[i][j] << " \t "; }
cout << “\n”;
}
return 0;
}

Output

Enter number of rows (between 1 and 100): 2


Enter number of columns (between 1 and 100): 2
Enter elements of 1st matrix:
Enter element a11: -4
Enter element a12: 5
Enter element a21: 6
Enter element a22: 8

Display the elements of Matrix a


-4 5
6 8

Enter elements of 2nd matrix:


Enter element b11: 3
Enter element b12: -9
Enter element b21: 7
Enter element b22: 2

Display the elements of Matrix b


3 -9
7 2
Sum of two matrix is:
-1 -4
13 10

This program takes n number of element from user(where, n is


specified by user) and stores data in an array. Then, this program
displays the largest element of that array using loops.
Example: Display Largest Element of an array
#include <iostream.h>

int main()
{
int i, n;
float arr[100];
cout << "Enter total number of elements(1 to 100): ";
cin >> n;
cout << endl;

// Store number entered by the user


for(i = 0; i < n; ++i)
{
cout << "Enter Number " << i + 1 << " : ";
cin >> arr[i];
}

// Loop to store largest number to arr[0]


for(i = 1;i < n; ++i)
{
// Change < to > if you want to find the smallest element
if(arr[0] < arr[i])
arr[0] = arr[i];
}
cout << "Largest element = " << arr[0];

return 0;
}
Output
Enter total number of elements: 8

Enter Number 1: 23.4


Enter Number 2: -34.5
Enter Number 3: 50
Enter Number 4: 33.5
Enter Number 5: 55.5
Enter Number 6: 43.7
Enter Number 7: 5.7
Enter Number 8: -66.5

Largest element = 55.5


This program takes n number of elements from user and stores it in
array arr[].
To find the largest element, the first two elements of array are
checked and largest of these two element is placed in arr[0].
Then, the first and third elements are checked and largest of these
two element is placed in arr[0].
This process continues until and first and last elements are checked.
After this process, the largest element of an array will be in arr[0]
position.

In this program, user is asked to entered the number of rows r and


columns c. The value of r and c should be less than 10 in this
program.
The user is asked to enter elements of the matrix (of order r*c).

Then, the program computes the transpose of the matrix and displays
it on the screen.

Example: Find Transpose of a Matrix

#include <iostream>
int main()
{ int a[10][10], trans[10][10], r, c, i, j;
cout << "Enter rows and columns of matrix: ";
cin >> r >> c; // Storing element of matrix entered by user in
array a[][].
cout << endl << "Enter elements of matrix: " << endl;
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{ cout << "Enter elements a" << i + 1 << j + 1 << ": ";
cin >> a[i][j]; } // Displaying the matrix a[ ][ ]
cout << endl << "Entered Matrix: " << endl;
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{ cout << " " << a[i][j];
if(j == c - 1)
cout << endl << endl; } // Finding transpose of matrix
a[][] and storing it in array trans[][].
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{ trans[j][i]=a[i][j]; }
// Displaying the transpose,i.e, Displaying array trans[][].
cout << endl << "Transpose of Matrix: " << endl;
for(i = 0; i < c; ++i)
for(j = 0; j < r; ++j)
{ cout << " " << trans[i][j];
if(j == r - 1)
cout << endl << endl; }
return 0; }

Output

Enter rows and column of matrix: 2 3


Enter elements of matrix: Enter elements a11: 1
Enter elements a12: 2
Enter elements a13: 9
Enter elements a21: 0
Enter elements a22: 4
Enter elements a23: 7
Entered Matrix: 1 2 9
0 4 7
Transpose of Matrix: 1 0
2 4
9 7
This program takes 10 words from the user and sort them in
lexicographical order

Example: Sort Words in Dictionary Order

#include <iostream.h>
int main()
{ string str[10], temp;
cout << "Enter 10 words: " << endl;
for(int i = 0; i < 10; ++i)
{ getline(cin, str[i]); }

for(int i = 0; i < 9; ++i)


for( int j = i+1; j < 10; ++j)
{ if(str[i] > str[j])
{ temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
cout << "In lexicographical order: " << endl;
for(int i = 0; i < 10; ++i)
{ cout << str[i] << endl; }
return 0; }

Output

Enter 10 words:
C
C++
Java
Python
Perl
R
Matlab
Ruby
JavaScript
PHP
In lexicographical order: C
C++
Java
JavaScript
Matlab
PHP
Perl
Python
R
Ruby

To solve this program, an array of string object str[10] is created


The 10 words entered by the user is stored in this array.

Then, the array is sorted in lexicographical order using nested for


loop and displayed on the screen.

#include<iostream>
#include<string.h>

int main()
{
char str[5][20], t[20];
int i, j;
cout<<"\n Enter Any Five Names : \n\n";
for(i=0; i<5; i++)
{
cout<<" ";
cin>>str[i];
}
for(i=1; i<5; i++)
{
for(j=1; j<5; j++)
{
if(strcmp(str[j-1], str[j])>0)
{
strcpy(t, str[j-1]);
strcpy(str[j-1], str[j]);
strcpy(str[j], t);
}
}
}
cout<<"\n Names Sorted in Alphabetical Order : \n\n";
for(i=0; i<5; i++)
{
cout<<" ";
cout<<str[i]<<"\n";
}
return 0;
}

Output:

You might also like