 # C++ Programming Code Examples

## C++ > Algorithms Code Examples

### Matrix Multiplication

/* Matrix Multiplication */ void main() { int row1=0, col1=1, row2=0, col2=0, **matrix1, **matrix2, **result; clrscr(); printf(" Enter number of row for first matrix "); scanf("%d",&row1); while (col1!=row2) { printf(" Enter number of column for first matrix "); scanf("%d",&col1); printf(" Enter number of row for second matrix "); scanf("%d",&row2); if (col1!=row2) { clrscr(); printf("Column number of first matrix must be same as the row number of second matrix"); } } printf(" Enter number of column for second matrix "); scanf("%d",&col2); matrix1=init(matrix1,row1,col1); matrix2=init(matrix2,row2,col2); /* setting values in matrix */ printf("First matrix \n"); set(matrix1,row1,col1); printf("Second matrix \n"); set(matrix2,row2,col2); /* printint matrix */ clrscr(); printf(" [ First matrix ]\n"); get(matrix1,row1,col1); printf(" [ Second matrix ]\n"); get(matrix2,row2,col2); printf(" [ Multiplication Result ]\n"); result=mul(matrix1,matrix2,row1,col2,col1); get(result,row1,col2); printf("\n\t\t Thanks from debmalya jash"); getch(); free(matrix1); free(matrix2); fress(result); } /* end main */ /* to initialize matrix */ int** init(int** arr,int row,int col) { int i=0, j=0; arr=(int**)malloc(sizeof(int)*row*col); for(i=0;i<row;i++) { for(j=0;j<col;j++) { *((arr+i)+j)=(int*)malloc(sizeof(int)); *(*(arr+i)+j)=0; } } return arr; } /* to set value in matrix */ int** set(int** arr,int row,int col) { int i=0, j=0, val=0; for(i=0;i<row;i++) { for(j=0;j<col;j++) { printf("Enter value for row %d col %d :",(i+1),(j+1)); scanf("%d",&val); *(*(arr+i)+j)=val; } } return arr; } /* print values of the passed matrix */ void get(int** arr,int row,int col) { int i=0, j=0; for(i=0;i<row;i++) { for(j=0;j<col;j++) { printf("%d\t",*(*(arr+i)+j)); } printf("\n"); } } /* mutiply two matrices and return the resultant matrix */ int** mul(int** arr1,int** arr2,int row,int col,int col1) { int **result, i=0, j=0, k=0; result=init(result,row,col); for(i=0;i<row;i++) { for(j=0;j<col;j++) { for(k=0;k<col1;k++) { printf("%dX%d(%d)",*(*(arr1+i)+k),*(*(arr2+k)+j),(*(*(arr1+i)+k))*(*(*(arr2+k)+j))); *(*(result+i)+j)+=(*(*(arr1+i)+k))*(*(*(arr2+k)+j)); if (k!=(col1-1)) printf("+"); } printf("\t"); } printf("\n"); } return result;

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.

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:

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.

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.

Allocate memory block. Allocates a block of size bytes of memory, returning a pointer to the beginning of the block. The content of the newly allocated block of memory is not initialized, remaining with indeterminate values. If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced. Malloc function in C++ is used to allocate a specified size of the block of memory dynamically uninitialized. It allocates the memory to the variable on the heap and returns the void pointer pointing to the beginning address of the memory block. The values in the memory block allocated remain uninitialized and indeterminate. In case the size specified in the function is zero then pointer returned must not be dereferenced as it can be a null pointer, and in this case, behavior depends on particular library implementation. When a memory block is allocated dynamically memory is allocated on the heap but the pointer is

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.

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.

Get characters. Extracts characters from the stream, as unformatted input. The get() function is used to read a character(at a time) from a file. The classes istream and ostream define two member functions get(), put() respectively to handle the single character input/output operations. There are two types of get() functions. Both get(char *) and get(void) prototype can be used to fetch a character including the blank space,tab and newline character. The get(char *) version assigns the input character to its argument and the get(void) version returns the input character. Since these functions are members of input/output Stream classes, these must be invoked using appropriate objects.

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.

The sizeof() is an operator that evaluates the size of data type, constants, variable. It is a compile-time operator as it returns the size of any variable or a constant at the compilation time. The size, which is calculated by the sizeof() operator, is the amount of RAM occupied in the computer. The sizeof is a keyword, but it is a compile-time operator that determines the size, in bytes, of a variable or data type. The sizeof operator can be used to get the size of classes, structures, unions and any other user defined data type. The data_type can be the data type of the data, variables, constants, unions, structures, or any other user-defined data type.

Check whether eofbit is set. Returns true if the eofbit error state flag is set for the stream. This flag is set by all standard input operations when the End-of-File is reached in the sequence associated with the stream. Note that the value returned by this function depends on the last operation performed on the stream (and not on the next). Operations that attempt to read at the End-of-File fail, and thus both the eofbit and the failbit end up set. This function can be used to check whether the failure is due to reaching the End-of-File or to some other reason.

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.

Deallocate memory block. A block of memory previously allocated by a call to malloc, calloc or realloc is deallocated, making it available again for further allocations. If ptr does not point to a block of memory allocated with the above functions, it causes undefined behavior. If ptr is a null pointer, the function does nothing. Notice that this function does not change the value of ptr itself, hence it still points to the same (now invalid) location. free() function in C++ <cstdlib> library is used to deallocate a memory block in C++. Whenever we call malloc, calloc or realloc function to allocate a memory block dynamically in C++, compiler allocates a block of size bytes of memory and returns a pointer to the start of the block. The new memory block allocated is not initialized but have intermediate values. free() method is used to free such block of memory. In case the pointer mentioned does not point to any memory block then it may lead to an undefined behavior, but does nothing in case of null