Write a simple C++ program to print "Hello, World!".
#includeint main() { std::cout << "Hello, World!" << std::endl; return 0; }
Perform basic arithmetic operations (addition, subtraction, multiplication, division).
#includeint main() { int a, b; std::cout << "Enter two numbers: "; std::cin >> a >> b; std::cout << "Addition: " << a + b << std::endl; std::cout << "Subtraction: " << a - b << std::endl; std::cout << "Multiplication: " << a * b << std::endl; std::cout << "Division: " << a / b << std::endl; return 0; }
Display the size of different data types in C++.
#includeint main() { std::cout << "Size of int: " << sizeof(int) << " bytes" << std::endl; std::cout << "Size of float: " << sizeof(float) << " bytes" << std::endl; std::cout << "Size of double: " << sizeof(double) << " bytes" << std::endl; std::cout << "Size of char: " << sizeof(char) << " bytes" << std::endl; return 0; }
Calculate the area of a circle given its radius.
#include#define PI 3.14159 int main() { float radius, area; std::cout << "Enter the radius of the circle: "; std::cin >> radius; area = PI * radius * radius; std::cout << "Area of the circle: " << area << std::endl; return 0; }
Convert temperature from Celsius to Fahrenheit.
#includeint main() { float celsius, fahrenheit; std::cout << "Enter temperature in Celsius: "; std::cin >> celsius; fahrenheit = (celsius * 9 / 5) + 32; std::cout << "Temperature in Fahrenheit: " << fahrenheit << std::endl; return 0; }
Check if a number is even or odd.
#includeint main() { int num; std::cout << "Enter an integer: "; std::cin >> num; if (num % 2 == 0) { std::cout << num << " is even." << std::endl; } else { std::cout << num << " is odd." << std::endl; } return 0; }
Find the largest of three numbers.
#includeint main() { int a, b, c; std::cout << "Enter three numbers: "; std::cin >> a >> b >> c; if (a >= b && a >= c) { std::cout << "The largest number is: " << a << std::endl; } else if (b >= a && b >= c) { std::cout << "The largest number is: " << b << std::endl; } else { std::cout << "The largest number is: " << c << std::endl; } return 0; }
Create a simple calculator using switch-case.
#includeint main() { char op; float num1, num2; std::cout << "Enter operator (+, -, *, /): "; std::cin >> op; std::cout << "Enter two operands: "; std::cin >> num1 >> num2; switch (op) { case '+': std::cout << num1 << " + " << num2 << " = " << num1 + num2 << std::endl; break; case '-': std::cout << num1 << " - " << num2 << " = " << num1 - num2 << std::endl; break; case '*': std::cout << num1 << " * " << num2 << " = " << num1 * num2 << std::endl; break; case '/': if (num2 != 0) { std::cout << num1 << " / " << num2 << " = " << num1 / num2 << std::endl; } else { std::cout << "Division by zero error!" << std::endl; } break; default: std::cout << "Invalid operator!" << std::endl; break; } return 0; }
Calculate the sum of first N natural numbers using a loop.
#includeint main() { int n, sum = 0; std::cout << "Enter a positive integer: "; std::cin >> n; for (int i = 1; i <= n; ++i) { sum += i; } std::cout << "Sum of first " << n << " natural numbers is: " << sum << std::endl; return 0; }
Print the multiplication table of a given number.
#includeint main() { int num; std::cout << "Enter a positive integer: "; std::cin >> num; for (int i = 1; i <= 10; ++i) { std::cout << num << " * " << i << " = " << num * i << std::endl; } return 0; }
Calculate the factorial of a number using a function.
#includeint factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } int main() { int num; std::cout << "Enter a positive integer: "; std::cin >> num; std::cout << "Factorial of " << num << " is: " << factorial(num) << std::endl; return 0; }
Check if a number is prime using a function.
#includebool 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 num; std::cout << "Enter a positive integer: "; std::cin >> num; if (isPrime(num)) { std::cout << num << " is a prime number." << std::endl; } else { std::cout << num << " is not a prime number." << std::endl; } return 0; }
Find the greatest common divisor (GCD) of two numbers using a function.
#includeint gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int main() { int num1, num2; std::cout << "Enter two positive integers: "; std::cin >> num1 >> num2; std::cout << "GCD of " << num1 << " and " << num2 << " is: " << gcd(num1, num2) << std::endl; return 0; }
Print the Fibonacci sequence up to N terms using a function.
#includevoid printFibonacci(int n) { int t1 = 0, t2 = 1, nextTerm = 0; for (int i = 1; i <= n; ++i) { if (i == 1) { std::cout << t1 << " "; continue; } if (i == 2) { std::cout << t2 << " "; continue; } nextTerm = t1 + t2; t1 = t2; t2 = nextTerm; std::cout << nextTerm << " "; } } int main() { int num; std::cout << "Enter the number of terms: "; std::cin >> num; std::cout << "Fibonacci Series: "; printFibonacci(num); std::cout << std::endl; return 0; }
Find the sum of digits of a number using a function.
#includesumOfDigits(int n) { int sum = 0; while (n != 0) { sum += n % 10; n /= 10; } return sum; } int main() { int num; std::cout << "Enter a positive integer: "; std::cin >> num; std::cout << "Sum of digits of " << num << " is: " << sumOfDigits(num) << std::endl; return 0; }
Calculate the sum of all elements in an array.
#includeint main() { int n, sum = 0; std::cout << "Enter the number of elements: "; std::cin >> n; int arr[n]; std::cout << "Enter the elements of the array: "; for (int i = 0; i < n; ++i) { std::cin >> arr[i]; sum += arr[i]; } std::cout << "Sum of array elements: " << sum << std::endl; return 0; }
Reverse the elements of an array.
#includeint main() { int n; std::cout << "Enter the number of elements: "; std::cin >> n; int arr[n]; std::cout << "Enter the elements of the array: "; for (int i = 0; i < n; ++i) { std::cin >> arr[i]; } std::cout << "Reversed array: "; for (int i = n - 1; i >= 0; --i) { std::cout << arr[i] << " "; } std::cout << std::endl; return 0; }
Find the largest element in an array.
#includeint main() { int n; std::cout << "Enter the number of elements: "; std::cin >> n; int arr[n]; std::cout << "Enter the elements of the array: "; for (int i = 0; i < n; ++i) { std::cin >> arr[i]; } int largest = arr[0]; for (int i = 1; i < n; ++i) { if (arr[i] > largest) { largest = arr[i]; } } std::cout << "The largest element in the array is: " << largest << std::endl; return 0; }
Check if a given string is a palindrome.
#include#include int main() { std::string str, revStr; std::cout << "Enter a string: "; std::cin >> str; revStr = std::string(str.rbegin(), str.rend()); if (str == revStr) { std::cout << str << " is a palindrome." << std::endl; } else { std::cout << str << " is not a palindrome." << std::endl; } return 0; }
Count the number of vowels in a given string.
#include#include int main() { std::string str; int count = 0; std::cout << "Enter a string: "; std::cin >> str; for (char ch : str) { if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') { ++count; } } std::cout << "Number of vowels in the string: " << count << std::endl; return 0; }
Demonstrate the basic use of pointers.
#includeint main() { int var = 20; int* ptr = &var; std::cout << "Value of var: " << var << std::endl; std::cout << "Address of var: " << &var << std::endl; std::cout << "Value of ptr: " << ptr << std::endl; std::cout << "Value pointed to by ptr: " << *ptr << std::endl; return 0; }
Allocate memory dynamically for an array.
#includeint main() { int n; std::cout << "Enter the number of elements: "; std::cin >> n; int* arr = new int[n]; std::cout << "Enter the elements of the array: "; for (int i = 0; i < n; ++i) { std::cin >> arr[i]; } std::cout << "Array elements: "; for (int i = 0; i < n; ++i) { std::cout << arr[i] << " "; } std::cout << std::endl; delete[] arr; return 0; }
Swap two numbers using pointers.
#includevoid swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } int main() { int x, y; std::cout << "Enter two numbers: "; std::cin >> x >> y; std::cout << "Before swapping: x = " << x << ", y = " << y << std::endl; swap(&x, &y); std::cout << "After swapping: x = " << x << ", y = " << y << std::endl; return 0; }
Reverse a string using pointers.
#include#include void reverse(char* str) { int n = strlen(str); for (int i = 0; i < n / 2; ++i) { char temp = str[i]; str[i] = str[n - i - 1]; str[n - i - 1] = temp; } } int main() { char str[100]; std::cout << "Enter a string: "; std::cin >> str; reverse(str); std::cout << "Reversed string: " << str << std::endl; return 0; }
Create a dynamic 2D array.
#includeint main() { int rows, cols; std::cout << "Enter number of rows and columns: "; std::cin >> rows >> cols; int** arr = new int*[rows]; for (int i = 0; i < rows; ++i) { arr[i] = new int[cols]; } std::cout << "Enter elements of the array:" << std::endl; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { std::cin >> arr[i][j]; } } std::cout << "Array elements:" << std::endl; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { std::cout << arr[i][j] << " "; } std::cout << std::endl; } for (int i = 0; i < rows; ++i) { delete[] arr[i]; } delete[] arr; return 0; }
Create a structure for a student and display the details.
#include#include struct Student { std::string name; int roll; float marks; }; int main() { Student s1; std::cout << "Enter name: "; std::cin >> s1.name; std::cout << "Enter roll number: "; std::cin >> s1.roll; std::cout << "Enter marks: "; std::cin >> s1.marks; std::cout << "Student Details:" << std::endl; std::cout << "Name: " << s1.name << std::endl; std::cout << "Roll Number: " << s1.roll << std::endl; std::cout << "Marks: " << s1.marks << std::endl; return 0; }
Create a structure for an employee and display the details.
#include#include struct Employee { std::string name; int id; float salary; }; int main() { Employee e1; std::cout << "Enter name: "; std::cin >> e1.name; std::cout << "Enter ID: "; std::cin >> e1.id; std::cout << "Enter salary: "; std::cin >> e1.salary; std::cout << "Employee Details:" << std::endl; std::cout << "Name: " << e1.name << std::endl; std::cout << "ID: " << e1.id << std::endl; std::cout << "Salary: " << e1.salary << std::endl; return 0; }
Read from and write to a file.
#include#include #include int main() { std::ofstream outFile("example.txt"); outFile << "Hello, file!" << std::endl; outFile.close(); std::ifstream inFile("example.txt"); std::string content; std::getline(inFile, content); std::cout << "Content of file: " << content << std::endl; inFile.close(); return 0; }
Write an array of integers to a file.
#include#include int main() { int n; std::cout << "Enter the number of elements: "; std::cin >> n; int arr[n]; std::cout << "Enter the elements of the array: "; for (int i = 0; i < n; ++i) { std::cin >> arr[i]; } std::ofstream outFile("array.txt"); for (int i = 0; i < n; ++i) { outFile << arr[i] << " "; } outFile.close(); std::ifstream inFile("array.txt"); int num; std::cout << "Content of file: "; while (inFile >> num) { std::cout << num << " "; } std::cout << std::endl; inFile.close(); return 0; }
Read student data from a file and display it.
#include#include #include struct Student { std::string name; int roll; float marks; }; int main() { Student s; std::ifstream inFile("student.txt"); if (inFile.is_open()) { while (inFile >> s.name >> s.roll >> s.marks) { std::cout << "Name: " << s.name << ", Roll: " << s.roll << ", Marks: " << s.marks << std::endl; } inFile.close(); } else { std::cout << "Unable to open file." << std::endl; } return 0; }
Create a class for a Rectangle with attributes length and width, and methods to calculate the area and perimeter.
#includeclass Rectangle { private: double length; double width; public: void setDimensions(double l, double w) { length = l; width = w; } double getArea() { return length * width; } double getPerimeter() { return 2 * (length + width); } }; int main() { Rectangle rect; rect.setDimensions(5.0, 3.0); std::cout << "Area: " << rect.getArea() << std::endl; std::cout << "Perimeter: " << rect.getPerimeter() << std::endl; return 0; }
Create a base class Shape and derive classes Circle and Square with appropriate attributes and methods.
#include#include class Shape { public: virtual double getArea() = 0; virtual double getPerimeter() = 0; }; class Circle : public Shape { private: double radius; public: Circle(double r) : radius(r) {} double getArea() override { return M_PI * radius * radius; } double getPerimeter() override { return 2 * M_PI * radius; } }; class Square : public Shape { private: double side; public: Square(double s) : side(s) {} double getArea() override { return side * side; } double getPerimeter() override { return 4 * side; } }; int main() { Circle c(3.0); Square s(4.0); std::cout << "Circle Area: " << c.getArea() << std::endl; std::cout << "Circle Perimeter: " << c.getPerimeter() << std::endl; std::cout << "Square Area: " << s.getArea() << std::endl; std::cout << "Square Perimeter: " << s.getPerimeter() << std::endl; return 0; }
Create a class hierarchy with polymorphic behavior for different types of employees: FullTimeEmployee and PartTimeEmployee.
#includeclass Employee { public: virtual void displayInfo() = 0; virtual double calculateSalary() = 0; }; class FullTimeEmployee : public Employee { private: std::string name; double salary; public: FullTimeEmployee(std::string n, double s) : name(n), salary(s) {} void displayInfo() override { std::cout << "Full-Time Employee: " << name << std::endl; } double calculateSalary() override { return salary; } }; class PartTimeEmployee : public Employee { private: std::string name; double hourlyRate; int hoursWorked; public: PartTimeEmployee(std::string n, double rate, int hours) : name(n), hourlyRate(rate), hoursWorked(hours) {} void displayInfo() override { std::cout << "Part-Time Employee: " << name << std::endl; } double calculateSalary() override { return hourlyRate * hoursWorked; } }; int main() { FullTimeEmployee fte("John Doe", 5000.0); PartTimeEmployee pte("Jane Smith", 20.0, 100); fte.displayInfo(); std::cout << "Salary: $" << fte.calculateSalary() << std::endl; pte.displayInfo(); std::cout << "Salary: $" << pte.calculateSalary() << std::endl; return 0; }
Create a program that demonstrates basic exception handling with try-catch blocks.
#includeint main() { int a, b; std::cout << "Enter two integers: "; std::cin >> a >> b; try { if (b == 0) { throw std::runtime_error("Division by zero error."); } std::cout << "Result: " << a / b << std::endl; } catch (const std::exception& e) { std::cout << "Exception: " << e.what() << std::endl; } return 0; }
Create a program that handles multiple exceptions.
#include#include double divide(int a, int b) { if (b == 0) { throw std::runtime_error("Division by zero error."); } return static_cast (a) / b; } int main() { int a, b; std::cout << "Enter two integers: "; std::cin >> a >> b; try { std::cout << "Result: " << divide(a, b) << std::endl; } catch (const std::runtime_error& e) { std::cout << "Runtime Error: " << e.what() << std::endl; } catch (const std::exception& e) { std::cout << "Exception: " << e.what() << std::endl; } return 0; }
Create a custom exception class and use it in a program.
#include#include class CustomException : public std::runtime_error { public: CustomException(const std::string& message) : std::runtime_error(message) {} }; double divide(int a, int b) { if (b == 0) { throw CustomException("Custom Exception: Division by zero."); } return static_cast (a) / b; } int main() { int a, b; std::cout << "Enter two integers: "; std::cin >> a >> b; try { std::cout << "Result: " << divide(a, b) << std::endl; } catch (const CustomException& e) { std::cout << "Custom Exception: " << e.what() << std::endl; } catch (const std::exception& e) { std::cout << "Exception: " << e.what() << std::endl; } return 0; }
Demonstrate the use of vectors in C++.
#include#include int main() { std::vector vec; // Add elements to vector vec.push_back(10); vec.push_back(20); vec.push_back(30); // Display elements std::cout << "Vector elements: "; for (int i : vec) { std::cout << i << " "; } std::cout << std::endl; // Remove last element vec.pop_back(); // Display elements after pop_back std::cout << "Vector elements after pop_back: "; for (int i : vec) { std::cout << i << " "; } std::cout << std::endl; return 0; }
Demonstrate the use of maps in C++.
#include#include
Demonstrate the use of sets in C++.
#include#include int main() { std::set numSet; // Insert elements numSet.insert(10); numSet.insert(20); numSet.insert(30); numSet.insert(20); // Duplicate element // Display elements std::cout << "Set elements: "; for (int i : numSet) { std::cout << i << " "; } std::cout << std::endl; // Check if an element exists int num = 20; if (numSet.find(num) != numSet.end()) { std::cout << num << " is in the set." << std::endl; } else { std::cout << num <<