0% found this document useful (0 votes)
5 views

C++ Example

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

C++ Example

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Simple Examples using C++

Example 1: Hello World!


#include <iostream>
using namespace std;

int main() {
cout<< "Hello, World!" <<endl;
return 0;
}

Example 2: Adding Two Numbers


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int a = 5, b = 3;
int sum = a + b;
cout<< "Sum: " << sum <<endl;
return 0;
}

Example 3: Subtracting Two Numbers


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int a = 5, b = 3;
int difference = a - b;
cout<< "Difference: " << difference <<endl;
return 0;
}

Example 4: Multiplying Two Numbers


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int a = 5, b = 3;
int product = a * b;
cout<< "Product: " << product <<endl;
return 0;
}

Example 5: Dividing Two Numbers


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int a = 6, b = 3;
int quotient = a / b;
cout<< "Quotient: " << quotient <<endl;
return 0;
}

Example 6: Finding Remainder


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int a = 7, b = 3;
int remainder = a % b;
cout<< "Remainder: " << remainder <<endl;
return 0;
}

Example 7: Swapping Two Numbers


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int a = 5, b = 3, temp;
temp = a;
a = b;
b = temp;
cout<< "a: " << a << ", b: " << b <<endl;
return 0;
}

Example 8: Checking Even or Odd


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int num = 5;
if (num % 2 == 0) {
cout<< num << " is even." <<endl;
} else {
cout<< num << " is odd." <<endl;
}
return 0;
}

Example 9: Checking Prime Number


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int num = 29;
bool isPrime = true;
for (int i = 2; i<= num / 2; ++i) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime)
cout<< num << " is a prime number." <<endl;
else
cout<< num << " is not a prime number." <<endl;
return 0;
}

Example 10: Finding Factorial


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int num = 5;
unsigned long long factorial = 1;
for (int i = 1; i<= num; ++i) {
factorial *= i;
}
cout<< "Factorial of " << num << " = " << factorial <<endl;
return 0;
}

Example 11: Finding Fibonacci Sequence


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int n = 10, t1 = 0, t2 = 1, nextTerm = 0;
cout<< "Fibonacci Series: " << t1 << ", " << t2 << ", ";
for (int i = 1; i<= n; ++i) {
nextTerm = t1 + t2;
cout<<nextTerm<< ", ";
t1 = t2;
t2 = nextTerm;
}
return 0;
}
Example 12: Finding GCD
cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int n1 = 56, n2 = 98;
while(n1 != n2) {
if(n1 > n2)
n1 -= n2;
else
n2 -= n1;
}
cout<< "GCD: " << n1 <<endl;
return 0;
}

Example 13: Finding LCM


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int n1 = 72, n2 = 120, lcm;
lcm = (n1 > n2) ? n1 : n2;
while(true) {
if(lcm % n1 == 0 && lcm % n2 == 0) {
cout<< "LCM: " << lcm <<endl;
break;
}
++lcm;
}
return 0;
}

Example 14: Checking Leap Year


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int year = 2020;
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0)
cout<< year << " is a leap year." <<endl;
else
cout<< year << " is not a leap year." <<endl;
} else
cout<< year << " is a leap year." <<endl;
} else
cout<< year << " is not a leap year." <<endl;
return 0;
}

Example 15: Reversing a Number


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int n = 12345, reversedNumber = 0, remainder;
while(n != 0) {
remainder = n % 10;
reversedNumber = reversedNumber * 10 + remainder;
n /= 10;
}
cout<< "Reversed Number: " <<reversedNumber<<endl;
return 0;
}

Example 16: Sum of Digits


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int n = 12345, sum = 0;
while(n != 0) {
sum += n % 10;
n /= 10;
}
cout<< "Sum of Digits: " << sum <<endl;
return 0;
}

Example 17: Palindrome Number


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int n = 12321, reversedNumber = 0, originalNumber, remainder;
originalNumber = n;
while(n != 0) {
remainder = n % 10;
reversedNumber = reversedNumber * 10 + remainder;
n /= 10;
}
if (originalNumber == reversedNumber)
cout<<originalNumber<< " is a palindrome." <<endl;
else
cout<<originalNumber<< " is not a palindrome." <<endl;
return 0;
}
Example 18: Armstrong Number
cpp
Copy code
#include <iostream>
#include <cmath>
using namespace std;

