C++ is programming language where you can develop software’s. its runs on different platforms
Windows, Mac, different version of Linux.
It is use to develop
- Application Software Development
- Programming languages development
- Computation Programming
- Games Development
- Embedded Systems
Object-Oriented Programming
C++ Supports OOP concepts with its Four Pillars.
More Detail….
- Encapsulation
- Data hiding
- Inheritance
- Polymorphism
C++ does not allow punctuation characters such as @, $, and % within identifiers. C++ is a case-sensitive programming language.
- <iostream> is a header, which contain information that is either necessary or useful to your program. the header <iostream> is needed for programs.
- The line using namespace std; tells the compiler to use the std namespace.
- main() where program execution begins.
- // is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line.
- The line int main() is the main function where program execution begins.
- cout << “Hello World”; shows the message “Hello World” to be displayed on the screen.
- return 0;
- terminates main( ) function. Because int method requires value to terminate the function.
Simple code to print Hello World.
#include <iostream>
using namespace std;
// main() is where program execution begins.
int main()
{ cout << "Hello World"; // prints Hello World
return 0;
}
- <iostream> is a header, which contain information that is either necessary or useful to your program. the header <iostream> is needed for programs.
- The line using namespace std; tells the compiler to use the std namespace.
- main() where program execution begins.
- // is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line.
- The line int main() is the main function where program execution begins.
- cout << “Hello World”; shows the message “Hello World” to be displayed on the screen.
- return 0;
- terminates main( ) function. Because int method requires value to terminate the function
How to Compile and Execute C++ Program.
- Open a text editor and add the code as above.
- Save the file as: result.cpp
- Open a command prompt and go to the directory where you saved the file.
- Type ‘g++ result.cpp’ and press enter to compile your code. command prompt will take you to the next line and would generate a.out executable file if there is no error.
- Now, type ‘a.out’ to run your program.
- You will be able to see ‘ Hello World ‘ printed on the window.
Semicolons and Blocks in C++
Samicolons are end operators which terminates the function and shows individually statements
x = y;
y = y + 1;
add(x, y);
A block is a set of logically connected statements that are surrounded by opening and closing braces. For example
{
cout << "Hello World";
// prints Hello World
return 0;
}
Primitive Built-in Types
Type | Keyword |
Boolean | bool |
Character | char |
Integer | int |
Floating point | float |
Double floating point | double |
Valueless | void |
Wide character | wchar_t |
Type | Typical Bit Width | Typical Range |
---|---|---|
char | 1byte | -127 to 127 or 0 to 255 |
unsigned char | 1byte | 0 to 255 |
signed char | 1byte | -127 to 127 |
int | 4bytes | -2147483648 to 2147483647 |
unsigned int | 4bytes | 0 to 4294967295 |
signed int | 4bytes | -2147483648 to 2147483647 |
short int | 2bytes | -32768 to 32767 |
unsigned short int | 2bytes | 0 to 65,535 |
signed short int | 2bytes | -32768 to 32767 |
long int | 8bytes | -2,147,483,648 to 2,147,483,647 |
signed long int | 8bytes | same as long int |
unsigned long int | 8bytes | 0 to 4,294,967,295 |
long long int | 8bytes | -(2^63) to (2^63)-1 |
unsigned long long int | 8bytes | 0 to 18,446,744,073,709,551,615 |
float | 4bytes | |
double | 8bytes | |
long double | 12bytes | |
wchar_t | 2 or 4 bytes | 1 wide character |
Example
#include <iostream>
using namespace std;
int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
Print Number Entered by User
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter an integer: ";
cin >> number;
cout << "You entered " << number;
return 0;
}
Output:
Enter an integer: 23
You entered 23
print triangles using *, numbers and characters
#include <iostream>
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;
}
Output
*
* *
* * *
* * * *
* * * * *
---------------------------------------
#include <iostream>
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 << j << " ";
}
cout << "\n";
}
return 0;
}
Output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
------------------------------
#include <iostream>
using namespace std;
int main()
{
char input, alphabet = 'A';
cout << "Enter the uppercase character you want to print in the last row: ";
cin >> input;
for(int i = 1; i <= (input-'A'+1); ++i)
{
for(int j = 1; j <= i; ++j)
{
cout << alphabet << " ";
}
++alphabet;
cout << endl;
}
return 0;
}
Output
A
B B
C C C
D D D D
E E E E E
----------------------------------------
#include <iostream>
using namespace std;
int main()
{
int rows;
cout << "Enter number of rows: ";
cin >> rows;
for(int i = rows; i >= 1; --i)
{
for(int j = 1; j <= i; ++j)
{
cout << "* ";
}
cout << endl;
}
return 0;
}
Output
* * * * *
* * * *
* * *
* *
*
-------------------------------------------
#include <iostream>
using namespace std;
int main()
{
int space, rows;
cout <<"Enter number of rows: ";
cin >> rows;
for(int i = 1, k = 0; i <= rows; ++i, k = 0)
{
for(space = 1; space <= rows-i; ++space)
{
cout <<" ";
}
while(k != 2*i-1)
{
cout << "* ";
++k;
}
cout << endl;
}
return 0;
}
Output
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
Length of String Object
#include <iostream>
using namespace std;
int main() {
string str = "C++ Programming";
// you can also use str.length()
cout << "String Length = " << str.size();
return 0;
}
Output
String Length = 15
Concatenate String Objects
#include <iostream>
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;
}
Output
Enter string s1: C++ Programming
Enter string s2: is awesome.
Resultant String = C++ Programming is awesome.
Copy String Object
#include <iostream>
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;
}
output
Enter string s1: C++ Strings
s1 = C++ Strings
s2 = C++ Strings
Simple Calculator using switch statement
# include <iostream>
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;
}
Output
Enter operator either + or - or * or divide : -
Enter two operands: 3.4 8.4
3.4 - 8.4 = -5.0
Program to Add Two Integers
#include <iostream>
using namespace std;
int main()
{
int firstNumber, secondNumber, sumOfTwoNumbers;
cout << "Enter two integers: ";
cin >> firstNumber >> secondNumber;
// sum of two numbers in stored in variable sumOfTwoNumbers
sumOfTwoNumbers = firstNumber + secondNumber;
// Prints sum
cout << firstNumber << " + " << secondNumber << " = " << sumOfTwoNumbers;
Output:
Enter two integers: 4
5
4 + 5 = 9
Quotient and remainder
#include <iostream>
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;
}
Output:
Enter dividend: 13
Enter divisor: 4
Quotient = 3
Remainder = 1
Find Size of a Variable
#include <iostream>
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;
}
Output:
Size of char: 1 byte
Size of int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes
Swap Numbers (Using Temporary Variable)
#include <iostream>
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;
}
Output:
Before swapping.
a = 5, b = 10
After swapping.
a = 10, b = 5
Print ASCII Value in C++
#include <iostream>
using namespace std;
int main() {
char c;
cout << "Enter a character: ";
cin >> c;
cout << "ASCII Value of " << c << " is " << int(c);
return 0;
}
Output
Enter a character: p
ASCII Value of p is 112
Program to Multiply Two Numbers:
#include <iostream>
using namespace std;
int main()
{
double firstNumber, secondNumber, productOfTwoNumbers;
cout << "Enter two numbers: ";
// Stores two floating point numbers in variable firstNumber and secondNumber respectively
cin >> firstNumber >> secondNumber;
// Performs multiplication and stores the result in variable productOfTwoNumbers
productOfTwoNumbers = firstNumber * secondNumber;
cout << "Product = " << productOfTwoNumbers;
return 0;
}
Output:
Enter two numbers: 3.4
5.5
Product = 18.7
Check Whether Number is Even or Odd
#include <iostream>
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;
Output:
Enter an integer: 23
23 is odd.
Check Whether Number is Even or Odd using ternary
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter an integer: ";
cin >> n;
(n % 2 == 0) ? cout << n << " is even." : cout << n << " is odd.";
return 0;
}
Check Whether a character is Vowel or Consonant.
#include <iostream>
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;
}
Output
Enter an alphabet: u
u is a vowel.
Find Largest Number Using if Statement
#include <iostream>
using namespace std;
int main() {
float n1, n2, n3;
cout << "Enter three numbers: ";
cin >> n1 >> n2 >> n3;
if(n1 >= n2 && n1 >= n3)
cout << "Largest number: " << n1;
if(n2 >= n1 && n2 >= n3)
cout << "Largest number: " << n2;
if(n3 >= n1 && n3 >= n2)
cout << "Largest number: " << n3;
return 0;
}
Output
Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3
Find Largest Number Using if…else Statement
#include <iostream>
using namespace std;
int main() {
float n1, n2, n3;
cout << "Enter three numbers: ";
cin >> n1 >> n2 >> n3;
if((n1 >= n2) && (n1 >= n3))
cout << "Largest number: " << n1;
else if ((n2 >= n1) && (n2 >= n3))
cout << "Largest number: " << n2;
else
cout << "Largest number: " << n3;
return 0;
}
Output
Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3
Find Largest Number Using Nested if…else statement
#include <iostream>
using namespace std;
int main() {
float n1, n2, n3;
cout << "Enter three numbers: ";
cin >> n1 >> n2 >> n3;
if (n1 >= n2) {
if (n1 >= n3)
cout << "Largest number: " << n1;
else
cout << "Largest number: " << n3;
}
else {
if (n2 >= n3)
cout << "Largest number: " << n2;
else
cout << "Largest number: " << n3;
}
return 0;
}
Output
Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3
Sum of Natural Numbers using loop
#include <iostream>
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;
}
output
Enter a positive integer: 50
Sum = 1275
Check if a year is leap year or not
#include <iostream>
using namespace std;
int main() {
int year;
cout << "Enter a year: ";
cin >> year;
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0)
cout << year << " is a leap year.";
else
cout << year << " is not a leap year.";
}
else
cout << year << " is a leap year.";
}
else
cout << year << " is not a leap year.";
return 0;
}
Output
Enter a year: 2014
2014 is not a leap year.
Find Factorial of a given number
#include <iostream>
using namespace std;
int main() {
int n;
long double 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;
}
Output
Enter a positive integer: 12
Factorial of 12 = 479001600
Display Multiplication table up to 10
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter a positive integer: ";
cin >> n;
for (int i = 1; i <= 10; ++i) {
cout << n << " * " << i << " = " << n * i << endl;
}
return 0;
}
Output:
Enter an integer: 5
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Display multiplication table up to a given range
#include <iostream>
using namespace std;
int main()
{
int n, range;
cout << "Enter an integer: ";
cin >> n;
cout << "Enter range: ";
cin >> range;
for (int i = 1; i <= range; ++i) {
cout << n << " * " << i << " = " << n * i << endl;
}
return 0;
}
Output
Enter an integer: 8
Enter range: 12
8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
8 * 8 = 64
8 * 9 = 72
8 * 10 = 80
8 * 11 = 88
8 * 12 = 96
Fibonacci Series up to n number of terms
#include <iostream>
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;
}
Output
Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
Program to Generate Fibonacci Sequence Up to a Certain Number
#include <iostream>
using namespace std;
int main() {
int t1 = 0, t2 = 1, nextTerm = 0, n;
cout << "Enter a positive number: ";
cin >> n;
// displays the first two terms which is always 0 and 1
cout << "Fibonacci Series: " << t1 << ", " << t2 << ", ";
nextTerm = t1 + t2;
while(nextTerm <= n) {
cout << nextTerm << ", ";
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}
Output
Enter a positive integer: 100
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
Find GCD using while loop
#include <iostream>
using namespace std;
int main()
{
int n1, n2;
cout << "Enter two numbers: ";
cin >> n1 >> n2;
while(n1 != n2)
{
if(n1 > n2)
n1 -= n2;
else
n2 -= n1;
}
cout << "HCF = " << n1;
return 0;
}
Output
Enter two numbers: 78
52
HCF = 26
Find HCF/GCD using for loop
#include <iostream>
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;
}
Find LCM
#include <iostream>
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;
}
output
Enter two numbers: 12
18
LCM = 36
Find LCM using HCF
#include <iostream>
using namespace std;
int main()
{
int n1, n2, hcf, temp, lcm;
cout << "Enter two numbers: ";
cin >> n1 >> n2;
hcf = n1;
temp = n2;
while(hcf != temp)
{
if(hcf > temp)
hcf -= temp;
else
temp -= hcf;
}
lcm = (n1 * n2) / hcf;
cout << "LCM = " << lcm;
return 0;
}
Reverse an Integer
#include <iostream>
using namespace std;
int main() {
int n, reversedNumber = 0, remainder;
cout << "Enter an integer: ";
cin >> n;
while(n != 0) {
remainder = n%10;
reversedNumber = reversedNumber*10 + remainder;
n /= 10;
}
cout << "Reversed Number = " << reversedNumber;
return 0;
}
Output
Enter an integer: 12345
Reversed number = 54321
Compute Power Manually
#include <iostream>
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;
}
Output
Enter base and exponent respectively: 3.4
5
3.4^5 = 454.354
Compute power using pow() Function
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float base, exponent, result;
cout << "Enter base and exponent respectively: ";
cin >> base >> exponent;
result = pow(base, exponent);
cout << base << "^" << exponent << " = " << result;
return 0;
}
Output
Enter base and exponent respectively: 2.3
4.5
2.3^4.5 = 42.44
Check Palindrome Number
#include <iostream>
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;
}
Output
Enter a positive number: 12321
The reverse of the number is: 12321
The number is a palindrome.
OR
Enter a positive number: 12331
The reverse of the number is: 13321
The number is not a palindrome.
Check Prime Number
#include <iostream>
using namespace std;
int main() {
int i, n;
bool isPrime = true;
cout << "Enter a positive integer: ";
cin >> n;
// 0 and 1 are not prime numbers
if (n == 0 || n == 1) {
isPrime = false;
}
else {
for (i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime)
cout << n << " is a prime number";
else
cout << n << " is not a prime number";
return 0;
}
Output
Enter a positive integer: 29
29 is a prime number.
Display Prime Numbers Between two Intervals
#include <iostream>
using namespace std;
int main() {
int low, high, i;
bool isPrime = true;
cout << "Enter two numbers (intervals): ";
cin >> low >> high;
cout << "\nPrime numbers between " << low << " and " << high << " are: " << endl;
while (low < high) {
isPrime = true;
if (low == 0 || low == 1) {
isPrime = false;
}
else {
for (i = 2; i <= low / 2; ++i) {
if (low % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime)
cout << low << " ";
++low;
}
return 0;
}
Output
Enter two numbers (intervals): 0 20
Prime numbers between 0 and 20 are:
2 3 5 7 11 13 17 19
Display Prime Numbers When Larger Number is Entered first
#include <iostream>
using namespace std;
int main()
{
int low, high, temp, i;
bool isPrime;
cout << "Enter two numbers (intevals): ";
cin >> low >> high;
//swapping numbers if low is greater than high
if (low > high) {
temp = low;
low = high;
high = temp;
}
cout << "\nPrime numbers between " << low << " and " << high << " are:" << endl;
while (low < high) {
isPrime = true;
if (low == 0 || low == 1) {
isPrime = false;
}
else {
for (i = 2; i <= low / 2; ++i) {
if (low % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime)
cout << low << " ";
++low;
}
return 0;
}
Output
Enter two numbers (intervals): 20 0
Prime numbers between 0 and 20 are:
2 3 5 7 11 13 17 19
Display all Factors of a Number
#include <iostream>
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;
}
Output
Enter a positive integer: 60
Factors of 60 are: 1 2 3 4 5 6 10 12 15 20 30 60
Check Prime Number
#include <iostream>
using namespace std;
bool checkPrimeNumber(int);
int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;
if (checkPrimeNumber(n))
cout << n << " is a prime number.";
else
cout << n << " is not a prime number.";
return 0;
}
bool checkPrimeNumber(int n) {
bool isPrime = true;
// 0 and 1 are not prime numbers
if (n == 0 || n == 1) {
isPrime = false;
}
else {
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
isPrime = false;
break;
}
}
}
return isPrime;
}
Output
Enter a positive integer: 23
23 is a prime number.
Calculate Sum of Natural numbers using Recursion
#include<iostream>
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;
}
Output
Enter an positive integer: 10
Sum = 55
Program to convert binary number to decimal
#include <iostream>
#include <cmath>
using namespace std;
int convertBinaryToDecimal(long long);
int main()
{
long long n;
cout << "Enter a binary number: ";
cin >> n;
cout << n << " in binary = " << convertBinaryToDecimal(n) << "in decimal";
return 0;
}
int convertBinaryToDecimal(long long n)
{
int decimalNumber = 0, i = 0, remainder;
while (n!=0)
{
remainder = n%10;
n /= 10;
decimalNumber += remainder*pow(2,i);
++i;
}
return decimalNumber;
}
Output
Enter a binary number: 1111
1111 in binary = 15
Program to convert decimal number to binary
#include <iostream>
#include <cmath>
using namespace std;
long long convertDecimalToBinary(int);
int main()
{
int n, binaryNumber;
cout << "Enter a decimal number: ";
cin >> n;
binaryNumber = convertDecimalToBinary(n);
cout << n << " in decimal = " << binaryNumber << " in binary" << endl ;
return 0;
}
long long convertDecimalToBinary(int n)
{
long long binaryNumber = 0;
int remainder, i = 1, step = 1;
while (n!=0)
{
remainder = n%2;
cout << "Step " << step++ << ": " << n << "/2, Remainder = " << remainder << ", Quotient = " << n/2 << endl;
n /= 2;
binaryNumber += remainder*i;
i *= 10;
}
return binaryNumber;
}
output
Enter a decimal number: 19
Step 1: 19/2, Remainder = 1, Quotient = 9
Step 2: 9/2, Remainder = 1, Quotient = 4
Step 3: 4/2, Remainder = 0, Quotient = 2
Step 4: 2/2, Remainder = 0, Quotient = 1
Step 5: 1/2, Remainder = 1, Quotient = 0
19 in decimal = 10011 in binary
Convert Octal Number to Decimal
#include <iostream>
#include <cmath>
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;
}
Output
Enter an octal number: 2341
2341 in octal = 1249 in decimal
Convert Decimal Number to Octal
#include <iostream>
#include <cmath>
using namespace std;
int decimalToOctal(int decimalNumber);
int main()
{
int decimalNumber;
cout << "Enter a decimal number: ";
cin >> decimalNumber;
cout << decimalNumber << " in decimal = " << decimalToOctal(decimalNumber) << " in octal";
return 0;
}
// Function to convert decimal number to octal
int decimalToOctal(int decimalNumber)
{
int rem, i = 1, octalNumber = 0;
while (decimalNumber != 0)
{
rem = decimalNumber % 8;
decimalNumber /= 8;
octalNumber += rem * i;
i *= 10;
}
return octalNumber;
}
Output
Enter an decimal number: 78
78 in decimal = 116 in octal
Program to Convert Binary to Octal
#include <iostream>
#include <cmath>
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;
}
Output
Enter a binary number: 10001
10001 in binary = 21 in octal
Program to Convert Octal to Binary
#include <iostream>
#include <cmath>
using namespace std;
long long convertOctalToBinary(int);
int main()
{
int octalNumber;
cout << "Enter an octal number: ";
cin >> octalNumber;
cout << octalNumber << " in octal = " << convertOctalToBinary(octalNumber) << "in binary";
return 0;
}
long long convertOctalToBinary(int octalNumber)
{
int decimalNumber = 0, i = 0;
long long binaryNumber = 0;
while(octalNumber != 0)
{
decimalNumber += (octalNumber%10) * pow(8,i);
++i;
octalNumber/=10;
}
i = 1;
while (decimalNumber != 0)
{
binaryNumber += (decimalNumber % 2) * i;
decimalNumber /= 2;
i *= 10;
}
return binaryNumber;
}
Output
Enter an octal number: 54
54 in octal = 101100
Reverse a sentence using recursion.
#include <iostream>
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));
}
}
Output
Enter a sentence: margorp emosewa
awesome program
Calculate Average of Numbers Using Arrays
#include <iostream>
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;
}
Output
Enter the numbers of data: 6
1. Enter number: 45.3
2. Enter number: 67.5
3. Enter number: -45.6
4. Enter number: 20.34
5. Enter number: 33
6. Enter number: 45.6
Average = 27.69
Find Largest Element of an Array
#include <iostream>
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 << "Largest element = " << arr[0];
return 0;
}
output
Enter total number of elements: 8
Enter Number 1: 23.4
Enter Number 2: -34.5
Enter Number 3: 50
Enter Number 4: 33.5
Enter Number 5: 55.5
Enter Number 6: 43.7
Enter Number 7: 5.7
Enter Number 8: -66.5
Largest element = 55.5
Calculate Standard Deviation
#include <iostream>
#include <cmath>
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);
}
output
Enter 10 elements: 1
2
3
4
5
6
7
8
9
10
Standard Deviation = 2.872281
Add Two Matrix Using Multi-dimensional Arrays
#include <iostream>
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;
}
return 0;
}
Output
Enter number of rows (between 1 and 100): 2
Enter number of columns (between 1 and 100): 2
Enter elements of 1st matrix:
Enter element a11: -4
Enter element a12: 5
Enter element a21: 6
Enter element a22: 8
Enter elements of 2nd matrix:
Enter element b11: 3
Enter element b12: -9
Enter element b21: 7
Enter element b22: 2
Sum of two matrix is:
-1 -4
13 10
Multiply Two Matrix Using Multi-dimensional Arrays
#include <iostream>
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;
}
Output
Enter rows and column for first matrix: 3
2
Enter rows and column for second matrix: 3
2
Error! column of first matrix not equal to row of second.
Enter rows and column for first matrix: 2
3
Enter rows and column for second matrix: 3
2
Enter elements of matrix 1:
Enter elements a11: 3
Enter elements a12: -2
Enter elements a13: 5
Enter elements a21: 3
Enter elements a22: 0
Enter elements a23: 4
Enter elements of matrix 2:
Enter elements b11: 2
Enter elements b12: 3
Enter elements b21: -9
Enter elements b22: 0
Enter elements b31: 0
Enter elements b32: 4
Output Matrix:
24 29
6 25
Find the Number of Vowels, Consonants, Digits and White Spaces in a String
#include <iostream>
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;
}
Output
Enter a line of string: This is 1 hell of a book.
Vowels: 7
Consonants: 10
Digits: 1
White spaces: 6
++ Increment Operator Overloading with no return
#include <iostream>
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;
}
Output
i=0
i=1