# C++ Programming Code Examples

## C++ > Mathematics Code Examples

### To Calculate Determinant of a Matrix Using Recursion

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
/* To Calculate Determinant of a Matrix Using Recursion This is a simple program implementing the concept of recursion to calculate the determinant of a matrix of any order. */ #include<iostream.h> #include<conio.h> #include<math.h> #include<process.h> void main() { int determinant(int[5][5],int);// FUNCTIONS void read(int[5][5],int); void print(int[5][5],int); // PROTOYPES int a[5][5],l,n; int result; l1:clrscr(); cout<<" ENTER ORDER OF MATRIX(MAX. OF 4X4):"; cin>>l>>n; if(l!=n) { //TESTING CONDITION cout<<" SORRY!!!!!\n ONLY SQUARE MATRIX"; goto l1; } read(a,n); result = determinant(a,n); print(a,n); cout<<" THE DETERMINANT OF THE ABOVE MATRIX IS:"<<result; getch(); } void read(int b[5][5],int m) //FUNCTION FOR READING MATRIX { cout<<" ENTER "<<m*m<<" ELEMENTS OF MATRIX(ROW-WISE):"; for(int i=0;i<m;i++) for(int j=0;j<m;j++) cin>>b[i][j]; } void print(int b[5][5],int m) { clrscr(); //FUNCTION FOR PRINTING MATRIX cout<<" MATRIX IS :- "; for(int i=0;i<m;i++) { cout<<" "; for(int j=0;j<m;j++) cout<<" "<<b[i][j]; } } int determinant(int b[5][5],int m) //FUNCTION TO CALCULATE DETERMINANT { int i,j,sum = 0,c[5][5]; if(m==2) { //BASE CONDITION sum = b[0][0]*b[1][1] - b[0][1]*b[1][0]; return sum; } for(int p=0;p<m;p++) { int h = 0,k = 0; for(i=1;i<m;i++) { for( j=0;j<m;j++) { if(j==p) continue; c[h][k] = b[i][j]; k++; if(k == m-1) { h++; k = 0; } } } sum = sum + b[0][p]*pow(-1,p)*determinant(c,m-1); } return sum; }

Read block of data. Extracts n characters from the stream and stores them in the array pointed to by s. This function simply copies a block of data, without checking its contents nor appending a null character at the end. If the input sequence runs out of characters to extract (i.e., the end-of-file is reached) before n characters have been successfully read, the array pointed to by s contains all the characters read until that point, and both the eofbit and failbit flags are set for the stream. Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true). Then (if good), it extracts characters from its associated stream buffer object as if calling its member functions sbumpc or sgetc, and finally destroys the sentry object before returning.

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.

Arithmetic Operator is used to performing mathematical operations such as addition, subtraction, multiplication, division, modulus, etc., on the given operands. For example: 6 + 3 = 9, 5 - 3 = 2, 3 * 4 = 12, etc. are the examples of arithmetic operators. Let's discuss the different types of Arithmetic Operators in the C programming. Plus Operator is a simple Plus (+) Operator used to add two given operands. We can use Plus Operator with different data types such as integer, float, long, double, enumerated and string type data to add the given operand. The minus operator is denoted by the minus (-) symbol. It is used to return the subtraction of the first number from the second number. The data type of the given number can be different types, such as int, float, double, long double, etc., in the programing language.

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.

The getch() is a predefined non-standard function that is defined in conio.h header file. It is mostly used by the Dev C/C++, MS- DOS's compilers like Turbo C to hold the screen until the user passes a single value to exit from the console screen. It can also be used to read a single byte character or string from the keyboard and then print. It does not hold any parameters. It has no buffer area to store the input character in a program. The getch() function does not accept any parameter from the user. It returns the ASCII value of the key pressed by the user as an input.

Raise to power. The pow() function returns the result of the first argument raised to the power of the second argument. This function is defined in the cmath header file. pow() function is a library function of cmath header, it is used to find the raise to the power, it accepts two arguments and returns the first argument to the power of the second argument.

Continue statement is used inside loops. Whenever a continue statement is encountered inside a loop, control directly jumps to the beginning of the loop for next iteration, skipping the execution of statements inside loop's body for the current iteration. The continue statement works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between. For the for loop, continue causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, program control passes to the conditional tests.

#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.

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).

The cout is a predefined object of ostream class. It is connected with the standard output device, which is usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to display the output on a console. On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout. The "c" in cout refers to "character" and "out" means "output". Hence cout means "character output". The cout object is used along with the insertion operator << in order to display a stream of characters.

In C++, goto is a jump statement and sometimes also referred as unconditional jump statement. It can be used to jump from goto to a labeled statement within the same function. The target label must be within the same file and context. Please note that the use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making hard to understand and modify the program.

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.

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.

It is a predefined function in "conio.h" (console input output header file) used to clear the console screen. It is a predefined function, by using this function we can clear the data from console (Monitor). Using of clrscr() is always optional but it should be place after variable or function declaration only. It is often used at the beginning of the program (mostly after variable declaration but not necessarily) so that the console is clear for our output.

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.

The first program uses temporary variable to swap numbers, whereas the second program doesn't use temporary variables. To perform 'swapping' in above example, three variables

This C++ program takes a sentence from user and "Reverses" that sentence using recursion. This sample doesn't 'use string' to reverse the sentence or store the sentence. User is asked

To perform "Binary Search" in 'C++', enter the array size, enter the array elements. Now ask to enter an element that is going to be search to "start searching" that element using binary

To improve "readability of program" make a separate function and function should return the "resultant number". In main function user enters input number. Calls the function, pass