In this blog, we will look into the codes that range from basic to intermediate and advanced levels and explore C++ programs that unlock the full potential of this versatile language.
Table of Contents
Check out our YouTube video on C programming language for absolute beginners!
What are C++ Programs?
C++ programs are software applications developed using the C++ programming language. Programmers can design a wide range of applications with this flexible and strong programming language, from straightforward console-based tools to complex high-performance software. C++ is renowned for its efficiency and speed in programming because it offers low-level access to hardware and memory.
C++ is used in designing system software, game development, embedded systems, and performance-critical applications. Because of its syntax and features, the language can be used for jobs that require great efficiency and optimization with fine-grained control over program execution.
Do you want to jumpstart your career in computer programming? Enroll in our C Programming Course and gain the skills to succeed!
Basic C++ Programs
Basic C++ programs are designed to introduce fundamental programming concepts and syntax to beginners. A typical simple C++ program involves declaring variables, taking input from the user, performing basic arithmetic operations, and displaying results. The iostream library is often used for input and output operations, and the using namespace std directive simplifies code by allowing the use of cin and cout without the std:: prefix.
Write a Program to Add Two Numbers
#include <iostream>
using namespace std;
int main() {
int num1, num2, sum;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
sum = num1 + num2;
cout << "Sum of " << num1 << " and " << num2 << " is: " << sum << endl;
return 0;
}
Output:
Write a Program to Check Whether a Number is Odd or Even
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
// Check if the number is divisible by 2
if (number % 2 == 0) {
cout << number << " is an even number." << endl;
} else {
cout << number << " is an odd number." << endl;
}
return 0;
}
Output:
Write a Program to Find the Quotient and Remainder
#include <iostream>
using namespace std;
int main() {
int dividend, divisor, quotient, remainder;
cout << "Enter dividend: ";
cin >> dividend;
cout << "Enter divisor: ";
cin >> divisor;
// Calculate quotient and remainder
quotient = dividend / divisor;
remainder = dividend % divisor;
cout << "Quotient: " << quotient << endl;
cout << "Remainder: " << remainder << endl;
return 0;
}
Output:
Write a Program to Swap Two Numbers
#include <iostream>
using namespace std;
int main() {
int firstNum, secondNum, temp;
cout << "Enter first number: ";
cin >> firstNum;
cout << "Enter second number: ";
cin >> secondNum;
cout << "Before swapping:" << endl;
cout << "First number = " << firstNum << endl;
cout << "Second number = " << secondNum << endl;
// Swapping logic using a temporary variable
temp = firstNum;
firstNum = secondNum;
secondNum = temp;
cout << "After swapping:" << endl;
cout << "First number = " << firstNum << endl;
cout << "Second number = " << secondNum << endl;
return 0;
}
Output:
Write a Program to Find the Largest of Two Numbers
#include <iostream>
using namespace std;
int main() {
int num1, num2;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
if (num1 > num2) {
cout << "The largest number is: " << num1 << endl;
} else if (num2 > num1) {
cout << "The largest number is: " << num2 << endl;
} else {
cout << "Both numbers are equal." << endl;
}
return 0;
}
Output:
Find out how to use the Boyer Moore Algorithm for Pattern Searching for Good Suffix Heuristics and Bad Character. Obtain the C++ code for it as well.
Write a Program to Check Whether a Character is a Vowel or Consonant
#include <iostream>
using namespace std;
int main() {
char ch;
cout << "Enter a character: ";
cin >> ch;
// Converting input to lowercase for easier comparison
ch = tolower(ch);
// Checking if the entered character is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
cout << ch << " is a vowel." << endl;
} else if ((ch >= 'a' && ch <= 'z')) {
cout << ch << " is a consonant." << endl;
} else {
cout << "Invalid input. Please enter an alphabet." << endl;
}
return 0;
}
Output:
Get 100% Hike!
Master Most in Demand Skills Now !
Write a Program to Print the Fibonacci Series
#include <iostream>
using namespace std;
int main() {
int n, firstTerm = 0, secondTerm = 1, nextTerm;
cout << "Enter the number of terms for Fibonacci series: ";
cin >> n;
cout << "Fibonacci Series:" << endl;
for (int i = 0; i < n; ++i) {
if (i <= 1) {
nextTerm = i;
} else {
nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
cout << nextTerm << " ";
}
cout << endl;
return 0;
}
Output:
Write a Program to Find the Factorial of a Number
#include <iostream>
using namespace std;
int main() {
int num;
unsigned long long factorial = 1;
cout << "Enter a positive integer: ";
cin >> num;
if (num < 0) {
cout << "Factorial is not defined for negative numbers." << endl;
} else {
for (int i = 1; i <= num; ++i) {
factorial *= i;
}
cout << "Factorial of " << num << " = " << factorial << endl;
}
return 0;
}
Output:
Write a Program to Check Whether a Number is Armstrong or Not
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int number, originalNumber, remainder, digits = 0;
double result = 0.0;
cout << "Enter an integer: ";
cin >> number;
originalNumber = number;
// Count number of digits
while (originalNumber != 0) {
originalNumber /= 10;
++digits;
}
originalNumber = number;
// Calculate result
while (originalNumber != 0) {
remainder = originalNumber % 10;
result += pow(remainder, digits);
originalNumber /= 10;
}
// Check if the number is Armstrong or not
if (static_cast<int>(result) == number) {
cout << number << " is an Armstrong number." << endl;
} else {
cout << number << " is not an Armstrong number." << endl;
}
return 0;
}
Output:
Write a Program to Check Whether a Number is a Palindrome or Not
#include <iostream>
using namespace std;
int main() {
int num, reversedNum = 0, originalNum, remainder;
cout << "Enter an integer: ";
cin >> num;
originalNum = num;
// Reversing the number
while (num > 0) {
remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}
// Checking if the number is a palindrome
if (originalNum == reversedNum) {
cout << originalNum << " is a palindrome." << endl;
} else {
cout << originalNum << " is not a palindrome." << endl;
}
return 0;
}
Output:
Intermediate C++ programs typically involve more complex logic and functionality compared to basic programs. These programs often include concepts such as functions, classes, and object-oriented programming principles. Intermediate-level C++ projects might require the use of data structures like arrays, vectors, and strings, along with control structures such as loops and conditional statements. Memory management, pointers, and dynamic memory allocation become more common at this stage.
Check out C++ Interview Questions to crack your next interview!
Write a Program to Reverse an Integer
#include <iostream>
using namespace std;
int main() {
int num, reversedNum = 0, remainder;
cout << "Enter an integer: ";
cin >> num;
while (num != 0) {
remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}
cout << "Reversed number: " << reversedNum << endl;
return 0;
}
Output:
Write a Program to Swap Nodes in Pairs
#include <iostream>
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* swapPairs(ListNode* head) {
// Create a dummy node to serve as the new head
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* prev = dummy;
while (head && head->next) {
// Nodes to be swapped
ListNode* firstNode = head;
ListNode* secondNode = head->next;
// Swapping
prev->next = secondNode;
firstNode->next = secondNode->next;
secondNode->next = firstNode;
// Move pointers for next iteration
prev = firstNode;
head = firstNode->next;
}
return dummy->next;
}
// Function to print the linked list
void printList(ListNode* head) {
while (head) {
std::cout << head->val << " ";
head = head->next;
}
std::cout << std::endl;
}
int main() {
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
std::cout << "Original List: ";
printList(head);
ListNode* swapped = swapPairs(head);
std::cout << "After Swapping in Pairs: ";
printList(swapped);
return 0;
}
Output:
Write a Program to Convert an Integer to Roman Numerals
#include <iostream>
#include <vector>
using namespace std;
string intToRoman(int num) {
vector<pair<int, string>> romanMap = {
{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"},
{90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"},
{5, "V"}, {4, "IV"}, {1, "I"}
};
string roman;
for (const auto& pair : romanMap) {
while (num >= pair.first) {
roman += pair.second;
num -= pair.first;
}
}
return roman;
}
int main() {
int num;
cout << "Enter an integer: ";
cin >> num;
if (num <= 0 || num > 3999) {
cout << "The number is out of the valid range (1 to 3999) for Roman numerals." << endl;
} else {
string romanNumeral = intToRoman(num);
cout << "The Roman numeral equivalent of " << num << " is: " << romanNumeral << endl;
}
return 0;
}
Output:
Write a Program to Divide Two Integers
#include <iostream>
#include <stdexcept>
int divideIntegers(int dividend, int divisor) {
if (divisor == 0) {
throw std::invalid_argument("Division by zero error");
}
return dividend / divisor;
}
int main() {
int dividend = 10;
int divisor = 2;
try {
int result = divideIntegers(dividend, divisor);
std::cout << "Result of division: " << result << std::endl;
} catch (const std::invalid_argument& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
Output:
Write a Program to Generate Parentheses
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void generateParentheses(int open, int close, int n, string current, vector<string>& result) {
if (current.length() == n * 2) {
result.push_back(current);
return;
}
if (open < n) {
generateParentheses(open + 1, close, n, current + '(', result);
}
if (close < open) {
generateParentheses(open, close + 1, n, current + ')', result);
}
}
vector<string> generateParenthesis(int n) {
vector<string> result;
generateParentheses(0, 0, n, "", result);
return result;
}
int main() {
int numPairs;
cout << "Enter the number of pairs for parentheses: ";
cin >> numPairs;
vector<string> parentheses = generateParenthesis(numPairs);
cout << "Valid combinations of parentheses for " << numPairs << " pairs:" << endl;
for (const string& p : parentheses) {
cout << p << endl;
}
return 0;
}
Output:
Write a Program to Find the Next Permutation
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void nextPermutation(vector<int>& nums) {
int n = nums.size(), i = n - 2;
// Find the first decreasing element from the right
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--;
}
if (i >= 0) {
int j = n - 1;
// Find the number just greater than nums[i]
while (nums[j] <= nums[i]) {
j--;
}
// Swap nums[i] and nums[j]
swap(nums[i], nums[j]);
}
// Reverse the sequence after i to get the next permutation
reverse(nums.begin() + i + 1, nums.end());
}
int main() {
vector<int> nums;
int size, input;
cout << "Enter the size of the sequence: ";
cin >> size;
cout << "Enter the elements of the sequence: ";
for (int i = 0; i < size; ++i) {
cin >> input;
nums.push_back(input);
}
cout << "Current permutation: ";
for (int num : nums) {
cout << num << " ";
}
cout << endl;
nextPermutation(nums);
cout << "Next permutation: ";
for (int num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}
Output:
Write a Program to Find a Combination Sum
#include <iostream>
#include <vector>
using namespace std;
void findCombinations(vector<int>& candidates, int target, vector<vector<int>>& result, vector<int>& combination, int start) {
if (target == 0) {
result.push_back(combination);
return;
}
for (int i = start; i < candidates.size() && target >= candidates[i]; ++i) {
combination.push_back(candidates[i]);
findCombinations(candidates, target - candidates[i], result, combination, i);
combination.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> result;
vector<int> combination;
findCombinations(candidates, target, result, combination, 0);
return result;
}
int main() {
vector<int> candidates = {2, 3, 6, 7}; // Example input
int target = 7; // Example target sum
vector<vector<int>> combinations = combinationSum(candidates, target);
cout << "Unique combinations that sum up to " << target << ":" << endl;
for (const auto& combination : combinations) {
cout << "[ ";
for (int num : combination) {
cout << num << " ";
}
cout << "]" << endl;
}
return 0;
}
Output:
Write a Program to Find the Maximum Subarray
#include <iostream>
#include <vector>
int maxSubArray(std::vector<int>& nums) {
int max_sum = nums[0];
int current_sum = nums[0];
for (size_t i = 1; i < nums.size(); ++i) {
current_sum = std::max(nums[i], current_sum + nums[i]);
max_sum = std::max(max_sum, current_sum);
}
return max_sum;
}
int main() {
std::vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int maxSum = maxSubArray(nums);
std::cout << "Maximum subarray sum is: " << maxSum << std::endl;
return 0;
}
Output:
Write a Program to Multiply String Numbers
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string multiplyStrings(string num1, string num2) {
int len1 = num1.size();
int len2 = num2.size();
// Result will have at most len1 + len2 digits
vector<int> result(len1 + len2, 0);
// Perform multiplication digit by digit
for (int i = len1 - 1; i >= 0; --i) {
for (int j = len2 - 1; j >= 0; --j) {
int product = (num1[i] - '0') * (num2[j] - '0');
int sum = product + result[i + j + 1];
result[i + j] += sum / 10;
result[i + j + 1] = sum % 10;
}
}
// Remove leading zeroes from result
int start = 0;
while (start < len1 + len2 && result[start] == 0) {
start++;
}
if (start == len1 + len2) {
return "0";
}
string res = "";
for (int i = start; i < len1 + len2; ++i) {
res += to_string(result[i]);
}
return res;
}
int main() {
string num1, num2;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
string product = multiplyStrings(num1, num2);
cout << "Product of " << num1 << " and " << num2 << " is: " << product << endl;
return 0;
}
Output:
Write a Program to Find Permutations
#include <iostream>
#include <vector>
using namespace std;
void generatePermutations(string& str, int start, vector<string>& result) {
if (start == str.size() - 1) {
result.push_back(str);
return;
}
for (int i = start; i < str.size(); ++i) {
swap(str[start], str[i]);
generatePermutations(str, start + 1, result);
swap(str[start], str[i]); // Backtrack
}
}
vector<string> permutations(string str) {
vector<string> result;
generatePermutations(str, 0, result);
return result;
}
int main() {
string input;
cout << "Enter a string: ";
cin >> input;
vector<string> perms = permutations(input);
cout << "Permutations of " << input << " are:" << endl;
for (const string& perm : perms) {
cout << perm << endl;
}
return 0;
}
Output:
Advanced C++ Programs
Advanced C++ programs typically involve the use of advanced features and techniques to create efficient, scalable, and robust software solutions. To improve code organization and maintainability, these systems may use ideas like smart pointers, templates, object-oriented programming (OOP), multithreading, and exception handling. Standard template library (STL) components are frequently used in advanced C++ to optimize code for speed in data structures and algorithms.
Learn what a Linear Data Structure is and how it works!
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int totalElements = nums1.size() + nums2.size();
int i = 0, j = 0, count = 0;
double median;
vector<int> merged;
while (i < nums1.size() && j < nums2.size() && count <= totalElements / 2) {
if (nums1[i] <= nums2[j]) {
merged.push_back(nums1[i]);
i++;
} else {
merged.push_back(nums2[j]);
j++;
}
count++;
}
while (i < nums1.size() && count <= totalElements / 2) {
merged.push_back(nums1[i]);
i++;
count++;
}
while (j < nums2.size() && count <= totalElements / 2) {
merged.push_back(nums2[j]);
j++;
count++;
}
if (totalElements % 2 == 0) {
median = (double)(merged[totalElements / 2 - 1] + merged[totalElements / 2]) / 2;
} else {
median = merged[totalElements / 2];
}
return median;
}
int main() {
int size1, size2;
cout << "Enter the size of the first sorted array: ";
cin >> size1;
vector<int> nums1(size1);
cout << "Enter elements of the first sorted array: ";
for (int i = 0; i < size1; ++i) {
cin >> nums1[i];
}
cout << "Enter the size of the second sorted array: ";
cin >> size2;
vector<int> nums2(size2);
cout << "Enter elements of the second sorted array: ";
for (int i = 0; i < size2; ++i) {
cin >> nums2[i];
}
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
cout << "\nSorted arrays:" << endl;
cout << "First sorted array: ";
for (int num : nums1) {
cout << num << " ";
}
cout << endl;
cout << "Second sorted array: ";
for (int num : nums2) {
cout << num << " ";
}
cout << endl;
double median = findMedianSortedArrays(nums1, nums2);
cout << "\nMedian of the two sorted arrays: " << median << endl;
return 0;
}
Output:
Write a Program to Implement Multiple Inheritance with Virtual Base Classes
#include <iostream>
using namespace std;
// Base class 1
class Base1 {
public:
void displayBase1() {
cout << "Base1 Display" << endl;
}
};
// Base class 2
class Base2 {
public:
void displayBase2() {
cout << "Base2 Display" << endl;
}
};
// Virtual base class
class VirtualBase {
public:
void displayVirtualBase() {
cout << "Virtual Base Display" << endl;
}
};
// Derived class inheriting from multiple base classes virtually
class Derived : public virtual Base1, public virtual Base2, public VirtualBase {
public:
void displayDerived() {
cout << "Derived Display" << endl;
}
};
int main() {
Derived obj;
// Accessing methods from derived class
obj.displayDerived();
// Accessing methods from base classes
obj.displayBase1();
obj.displayBase2();
// Accessing method from virtual base class
obj.displayVirtualBase();
return 0;
}
Output:
Write a Program to Solve Sudoku
#include <iostream>
#include <vector>
using namespace std;
const int BOARD_SIZE = 9;
bool isValid(vector<vector<int>>& board, int row, int col, int num) {
// Check row and column for the presence of the number
for (int i = 0; i < BOARD_SIZE; ++i) {
if (board[row][i] == num || board[i][col] == num) {
return false;
}
}
// Check 3x3 subgrid for the presence of the number
int subgridStartRow = row - row % 3;
int subgridStartCol = col - col % 3;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (board[subgridStartRow + i][subgridStartCol + j] == num) {
return false;
}
}
}
return true;
}
bool findEmptyLocation(vector<vector<int>>& board, int& row, int& col) {
for (row = 0; row < BOARD_SIZE; ++row) {
for (col = 0; col < BOARD_SIZE; ++col) {
if (board[row][col] == 0) {
return true;
}
}
}
return false;
}
bool solveSudoku(vector<vector<int>>& board) {
int row, col;
if (!findEmptyLocation(board, row, col)) {
return true; // Puzzle solved
}
for (int num = 1; num <= BOARD_SIZE; ++num) {
if (isValid(board, row, col, num)) {
board[row][col] = num;
if (solveSudoku(board)) {
return true; // Recursively solve the rest of the puzzle
}
board[row][col] = 0; // Backtrack if the current choice doesn't lead to a solution
}
}
return false; // No solution found
}
void printBoard(const vector<vector<int>>& board) {
for (int i = 0; i < BOARD_SIZE; ++i) {
for (int j = 0; j < BOARD_SIZE; ++j) {
cout << board[i][j] << " ";
}
cout << endl;
}
}
int main() {
vector<vector<int>> board = {
{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}
};
if (solveSudoku(board)) {
cout << "Sudoku puzzle solved:" << endl;
printBoard(board);
} else {
cout << "No solution exists for the given Sudoku puzzle." << endl;
}
return 0;
}
Output:
Write a Program to Implement a Custom Allocator for STL Containers
#include <iostream>
#include <memory>
#include <vector>
// Custom allocator class
template <typename T>
class CustomAllocator {
public:
using value_type = T;
CustomAllocator() noexcept = default;
template <class U>
CustomAllocator(const CustomAllocator<U>&) noexcept {}
T* allocate(std::size_t n) {
return static_cast<T*>(::operator new(n * sizeof(T)));
}
void deallocate(T* p, std::size_t) noexcept {
::operator delete(p);
}
};
// Example usage of the custom allocator with a vector
int main() {
// Define a vector that uses the custom allocator
std::vector<int, CustomAllocator<int>> customVector;
// Push elements into the vector
for (int i = 1; i <= 5; ++i) {
customVector.push_back(i * 10);
}
// Display elements in the vector
for (const auto& num : customVector) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
Output:
Write a Program to Simulate a Garbage Collector Using Smart Pointers
#include <iostream>
#include <memory>
#include <vector>
// Define a simple class
class MyClass {
public:
MyClass() {
std::cout << "MyClass Constructor" << std::endl;
}
~MyClass() {
std::cout << "MyClass Destructor" << std::endl;
}
void display() {
std::cout << "Displaying MyClass object" << std::endl;
}
};
int main() {
// Creating a shared pointer to MyClass
std::shared_ptr<MyClass> ptr1 = std::make_shared<MyClass>();
// Using the shared pointer
ptr1->display();
// Creating another shared pointer to the same object
std::shared_ptr<MyClass> ptr2 = ptr1;
// Displaying reference count
std::cout << "Reference count: " << ptr1.use_count() << std::endl;
// Exiting the scope of ptr1, but ptr2 still holds a reference
ptr1.reset();
// Displaying reference count after resetting ptr1
std::cout << "Reference count after reset: " << ptr2.use_count() << std::endl;
// Exiting the scope of ptr2, no more references
ptr2.reset();
return 0;
}
Output:
Write a Program to Demonstrate Compile-Time and Run-Time Polymorphism Together
#include <iostream>
// Compile-time polymorphism using function overloading
class CompileTimePolymorphism {
public:
void show(int value) {
std::cout << "Showing integer value: " << value << std::endl;
}
void show(double value) {
std::cout << "Showing double value: " << value << std::endl;
}
};
// Run-time polymorphism using inheritance and virtual functions
class Base {
public:
virtual void display() {
std::cout << "Base class display" << std::endl;
}
};
class Derived : public Base {
public:
void display() override {
std::cout << "Derived class display" << std::endl;
}
};
int main() {
// Compile-time polymorphism
CompileTimePolymorphism ctp;
ctp.show(10);
ctp.show(3.14);
// Run-time polymorphism
Base* basePtr;
Derived derivedObj;
basePtr = &derivedObj; // Assigning address of derived class object to base class pointer
basePtr->display(); // Calls the overridden function based on the actual object type
return 0;
}
Output:
Write a Program to Implement Your Own Type-Trai
#include <iostream>
#include <type_traits>
// Primary template
template <typename T>
struct IsInteger {
static constexpr bool value = std::is_integral<T>::value;
};
// Test function to check type
template <typename T>
void CheckIntegerType() {
if (IsInteger<T>::value) {
std::cout << "Type is an integer." << std::endl;
} else {
std::cout << "Type is not an integer." << std::endl;
}
}
int main() {
CheckIntegerType<int>(); // Test with int
CheckIntegerType<float>(); // Test with float
return 0;
}
Output:
Write a Program to Demonstrate Exception Handling Across Multiple Threads
#include <iostream>
#include <thread>
#include <future>
#include <stdexcept>
void threadFunction(std::promise<std::exception_ptr>& prom) {
try {
// Simulate an exception in a thread
throw std::runtime_error("Exception in threadFunction");
} catch (...) {
// Store the exception in the promise
prom.set_exception(std::current_exception());
}
}
int main() {
std::promise<std::exception_ptr> prom;
std::future<std::exception_ptr> fut = prom.get_future();
// Launch a thread with exception handling
std::thread t(threadFunction, std::ref(prom));
// Wait for the thread to finish
t.join();
// Check for any exceptions thrown in the thread
try {
// Retrieve the exception from the future
std::exception_ptr eptr = fut.get();
if (eptr) {
// Re-throw the exception caught in the thread
std::rethrow_exception(eptr);
} else {
std::cout << "No exception in the thread." << std::endl;
}
} catch (const std::exception& e) {
// Handle the exception caught from the thread
std::cout << "Exception caught in main: " << e.what() << std::endl;
}
return 0;
}
Output:
Write a Program for Regular Expression Matching
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string text = "The quick brown fox jumps over the lazy dog";
std::regex pattern("quick.*fox");
// Using regex_search to check if the pattern matches the text
if (std::regex_search(text, pattern)) {
std::cout << "Pattern found in the text!" << std::endl;
} else {
std::cout << "Pattern not found in the text." << std::endl;
}
return 0;
}
Output:
Write a Program for Text Justification
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
// Function to justify text within a given line width
vector<string> justifyText(const string& text, int line_width) {
vector<string> justified_text;
istringstream iss(text);
string word;
string line;
while (iss >> word) {
if (line.size() + word.size() <= static_cast<size_t>(line_width)) {
line += word + " ";
} else {
justified_text.push_back(line);
line = word + " ";
}
}
if (!line.empty()) {
justified_text.push_back(line);
}
return justified_text;
}
// Function to display justified text
void displayJustifiedText(const vector<string>& justified_text) {
for (const auto& line : justified_text) {
cout << line << endl;
}
}
int main() {
// Input text to be justified
string input_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
// Justify the input text with a line width of 30 characters
int line_width = 30;
vector<string> justified_text = justifyText(input_text, line_width);
// Display the justified text
displayJustifiedText(justified_text);
return 0;
}
Output:
Don’t miss out on the latest programming trends and advancements; be part of today!