int main() {
int n = 153, originalNumber, remainder, result = 0, nDigits = 0;
originalNumber = n;
while (originalNumber != 0) {
originalNumber /= 10;
++nDigits;
}
originalNumber = n;
while (originalNumber != 0) {
remainder = originalNumber % 10;
result += pow(remainder, nDigits);
originalNumber /= 10;
}
if (result == n)
cout<< n << " is an Armstrong number." <<endl;
else
cout<< n << " is not an Armstrong number." <<endl;
return 0;
}

Example 19: Prime Numbers in a Range


cpp
Copy code
#include <iostream>
using namespace std;

bool isPrime(int n) {
if (n <= 1)
return false;
for (int i = 2; i<= n / 2; ++i) {
if (n % i == 0)
return false;
}
return true;
}

int main() {
int low = 10, high = 50;
cout<< "Prime numbers between " << low << " and " << high << " are: ";
for (int i = low; i<= high; ++i) {
if (isPrime(i))
cout<<i<< " ";
}
cout<<endl;
return 0;
}

Example 20: Sum of Prime Numbers in a Range


cpp
Copy code
#include <iostream>
using namespace std;

bool isPrime(int n) {
if (n <= 1)
return false;
for (int i = 2; i<= n / 2; ++i) {
if (n % i == 0)
return false;
}
return true;
}

int main() {
int low = 10, high = 50, sum = 0;
for (int i = low; i<= high; ++i) {
if (isPrime(i))
sum += i;
}
cout<< "Sum of prime numbers between " << low << " and " << high << " is: " <<
sum <<endl;
return 0;
}

Example 21: Finding Largest Element in an Array


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int max = arr[0];
for (int i = 1; i< n; ++i) {
if (arr[i] > max)
max = arr[i];
}
cout<< "Largest element: " << max <<endl;
return 0;
}

Example 22: Finding Smallest Element in an Array


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int min = arr[0];
for (int i = 1; i< n; ++i) {
if (arr[i] < min)
min = arr[i];
}
cout<< "Smallest element: " << min <<endl;
return 0;
}
Example 23: Sum of Array Elements
cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int sum = 0;
for (int i = 0; i< n; ++i) {
sum += arr[i];
}
cout<< "Sum of elements: " << sum <<endl;
return 0;
}

Example 24: Reversing an Array


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i< n / 2; ++i) {
int temp = arr[i];
arr[i] = arr[n - i - 1];
arr[n - i - 1] = temp;
}
cout<< "Reversed array: ";
for (int i = 0; i< n; ++i) {
cout<<arr[i] << " ";
}
cout<<endl;
return 0;
}

