C++ Programming Code Examples
C++ > Beginners Lab Assignments Code Examples
This is a program of matrix capable of doing several works with two matrices.
/* This is a program of matrix capable of doing several works with two matrices.
It can add, subtract, multiply of two matrices and
if user wants to see the input entered in two matrices he can also see. It
provides the facility to user to do again some work on another matrix
without running the program twice. */
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
#include<process.h>
#define sk 100
class matrix
{
public:
int i,j,k,sum,r1,r2,c1,c2;
int m1[sk][sk],m2[sk][sk];
char reply;
void getin(void);
void mply(void);
void add(void);
void minus(void);
void read(void);
void input(void);
};
void matrix::getin()
{
cout<<"
WELCOME TO SOLUTION OF TWO MATRICRES ";
cout<<"
-------------------------------------";
cout<<"
YOU CAN CALCULATE UPTO A LIMIT OF MATRIX 100 * 100 ";
cout<<"
YOU CAN DO THE FOLLOWING :
ADDITION
SUBTRACTION
";
cout<<"
MULTIPLICATION AND
READ ONLY ";
cout<<"
DO YOU WANT TO CONTINUE [Y/N] : ";
cin >>reply;
if(reply=='y'||reply=='Y')
{
cout<<"
Enter the number of rows and columns of matrix 1 : ";
cin>>r1>>c1;
cout<<"
Enter the value of matrix 1 : "<<endl;
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
cin>>m1[i][j];
cout<<"
Enter the number of rows and columns of matrix 2 : ";
cin>>r2>>c2;
cout<<"
Enter the value of matrix 2 : "<<endl;
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
cin>>m2[i][j];
}
else exit(0);
}
void matrix::mply()
{
cout<<"
THE RESULT AFTER MULTIPLICATION IS :
";
if(c1==r2)
{
for(i=0;i<r1;i++)
{
cout<<endl;
for(j=0;j<c2;j++)
{
sum=0;
for(k=0;k<c1;k++)
sum+=m1[i][k]*m2[k][j];
cout<<setw(6)<<sum;
}
}
}
else
{
cout<<"
INVALID INPUT ";
cout<<"
MULTIPLICATION NOT POSSIBLE ";
}
}
void matrix::add()
{
cout<<"
THE RESULT AFTER ADDITION IS :
";
if(r1==r2&&c1==c2)
{
for(i=0;i<r1;i++)
{
cout<<endl;
for(j=0;j<c1;j++)
cout<<setw(3)<<(m1[i][j]+m2[i][j]);
}
}
else
{
cout<<"
INVALID INPUT ";
cout<<"
ADDITION NOT POSIIBLE ";
}
}
void matrix::minus()
{
cout<<"
THE RESULT AFTER SUBTRACTION IS :
";
if(r1==r2&&c1==c2)
{
for(i=0;i<r1;i++)
{
cout<<endl;
for(j=0;j<c1;j++)
cout<<setw(3)<<(m1[i][j]-m2[i][j]);
}
}
else
{
cout<<"
INVALID INPUT ";
cout<<"
SUBTRACTION NOT POSSIBLE ";
}
}
void matrix::read()
{
cout<<"
ENTERED MATRIX 1 IS :
";
for(i=0;i<r1;i++)
{
cout<<endl;
for(j=0;j<c1;j++)
cout<<setw(3)<<m1[i][j];
}
cout<<endl;
cout<<"
ENTERED MATRIX 2 IS :
";
for(i=0;i<r2;i++)
{
cout<<endl;
for(j=0;j<c2;j++)
cout<<setw(3)<<m2[i][j];
}
}
void main()
{
int ans,option;
char response;
matrix m;
clrscr();
start :
m.getin();
again :
cout<<"
What you wish to do : "<<endl;
cout<<"
1.ADDITION ";
cout<<"
2.SUBTRACTION ";
cout<<"
3.MULTIPLY ";
cout<<"
4.READ ONLY ";
cout<<"
5.EXIT ";
cout<<"
ENTER YOUR CHOICE IN NUMBERS : ";
repeat :
cin>>ans;
switch(ans)
{
case 1 : m.add(); break;
case 2 : m.minus(); break;
case 3 : m.mply(); break;
case 4 : m.read(); break;
case 5 : goto exit ;
default :
{
cout<<"
INVALID ENTRY
ENTER YOUR CHOICE AGAIN : ";
goto repeat;
}
}
cout<<"
DO YOU WANT TO DO IT FOR ANOTHER TIME [Y/N] : ";
cin>>response;
if(response=='y'||response=='Y')
{
wrong:
cout<<"
Enter your choice in number
";
cout<<"
1.FOR Same matrix
2.FOR Another matrix
";
cin>>option;
switch(option)
{
case 1 : goto again;
case 2 : goto start;
default: cout<<"
INVALID ENTRY "; goto wrong;
}
}
exit :
getch();
}
#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.
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 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.
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, 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.
Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found. If a case match is NOT found, then the default statement is executed, and the control goes out of the switch block. • The expression can be integer expression or a character expression. • Value-1, 2, n are case labels which are used to identify each case individually. Remember that case labels should not be same as it may create a problem while executing a program. Suppose we have two cases with the same label as '1'. Then while executing the program, the case that appears first will be executed even though you want the program to execute a second case. This creates problems in the program and
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.
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.
In C++, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C++ has the same name as class or structure. Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object. Whereas, Destructor on the other hand is used to destroy the class object. • Default Constructor: A constructor which has no argument is known as default constructor. It is invoked at the time of creating object.
Set field width. Sets the field width to be used on output operations. The C++ function std::setw behaves as if member width were called with n as argument on the stream on which it is inserted/extracted as a manipulator (it can be inserted/extracted on input streams or output streams). It is used to sets the field width to be used on output operations. This manipulator is declared in header <iomanip>. This method accepts n as a parameter which is the integer argument corresponding to which the field width is to be set. This function returns an object of unspecified type. The setw function should only be used as a stream manipulator.
Break statement in C++ is a loop control statement defined using the break keyword. It is used to stop the current execution and proceed with the next one. When a compiler calls the break statement, it immediately stops the execution of the loop and transfers the control outside the loop and executes the other statements. In the case of a nested loop, break the statement stops the execution of the inner loop and proceeds with the outer loop. The statement itself says it breaks the loop. When the break statement is called in the program, it immediately terminates the loop and transfers the flow control to the statement mentioned outside the loop.
The exit function terminates the program normally. Automatic objects are not destroyed, but static objects are. Then, all functions registered with atexit are called in the opposite order of registration. The code is returned to the operating system. An exit code of 0 or EXIT_SUCCESS means successful completion. If code is EXIT_FAILURE, an indication of program failure is returned to the operating system. Other values of code are implementation-defined. Calls all functions registered with the atexit() function, and destroys C++ objects with static storage duration, all in last-in-first-out (LIFO) order. C++ objects with static storage duration are destroyed in the reverse order of the completion of their constructor. (Automatic objects are not destroyed as a result of calling exit().)
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:
Put character. Inserts character c into the stream. Internally, the function accesses the output sequence by first constructing a sentry object. Then (if good), it inserts c into its associated stream buffer object as if calling its member function sputc, and finally destroys the sentry object before returning. Function returns the ostream object (*this).
The main purpose of C++ programming is to add object orientation to the C programming language and classes are the central feature of C++ that supports object-oriented programming and are often called user-defined types. A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.
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).
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.
A predefined object of the class called iostream class is used to insert the new line characters while flushing the stream is called endl in C++. This endl is similar to \n which performs the functionality of inserting new line characters but it does not flush the stream whereas endl does the job of inserting the new line characters while flushing the stream. Hence the statement cout<<endl; will be equal to the statement cout<< '\n' << flush; meaning the new line character used along with flush explicitly becomes equivalent to the endl statement in C++.
In the C++ Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables. You generally use this syntax when creating constants that represent numbers, strings or expressions. The syntax for creating a constant using #define in the C++ is: #define token value
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.
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.
Logical Operators are used to compare and connect two or more expressions or variables, such that the value of the expression is completely dependent on the original expression or value or variable. We use logical operators to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0. Assume variable A holds 1 and variable B holds 0:
A class that inherits another class is known as child class, it is also known as derived class or subclass. What is parent class? The class that is "being inherited" by other class is known as
Operators declared on the type list. Reading a list from input. Writing a list on the output. Gets a list and returns its length. Getting an element and returns its positon in the list. If
Global variables are accessible in full file. But "local variables" are not accessible in full file. And the local variable's scope is between the block of instruction that is defined between
For example reverse of 849 is 948. This code is write using for loop, 'Modulus Operator', if condition statement. User enter any number. 'Receive integer' value from user. Then check
Returns whether n is "prime" or not. Find next prime size of the table. Function To Generate Hash. Function to Initialize Table. Function to "Find Element" at a key. Insert Element into a