While learning any programming language, practicing the language with examples will help you to understand the concepts better.
We have collected the List of Frequently asked questions (FAQ code examples) in C++ programming. the list contain C++ language basic and simple source codes and examples. This list of C++ tutorials with examples can be very useful to learn the basic concepts in C++.
Example 1: C++ Program to Print Hello World
To print Hello, World! in C++ programming, just place Hello, World! inside inverted comma (“”) after cout<< as shown in the program given below:
The question is, write a program in C++ to print Hello, World!. Here is its answer:
1 2 3 4 5 6 7 8 9 10 | #include<iostream> using namespace std; int main() { cout<<"Hello, World!"; cout<<endl; return 0; } |
Example 2: C++ Program to Get Input from User
This C++ program asks from user to enter an integer value or number to receive it and store in a variable say val. Then further displays the entered number on the screen:
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include<iostream> using namespace std; int main() { int val; cout<<"Enter the Number: "; cin>>val; cout<<"\nThe Value is "<<val; cout<<endl; return 0; } |
Example 3: C++ Program to Print an Integer
To print any integer or number on output in C++ programming, just put the variable that holds the value, after cout<< like:
whatever the value of num is, it gets printed on output. Here is the complete program on printing of an integer value along with some string (or message) before it.
1 2 3 4 5 6 7 8 9 10 11 | #include<iostream> using namespace std; int main() { int num=10; cout<<"The Value of 'num' is "<<num; cout<<endl; return 0; } |
Example 4: C++ Program to Add Two Numbers
Let’s first start with very simple program for the addition of two number. The dry run of this program is given just after the output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include<iostream> using namespace std; int main() { int num1, num2, add; cout<<"Enter Two Numbers: "; cin>>num1>>num2; add = num1+num2; cout<<"\nResult = "<<add; cout<<endl; return 0; } |
Example 5: C++ Program to Perform Addition Subtraction Multiplication Division
To perform addition, subtraction, multiplication and division of any two numbers in C++ programming, you have to ask from user to enter the two numbers to perform all the basic mathematical operation such as addition, subtraction, multiplication, and division. And display the result on the screen as shown in the program given below.
The subtraction and division operation goes in a way that, the second number gets subtracted from the first one. Similarly, second number divides the first one. For example, if user enters 20 and 10 as first and second number. Then, the subtraction result will be 10, because 10 (the second number) gets subtracted from 20 (the first number). And the division result will be 2, because 10 divides 20.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include<iostream> using namespace std; int main() { int num1, num2, res; cout<<"Enter Two Numbers: "; cin>>num1>>num2; res = num1+num2; cout<<endl<<"Addition Result = "<<res<<endl; res = num1-num2; cout<<endl<<"Subtraction Result = "<<res<<endl; res = num1*num2; cout<<endl<<"Multiplication Result = "<<res<<endl; res = num1/num2; cout<<endl<<"Division Result = "<<res<<endl; return 0; } |
Example 6: C++ Program to Find Sum of Digits of a Number
To add digits of any number in C++ programming, you have to ask from user to enter the number to add its digits and display the addition result on output screen as shown here in the following program.
Let’s first start while loop. That is, the program given below find and prints the sum of digits of a number using while loop in C++.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include<iostream> using namespace std; int main() { int num, rem, sum=0; cout<<"Enter the Number: "; cin>>num; while(num>0) { rem = num%10; sum = sum+rem; num = num/10; } cout<<"\nSum of Digits = "<<sum; cout<<endl; return 0; } |
The same program is created here using for loop. Unlike while loop, the initialization and update part can also be written under for loop. Therefore, we have initialized the value of sum=0 as first statement of for loop, the second statement is condition checking as done in while loop, and at last, the update part is written as the third statement under for loop. Rest of the things will be same
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include<iostream> using namespace std; int main() { int num, rem, sum; cout<<"Enter the Number: "; cin>>num; for(sum=0; num>0; num=num/10) { rem = num%10; sum = sum+rem; } cout<<"\nSum of Digits = "<<sum; cout<<endl; return 0; } |
Example 7: C++ Program to Calculate Average, Percentage Marks
To find average marks in n number of subjects, just add all the marks and divide it by n. For example, to find average mark with marks obtained in three subjects say 10, 20, 30, then it will be:
1 2 3 4 5 | avg = (10+20+30)/3 = 60/3 = 20 |
To find percentage mark, use following formula:
1 2 3 | perc = ((marks obtained)/(total marks))*100 |
For example, if marks of three subjects are 10, 11, 12 out of 25. That is, the maximum mark is 25. And out of 25, the student got 10, 11, 12 in 3 subjects. Therefore, his/her percentage mark can be calculated as:
1 2 3 4 5 6 | perc = ((10+11+12)/(25*3))*100 = (33/75)*100 = (0.44)*100 = 44 |
To calculate average and percentage marks (in 5 subjects) of a student in C++ programming, you have to ask from user to enter marks obtained in 5 subjects.
Now place the summation result of 5 subject’s mark in a variable say sum and place sum/5 in a variable say avg (average of 5 subjects). Then place sum/500*100 in a variable say perc (percentage marks), then display the result on the screen as shown here in the following program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include<iostream> using namespace std; int main() { int i, mark[5]; float sum=0, avg, perc; cout<<"Enter Marks obtained in 5 Subjects: "; for(i=0; i<5; i++) { cin>>mark[i]; sum = sum+mark[i]; } avg = sum/5; perc = (sum/500)*100; cout<<"\nAverage Marks = "<<avg; cout<<"\nPercentage Marks = "<<perc<<"%"; cout<<endl; return 0; } |
Example 8: C++ Program to Calculate Arithmetic Mean
If there are n set of numbers, therefore to find arithmetic mean, we have a formula:
1 2 3 | am = (n1+n2+n3+...+nn)/n |
Here am indicates arithmetic mean, whereas n1, n2, n3, and nn indicates first, second, third, and last number.
For example, if we have 5 set of numbers say 10, 20, 30, 40, 50, then its arithmetic means can be calculated as:
1 2 3 4 5 | am = (10+20+30+40+50)/5 = 150/5 = 30 |
To calculate (or find) arithmetic mean (of numbers) in C++ programming, you have to ask from user to enter the size (how many set of number), then ask to enter all numbers of that size to find and print arithmetic mean.
To calculate arithmetic mean of numbers, first perform addition of all the numbers, then make a variable responsible for the arithmetic mean and place addition/size in a variable say armean (arithmetic mean), then display the result on the output screen as shown here in the following program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include<iostream> using namespace std; int main() { int n, i; float arr[50], sum=0, armean; cout<<"How many number, You want to enter ? "; cin>>n; cout<<"\nEnter "<<n<<" Number: "; for(i=0; i<n; i++) { cin>>arr[i]; sum = sum+arr[i]; } armean = sum/n; cout<<"\nArithmetic Mean = "<<armean; cout<<endl; return 0; } |
This function does the same job as of previous program. But it is created using function. That is, a function arithmeticMean() takes two arguments, the first one is the array, and second is the size. And returns the arithmetic mean of all numbers stored in the array.
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 | #include<iostream> using namespace std; float arithmeticMean(float [], int); int main() { int n, i; float arr[50], armean; cout<<"Enter the Size (maz. 50): "; cin>>n; cout<<"\nEnter "<<n<<" Numbers: "; for(i=0; i<n; i++) cin>>arr[i]; armean = arithmeticMean(arr, n); cout<<"\nArithmetic Mean = "<<armean; cout<<endl; return 0; } float arithmeticMean(float arr[], int n) { int i; float sum=0, am; for(i=0; i<n; i++) sum = sum+arr[i]; am = sum/n; return am; } |
Example 9: C++ Program to Find and Print Sum of First n Natural Numbers
The question is, write a program in C++ that receives the value of n and print the sum of first n natural numbers. Here is its answer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include<iostream> using namespace std; int main() { int n, natural=1, sum=0; cout<<"Enter the Value of n: "; cin>>n; while(natural<=n) { sum = sum+natural; natural++; } cout<<"\nSum of First "<<n<<" Natural Numbers = "<<sum; cout<<endl; return 0; } |
This program is created using for loop, instead of while.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include<iostream> using namespace std; int main() { int n, natural, sum=0; cout<<"Enter the Value of n: "; cin>>n; for(natural=1; natural<=n; natural++) sum = sum+natural; cout<<"\nSum of First "<<n<<" Natural Numbers = "<<sum; cout<<endl; return 0; } |
This is the last program created using a user-defined function named myfun() that takes an integer say n as its argument, then find and return the sum of first n natural numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include<iostream> using namespace std; int myfun(int); int main() { int n, sum; cout<<"Enter the Value of n: "; cin>>n; sum = myfun(n); cout<<"\nSum of First "<<n<<" Natural Numbers = "<<sum; cout<<endl; return 0; } int myfun(int n) { int natural, sum=0; for(natural=1; natural<=n; natural++) sum += natural; return sum; } |
Example 10: C++ Program to Add n Numbers
To add n numbers in C++ programming, you have to ask from user to enter the value of n (i.e., how many numbers he/she wants to enter), then ask to enter n numbers to perform the addition of all the given numbers and finally display the result on the screen as shown here in the following program.
This program is created using for loop to do the job. The question is, write a program in C++ to find and print the sum of n numbers using for loop. And here is the answer to this question:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include<iostream> using namespace std; int main() { int i, n, num, sum=0; cout<<"How many numbers you want to enter ? "; cin>>n; cout<<"Enter "<<n<<" numbers: "; for(i=0; i<n; i++) { cin>>num; sum = sum+num; } cout<<"\nSum of all "<<n<<" numbers is "<<sum; cout<<endl; return 0; } |
The question is, write a program in C++ that find and prints the sum of n given numbers using while loop. The answer to this question is given below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include<iostream> using namespace std; int main() { int n, i=0, num, sum=0; cout<<"Enter the value of n: "; cin>>n; cout<<"Enter "<<n<<" numbers: "; while(i<n) { cin>>num; sum = sum+num; i++; } cout<<"\nSum = "<<sum; cout<<endl; return 0; } |
Example 11: C++ Program to Find Area, Perimeter of Square
To find area of a square, use following formula:
1 2 3 | area = len*len |
len indicates the length of square. Because all the sides are of equal length in square, therefore get the length of side and square it. That will be the area.
To find perimeter of a square, use following formula:
1 2 3 | perimeter = 4*len |
To calculate area of a square in C++ programming, you have to ask from user to enter the side length of square. With this side length, apply the formula as given above and initialize its value to a variable say area and print its value as output as shown here in the following program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include<iostream> using namespace std; int main() { float len, area; cout<<"Enter the Length of Square: "; cin>>len; area = len*len; cout<<"\nArea = "<<area; cout<<endl; return 0; } |
Example 12: C++ Program to Find Area, Perimeter of Rectangle
The formula to calculate area of a rectangle is given below:
1 2 3 | area = len*bre |
Here, len indicates length and bre indicates breadth of rectangle.
To calculate perimeter of rectangle, use following formula:
1 2 3 | perimeter = 2*(len+bre) |
Here also, len and bre indicates to length and breadth of the rectangle. Now let’s move on to the program.
The question is, write a program in C++ to find and print area of a rectangle. The program given below is the answer of this question:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include<iostream> using namespace std; int main() { float len, bre, area; cout<<"Enter Length of Rectangle: "; cin>>len; cout<<"Enter Breadth of Rectangle: "; cin>>bre; area = len*bre; cout<<"\nArea = "<<area; cout<<endl; return 0; } |
Example 13: C++ Program to Find Area, Perimeter of Triangle
This program finds area of a triangle based on its base and height value. The question is, write a program in C++ to find area of a triangle with base and height entered by user at run-time. Here is its answer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include<iostream> using namespace std; int main() { float b, h, area; cout<<"Enter Base length of Triangle: "; cin>>b; cout<<"Enter Height length of Triangle: "; cin>>h; area = 0.5*b*h; cout<<"\nArea = "<<area; cout<<endl; return 0; } |
Example 14: C++ Program to Find Area, Circumference of Circle
Before starting the program, let’s first get the formula used to find area and circumference of a circle.
To find area of a circle, use this formula:
1 2 3 | area = 3πr2 |
The value of π is 3.14. And r indicates radius of circle. This formula can also be written as:
1 2 3 | area = 3*3.14*r*r |
To calculate area of any circle in C++ programming, you have to ask from user to enter the radius of circle, place the radius in a variable say rad and then initialize 3.14*rad*rad in a variable that holds the value of area of circle, as shown here in the following program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include<iostream> using namespace std; int main() { float rad, area; cout<<"Enter the Radius of Circle: "; cin>>rad; area = 3.14*rad*rad; cout<<"\nArea of Circle = "<<area; cout<<endl; return 0; } |
Example 15: C++ Program to Calculate Simple Interest
The question is, write a program in C++ to find and print simple interest based on the P, R, and T (data) entered by user at run-time. The program given below is the answer to this question:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include<iostream> using namespace std; int main() { float p, r, t, si; cout<<"Enter Principle Amount: "; cin>>p; cout<<"Enter Rate of Interest: "; cin>>r; cout<<"Enter Time Period: "; cin>>t; si = (p*r*t)/100; cout<<"\nSimple Interest Amount: "<<si; cout<<endl; return 0; } |
Example 16: C++ Program to Convert Fahrenheit to Celsius
To convert temperature from Fahrenheit to Celsius in C++ programming, you have to ask from user to enter the temperature in Fahrenheit first. And then convert it into its equivalent value in Celsius with the formula given above.
The question is, write a program in C++ that receives temperature in degree Fahrenheit and prints its equivalent value in degree Celsius.. Here is its answer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include<iostream> using namespace std; int main() { float fahrenheit, celsius; cout<<"Enter the Temperature in Fahrenheit: "; cin>>fahrenheit; celsius = (fahrenheit-32)/1.8; cout<<"\nEquivalent Temperature in Celsius: "<<celsius; cout<<endl; return 0; } |
Example 17: C++ Program to Convert Celsius to Fahrenheit
To convert temperature from Celsius (or centigrade) to Fahrenheit in C++ programming, you have to ask from user to enter the temperature in Celsius. And then convert it into its equivalent value in Fahrenheit using the formula given above, as shown in the program given below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include<iostream> using namespace std; int main() { float celsius, fahrenheit; cout<<"Enter the Temperature in Celsius: "; cin>>celsius; fahrenheit = (celsius*1.8)+32; cout<<"\nEquivalent Temperature in Fahrenheit: "<<fahrenheit; cout<<endl; return 0; } |
Example 18: C++ Program to Print Prime Numbers
This program prints all prime numbers between 1 to 100 using for loop. The question is, write a program in C++ to print prime numbers from 1 to 100. Here is its answer:
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 | #include<iostream> using namespace std; int main() { int i, chk=0, j; cout<<"Prime Numbers Between 1 to 100 are:\n"; for(i=1; i<=100; i++) { for(j=2; j<i; j++) { if(i%j==0) { chk++; break; } } if(chk==0 && i!=1) cout<<i<<endl; chk = 0; } cout<<endl; return 0; } |
Example 19: C++ Program to Reverse a Number
To reverse a number in C++ programming, then you have to ask from user to enter a number. Now find the reverse of that number, and then print its reverse on output as shown in the program given below:
The question is, write a program in C++ to reverse a number. Here is its answer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include<iostream> using namespace std; int main() { int num, rem, rev=0; cout<<"Enter the Number: "; cin>>num; while(num!=0) { rem = num%10; rev = rem + (rev*10); num = num/10; } cout<<"\nReverse = "<<rev; cout<<endl; return 0; } |
Example 20: C++ Program to Swap Two Numbers
To swap two numbers in C++ programming, you have to ask from user to enter the two numbers. The entered two numbers gets stored in two variables say numOne and numTwo. Now swap both numbers using its variable as shown in the program given below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include<iostream> using namespace std; int main() { int numOne, numTwo, temp; cout<<"Enter the First Number: "; cin>>numOne; cout<<"Enter the Second Number: "; cin>>numTwo; cout<<"\nBefore Swap:\n"; cout<<"First Number = "<<numOne<<"\tSecond Number = "<<numTwo; temp = numOne; numOne = numTwo; numTwo = temp; cout<<"\n\nAfter Swap:\n"; cout<<"First Number = "<<numOne<<"\tSecond Number = "<<numTwo; cout<<endl; return 0; } |
Example 21: Program to Make Simple calculator in C++
Write a program and call it calc.cpp which is the basic calculator and receives three values from input via keyboard.
- The first value as an operator (Op1) should be a char type and one of (+, -, *, /, s) characters with the following meanings:
- ‘+’ for addition (num1 + num2)
- ‘-’ for subtraction (num1 – num2)
- ‘*’ for multiplication (num1 * num2)
- ‘/’ for division (num1 / num2)
- ‘s’ for swap
- Program should receive another two operands (Num1, Num2) which could be float or integer.
- The program should apply the first given operator (Op1) into the operands (Num1, Num2) and prints the relevant results with related messages in the screen.
- Swap operator exchanges the content (swap) of two variables, for this task you are not allowed to use any further variables (You should use just two variables to swap).
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 | #include<iostream> #include<cmath> using namespace std; int main() { //-------defining variables and initializing them------------- double num1,num2; char operation,redo; //--------Printing my name on screen---------------- cout<<"Welcome to the calculater program v.1.0 written by Your Name"<<endl; cout<<"***************************************************************"<<endl; cout<<endl<<endl<<endl; //--here do loop is used so that the program can be used more then one time //without exiting the run screen--------------------------- do { //----receiving the variables from input-------------- cout<<" Please enter an operation which you like to calculate (+,-,*,/,s)"; cout<<"[s stands for swap]:"; cin>>operation ; cout<<endl<<endl; cout<<" Please enter two numbers to apply your requested operation("; cout<<operation<<"):"<<endl<<"1st num:"; cin>>num1; cout<<"2nd num:" ; cin>>num2; cout<<endl; //---used switch function so thet the operater can be decided------------ switch (operation) { //------calculating the requested equation for inputs------------- //-------at the same time printing the results on screen----------- case'+': cout<<"The addition of two numbers ("<<num1<<","<<num2<<"):"; cout<<num1+num2<<endl; break; case'-': cout<<"The substraction of two numbers ("<<num1<<","<<num2<<"):"; cout<<num1-num2<<endl; break; case'*': cout<<"The multiplication of two numbers ("<<num1<<","<<num2<<"):"; cout<<num1*num2<<endl; break; case'/': cout<<"The division of two numbers ("<<num1<<","<<num2<<"):"; if(num2==0) { cout<<"not valid"<<endl; } cout<<(num1/num2)<<endl; break; case's': cout<<"The swap of two numbers ("<<num1<<","<<num2<<"):"; swap(num1,num2); cout<<"1stnumber="<<num1<<"and 2nd number="<<num2<<endl<<endl; break; default: cout<<"unknown command"<<endl; } //----now once again the program will ask the user if want to continue or not cout<<"enter y or Y to continue:"; cin>>redo; cout<<endl<<endl; } while(redo=='y'||redo=='Y'); return 0; } |
Example 23: C++ Program to Find LCM and HCF (GCD) of Two Numbers
To find the LCF of two numbers in C++ programming, you have to ask from user to enter the two number. Then find and print its LCM on output as shown in the program given below.
Note – LCM is the Lowest Common Multiple or Least Common Divisor. For example, if there are two numbers say 10 and 12. Then its Least Common Divisor is 60. That is, both numbers 10 and 12 divides 60 without leaving any remainder (or with leaving 0 as remainder).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include<iostream> using namespace std; int main() { intnumOne, numTwo, mp; cout<<"Enter Two Numbers: "; cin>>numOne>>numTwo; if(numOne>numTwo) mp = numOne; else mp = numTwo; while(1) { if((mp%numOne == 0) && (mp%numTwo == 0)) break; else mp++; } cout<<"\nLCM ("<<numOne<<", "<<numTwo<<") = "<<mp; cout<<endl; return 0; } |
Unlike LCM, that deals multiple (lowest common), HCM deals with factor (highest common). HCF can be called as Highest Common Factor, or Greatest Common Factor (GCD).
For example, if there are two numbers say 10 and 12, then its highest common factor is 2. That is, 2 is the highest number that divides both the number. 1 also divides both numbers, but 2 is greater, so 2 is HCF of 10 and 12.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include<iostream> using namespace std; int main() { intnumOne, numTwo, mp; cout<<"Enter Two Numbers: "; cin>>numOne>>numTwo; if(numOne<numTwo) mp = numOne; else mp = numTwo; while(1) { if((numOne%mp == 0) && (numTwo%mp == 0)) break; else mp--; } cout<<"\nHCF ("<<numOne<<", "<<numTwo<<") = "<<mp; cout<<endl; return 0; } |
Example 24: C++ Program to Make Simple Calculator
The program given below creates a simple calculator in C++ programming that performs four basic mathematical operations such as addition, subtraction, multiplicatin, and division, depending on the user’s choice.
To do the task of calculator, first receive the choice and then any two numbers (if choice is not to exit). Then use the switch case to identify the choice and perform required things as shown in the program given below:
The question is, write a calculator program in C++. Here is its answer:
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 | #include<iostream> using namespace std; int main() { float numOne, numTwo, res; int choice; do { cout<<"1. Addition\n"; cout<<"2. Subtraction\n"; cout<<"3. Multiplication\n"; cout<<"4. Division\n"; cout<<"5. Exit\n\n"; cout<<"Enter Your Choice(1-5): "; cin>>choice; if(choice>=1 && choice<=4) { cout<<"\nEnter any two Numbers: "; cin>>numOne>>numTwo; } switch(choice) { case 1: res = numOne+numTwo; cout<<"\nResult = "<<res; break; case 2: res = numOne-numTwo; cout<<"\nResult = "<<res; break; case 3: res = numOne*numTwo; cout<<"\nResult = "<<res; break; case 4: res = numOne/numTwo; cout<<"\nResult = "<<res; break; case 5: return 0; default: cout<<"\nWrong Choice!"; break; } cout<<"\n------------------------\n"; }while(choice!=5); cout<<endl; return 0; } |
Example 25: C++ Program to Count Total Digits in a Number
The question is, write a C++ program that receives a number from user to count and print the total number of digits available in that given number. Here is the answer to this question:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include<iostream> using namespace std; int main() { int num, tot=0; cout<<"Enter the Number: "; cin>>num; while(num>0) { tot++; num = num/10; } cout<<"\nTotal Digits = "<<tot; cout<<endl; return 0; } |
Example 26: C++ Program to Find Sum of First and Last Digit of a Number
The question is, write a program in C++ that receives a number from user as input and print the sum of first and last digit of given number as output. Here is its answer:
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 | #include<iostream> using namespace std; int main() { int num, temp=0, last, rem, sum=0; cout<<"Enter a Number: "; cin>>num; while(num!=0) { if(temp==0) { last = num%10; temp++; } rem = num%10; num = num/10; } sum = rem + last; cout<<"\nSum of First ("<<rem<<") and Last ("<<last<<") Digit = "<<sum; cout<<endl; return 0; } |
Since for loop also contains initialize and update statements along with condition checking. Therefore, just place any initialization say temp=0 or sum=0 and the update statement as num = num/10 like shown in the program given below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include<iostream> using namespace std; int main() { int num, temp, last, rem, sum=0; cout<<"Enter a Number: "; cin>>num; for(temp=0; num!=0; num=num/10) { if(temp==0) { last = num%10; temp++; } rem = num%10; } sum = rem + last; cout<<"\nSum of First ("<<rem<<") and Last ("<<last<<") Digit = "<<sum; cout<<endl; return 0; } |
Example 27: C++ Program to Find and Print Product of Digits of a Number
The question is, write a C++ program that receives a number from user and print the product or multiplication of its digit. The program given below is its answer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include<iostream> using namespace std; int main() { int num, rem, prod=1; cout<<"Enter a Number: "; cin>>num; while(num>0) { rem = num%10; prod = prod*rem; num = num/10; } cout<<"\nProduct of all digits of given number is: "<<prod; cout<<endl; return 0; } |
Example 28: C Program to show Fibonacci Series
Write a C program , that prints all the Fibonacci numbers , which are smaller than or equal to a number k(k≥2) ,which was entered by the user.
- The Fibonacci numbers are a sequence of numbers,where then-th number of Fibonacci is defined as:
- Fib(0)=0,
- Fib(1)=1,
- Fib(n)=Fib(n-1)+Fib(n-2) Usage :> Input of k:21 > Fibonacci numbers<=21:01123581321
Solution 1 –
The solution below will answer following questions :
1. Write a program to generate the Fibonacci series in C.
2. Fibonacci series in C using for loop.
3. How to print Fibonacci series in C.
4. Write a program to print Fibonacci series inC.
5. How to find Fibonacci series in C programming.
6. Basic C programs Fibonacci series.
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 | #include <stdio.h> #include <stdlib.h> int main () { int r=0,a=0,n,b=1,i,c; char redo; do { a=0; b=1; printf("enter the the value of n:"); scanf("%d", &n); if(n>100) { printf("enter some lessor value\n"); } else { for (i=0;i<=n;i++) { c=a+b; a=b; b=c; printf("serial no.%d => ", i+1); printf("%d\n",a); } printf("enter y or Y to continue:"); scanf("%s", &redo); printf("\n"); } } while(redo=='y'||redo=='Y'); return 0; } |
Solution 2 –
If we want to Write a program to generate the Fibonacci series in C using recursion, the follow the solution below :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <stdio.h> #include <stdlib.h> int Fibonacci(int x) { if (x < 2){ return x; } return (Fibonacci (x - 1) + Fibonacci (x - 2)); } int main(void) { int number; printf( "Please enter a positive integer: "); scanf("%d", &number); if (number < 0) printf( "That is not a positive integer.\n"); else printf("%d Fibonacci is: %d\n", number, Fibonacci(number)); return 0; } |
Solution 3 –
The solution below will answer following questions :
1. Fibonacci series using array in C
2. Fibonacci series program in C language
3. Source code of Fibonacci series inC
4.Write a program to print Fibonacci series in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <stdio.h> #include <stdlib.h> int main(void) { int i,number; long int arr[40]; printf( "Enter the number : \n"); scanf("%d", &number); arr[0]=0; arr[1]=1; for(i = 2; i< number ; i++){ arr[i] = arr[i-1] + arr[i-2]; } printf("Fibonacci series is: \n"); for(i=0; i< number; i++) printf("%d\n", arr[i]); return 0; } |
Example 29: C++ Program to Find Sum of Squares of Digits of a Number
For example, if given number is 32041, then the result will be calculate as:
1 2 3 4 5 | 32041 = 32 + 22 + 02 + 42 + 12 = 9 + 4 + 1 + 16 + 1 = 31 |
The question is, write a C++ program that receives a number from user to find and print the sum of squares of its digits. The program given below is its answer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include<iostream> using namespace std; int main() { int num, rem, sq, sum=0; cout<<"Enter a Number: "; cin>>num; while(num>0) { rem = num%10; if(rem==0) sq = 1; else sq = rem*rem; sum = sum + sq; num = num/10; } cout<<"\nSum of squares of all digits = "<<sum; cout<<endl; return 0; } |
Example 30: C++ Program to Interchange the Digits of a Number
To interchange first and last digit of a number in C++ programming, you have to ask from user to enter the number. And then interchange its first and last digit as shown in the program given below:
The question is, write a program in C++ to interchange first and last digit of a number. Here is its answer:
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 | #include<iostream> using namespace std; int main() { int num, rem, temp, rev=0, noOfDigit=0; int noOfDigitTemp, revNum, remTemp; cout<<"Enter the Number: "; cin>>num; temp = num; while(temp>0) { temp = temp/10; noOfDigit++; } if(noOfDigit<2) { cout<<"\nIt is a Single-digit Number!"; cout<<"\nTry again with a Number with Two or More Digits!"; } else if(noOfDigit==2) { temp = num; while(temp>0) { rem = temp%10; rev = (rev*10)+rem; temp = temp/10; } cout<<"\nFirst and Last Digit Interchanged Successfully!"; cout<<"\n\nNew Number = "<<rev; } else { temp = num; while(temp>0) { rem = temp%10; rev = (rev*10)+rem; temp = temp/10; } revNum = rev; rev = 0; temp = num; noOfDigitTemp = noOfDigit; while(temp>0) { remTemp = revNum%10; if(noOfDigitTemp==noOfDigit) { rem = temp%10; rev = (rev*10)+rem; } else if(noOfDigitTemp==1) { rem = temp%10; rev = (rev*10)+rem; } else { rev = (rev*10)+remTemp; } temp = temp/10; revNum = revNum/10; noOfDigitTemp--; } cout<<"\nFirst and Last Digit Interchanged Successfully!"; cout<<"\n\nNew Number = "<<rev; } cout<<endl; return 0; } |
Example 31: C++ program to find Square Root of a Number
In this Example we will learn how to find the square root of a given number using C++.
In the first example we are going to use std::pow function to calculate the square root.
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <iostream> #include <cmath> using namespace std; int main() { int number, result; cout <<"Enter any number: "; cin >> number; result = pow(number, 0.5); cout<<"\nSqure of "<<number<<" is: " << result << endl; } |
Now In the next example we will learn how to find the square root of a given number using std::sqrt function.
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <iostream> #include <cmath> using namespace std; int main() { int number,result; cout << "Enter any numberber: "; cin >> number; result = sqrt(number); cout<<"\nSqure of " << number << " is: " <<result; } |
Example 32: C++ Program to Find Cube Root of Number
In this example we will learn C++ Program to Find Cube Root of Number.
In the first example we will use std::pow function to find the cube root of a given number.
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <iostream> #include <cmath> using namespace std; int main() { int number, result; cout << "Enter any number : "; cin >> number; result = pow(number, 1.0/3.0); cout << "\n\Cube root of " << number << " is: " << result; } |
In the next example we will use std::cbrt function to find the cube root of a given number.
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <iostream> #include <cmath> using namespace std; int main() { int number, result; cout << "Enter any number: "; cin >> number; result = cbrt(number);; cout << "\n Cube Root of "<< number <<" is: " <<result; } |
Example 33: C++ program to find ASCII Code for Characters and numbers
C++ Program Write a Program to Enter Char or Number and Check its ASCII Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include <iostream> using namespace std; int main(){ char ascii; int numeric; cout << "Give character: "; cin >> ascii; cout << "Its ascii value is: " << (int) ascii << endl; cout << "Give a number to convert to ascii: "; cin >> numeric; cout << "The ascii value of " << numeric << " is " << (char) numeric; return 0; } |
Example 34: C Program to show Fibonacci Series
Write a C program , that prints all the Fibonacci numbers , which are smaller than or equal to a number k(k≥2) ,which was entered by the user.
- The Fibonacci numbers are a sequence of numbers,where then-th number of Fibonacci is defined as:
- Fib(0)=0,
- Fib(1)=1,
- Fib(n)=Fib(n-1)+Fib(n-2) Usage :> Input of k:21 > Fibonacci numbers<=21:01123581321
Solution 1 –
The solution below will answer following questions :
1. Write a program to generate the Fibonacci series in C.
2. Fibonacci series in C using for loop.
3. How to print Fibonacci series in C.
4. Write a program to print Fibonacci series inC.
5. How to find Fibonacci series in C programming.
6. Basic C programs Fibonacci series.
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 | #include <stdio.h> #include <stdlib.h> int main () { int r=0,a=0,n,b=1,i,c; char redo; do { a=0; b=1; printf("enter the the value of n:"); scanf("%d", &n); if(n>100) { printf("enter some lessor value\n"); } else { for (i=0;i<=n;i++) { c=a+b; a=b; b=c; printf("serial no.%d => ", i+1); printf("%d\n",a); } printf("enter y or Y to continue:"); scanf("%s", &redo); printf("\n"); } } while(redo=='y'||redo=='Y'); return 0; } |
Solution 2 –
If we want to Write a program to generate the Fibonacci series in C using recursion, the follow the solution below :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <stdio.h> #include <stdlib.h> int Fibonacci(int x) { if (x < 2){ return x; } return (Fibonacci (x - 1) + Fibonacci (x - 2)); } int main(void) { int number; printf( "Please enter a positive integer: "); scanf("%d", &number); if (number < 0) printf( "That is not a positive integer.\n"); else printf("%d Fibonacci is: %d\n", number, Fibonacci(number)); return 0; } |
Solution 3 – The solution below will answer following questions : 1. Fibonacci series using array in C 2. Fibonacci series program in C language 3. Source code of Fibonacci series inC 4.Write a program to print Fibonacci series in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <stdio.h> #include <stdlib.h> int main(void) { int i,number; long int arr[40]; printf( "Enter the number : \n"); scanf("%d", &number); arr[0]=0; arr[1]=1; for(i = 2; i< number ; i++){ arr[i] = arr[i-1] + arr[i-2]; } printf("Fibonacci series is: \n"); for(i=0; i< number; i++) printf("%d\n", arr[i]); return 0; } |
Example 36: C++ Program to Check Palindrome Number
In this example we will learn how to Check if the particular number is Palindrome or not.
C++ – PALINDROMIC NUMBERS Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include<stdio.h> #include <iostream> using namespace std; int main(){ int num,r,sum=0,temp; cout << "Enter a number: "; cin >> num; for(temp=num;num!=0;num=num/10){ r=num%10; sum=sum*10+r; } if(temp==sum) cout << temp << " is a palindrome"; else cout << temp << " is not a palindrome"; return 0; } |
Example 37: C++ Program for random number generator
Random number generator using C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include<iostream> #include<time.h> #include<stdlib.h> #define MAX_NUM 10 using namespace std; void randnum() { int random; srand(time(NULL)); for(int i=0;i<10;i++) { random=rand()%MAX_NUM; cout<<random<<endl; } } int main() { cout<<"The ten random number are "<<endl; randnum(); return 0; } |
Example 38: C++ Examples – Bubble sort in C++ code example
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 | #include<iostream> using namespace std; int main(){ //declaring array int array[5]; cout<<"Enter 5 numbers randomly : "<<endl; for(int i=0; i<5; i++) { //Taking input in array cin>>array[i]; } cout<<endl; cout<<"Input array is: "<<endl; for(int j=0; j<5; j++) { //Displaying Array cout<<"\t\t\tValue at "<<j<<" Index: "<<array[j]<<endl; } cout<<endl; // Bubble Sort Starts Here int temp; for(int i2=0; i2<=4; i2++) { for(int j=0; j<4; j++) { //Swapping element in if statement if(array[j]>array[j+1]) { temp=array[j]; array[j]=array[j+1]; array[j+1]=temp; } } } // Displaying Sorted array cout<<" Sorted Array is: "<<endl; for(int i3=0; i3<5; i3++) { cout<<"\t\t\tValue at "<<i3<<" Index: "<<array[i3]<<endl; } return 0; } |
Example 39: C++ Program to Check Leap Year
In the Julian Calendar, Leap Year (LY) occurs every year divisible by 4. Normally February has 28 days but in a leap year February has 29 days.
In this lesson we will learn how to write a C++ program to check if the giver year is leap year or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> using namespace std; int main() { int year; cout<<"Enter a year: "<< endl; cin>> year; if((year % 4) ==0) { cout<<" Leap Year "; } else { cout <<" Not a Leap Year" << endl; } return 0; } |
Example 40: C++ program for Calculation of the surface Area and volume of cone
Write a program that calculates the volume of a solid cone.The formula is: volume=(PI x radius² x height)/3
Read in the values for the parameters height and radius(as floating point numbers).
Then the program should calculate the volume considering the following restriction :radius and height must be greater than0
If the user types in a correct value for one of the variables ,the program should print out an error message and quit.Otherwise,it displays the result.
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 | #include<iostream> #include<cmath> using namespace std; int main() { double r,h,a; cout<<"enter the radius="<<endl; cin>>r; cout<<"enter the hight="<<endl; cin>>h; if (r==0 || h==0) { cout<<"invalid operation"<<endl; } if(r!=0 && h!=0) { a=(3.14*r*r*h)/3; cout<<"the area="<<a<<endl; } system("pause"); return 0; } |
Example 41: Write a C++ program to Solve Quadratic equation
Write a program that calculates the real solution of the quadratic equation ax²+bx+c=0
Read in the values for the parameters a,b,c(type float).
Then the program should calculate the solution considering the following circumstances:
a=0andb=0=>Not a valid equation
a=0 and b≠0 => x=-c/b
b² -4ac < 0 => Not a Real Solution
b² -4ac >0 => x1= (-b+√(b² -4ac))/2a , x1= (-b -√(b² -4ac))/2a
Hint:The c++ function for √x is sqrt(x).
To use this function you need to includemath.has a header file#include<math.h>
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 | #include<iostream> #include<cmath> #include<cstdlib> #include<cstring> using namespace std; int main() { double a,b,c,x1,x2; char x; cout<<"enter the value of a="; cin>>a; cout<<"enter the value of b="; cin>>b; cout<<"enter the value of c="; cin>>c; cout<<"the quadratic equation is"<<a; cout<<"*x*x+"<<b; cout<<"*x+"<<c<<endl; if (a==0 && b==0) cout<<"not a valid equation"; if (a==0 && b!=0) { x1=-(c/b); cout<<endl; cout<<"root="<<x1; cout<<endl; } if ((b*b-4*a*c)>0) { x2=(b*b)-(4*a*c); x1=-b+sqrt(x2); cout<<"root="<<x1<<endl; } if ((b*b-4*a*c)<0) { cout<<"not a real root"<<endl; } system("pause"); return 0; } |
Example 42: C++ Program to find the Factorial using recursive function
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 | #include<iostream> using namespace std; int Factorial(int n){ static int i=1;// to make one time initialization cout<<i<<" : time"<<endl; // counting the function calls if(n==1){ return 1;//base case } else{ i++; return n=n*Factorial(n-1); } } int main(){ cout<<"Enter to number to find Factorial: "; int num; cin>>num; num=Factorial(num); // function call cout<<"\nFactorial of number is: "<<num << endl; return 0; } |
Example 43: C++ program to convert a string into upper-case or lower-case
Here we will learn c++ program in order to convert a string into upper case or lower case.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | # include < iostream> # include < string> using namespace std; int main() { char str1 [30], temp[30]; cout < < "Enter the string:"; cin > > str1; strcpy ( temp, str1); cout < < "strupr ( temp ) : " < < strupr (temp) < < end1; cout < < "strlwr (temp) : " < < strlwr ( temp) < < end1; system("pause"); return 0; } |
Example 44: C++ program to concatenate strings
Here we will learn how to write a program to Concatenate strings.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | # include < iostream> # include < string > using namespace std; int main() { char str1[50], str2 [35]; cout << "Enter string str1;"; cin >> str1; cout << "Enter string str2:"; cin >> str2; strcat(str1,str2); cout << "strcat (str1, str2 ) : "<< str1; system("pause"); return 0; } |
Example 45: Write a C++ program to 1. Initialize Matrices 2. Print Matrices 3. Multiply Matrices 4. Transpose of 2nd Matrix 5. Move Row and Column of 2nd Matrix 6. Quit
Write a program that shows a menu such as figure 2.1 and does the following described tasks for entered number between 1 and 6.
The instruction menu:1. Initialize Matrices2. Print Matrices3. Multiply Matrices4. Transpose of 2nd Matrix5. Move Row and Column of 2nd Matrix6. QuitPlease enter your requested instruction (1..6)?Note that to do the specific task related to each menu user should press relevant number. (e.g. ‘2’ for print task or ‘4’ for transpose operation). The description of tasks is as follows:
1. Initialize:In this step, your program should get dimensions for two matrices from input and initials these matrices randomly based on the entered dimensions. Note that your program should initialize matrices with different numbers in each time of execution. The first matrix should be square matrix. A square matrix is a matrix with the same number of rows and columns. Note that user can re-initialize matrices (and of course dimensions) by using the first command during the executionPlease enter the number of rows and columns for the first square matrix? 3Please enter the number of rows for the second matrix? 4Please enter the number of columns for the second matrix? 6
2. Print:In this step, your program should print the content of two matrices in the screen as showed in the figure 2.3. The “Print” operation could be requested after each step to see the changes which have been made during the execution of different instructions. It means that you do not need to show the results of each operation in the screen, user has to request instruction number ‘2’ to see the actual content of matrices.Content of the first Matrix (3*3):1 3 59 7 898 6 51Content of the second Matrix (4*6):34 73 83 23 98 2081 92 68 28 34 76-65 78 -12 67 1 12389 -61 67 43 17 843. Multiplication:In this step, your program should multiplies two matrices A and B (C=A*B).
4. Transpose:In this step, your program should calculate transpose of the second matrix. Wikipediadefined transpose of a matrix as follows:“In linear algebra, the transpose of a matrix A is another matrix AT created by any one of thefollowing equivalent actions: reflect A over its main diagonal (which runs top-left to bottom-right) to obtain AT write the rows of A as the columns of AT write the columns of A as the rows of AT visually rotate A 90 degrees clockwise, and mirror the image in a vertical line toobtain ATFormally, the (i,j) element of AT is the (j,i) element of A. [AT]ij = [A]jiIf A is an m × n matrix then AT is an n × m matrix.”
5. Move row and column:In this step, your program should get two numbers (m, n) and first movesthe row number m of the second matrix to the end of the matrix and then moves the columnnumber n of the matrix to the end of the matrix
6. Quit:In this step, the execution should be ended. Note that your program shouldn’t be finished inother steps. It means that user can request multiple executions of different steps before requesting the “Quit” operation.
Points:User needs to initiate matrices at least once by requesting step ‘1’ at the beginning of an execution.Therefore you should prevent the user for requesting other steps before step ‘1’ just once at thebeginning of an execution.
Solution-
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 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 | #include<iostream> #include<cmath> using namespace std; void swapcol(int a[50][50], int r, int c, int b); void swaprow(int a[50][50], int r, int c,int b); int swapmx(int arr[50][50],int m,int n,int a ,int b ); void arrey(int arr1[50][50],int arr2[50][50], int sizemx1, int p,int q); int main() { //-------defining variables and initializing them------------- int e,flag=0,i,j,flag1=0; int arrey1[50][50],arrey2[50][50],arrey3[50][50],arrey4[50][50],arrey5[50][50],arrey6[50][50],arrey7[50][50],arrey8[50][50]; int k,sizemx1,p,q,r,x,y,temp=0; int m, n,a,b,l; char operation,redo; //--------Printing my name on screen---------------- cout<<"Welcome to the program 2.1 written by Your Name"<<endl; cout<<"***************************************************************"<<endl; cout<<endl<<endl<<endl; cout<<"The instruction menu:"<<endl<<endl<<endl; cout<<" 1. Initialize Matrices"<<endl; cout<<" 2. Print Matrices"<<endl; cout<<" 3. Multiply Matrices"<<endl; cout<<" 4. Transpose of 2nd Matrix"<<endl; cout<<" 5. Move Row and Column of 2nd Matrix"<<endl; cout<<" 6. Quit"<<endl<<endl; //--here do loop is used so that the program can be used more then one time //without exiting the run screen--------------------------- do { do { cout<<"Please enter your requested instruction (1..6)?= "; while(!(cin>>operation)) //Reciving vaiables from input : is it no/character ? { cout << "Please enter a number! Try again: "; cin.clear (); cin.ignore (1000, '\n'); // Skip to next newline or 1000 chars, // whichever comes first. } //cin>>operation ; cout<<endl; //---used switch function so thet the operater can be decided------------ switch (operation) { //------calculating the requested equation for inputs------------- //-------at the same time printing the results on screen----------- case'1': cout<<"Enter the Size of 1st square Matrix"<<endl; cout<<"Row & Column="; while(!(cin>>sizemx1)) //Reciving vaiables from input : is it no/character ? { cout << "Please enter a number! Try again: "; cin.clear (); cin.ignore (1000, '\n'); // Skip to next newline or 1000 chars, // whichever comes first. } //cin>>sizemx1; if (sizeof(sizemx1)<4){ cout<<"unknown command"<<endl; } cout<<"Enter the of 2nd Matrix"<<endl; cout<<"Row="; while(!(cin>>p)) //Reciving vaiables from input : is it no/character ? { cout << "Please enter a number! Try again: "; cin.clear (); cin.ignore (1000, '\n'); // Skip to next newline or 1000 chars, // whichever comes first. } //cin>>p; cout<<"Column="; while(!(cin>>q)) //Reciving vaiables from input : is it no/character ? { cout << "Please enter a number! Try again: "; cin.clear (); cin.ignore (1000, '\n'); // Skip to next newline or 1000 chars, // whichever comes first. } //cin>>q; flag=flag+1; //cout<<"flag="<<flag<<endl; break; case'2': //2. Print Matrices //cout<<"flag="<<flag<<endl; //cout<<"flag1="<<flag1<<endl; if(flag<1){ cout<<"flag="<<flag<<endl; cout<<"Please perforform operation no.1 firest"<<endl; } if(flag>=1){ cout<<"flag="<<flag<<endl; // arrey( arrey1,arrey2, sizemx1, p,q); /*cout<<"Enter the elements in the 1st Array"<<endl; for(i=0;i<sizemx1;i++) { for(j=0;j<sizemx1;j++) { cin>>arrey1[i][j]; } } cout<<"Enter the elements in the 2nd Array"<<endl; for(i=0;i<p;i++) { for(j=0;j<q;j++) { cin>>arrey2[i][j]; } }*/ cout<<"\nDisplaying the 1st Array"<<endl; for(i=0;i<sizemx1;i++) { for(j=0;j<sizemx1;j++) { arrey1[i][j] = 50+rand() %(100-50+1); cout<<arrey1[i][j]<<"\t"; } cout<<endl; } cout<<"\nDisplaying the 2nd Array"<<endl; for(i=0;i<p;i++) { for(j=0;j<q;j++) { arrey2[i][j] = 50+rand() %(100-50+1); cout<<arrey2[i][j]<<"\t"; } cout<<endl; } flag1=flag1+1; } arrey2[10][10]=arrey4[10][10]; for(i=0;i<p;i++) { for(j=0;j<q;j++) { arrey5[i][j]=arrey2[i][j]; arrey6[i][j]=arrey2[i][j]; } } break; case'3': //3. Multiply Matrices //cout<<"flag1="<<flag1<<endl; if(flag1<1){ cout<<"Please perforform operation no.1 and no.2 firest"<<endl; }else{ if(sizemx1!=p){ cout<<"Multiplication is not possible"<<endl; } if(sizemx1==p) { for(i=0;i<sizemx1;i++) { for(j=0;j<q;j++) { arrey3[i][j]=0; for(k=0;k<p;k++) { arrey3[i][j]=arrey3[i][j]+arrey1[i][k]*arrey2[k][j]; } } } cout<<"\nDisplaying the array elements after multiplication"<<endl; for(i=0;i<sizemx1;i++) { for(j=0;j<q;j++) { cout<<arrey3[i][j]<<"\t"; } cout<<endl; } } } break; case'4': //4. Transpose of 2nd Matrix if(flag1<1){ cout<<"Please perforform operation no.1 and no.2 firest"<<endl; } else{ for(i=0;i<p;i++) { for(j=0;j<q;j++) { arrey7[i][j]=arrey6[i][j]; } } cout<<"\nDisplaying trannspose the 2nd Matrix"<<endl; for(i=0;i<=q-1;i++) { for(j=0;j<=p-1;j++) { temp=arrey7[j][i]; arrey7[j][i]=arrey4[i][j]; arrey4[i][j]=temp; //cout<<i<<j; cout<<temp<<"\t"; } cout<<endl; } } break; case'5': //5. Move Row and Column of 2nd Matrix if(flag1<1){ cout<<"Please perforform operation no.1 and no.2 firest"<<endl; } else{ cout <<"enter the row number you want to swap:"<<endl; // cin>>x>>y; while(!(cin>>x)) //Reciving vaiables from input : is it no/character ? { cout << "Please enter a number! Try again: "; cin.clear (); cin.ignore (1000, '\n'); // Skip to next newline or 1000 chars, // whichever comes first. } cout<<endl; cout <<"enter the column number you want to swap:"<<endl; while(!(cin>>y)) //Reciving vaiables from input : is it no/character ? { cout << "Please enter a number! Try again: "; cin.clear (); cin.ignore (1000, '\n'); // Skip to next newline or 1000 chars, // whichever comes first. } cout<<endl; for(i=0;i<p;i++) { for(j=0;j<q;j++) { arrey8[i][j]=arrey5[i][j]; } } cout<<"The original matrix is"<<endl; cout<< endl; for(i=0;i<p;i++) { for(j=0;j<q;j++) { cout<<arrey8[i][j]<<"\t"; } cout<< endl; } swapmx(arrey8,p,q,x,y); cout<< endl; } break; case'6': // 6. Quit cout<<"Thanks do u want to start again:"; cout<<endl<<endl; goto label; break; default: cout<<"unknown command"<<endl; } } while(operation=='1'||operation=='2'||operation=='3'||operation=='4'||operation=='5'||operation=='6'); //----now once again the program will ask the user if want to continue or not cout<<"enter y or Y to continue:"; cin>>redo; cout<<endl<<endl; } while(redo=='y'||redo=='Y'); label: system("pause"); return 0; } void arrey(int arr1[50][50],int arr2[50][50], int sizemx1, int p,int q) { cout<<"Enter the elements in the 1st Array"<<endl; for(int i=0;i<sizemx1;i++) { for(int j=0;j<sizemx1;j++) { //cin>>arr1[i][j]; while(!(cin>>arr1[i][j])) //Reciving vaiables from input : is it no/character ? { cout << "Please enter a number! Try again: "; cin.clear (); cin.ignore (1000, '\n'); // Skip to next newline or 1000 chars, // whichever comes first. } } } cout<<"Enter the elements in the 2nd Array"<<endl; for(int i=0;i<p;i++) { for(int j=0;j<q;j++) { //cin>>arr2[i][j]; while(!(cin>>arr2[i][j])) //Reciving vaiables from input : is it no/character ? { cout << "Please enter a number! Try again: "; cin.clear (); cin.ignore (1000, '\n'); // Skip to next newline or 1000 chars, // whichever comes first. } } } } void swapcol(int a[50][50], int r, int c,int b) // r -> row, c ->col { int t,s; while(b < (c-1)) { for(int i=0; i<r; i++) { t = a[i][b]; a[i][b] = a[i][b+1]; a[i][b+1] = t; } b++; } } void swaprow(int a[50][50], int r, int c,int b) // r -> row, c ->col { int t; while(b < (r-1)) { for(int i=0; i<c; i++) { t = a[b][i]; a[b][i] = a[b+1][i]; a[b+1][i] = t; } b++; } /*for(int i = 0; i< c ; i++) { t = a[b-1][i]; a[b-1][i] = a[r-1][i]; a[r-1][i] = t; }*/ } int swapmx(int arr[50][50],int m,int n,int a ,int b ) { int i, j,k,l; //for( l = 0; l <=a-1; l ++){ /* Swap function call */ cout<<"The matrix after shifting row"<<endl; swaprow(arr, m, n, a-1); for( i = 0; i < m ; i ++) { cout<< endl; for ( j = 0; j < n ; j ++) cout << arr[i][j] <<"\t"; } cout<< endl; cout<< endl; //} cout<<endl<<endl; cout<<"The matrix after shifting column"<<endl; //for( k = 0; k <=b ; k ++){ swapcol(arr, m, n, b-1); //cout<<"k="<<k<<endl; /* Display Array in Matrix form */ //} for( i = 0; i < m ; i ++) { cout<< endl; for ( j = 0; j < n ; j ++) cout << arr[i][j] <<"\t"; } cout<< endl; return 1; } |
Source:
[…] You may also like this: C++ Program Examples […]