Example 25: Sorting an Array


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int arr[] = {5, 2, 9, 1, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i< n - 1; ++i) {
for (int j = 0; j < n - i - 1; ++j) {
if (arr[j] >arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
cout<< "Sorted array: ";
for (int i = 0; i< n; ++i) {
cout<<arr[i] << " ";
}
cout<<endl;
return 0;
}

Example 26: Linear Search


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 3;
bool found = false;
for (int i = 0; i< n; ++i) {
if (arr[i] == key) {
found = true;
break;
}
}
if (found)
cout<< "Element found." <<endl;
else
cout<< "Element not found." <<endl;
return 0;
}

Example 27: Binary Search


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 3;
int low = 0, high = n - 1, mid;
bool found = false;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] == key) {
found = true;
break;
} else if (arr[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
if (found)
cout<< "Element found." <<endl;
else
cout<< "Element not found." <<endl;
return 0;
}

Example 28: Bubble Sort


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int arr[] = {5, 2, 9, 1, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i< n - 1; ++i) {
for (int j = 0; j < n - i - 1; ++j) {
if (arr[j] >arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
cout<< "Sorted array: ";
for (int i = 0; i< n; ++i) {
cout<<arr[i] << " ";
}
cout<<endl;
return 0;
}

Example 29: Insertion Sort


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int arr[] = {5, 2, 9, 1, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 1; i< n; ++i) {
int key = arr[i];
int j = i - 1;
while (j >= 0 &&arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
cout<< "Sorted array: ";
for (int i = 0; i< n; ++i) {
cout<<arr[i] << " ";
}
cout<<endl;
return 0;
}

Example 30: Selection Sort


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int arr[] = {5, 2, 9, 1, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i< n - 1; ++i) {
int min_idx = i;
for (int j = i + 1; j < n; ++j) {
if (arr[j] <arr[min_idx])
min_idx = j;
}
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
cout<< "Sorted array: ";
for (int i = 0; i< n; ++i) {
cout<<arr[i] << " ";
}
cout<<endl;
return 0;
}

Example 31: String Concatenation


cpp
Copy code
#include <iostream>
#include <string>
using namespace std;

int main() {
string str1 = "Hello, ", str2 = "World!";
string result = str1 + str2;
cout<< "Concatenated String: " << result <<endl;
return 0;
}

Example 32: String Length


cpp
Copy code
#include <iostream>
#include <string>
using namespace std;

int main() {
string str = "Hello, World!";
cout<< "Length of string: " <<str.length() <<endl;
return 0;
}

Example 33: String Reverse


cpp
Copy code
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, World!";
string reversed_str = string(str.rbegin(), str.rend());
cout<< "Reversed String: " <<reversed_str<<endl;
return 0;
}

Example 34: String Palindrome


cpp
Copy code
#include <iostream>
#include <string>
using namespace std;

int main() {
string str = "madam";
string reversed_str = string(str.rbegin(), str.rend());
if (str == reversed_str)
cout<< str << " is a palindrome." <<endl;
else
cout<< str << " is not a palindrome." <<endl;
return 0;
}

Example 35: Counting Vowels in a String


cpp
Copy code
#include <iostream>
#include <string>
using namespace std;

int main() {
string str = "Hello, World!";
int vowel_count = 0;
for (char c : str) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
vowel_count++;
}
}
cout<< "Number of vowels: " <<vowel_count<<endl;
return 0;
}

Example 36: Counting Words in a String


cpp
Copy code
#include <iostream>
#include <string>
using namespace std;

int main() {
string str = "Hello, World!";
int word_count = 0;
bool in_word = false;
for (char c : str) {
if (isspace(c)) {
in_word = false;
} else {
if (!in_word) {
word_count++;
in_word = true;
}
}
}
cout<< "Number of words: " <<word_count<<endl;
return 0;
}

Example 37: Swapping Two Strings


cpp
Copy code
#include <iostream>
#include <string>
using namespace std;

int main() {
string str1 = "Hello", str2 = "World";
string temp = str1;
str1 = str2;
str2 = temp;
cout<< "str1: " << str1 << ", str2: " << str2 <<endl;
return 0;
}

Example 38: Matrix Addition


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int sum[2][2];

for (int i = 0; i< 2; ++i) {


for (int j = 0; j < 2; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}
}

cout<< "Sum of matrices:" <<endl;


for (int i = 0; i< 2; ++i) {
for (int j = 0; j < 2; ++j) {
cout<< sum[i][j] << " ";
}
cout<<endl;
}
return 0;
}

Example 39: Matrix Multiplication


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int product[2][2] = {0};

for (int i = 0; i< 2; ++i) {


for (int j = 0; j < 2; ++j) {
for (int k = 0; k < 2; ++k) {
product[i][j] += a[i][k] * b[k][j];
}
}
}

cout<< "Product of matrices:" <<endl;


for (int i = 0; i< 2; ++i) {
for (int j = 0; j < 2; ++j) {
cout<< product[i][j] << " ";
}
cout<<endl;
}
return 0;
}

Example 40: Transpose of a Matrix


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int transpose[2][2];

for (int i = 0; i< 2; ++i) {


for (int j = 0; j < 2; ++j) {
transpose[i][j] = a[j][i];
}
}

cout<< "Transpose of matrix:" <<endl;


