 # C++ Programming Code Examples

## C++ > Arrays and Matrices Code Examples

### Program to Multiply two Matrices by Passing Matrix to Function

/* Program to Multiply two Matrices by Passing Matrix to Function In this example, you'll learn to multiply two matrices and display it using user defined function. This program asks user to enter the size of the matrix (rows and columns). Then, it asks the user to enter the elements of two matrices and finally it multiplies two matrix and displays the result. To perform this task three functions are made: To take matrix elements from user To multiply two matrix To display the resultant matrix after multiplication */ #include <iostream> using namespace std; void enterData(int firstMatrix[], int secondMatrix[], int rowFirst, int columnFirst, int rowSecond, int columnSecond); void multiplyMatrices(int firstMatrix[], int secondMatrix[], int multResult[], int rowFirst, int columnFirst, int rowSecond, int columnSecond); void display(int mult[], int rowFirst, int columnSecond); int main() { int firstMatrix, secondMatrix, mult, rowFirst, columnFirst, rowSecond, columnSecond, x, j, k; cout << "Enter rows and column for first matrix: "; cin >> rowFirst >> columnFirst; cout << "Enter rows and column for second matrix: "; cin >> rowSecond >> columnSecond; // If colum of first matrix in not equal to row of second matrix, asking user to enter the size of matrix again. while (columnFirst != rowSecond) { cout << "Error! column of first matrix not equal to row of second." << endl; cout << "Enter rows and column for first matrix: "; cin >> rowFirst >> columnFirst; cout << "Enter rows and column for second matrix: "; cin >> rowSecond >> columnSecond; } // Function to take matrices data enterData(firstMatrix, secondMatrix, rowFirst, columnFirst, rowSecond, columnSecond); // Function to multiply two matrices. multiplyMatrices(firstMatrix, secondMatrix, mult, rowFirst, columnFirst, rowSecond, columnSecond); // Function to display resultant matrix after multiplication. display(mult, rowFirst, columnSecond); return 0; } void enterData(int firstMatrix[], int secondMatrix[], int rowFirst, int columnFirst, int rowSecond, int columnSecond) { int x, j; cout << endl << "Enter elements of matrix 1:" << endl; for(x = 0; x < rowFirst; ++x) { for(j = 0; j < columnFirst; ++j) { cout << "Enter elements a"<< x + 1 << j + 1 << ": "; cin >> firstMatrix[x][j]; } } cout << endl << "Enter elements of matrix 2:" << endl; for(x = 0; x < rowSecond; ++x) { for(j = 0; j < columnSecond; ++j) { cout << "Enter elements b" << x + 1 << j + 1 << ": "; cin >> secondMatrix[x][j]; } } } void multiplyMatrices(int firstMatrix[], int secondMatrix[], int mult[], int rowFirst, int columnFirst, int rowSecond, int columnSecond) { int x, j, k; // Initializing elements of matrix mult to 0. for(x = 0; x < rowFirst; ++x) { for(j = 0; j < columnSecond; ++j) { mult[x][j] = 0; } } // Multiplying matrix firstMatrix and secondMatrix and storing in array mult. for(x = 0; x < rowFirst; ++x) { for(j = 0; j < columnSecond; ++j) { for(k=0; k<columnFirst; ++k) { mult[x][j] += firstMatrix[x][k] * secondMatrix[k][j]; } } } } void display(int mult[], int rowFirst, int columnSecond) { int x, j; cout << "Output Matrix:" << endl; for(x = 0; x < rowFirst; ++x) { for(j = 0; j < columnSecond; ++j) { cout << mult[x][j] << " "; if(j == columnSecond - 1) cout << endl << endl; } } }

The cin object is used to accept input from the standard input device i.e. keyboard. It is defined in the iostream header file. C++ cin statement is the instance of the class istream and is used to read input from the standard input device which is usually a keyboard. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard. The "c" in cin refers to "character" and "in" means "input". Hence cin means "character input". The cin object is used along with the extraction operator >> in order to receive a stream of characters.

In computer programming, loops are used to repeat a block of code. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop. The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.

An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list; A two dimensional array is like a table; The C++ language places no limits on the number of dimensions in an array, though specific implementations may. Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as matrices, and use the general term arrays when the number of dimensions is unspecified or unimportant. (2D) array in C++ programming is also known as matrix. A matrix can be represented as a table of rows and columns. In C/C++, we can define multi dimensional arrays in simple words as array of arrays. Data in multi dimensional arrays are stored in tabular form (in row major order).

In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement, The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.

#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.

A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.

An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C++ programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number. C++ array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations.

As the name already suggests, these operators help in assigning values to variables. These operators help us in allocating a particular value to the operands. The main simple assignment operator is '='. We have to be sure that both the left and right sides of the operator must have the same data type. We have different levels of operators. Assignment operators are used to assign the value, variable and function to another variable. Assignment operators in C are some of the C Programming Operator, which are useful to assign the values to the declared variables. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. The following table lists the assignment operators supported by the C language:

The function in C++ language is also known as procedure or subroutine in other programming languages. To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability. Functions are used to provide modularity to a program. Creating an application using function makes it easier to understand, edit, check... Function declaration, is done to tell the compiler about the existence of the function. Function's return type, its name & parameter list is mentioned. Function body is written in its definition. Functions are called by their names. If the function is without argument, it can be called directly using its name. But for functions with arguments, we have two ways to call them:

Consider a situation, when we have two persons with the same name, jhon, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother's or father's name, etc. Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.

C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop. A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required. Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.

Find the minimum spanning tree of the given graph using Prims algorihtm. This algorithm is a "greedy algorithm" that finds a minimum spanning tree for a "Connected Undirected"

Control statement itself has three parts: for ( "initialization"; test condition; run every time command ). "Initialization" part is performed only once at for loop start. We can initialize a

C++ Program to implement "Tower Of Hanoi" alogithm using recursion. Shows Movements of disk from one tower to another when a key is pressed. Entering the fibonacci number and

First Input the length of a side of the triangle. Then Input the 'length of another side' of the triangle, then input the angle between these sides of the triangle. The area of the Scalene

"Multilevel inheritance" represents a type of inheritance when a "Derived" class is a base class for another class. In c++ deriving a class from a derived class is known as 'multi-level'