Welcome To StudyDoc Ltd.
StudyDoc


C++ Program's

1
Hello World
#include using namespace std; int main() { cout << "Hello World"; return 0; }
2
Print Number Entered by User
Print Number Entered by User #include using namespace std; int main() { int number; cout << "Enter an integer: "; cin >> number; cout << "You entered " << number; return 0; }
3
Add Two Integers
#include using namespace std; int main() { int first_number, second_number, sum; cout << "Enter two integers: "; cin >> first_number >> second_number; // sum of two numbers in stored in variable sumOfTwoNumbers sum = first_number + second_number; // prints sum cout << first_number << " + " << second_number << " = " << sum; return 0; }
4
Compute quotient and remainder
#include using namespace std; int main() { int divisor, dividend, quotient, remainder; cout << "Enter dividend: "; cin >> dividend; cout << "Enter divisor: "; cin >> divisor; quotient = dividend / divisor; remainder = dividend % divisor; cout << "Quotient = " << quotient << endl; cout << "Remainder = " << remainder; return 0; }
5
Find Size of a Variable
Find Size of a Variable #include using namespace std; int main() { cout << "Size of char: " << sizeof(char) << " byte" << endl; cout << "Size of int: " << sizeof(int) << " bytes" << endl; cout << "Size of float: " << sizeof(float) << " bytes" << endl; cout << "Size of double: " << sizeof(double) << " bytes" << endl; return 0; }
6
Swap Numbers
Swap Numbers (Using Temporary Variable) #include using namespace std; int main() { int a = 5, b = 10, temp; cout << "Before swapping." << endl; cout << "a = " << a << ", b = " << b << endl; temp = a; a = b; b = temp; cout << "\nAfter swapping." << endl; cout << "a = " << a << ", b = " << b << endl; return 0; }
7
Print ASCII Value
Print ASCII Value in C++ #include using namespace std; int main() { char c; cout << "Enter a character: "; cin >> c; cout << "ASCII Value of " << c << " is " << int(c); return 0; }
8
Multiply Two Numbers
#include using namespace std; int main() { double num1, num2, product; cout << "Enter two numbers: "; // stores two floating point numbers in num1 and num2 respectively cin >> num1 >> num2; // performs multiplication and stores the result in product variable product = num1 * num2; cout << "Product = " << product; return 0; }
9
Even or Odd
#include using namespace std; int main() { int n; cout << "Enter an integer: "; cin >> n; if ( n % 2 == 0) cout << n << " is even."; else cout << n << " is odd."; return 0; }
10
Vowel or a Consonant Manually
Vowel or a Consonant Manually #include using namespace std; int main() { char c; bool isLowercaseVowel, isUppercaseVowel; cout << "Enter an alphabet: "; cin >> c; // evaluates to 1 (true) if c is a lowercase vowel isLowercaseVowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); // evaluates to 1 (true) if c is an uppercase vowel isUppercaseVowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'); // show error message if c is not an alphabet if (!isalpha(c)) printf("Error! Non-alphabetic character."); else if (isLowercaseVowel || isUppercaseVowel) cout << c << " is a vowel."; else cout << c << " is a consonant."; return 0; }
11
Largest number
#include using namespace std; int main() { double n1, n2, n3; cout << "Enter three numbers: "; cin >> n1 >> n2 >> n3; // check if n1 is the largest number if(n1 >= n2 && n1 >= n3) cout << "Largest number: " << n1; // check if n2 is the largest number else if(n2 >= n1 && n2 >= n3) cout << "Largest number: " << n2; // if neither n1 nor n2 are the largest, n3 is the largest else cout << "Largest number: " << n3; return 0; }
12
Roots of a Quadratic Equation
#include #include using namespace std; int main() { float a, b, c, x1, x2, discriminant, realPart, imaginaryPart; cout << "Enter coefficients a, b and c: "; cin >> a >> b >> c; discriminant = b*b - 4*a*c; if (discriminant > 0) { x1 = (-b + sqrt(discriminant)) / (2*a); x2 = (-b - sqrt(discriminant)) / (2*a); cout << "Roots are real and different." << endl; cout << "x1 = " << x1 << endl; cout << "x2 = " << x2 << endl; } else if (discriminant == 0) { cout << "Roots are real and same." << endl; x1 = -b/(2*a); cout << "x1 = x2 =" << x1 << endl; } else { realPart = -b/(2*a); imaginaryPart =sqrt(-discriminant)/(2*a); cout << "Roots are complex and different." << endl; cout << "x1 = " << realPart << "+" << imaginaryPart << "i" << endl; cout << "x2 = " << realPart << "-" << imaginaryPart << "i" << endl; } return 0; }
13
Sum of Natural Numbers
Sum of Natural Numbers using loop #include using namespace std; int main() { int n, sum = 0; cout << "Enter a positive integer: "; cin >> n; for (int i = 1; i <= n; ++i) { sum += i; } cout << "Sum = " << sum; return 0; }
14
Leap Year
#include using namespace std; int main() { int year; cout << "Enter a year: "; cin >> year; // leap year if perfectly divisible by 400 if (year % 400 == 0) { cout << year << " is a leap year."; } // not a leap year if divisible by 100 // but not divisible by 400 else if (year % 100 == 0) { cout << year << " is not a leap year."; } // leap year if not divisible by 100 // but divisible by 4 else if (year % 4 == 0) { cout << year << " is a leap year."; } // all other years are not leap years else { cout << year << " is not a leap year."; } return 0; }
15
Factorial of a Given Number
#include using namespace std; int main() { int n; long factorial = 1.0; cout << "Enter a positive integer: "; cin >> n; if (n < 0) cout << "Error! Factorial of a negative number doesn't exist."; else { for(int i = 1; i <= n; ++i) { factorial *= i; } cout << "Factorial of " << n << " = " << factorial; } return 0; }
16
Multiplication Table
#include using namespace std; int main() { int n; cout << "Enter a positive integer: "; cin >> n; // run a loop from 1 to 10 // print the multiplication table for (int i = 1; i <= 10; ++i) { cout << n << " * " << i << " = " << n * i << endl; } return 0; }
17
Fibonacci Series up to n number of terms
#include using namespace std; int main() { int n, t1 = 0, t2 = 1, nextTerm = 0; cout << "Enter the number of terms: "; cin >> n; cout << "Fibonacci Series: "; for (int i = 1; i <= n; ++i) { // Prints the first two terms. if(i == 1) { cout << t1 << ", "; continue; } if(i == 2) { cout << t2 << ", "; continue; } nextTerm = t1 + t2; t1 = t2; t2 = nextTerm; cout << nextTerm << ", "; } return 0; }
18
Find HCF/GCD
#include using namespace std; int main() { int n1, n2, hcf; cout << "Enter two numbers: "; cin >> n1 >> n2; // swapping variables n1 and n2 if n2 is greater than n1. if ( n2 > n1) { int temp = n2; n2 = n1; n1 = temp; } for (int i = 1; i <= n2; ++i) { if (n1 % i == 0 && n2 % i ==0) { hcf = i; } } cout << "HCF = " << hcf; return 0; }
19
Find LCM
#include using namespace std; int main() { int n1, n2, max; cout << "Enter two numbers: "; cin >> n1 >> n2; // maximum value between n1 and n2 is stored in max max = (n1 > n2) ? n1 : n2; do { if (max % n1 == 0 && max % n2 == 0) { cout << "LCM = " << max; break; } else ++max; } while (true); return 0; }
20
Reverse an Integer
#include using namespace std; int main() { int n, reversed_number = 0, remainder; cout << "Enter an integer: "; cin >> n; while(n != 0) { remainder = n % 10; reversed_number = reversed_number * 10 + remainder; n /= 10; } cout << "Reversed Number = " << reversed_number; return 0; }
21
Compute Power Manually
#include using namespace std; int main() { int exponent; float base, result = 1; cout << "Enter base and exponent respectively: "; cin >> base >> exponent; cout << base << "^" << exponent << " = "; while (exponent != 0) { result *= base; --exponent; } cout << result; return 0; }
22
Prefix ++ Increment Operator Overloading
Prefix ++ Increment Operator Overloading with no return type #include using namespace std; class Check { private: int i; public: Check(): i(0) { } void operator ++() { ++i; } void Display() { cout << "i=" << i << endl; } }; int main() { Check obj; // Displays the value of data member i for object obj obj.Display(); // Invokes operator function void operator ++( ) ++obj; // Displays the value of data member i for object obj obj.Display(); return 0; }
23
Binary Operator Overloading
Binary Operator Overloading to Subtract Complex Number #include using namespace std; class Complex { private: float real; float imag; public: Complex(): real(0), imag(0){ } void input() { cout << "Enter real and imaginary parts respectively: "; cin >> real; cin >> imag; } // Operator overloading Complex operator - (Complex c2) { Complex temp; temp.real = real - c2.real; temp.imag = imag - c2.imag; return temp; } void output() { if(imag < 0) cout << "Output Complex number: "<< real << imag << "i"; else cout << "Output Complex number: " << real << "+" << imag << "i"; } }; int main() { Complex c1, c2, result; cout<<"Enter first complex number:\n"; c1.input(); cout<<"Enter second complex number:\n"; c2.input(); // In case of operator overloading of binary operators in C++ programming, // the object on right hand side of operator is always assumed as argument by compiler. result = c1 - c2; result.output(); return 0; }
24
Check Palindrome Number
#include using namespace std; int main() { int n, num, digit, rev = 0; cout << "Enter a positive number: "; cin >> num; n = num; do { digit = num % 10; rev = (rev * 10) + digit; num = num / 10; } while (num != 0); cout << " The reverse of the number is: " << rev << endl; if (n == rev) cout << " The number is a palindrome."; else cout << " The number is not a palindrome."; return 0; }
25
Multiply Two Numbers
#include using namespace std; int main() { double num1, num2, product; cout << "Enter two numbers: "; // stores two floating point numbers in num1 and num2 respectively cin >> num1 >> num2; // performs multiplication and stores the result in product variable product = num1 * num2; cout << "Product = " << product; return 0; }
26
Armstrong Number Between Intervals
#include #include using namespace std; int main() { int num1, num2, i, num, digit, sum, count; cout << "Enter first number: "; cin >> num1; cout << "Enter second number: "; cin >> num2; // swap if num1 > num2 if (num1 > num2) { num1 = num1 + num2; num2 = num1 - num2; num1 = num1 - num2; } cout << "Armstrong numbers between " << num1 << " and " << num2 << " are: " << endl; // print Armstrong numbers from num1 to num2 for(i = num1; i <= num2; i++) { // count gives the number of digits in i count = 0; // store value of i in num num = i; // count the number of digits in num and i while(num > 0) { ++count; num /= 10; } // initialize sum to 0 sum = 0; // store i in num again num = i; // get sum of power of all digits of i while(num > 0) { digit = num % 10; sum = sum + pow(digit, count); num /= 10; } // if sum is equal to i, then it is Armstrong if(sum == i) { cout << i << ", "; } } return 0; }
27
prime number
#include using namespace std; int main() { int i, n; bool is_prime = true; cout << "Enter a positive integer: "; cin >> n; // 0 and 1 are not prime numbers if (n == 0 || n == 1) { is_prime = false; } // loop to check if n is prime for (i = 2; i <= n/2; ++i) { if (n % i == 0) { is_prime = false; break; } } if (is_prime) cout << n << " is a prime number"; else cout << n << " is not a prime number"; return 0; }
28
Prime Numbers Between two Intervals
#include using namespace std; int main() { int low, high, i; bool is_prime = true; cout << "Enter two numbers (intervals): "; cin >> low >> high; cout << "\nPrime numbers between " << low << " and " << high << " are: " << endl; while (low < high) { is_prime = true; // 0 and 1 are not prime numbers if (low == 0 || low == 1) { is_prime = false; } for (i = 2; i <= low/2; ++i) { if (low % i == 0) { is_prime = false; break; } } if (is_prime) cout << low << ", "; ++low; } return 0; }
29
Armstrong number
#include using namespace std; int main() { int num, originalNum, remainder, result = 0; cout << "Enter a three-digit integer: "; cin >> num; originalNum = num; while (originalNum != 0) { // remainder contains the last digit remainder = originalNum % 10; result += remainder * remainder * remainder; // removing last digit from the orignal number originalNum /= 10; } if (result == num) cout << num << " is an Armstrong number."; else cout << num << " is not an Armstrong number."; return 0; }
30
Armstrong Number Between Intervals
#include #include using namespace std; int main() { int num1, num2, i, num, digit, sum, count; cout << "Enter first number: "; cin >> num1; cout << "Enter second number: "; cin >> num2; // swap if num1 > num2 if (num1 > num2) { num1 = num1 + num2; num2 = num1 - num2; num1 = num1 - num2; } cout << "Armstrong numbers between " << num1 << " and " << num2 << " are: " << endl; // print Armstrong numbers from num1 to num2 for(i = num1; i <= num2; i++) { // count gives the number of digits in i count = 0; // store value of i in num num = i; // count the number of digits in num and i while(num > 0) { ++count; num /= 10; } // initialize sum to 0 sum = 0; // store i in num again num = i; // get sum of power of all digits of i while(num > 0) { digit = num % 10; sum = sum + pow(digit, count); num /= 10; } // if sum is equal to i, then it is Armstrong if(sum == i) { cout << i << ", "; } } return 0; }
31
all Factors of a Number
#include using namespace std; int main() { int n, i; cout << "Enter a positive integer: "; cin >> n; cout << "Factors of " << n << " are: "; for(i = 1; i <= n; ++i) { if(n % i == 0) cout << i << " "; } return 0; }
32
Pyramid
#include using namespace std; int main() { int rows; cout << "Enter number of rows: "; cin >> rows; for(int i = 1; i <= rows; ++i) { for(int j = 1; j <= i; ++j) { cout << "* "; } cout << "\n"; } return 0; }
33
Swap Elements Using Call by Reference
#include using namespace std; void cyclicSwap(int *a, int *b, int *c); int main() { int a, b, c; cout << "Enter value of a, b and c respectively: "; cin >> a >> b >> c; cout << "Value before swapping: " << endl; cout << "a, b and c respectively are: " << a << ", " << b << ", " << c << endl; cyclicSwap(&a, &b, &c); cout << "Value after swapping numbers in cycle: " << endl; cout << "a, b and c respectively are: " << a << ", " << b << ", " << c << endl; return 0; } void cyclicSwap(int *a, int *b, int *c) { int temp; temp = *b; *b = *a; *a = *c; *c = temp; }
34
Simple Calculator
# include using namespace std; int main() { char op; float num1, num2; cout << "Enter operator: +, -, *, /: "; cin >> op; cout << "Enter two operands: "; cin >> num1 >> num2; switch(op) { case '+': cout << num1 << " + " << num2 << " = " << num1 + num2; break; case '-': cout << num1 << " - " << num2 << " = " << num1 - num2; break; case '*': cout << num1 << " * " << num2 << " = " << num1 * num2; break; case '/': cout << num1 << " / " << num2 << " = " << num1 / num2; break; default: // If the operator is other than +, -, * or /, error message is shown cout << "Error! operator is not correct"; break; } return 0; }
35
Prime Numbers Between two Intervals
#include using namespace std; int check_prime(int); int main() { int n1, n2; bool flag; cout << "Enter two positive integers: "; cin >> n1 >> n2; // swapping n1 and n2 if n1 is greater than n2 if (n1 > n2) { n2 = n1 + n2; n1 = n2 - n1; n2 = n2 - n1; } cout << "Prime numbers between " << n1 << " and " << n2 << " are:\n"; for(int i = n1+1; i < n2; ++i) { // if i is a prime number, flag will be equal to 1 flag = check_prime(i); if(flag) cout << i << ", "; } return 0; } // user-defined function to check prime number int check_prime(int n) { bool is_prime = true; // 0 and 1 are not prime numbers if (n == 0 || n == 1) { is_prime = false; } for(int j = 2; j <= n/2; ++j) { if (n%j == 0) { is_prime = false; break; } } return is_prime; }
36
Check Prime Number
#include using namespace std; bool check_prime(int); int main() { int n; cout << "Enter a positive integer: "; cin >> n; if (check_prime(n)) cout << n << " is a prime number."; else cout << n << " is not a prime number."; return 0; } bool check_prime(int n) { bool is_prime = true; // 0 and 1 are not prime numbers if (n == 0 || n == 1) { is_prime = false; } for (int i = 2; i <= n / 2; ++i) { if (n % i == 0) { is_prime = false; break; } } return is_prime; }
37
Number can be Expressed as a Sum of Two Prime Numbers
#include using namespace std; bool check_prime(int n); int main() { int n, i; bool flag = false; cout << "Enter a positive integer: "; cin >> n; for(i = 2; i <= n/2; ++i) { if (check_prime(i)) { if (check_prime(n - i)) { cout << n << " = " << i << " + " << n-i << endl; flag = true; } } } if (!flag) cout << n << " can't be expressed as sum of two prime numbers."; return 0; } // check prime number bool check_prime(int n) { int i; bool is_prime = true; // 0 and 1 are not prime numbers if (n == 0 || n == 1) { is_prime = false; } for(i = 2; i <= n/2; ++i) { if(n % i == 0) { is_prime = false; break; } } return is_prime; }
38
Sum of Natural numbers
Sum of Natural numbers using Recursion #include using namespace std; int add(int n); int main() { int n; cout << "Enter a positive integer: "; cin >> n; cout << "Sum = " << add(n); return 0; } int add(int n) { if(n != 0) return n + add(n - 1); return 0; }
39
Calculate Factorial Using Recursion
#include using namespace std; int factorial(int n); int main() { int n; cout << "Enter a positive integer: "; cin >> n; cout << "Factorial of " << n << " = " << factorial(n); return 0; } int factorial(int n) { if(n > 1) return n * factorial(n - 1); else return 1; }
40
H.C.F using recursion
#include using namespace std; int hcf(int n1, int n2); int main() { int n1, n2; cout << "Enter two positive integers: "; cin >> n1 >> n2; cout << "H.C.F of " << n1 << " & " << n2 << " is: " << hcf(n1, n2); return 0; } int hcf(int n1, int n2) { if (n2 != 0) return hcf(n2, n1 % n2); else return n1; }
41
Convert Binary Number to Decimal
// convert binary to decimal #include #include using namespace std; // function prototype int convert(long long); int main() { long long n; cout << "Enter a binary number: "; cin >> n; cout << n << " in binary = " << convert(n) << " in decimal"; return 0; } // function definition int convert(long long n) { int dec = 0, i = 0, rem; while (n!=0) { rem = n % 10; n /= 10; dec += rem * pow(2, i); ++i; } return dec; }
42
Convert Octal Number to Decimal
Convert Octal Number to Decimal #include #include using namespace std; int octalToDecimal(int octalNumber); int main() { int octalNumber; cout << "Enter an octal number: "; cin >> octalNumber; cout << octalNumber << " in octal = " << octalToDecimal(octalNumber) << " in decimal"; return 0; } // Function to convert octal number to decimal int octalToDecimal(int octalNumber) { int decimalNumber = 0, i = 0, rem; while (octalNumber != 0) { rem = octalNumber % 10; octalNumber /= 10; decimalNumber += rem * pow(8, i); ++i; } return decimalNumber; }
43
decimal number is converted to octal.
#include #include using namespace std; int convertBinarytoOctal(long long); int main() { long long binaryNumber; cout << "Enter a binary number: "; cin >> binaryNumber; cout << binaryNumber << " in binary = " << convertBinarytoOctal(binaryNumber) << " in octal "; return 0; } int convertBinarytoOctal(long long binaryNumber) { int octalNumber = 0, decimalNumber = 0, i = 0; while(binaryNumber != 0) { decimalNumber += (binaryNumber%10) * pow(2,i); ++i; binaryNumber/=10; } i = 1; while (decimalNumber != 0) { octalNumber += (decimalNumber % 8) * i; decimalNumber /= 8; i *= 10; } return octalNumber; }
44
Reverse a sentence
Reverse a sentence using recursion. #include using namespace std; // function prototype void reverse(const string& a); int main() { string str; cout << " Please enter a string " << endl; getline(cin, str); // function call reverse(str); return 0; } // function definition void reverse(const string& str) { // store the size of the string size_t numOfChars = str.size(); if(numOfChars == 1) { cout << str << endl; } else { cout << str[numOfChars - 1]; // function recursion reverse(str.substr(0, numOfChars - 1)); } }
45
Program to Computer Power
Program to Computer Power Using Recursion #include using namespace std; int calculatePower(int, int); int main() { int base, powerRaised, result; cout << "Enter base number: "; cin >> base; cout << "Enter power number(positive integer): "; cin >> powerRaised; result = calculatePower(base, powerRaised); cout << base << "^" << powerRaised << " = " << result; return 0; } int calculatePower(int base, int powerRaised) { if (powerRaised != 0) return (base*calculatePower(base, powerRaised-1)); else return 1; }
46
Calculate Average of Numbers
Calculate Average of Numbers Using Arrays #include using namespace std; int main() { int n, i; float num[100], sum=0.0, average; cout << "Enter the numbers of data: "; cin >> n; while (n > 100 || n <= 0) { cout << "Error! number should in range of (1 to 100)." << endl; cout << "Enter the number again: "; cin >> n; } for(i = 0; i < n; ++i) { cout << i + 1 << ". Enter number: "; cin >> num[i]; sum += num[i]; } average = sum / n; cout << "Average = " << average; return 0; }
47
Largest Element of an array
#include using namespace std; int main() { int i, n; float arr[100]; cout << "Enter total number of elements(1 to 100): "; cin >> n; cout << endl; // Store number entered by the user for(i = 0; i < n; ++i) { cout << "Enter Number " << i + 1 << " : "; cin >> arr[i]; } // Loop to store largest number to arr[0] for(i = 1;i < n; ++i) { // Change < to > if you want to find the smallest element if(arr[0] < arr[i]) arr[0] = arr[i]; } cout << endl << "Largest element = " << arr[0]; return 0; }
48
Calculate Standard Deviation
#include #include using namespace std; float calculateSD(float data[]); int main() { int i; float data[10]; cout << "Enter 10 elements: "; for(i = 0; i < 10; ++i) { cin >> data[i]; } cout << endl << "Standard Deviation = " << calculateSD(data); return 0; } float calculateSD(float data[]) { float sum = 0.0, mean, standardDeviation = 0.0; int i; for(i = 0; i < 10; ++i) { sum += data[i]; } mean = sum / 10; for(i = 0; i < 10; ++i) { standardDeviation += pow(data[i] - mean, 2); } return sqrt(standardDeviation / 10); }
49
Add Two Matrices
Add Two Matrices using Multi-dimensional Arrays #include using namespace std; int main() { int r, c, a[100][100], b[100][100], sum[100][100], i, j; cout << "Enter number of rows (between 1 and 100): "; cin >> r; cout << "Enter number of columns (between 1 and 100): "; cin >> c; cout << endl << "Enter elements of 1st matrix: " << endl; // Storing elements of first matrix entered by user. for(i = 0; i < r; ++i) for(j = 0; j < c; ++j) { cout << "Enter element a" << i + 1 << j + 1 << " : "; cin >> a[i][j]; } // Storing elements of second matrix entered by user. cout << endl << "Enter elements of 2nd matrix: " << endl; for(i = 0; i < r; ++i) for(j = 0; j < c; ++j) { cout << "Enter element b" << i + 1 << j + 1 << " : "; cin >> b[i][j]; } // Adding Two matrices for(i = 0; i < r; ++i) for(j = 0; j < c; ++j) sum[i][j] = a[i][j] + b[i][j]; // Displaying the resultant sum matrix. cout << endl << "Sum of two matrix is: " << endl; for(i = 0; i < r; ++i) for(j = 0; j < c; ++j) { cout << sum[i][j] << " "; if(j == c - 1) cout << endl; }
50
Multiply two matrices
Multiply two matrices without using functions #include using namespace std; int main() { int a[10][10], b[10][10], mult[10][10], r1, c1, r2, c2, i, j, k; cout << "Enter rows and columns for first matrix: "; cin >> r1 >> c1; cout << "Enter rows and columns for second matrix: "; cin >> r2 >> c2; // If column of first matrix in not equal to row of second matrix, // ask the user to enter the size of matrix again. while (c1!=r2) { cout << "Error! column of first matrix not equal to row of second."; cout << "Enter rows and columns for first matrix: "; cin >> r1 >> c1; cout << "Enter rows and columns for second matrix: "; cin >> r2 >> c2; } // Storing elements of first matrix. cout << endl << "Enter elements of matrix 1:" << endl; for(i = 0; i < r1; ++i) for(j = 0; j < c1; ++j) { cout << "Enter element a" << i + 1 << j + 1 << " : "; cin >> a[i][j]; } // Storing elements of second matrix. cout << endl << "Enter elements of matrix 2:" << endl; for(i = 0; i < r2; ++i) for(j = 0; j < c2; ++j) { cout << "Enter element b" << i + 1 << j + 1 << " : "; cin >> b[i][j]; } // Initializing elements of matrix mult to 0. for(i = 0; i < r1; ++i) for(j = 0; j < c2; ++j) { mult[i][j]=0; } // Multiplying matrix a and b and storing in array mult. for(i = 0; i < r1; ++i) for(j = 0; j < c2; ++j) for(k = 0; k < c1; ++k) { mult[i][j] += a[i][k] * b[k][j]; } // Displaying the multiplication of two matrix. cout << endl << "Output Matrix: " << endl; for(i = 0; i < r1; ++i) for(j = 0; j < c2; ++j) { cout << " " << mult[i][j]; if(j == c2-1) cout << endl; } return 0; }
51
Find Transpose of a Matrix
#include using namespace std; int main() { int a[10][10], transpose[10][10], row, column, i, j; cout << "Enter rows and columns of matrix: "; cin >> row >> column; cout << "\nEnter elements of matrix: " << endl; // Storing matrix elements for (int i = 0; i < row; ++i) { for (int j = 0; j < column; ++j) { cout << "Enter element a" << i + 1 << j + 1 << ": "; cin >> a[i][j]; } } // Printing the a matrix cout << "\nEntered Matrix: " << endl; for (int i = 0; i < row; ++i) { for (int j = 0; j < column; ++j) { cout << " " << a[i][j]; if (j == column - 1) cout << endl << endl; } }
52
Program to Time Difference
ple: Program to Time Difference // Computes time difference of two time period // Time periods are entered by the user #include using namespace std; struct TIME { int seconds; int minutes; int hours; }; void computeTimeDifference(struct TIME, struct TIME, struct TIME *); int main() { struct TIME t1, t2, difference; cout << "Enter start time." << endl; cout << "Enter hours, minutes and seconds respectively: "; cin >> t1.hours >> t1.minutes >> t1.seconds; cout << "Enter stop time." << endl; cout << "Enter hours, minutes and seconds respectively: "; cin >> t2.hours >> t2.minutes >> t2.seconds; computeTimeDifference(t1, t2, &difference); cout << endl << "TIME DIFFERENCE: " << t1.hours << ":" << t1.minutes << ":" << t1.seconds; cout << " - " << t2.hours << ":" << t2.minutes << ":" << t2.seconds; cout << " = " << difference.hours << ":" << difference.minutes << ":" << difference.seconds; return 0; } void computeTimeDifference(struct TIME t1, struct TIME t2, struct TIME *difference){ if(t2.seconds > t1.seconds) { --t1.minutes; t1.seconds += 60; } difference->seconds = t1.seconds - t2.seconds; if(t2.minutes > t1.minutes) { --t1.hours; t1.minutes += 60; } difference->minutes = t1.minutes-t2.minutes; difference->hours = t1.hours-t2.hours; }
53
Multiply Matrix by Passing
Multiply Matrix by Passing it to a Function #include using namespace std; void enterData(int firstMatrix[][10], int secondMatrix[][10], int rowFirst, int columnFirst, int rowSecond, int columnSecond); void multiplyMatrices(int firstMatrix[][10], int secondMatrix[][10], int multResult[][10], int rowFirst, int columnFirst, int rowSecond, int columnSecond); void display(int mult[][10], int rowFirst, int columnSecond); int main() { int firstMatrix[10][10], secondMatrix[10][10], mult[10][10], rowFirst, columnFirst, rowSecond, columnSecond, i, j, k; cout << "Enter rows and column for first matrix: "; cin >> rowFirst >> columnFirst; cout << "Enter rows and column for second matrix: "; cin >> rowSecond >> columnSecond; // If colum of first matrix in not equal to row of second matrix, asking user to enter the size of matrix again. while (columnFirst != rowSecond) { cout << "Error! column of first matrix not equal to row of second." << endl; cout << "Enter rows and column for first matrix: "; cin >> rowFirst >> columnFirst; cout << "Enter rows and column for second matrix: "; cin >> rowSecond >> columnSecond; } // Function to take matrices data enterData(firstMatrix, secondMatrix, rowFirst, columnFirst, rowSecond, columnSecond); // Function to multiply two matrices. multiplyMatrices(firstMatrix, secondMatrix, mult, rowFirst, columnFirst, rowSecond, columnSecond); // Function to display resultant matrix after multiplication. display(mult, rowFirst, columnSecond); return 0; } void enterData(int firstMatrix[][10], int secondMatrix[][10], int rowFirst, int columnFirst, int rowSecond, int columnSecond) { int i, j; cout << endl << "Enter elements of matrix 1:" << endl; for(i = 0; i < rowFirst; ++i) { for(j = 0; j < columnFirst; ++j) { cout << "Enter elements a"<< i + 1 << j + 1 << ": "; cin >> firstMatrix[i][j]; } } cout << endl << "Enter elements of matrix 2:" << endl; for(i = 0; i < rowSecond; ++i) { for(j = 0; j < columnSecond; ++j) { cout << "Enter elements b" << i + 1 << j + 1 << ": "; cin >> secondMatrix[i][j]; } } } void multiplyMatrices(int firstMatrix[][10], int secondMatrix[][10], int mult[][10], int rowFirst, int columnFirst, int rowSecond, int columnSecond) { int i, j, k; // Initializing elements of matrix mult to 0. for(i = 0; i < rowFirst; ++i) { for(j = 0; j < columnSecond; ++j) { mult[i][j] = 0; } }
54
Access Array Elements Using Pointer
Access Array Elements Using Pointer #include using namespace std; int main() { int data[5]; cout << "Enter elements: "; for(int i = 0; i < 5; ++i) cin >> data[i]; cout << "You entered: "; for(int i = 0; i < 5; ++i) cout << endl << *(data + i); return 0; }
55
Swap Elements Using Call by Reference
#include using namespace std; void cyclicSwap(int *a, int *b, int *c); int main() { int a, b, c; cout << "Enter value of a, b and c respectively: "; cin >> a >> b >> c; cout << "Value before swapping: " << endl; cout << "a, b and c respectively are: " << a << ", " << b << ", " << c << endl; cyclicSwap(&a, &b, &c); cout << "Value after swapping numbers in cycle: " << endl; cout << "a, b and c respectively are: " << a << ", " << b << ", " << c << endl; return 0; } void cyclicSwap(int *a, int *b, int *c) { int temp; temp = *b; *b = *a; *a = *c; *c = temp; }
56
Find Frequency of Characters
Find Frequency of Characters of a String Object #include using namespace std; int main() { string str = "C++ Programming is awesome"; char checkCharacter = 'a'; int count = 0; for (int i = 0; i < str.size(); i++) { if (str[i] == checkCharacter) { ++ count; } } cout << "Number of " << checkCharacter << " = " << count; return 0; }
57
From a C-style string
From a C-style string This program takes a C-style string from the user and calculates the number of vowels, consonants, digits and white-spaces. #include using namespace std; int main() { char line[150]; int vowels, consonants, digits, spaces; vowels = consonants = digits = spaces = 0; cout << "Enter a line of string: "; cin.getline(line, 150); for(int i = 0; line[i]!='\0'; ++i) { if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u' || line[i]=='A' || line[i]=='E' || line[i]=='I' || line[i]=='O' || line[i]=='U') { ++vowels; } else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z')) { ++consonants; } else if(line[i]>='0' && line[i]<='9') { ++digits; } else if (line[i]==' ') { ++spaces; } } cout << "Vowels: " << vowels << endl; cout << "Consonants: " << consonants << endl; cout << "Digits: " << digits << endl; cout << "White spaces: " << spaces << endl; return 0; }
58
removes all characters except alphabets
removes all characters except alphabets. #include using namespace std; int main() { string line; string temp = ""; cout << "Enter a string: "; getline(cin, line); for (int i = 0; i < line.size(); ++i) { if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z')) { temp = temp + line[i]; } } line = temp; cout << "Output String: " << line; return 0; }
59
Length of String Object
Length of String Object #include using namespace std; int main() { string str = "C++ Programming"; // you can also use str.length() cout << "String Length = " << str.size(); return 0; }
60
Concatenate String Objects
Concatenate String Objects #include using namespace std; int main() { string s1, s2, result; cout << "Enter string s1: "; getline (cin, s1); cout << "Enter string s2: "; getline (cin, s2); result = s1 + s2; cout << "Resultant String = "<< result; return 0; }
61
Copy String Object
Copy String Object #include using namespace std; int main() { string s1, s2; cout << "Enter string s1: "; getline (cin, s1); s2 = s1; cout << "s1 = "<< s1 << endl; cout << "s2 = "<< s2; return 0; }
62
Sort Words in Dictionary Order
Sort Words in Dictionary Order #include using namespace std; int main() { string str[10], temp; cout << "Enter 10 words: " << endl; for(int i = 0; i < 10; ++i) { getline(cin, str[i]); } // Use Bubble Sort to arrange words for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9 - i; ++j) { if (str[j] > str[j + 1]) { temp = str[j]; str[j] = str[j + 1]; str[j + 1] = temp; } } } cout << "In lexicographical order: " << endl; for(int i = 0; i < 10; ++i) { cout << str[i] << endl; } return 0; }
63
Store and Display Information
Store and Display Information Using Structure #include using namespace std; struct student { char name[50]; int roll; float marks; }; int main() { student s; cout << "Enter information," << endl; cout << "Enter name: "; cin >> s.name; cout << "Enter roll number: "; cin >> s.roll; cout << "Enter marks: "; cin >> s.marks; cout << "\nDisplaying Information," << endl; cout << "Name: " << s.name << endl; cout << "Roll: " << s.roll << endl; cout << "Marks: " << s.marks << endl; return 0; }
64
Add Distances Using Structures
Add Distances Using Structures #include using namespace std; struct Distance { int feet; float inch; }d1 , d2, sum; int main() { cout << "Enter 1st distance," << endl; cout << "Enter feet: "; cin >> d1.feet; cout << "Enter inch: "; cin >> d1.inch; cout << "\nEnter information for 2nd distance" << endl; cout << "Enter feet: "; cin >> d2.feet; cout << "Enter inch: "; cin >> d2.inch; sum.feet = d1.feet+d2.feet; sum.inch = d1.inch+d2.inch; // changing to feet if inch is greater than 12 if(sum.inch > 12) { // extra feet int extra = sum.inch / 12; sum.feet += extra; sum.inch -= (extra * 12); } cout << endl << "Sum of distances = " << sum.feet << " feet " << sum.inch << " inches"; return 0; }
65
Source Code to Add Two Complex Numbers
// Complex numbers are entered by the user #include using namespace std; typedef struct complex { float real; float imag; } complexNumber; complexNumber addComplexNumbers(complex, complex); int main() { complexNumber num1, num2, complexSum; char signOfImag; cout << "For 1st complex number," << endl; cout << "Enter real and imaginary parts respectively:" << endl; cin >> num1.real >> num1.imag; cout << endl << "For 2nd complex number," << endl; cout << "Enter real and imaginary parts respectively:" << endl; cin >> num2.real >> num2.imag; // Call add function and store result in complexSum complexSum = addComplexNumbers(num1, num2); // Use Ternary Operator to check the sign of the imaginary number signOfImag = (complexSum.imag > 0) ? '+' : '-'; // Use Ternary Operator to adjust the sign of the imaginary number complexSum.imag = (complexSum.imag > 0) ? complexSum.imag : -complexSum.imag; cout << "Sum = " << complexSum.real << signOfImag << complexSum.imag << "i"; return 0; } complexNumber addComplexNumbers(complex num1, complex num2) { complex temp; temp.real = num1.real + num2.real; temp.imag = num1.imag + num2.imag; return (temp); }