for (int i = 0; i< 2; ++i) {
for (int j = 0; j < 2; ++j) {
cout<< transpose[i][j] << " ";
}
cout<<endl;
}
return 0;
}

Example 41: Class and Object


cpp
Copy code
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
void display() {
cout<< "Name: " << name << ", Age: " << age <<endl;
}
};

int main() {
Person p1;
p1.name = "John";
p1.age = 30;
p1.display();
return 0;
}

Example 42: Constructor and Destructor


cpp
Copy code
#include <iostream>
using namespace std;

class Person {
public:
string name;
int age;

Person(string n, int a) {
name = n;
age = a;
cout<< "Constructor called" <<endl;
}

~Person() {
cout<< "Destructor called" <<endl;
}

void display() {
cout<< "Name: " << name << ", Age: " << age <<endl;
}
};

int main() {
Person p1("John", 30);
p1.display();
return 0;
}

Example 43: Inheritance


cpp
Copy code
#include <iostream>
using namespace std;

class Animal {
public:
void eat() {
cout<< "Eating..." <<endl;
}
};

class Dog : public Animal {


public:
void bark() {
cout<< "Barking..." <<endl;
}
};

int main() {
Dog d;
d.eat();
d.bark();
return 0;
}

Example 44: Polymorphism


cpp
Copy code
#include <iostream>
using namespace std;

class Animal {
public:
virtual void sound() {
cout<< "Animal sound" <<endl;
}
};

class Dog : public Animal {


public:
void sound() override {
cout<< "Bark" <<endl;
}
};

class Cat : public Animal {


public:
void sound() override {
cout<< "Meow" <<endl;
}
};

int main() {
Animal* a;
Dog d;
Cat c;

a = &d;
a->sound();

a = &c;
a->sound();

return 0;
}

Example 45: Friend Function


cpp
Copy code
#include <iostream>
using namespace std;

class Box {
double width;

public:
friend void printWidth(Box b);
void setWidth(double w) {
width = w;
}
};

void printWidth(Box b) {
cout<< "Width of box: " <<b.width<<endl;
}

int main() {
Box b;
b.setWidth(10.5);
printWidth(b);
return 0;
}

Example 46: Operator Overloading


cpp
Copy code
#include <iostream>
using namespace std;

class Complex {
public:
int real, imag;

Complex() : real(0), imag(0) {}

Complex operator + (const Complex& obj) {


Complex temp;
temp.real = real + obj.real;
temp.imag = imag + obj.imag;
return temp;
}
};

int main() {
Complex c1, c2, result;
c1.real = 3;
c1.imag = 2;
c2.real = 1;
c2.imag = 7;
result = c1 + c2;
cout<< "Result = " <<result.real<< " + " <<result.imag<< "i" <<endl;
return 0;
}

Example 47: Templates


cpp
Copy code
#include <iostream>
using namespace std;

template <typename T>


T add(T a, T b) {
return a + b;
}

int main() {
cout<< "Sum of integers: " << add<int>(3, 4) <<endl;
cout<< "Sum of doubles: " << add<double>(3.5, 4.5) <<endl;
return 0;
}

Example 48: Exception Handling


cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int x = 5, y = 0;
try {
if (y == 0) {
throw "Division by zero!";
}
cout<< x / y <<endl;
} catch (const char* msg) {
cout<< "Error: " << msg <<endl;
}
return 0;
}

Example 49: File I/O


cpp
Copy code
#include <iostream>
#include <fstream>
using namespace std;

int main() {
ofstreamoutFile("example.txt");
outFile<< "Hello, World!" <<endl;
outFile.close();

ifstreaminFile("example.txt");
string line;
while (getline(inFile, line)) {
cout<< line <<endl;
}
inFile.close();
return 0;
}

Example 50: Using the vector STL


cpp
Copy code
#include <iostream>
#include <vector>
using namespace std;

int main() {
vector<int>vec = {1, 2, 3, 4, 5};
vec.push_back(6);
for (int i :vec) {
cout<<i<< " ";
}
cout<<endl;
return 0;
}

You might also like