C++ Notes
Personal C++ reference covering essential concepts and practical examples. Focused on OOP, operators, loops, conditionals, file handling, and common algorithms.
C++ Number Pyramid
#include <iostream>
using namespace std;
// prints a simple number pyramid from 1 to 5
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
cout << j << " ";
}
cout << endl;
}
return 0;
}
C++ Palindrome Check
#include <iostream>
#include <string>
using namespace std;
// checks if a string is a palindrome
int main() {
string str, reversedStr;
cout << "Enter a string: ";
cin >> str;
reversedStr = string(str.rbegin(), str.rend());
if (str == reversedStr) {
cout << "The string is palindrome." << endl;
} else {
cout << "This string is not a palindrome." << endl;
}
return 0;
}
C++ Armstrong Number Check
#include <iostream>
#include <cmath>
using namespace std;
// checks if a number is an Armstrong number
int main() {
int num, originalNum, remainder, result = 0;
cout << "Enter a number: ";
cin >> num;
originalNum = num;
while (originalNum != 0) {
remainder = originalNum % 10;
result += pow(remainder, 3);
originalNum /= 10;
}
if (result == num)
cout << num << " is an Armstrong number." << endl;
else
cout << num << " is not an Armstrong number." << endl;
return 0;
}
C++ Prime Number Checker Using Class
#include <iostream>
using namespace std;
// checks if entered number is prime using a class method
class Test {
public:
int x;
Test() {
cout << "Enter a number: ";
cin >> x;
}
void check() {
int i, p = 0;
for (i = 2; i < x; i++) {
if (x % i == 0) {
p = 1;
break;
}
}
if (p == 0)
cout << "Number is prime: " << x << endl;
else
cout << "Number is not prime: " << x << endl;
}
};
int main() {
Test obj;
obj.check();
return 0;
}
C++ String Reverser Using Class
#include <iostream>
using namespace std;
// reverses a given string using class method
class StringReverser {
private:
string str;
public:
StringReverser(string s) {
str = s;
}
void displayReversed() {
cout << "Reversed String: ";
for (int i = str.length() - 1; i >= 0; i--) {
cout << str[i];
}
cout << endl;
}
};
int main() {
string input;
cout << "Enter a string: ";
getline(cin, input);
StringReverser sr(input);
sr.displayReversed();
return 0;
}
C++ Number Pattern Using Class
#include <iostream>
using namespace std;
// prints number pattern using class constructor
class Pattern {
public:
Pattern() {
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
cout << i;
}
cout << endl;
}
}
};
int main() {
Pattern p;
return 0;
}
C++ Operator Overloading Example
#include <iostream>
using namespace std;
// demonstrates operator overloading for + and - in a class
class Number {
private:
int value;
public:
Number(int v = 0) {
value = v;
}
Number operator+(Number obj) {
return Number(value + obj.value);
}
Number operator-(Number obj) {
return Number(value - obj.value);
}
void display() {
cout << "Value: " << value << endl;
}
};
int main() {
Number n1(10), n2(4), result;
cout << "First number: ";
n1.display();
cout << "Second number: ";
n2.display();
result = n1 + n2;
cout << "After addition: ";
result.display();
result = n1 - n2;
cout << "After subtraction: ";
result.display();
return 0;
}
C++ Operator Overloading for * and ==
#include <iostream>
using namespace std;
// demonstrates operator overloading for * and == in a class
class Number {
private:
int value;
public:
Number(int v = 0) {
value = v;
}
Number operator*(Number obj) {
return Number(value * obj.value);
}
bool operator==(Number obj) {
return value == obj.value;
}
void display() {
cout << "Value: " << value << endl;
}
};
int main() {
Number n1(5), n2(3), n3(5), result;
cout << "First number: ";
n1.display();
cout << "Second number: ";
n2.display();
// Multiplication
result = n1 * n2;
cout << "Multiplication (n1 * n2): ";
result.display();
// Equality check
if (n1 == n3) {
cout << "n1 is equal to n3" << endl;
} else {
cout << "n1 is not equal to n3" << endl;
}
return 0;
}
C++ Complex Number Input/Output Using Friend Operators
#include <iostream>
using namespace std;
// uses friend functions to overload >> and << for complex numbers
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0) {
real = r;
imag = i;
}
friend ostream& operator<<(ostream &out, const Complex &c);
friend istream& operator>>(istream &in, Complex &c);
};
istream& operator>>(istream &in, Complex &c) {
cout << "Enter Real Part: ";
in >> c.real;
cout << "Enter Imaginary Part: ";
in >> c.imag;
return in;
}
ostream& operator<<(ostream &out, const Complex &c) {
out << c.real << " + " << c.imag << "i";
return out;
}
int main() {
Complex c1;
cin >> c1;
cout << "The Complex object is: ";
cout << c1;
return 0;
}
C++ Simple Interest Using Inline Function
#include <iostream>
using namespace std;
// calculates simple interest using inline function
inline float simpleInterest(float principle, float rate, float time) {
return (principle * rate * time) / 100;
}
int main() {
float p, r, t;
cout << "Enter Principle amount: ";
cin >> p;
cout << "Enter Rate of Interest: ";
cin >> r;
cout << "Enter Time: ";
cin >> t;
float si = simpleInterest(p, r, t);
cout << "Simple Interest is: " << si << endl;
return 0;
}
C++ Function Overloading for Area Calculations
#include <iostream>
#include <cmath>
using namespace std;
// demonstrates function overloading for circle, triangle, and cylinder
class Area {
public:
float calculate(float radius) {
return 2 * 3.14159 * radius;
}
float calculate(float base, float height) {
return 0.5 * base * height;
}
float calculate(float radius, float height, bool isCylinder) {
if (isCylinder)
return 2 * 3.14159 * radius * (radius + height);
else
return 0;
}
};
int main() {
Area a;
float radius = 5.0;
float base = 6.0, height = 4.0;
float cylRadius = 3.0, cylHeight = 7.0;
cout << "Circumference of circle (r = " << radius << ") : "
<< a.calculate(radius) << endl;
cout << "Area of triangle (base = " << base << ", height = "
<< height << ") : " << a.calculate(base, height) << endl;
cout << "Surface area of cylinder (r = " << cylRadius << ", h = "
<< cylHeight << ") : "
<< a.calculate(cylRadius, cylHeight, true) << endl;
return 0;
}
C++ Simple Login with Exception Handling
#include <iostream>
#include <string>
using namespace std;
// demonstrates basic login authentication using exceptions
class Login {
private:
string correctUserID = "admin";
string correctPassword = "1234";
public:
void authenticate(string userID, string password) {
if (userID != correctUserID || password != correctPassword) {
throw "Invalid credentials!";
} else {
cout << "Login successful!" << endl;
}
}
};
int main() {
Login login;
string userID, password;
cout << "Enter User ID: ";
cin >> userID;
cout << "Enter Password: ";
cin >> password;
try {
login.authenticate(userID, password);
} catch (const char* msg) {
cout << "Exception caught: " << msg << endl;
}
return 0;
}
C++ File Copy Using Class
#include <iostream>
#include <fstream>
using namespace std;
// copies content from one file to another using a class
class FileCopier {
string sourceFile;
string destinationFile;
public:
FileCopier(string src, string dest) {
sourceFile = src;
destinationFile = dest;
}
void copyFile() {
ifstream inFile(sourceFile);
ofstream outFile(destinationFile);
if (!inFile || !outFile) {
cout << "Error opening file!" << endl;
return;
}
string line;
while (getline(inFile, line)) {
outFile << line << endl;
}
cout << "File copied successfully!" << endl;
inFile.close();
outFile.close();
}
};
int main() {
string source, destination;
cout << "Enter source file name: ";
cin >> source;
cout << "Enter destination file name: ";
cin >> destination;
FileCopier copier(source, destination);
copier.copyFile();
return 0;
}
C++ Factorial Using Copy Constructor
#include <iostream>
using namespace std;
// calculates factorial using normal and copy constructor
class FactorialCopy {
public:
int fact, num, i;
FactorialCopy(int n) {
num = n;
fact = 1;
}
FactorialCopy(FactorialCopy &n) {
num = n.num;
fact = 1;
}
void calculate() {
for (int i = 1; i <= num; i++)
fact = fact * i;
}
void display() {
cout << "Factorial of " << num << " is " << fact << endl;
}
};
int main() {
int num;
cout << "Enter the number to find factorial:\t";
cin >> num;
cout << endl;
cout << "Printing from constructor:" << endl;
FactorialCopy fact(num);
fact.calculate();
fact.display();
cout << endl;
cout << "Printing from copy constructor:" << endl;
FactorialCopy factcopy(fact);
factcopy.calculate();
factcopy.display();
return 0;
}
C++ Fibonacci Series Using Class
#include <iostream>
using namespace std;
// prints Fibonacci series using class methods
class Fibonacci {
int n1 = 0, n2 = 1, n3, i, number;
public:
void getdata() {
cout << "Enter the number of elements: ";
cin >> number;
cout << n1 << " " << n2 << " ";
}
void findFibonacci() {
for (i = 2; i < number; i++) {
n3 = n1 + n2;
cout << n3 << " ";
n1 = n2;
n2 = n3;
}
}
};
int main() {
Fibonacci f;
f.getdata();
f.findFibonacci();
return 0;
}
C++ Division with Exception Handling
#include <iostream>
using namespace std;
// handles division by zero using try-catch
int main() {
int numerator, denominator;
float result;
cout << "Enter the dividend: ";
cin >> numerator;
cout << "\nEnter the divisor: ";
cin >> denominator;
cout << "\n";
try {
if (denominator != 0) {
result = static_cast<float>(numerator) / denominator;
cout << "ANSWER: " << result;
} else {
throw(denominator);
}
} catch (int exc) {
cout << "Division by zero is not possible. Please try again with different value of variables.";
}
return 0;
}
C++ Matrix Addition and Multiplication
#include <iostream>
using namespace std;
// performs matrix addition and multiplication using class
class matrix {
int a[10][10], r, c;
public:
matrix(int x = 0, int y = 0) {
r = x;
c = y;
}
void input() {
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
cin >> a[i][j];
}
void display() {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++)
cout << a[i][j] << " ";
cout << endl;
}
}
matrix add(matrix m) {
matrix rs(r, c);
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
rs.a[i][j] = a[i][j] + m.a[i][j];
return rs;
}
matrix mul(matrix m) {
matrix rs(r, m.c);
for (int i = 0; i < r; i++) {
for (int j = 0; j < m.c; j++) {
rs.a[i][j] = 0;
for (int k = 0; k < c; k++)
rs.a[i][j] += a[i][k] * m.a[k][j];
}
}
return rs;
}
};
int main() {
int r1, c1, r2, c2;
cout << "Enter size A: ";
cin >> r1 >> c1;
cout << "Enter size B: ";
cin >> r2 >> c2;
matrix A(r1, c1), B(r2, c2);
cout << "Enter A:\n";
A.input();
cout << "Enter B:\n";
B.input();
if (r1 == r2 && c1 == c2) {
cout << "Add:\n";
A.add(B).display();
}
if (c1 == r2) {
cout << "Mul:\n";
A.mul(B).display();
}
return 0;
}
C++ Prime Numbers from 1 to 100
#include <iostream>
using namespace std;
// prints all prime numbers between 1 and 100
int main() {
cout << "Prime numbers between 1 and 100 are:\n";
for (int num = 2; num <= 100; num++) {
int count = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
count++;
}
}
if (count == 2) {
cout << num << " ";
}
}
cout << endl;
return 0;
}
C++ String Length Comparison with Operator Overloading
#include <iostream>
#include <string>
using namespace std;
// compares string lengths using overloaded operators >, <, ==
class MyString {
string s;
public:
MyString(string str) : s(str) {}
bool operator > (MyString b) {
return s.length() > b.s.length();
}
bool operator < (MyString b) {
return s.length() < b.s.length();
}
bool operator == (MyString b) {
return s.length() == b.s.length();
}
string get() { return s; }
};
int main() {
MyString a("hello"), b("worldwide");
if (a > b)
cout << a.get() << " is longer\n";
else if (a < b)
cout << b.get() << " is longer\n";
else
cout << "Both strings are equal in length\n";
return 0;
}
C++ Using main
as Friend Function
#include <iostream>
using namespace std;
// demonstrates using main() as a friend function to access private members
class mainasfriend {
int a, b;
public:
mainasfriend(int x, int y) {
a = x;
b = y;
}
friend int main();
};
int main() {
mainasfriend ob(5, 7);
cout << ob.a + ob.b;
return 0;
}
C++ Polymorphism: Area of Shapes
#include <iostream>
using namespace std;
// demonstrates runtime polymorphism with virtual functions for different shapes
class shape {
public:
virtual void area() = 0;
};
class circle : public shape {
double radius;
public:
circle(double r) {
radius = r;
}
void area() {
double result = 3.14 * radius * radius;
cout << "Area of circle: " << result << endl;
}
};
class square : public shape {
double side;
public:
square(double s) {
side = s;
}
void area() {
double result = side * side;
cout << "Area of square: " << result << endl;
}
};
class triangle : public shape {
double base, height;
public:
triangle(double b, double h) {
base = b;
height = h;
}
void area() {
double result = 0.5 * base * height;
cout << "Area of triangle: " << result << endl;
}
};
int main() {
circle c(5);
square s(4);
triangle t(6, 3);
c.area();
s.area();
t.area();
return 0;
}
C++ Pascal's Triangle Using Class
#include <iostream>
using namespace std;
// prints Pascal's Triangle using class methods
class PascalTriangle {
private:
int rows;
public:
PascalTriangle(int r) {
rows = r;
}
int factorial(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
int combination(int n, int r) {
return factorial(n) / (factorial(r) * factorial(n - r));
}
void display() {
for (int i = 0; i < rows; i++) {
for (int space = 0; space < rows - i; space++) {
cout << " ";
}
for (int j = 0; j <= i; j++) {
cout << combination(i, j) << " ";
}
cout << endl;
}
}
};
int main() {
int n;
cout << "Enter the number of rows for Pascal's Triangle: ";
cin >> n;
PascalTriangle pt(n);
cout << "\nPascal's Triangle:\n";
pt.display();
return 0;
}
C++ File Analyzer Using Class
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
// counts lines, words, and characters in a file using a class
class FileAnalyzer {
private:
string filename;
int lineCount;
int wordCount;
int charCount;
public:
FileAnalyzer(string fname) {
filename = fname;
lineCount = wordCount = charCount = 0;
}
void analyze() {
ifstream file(filename);
if (!file) {
cerr << "Error opening file: " << filename << endl;
return;
}
string line;
while (getline(file, line)) {
lineCount++;
charCount += line.length();
stringstream ss(line);
string word;
while (ss >> word) {
wordCount++;
}
}
file.close();
}
void displayResults() {
cout << "File: " << filename << endl;
cout << "Total Lines: " << lineCount << endl;
cout << "Total Words: " << wordCount << endl;
cout << "Total Characters: " << charCount << endl;
}
};
int main() {
string filename;
cout << "Enter the filename to analyze: ";
cin >> filename;
FileAnalyzer analyzer(filename);
analyzer.analyze();
analyzer.displayResults();
return 0;
}
C++ Square of a Number Using Inline Function
#include <iostream>
using namespace std;
// calculates square using inline function
inline int square(int num) {
return num * num;
}
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
int result = square(number);
cout << "The square of " << number << " is: " << result << endl;
return 0;
}
C++ Polymorphism: Square Root Calculation
#include <iostream>
#include <cmath>
using namespace std;
// demonstrates runtime polymorphism for calculating square root of int, float, and double
class Number {
public:
virtual void calculateSqrt() = 0;
};
class IntNumber : public Number {
int num;
public:
IntNumber(int n) : num(n) {}
void calculateSqrt() override {
cout << "Square root of int " << num << " is "
<< sqrt((double)num) << endl;
}
};
class FloatNumber : public Number {
float num;
public:
FloatNumber(float n) : num(n) {}
void calculateSqrt() override {
cout << "Square root of float " << num << " is "
<< sqrt(num) << endl;
}
};
class DoubleNumber : public Number {
double num;
public:
DoubleNumber(double n) : num(n) {}
void calculateSqrt() override {
cout << "Square root of double " << num << " is "
<< sqrt(num) << endl;
}
};
int main() {
IntNumber intObj(25);
FloatNumber floatObj(49.0F);
DoubleNumber doubleObj(81.0);
Number* ptr;
ptr = &intObj;
ptr->calculateSqrt();
ptr = &floatObj;
ptr->calculateSqrt();
ptr = &doubleObj;
ptr->calculateSqrt();
return 0;
}
C++ Car Class with Getters and Setters
#include <iostream>
using namespace std;
// demonstrates encapsulation using getter and setter methods
class Car {
private:
string company;
string model;
int year;
public:
void setCompany(const string &c) {
company = c;
}
string getCompany() const {
return company;
}
void setModel(const string &m) {
model = m;
}
string getModel() const {
return model;
}
void setYear(int y) {
year = y;
}
int getYear() const {
return year;
}
};
int main() {
Car myCar;
myCar.setCompany("Toyota");
myCar.setModel("Corolla");
myCar.setYear(2020);
cout << "Car Details:" << endl;
cout << "Company: " << myCar.getCompany() << endl;
cout << "Model: " << myCar.getModel() << endl;
cout << "Year: " << myCar.getYear() << endl;
return 0;
}
C++ Bank Account Class with Deposit and Withdraw
#include <iostream>
using namespace std;
// simulates a simple bank account with deposit and withdrawal functions
class BankAccount {
private:
int accountNumber;
double balance;
public:
BankAccount(int accNum, double initialBalance) {
accountNumber = accNum;
balance = initialBalance;
}
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited: " << amount << ". New balance is: " << balance << endl;
} else {
cout << "Deposit amount must be positive!" << endl;
}
}
void withdraw(double amount) {
if (amount > 0) {
if (amount <= balance) {
balance -= amount;
cout << "Withdraw: " << amount << ". New balance is: " << balance << endl;
} else {
cout << "Insufficient funds" << endl;
}
} else {
cout << "Withdraw amount must be positive!" << endl;
}
}
void displayAccountDetails() {
cout << "\nAccount Number: " << accountNumber << endl;
cout << "Balance: " << balance << endl;
}
};
int main() {
int accountNumber;
double initialBalance, depositAmount, withdrawAmount;
cout << "Enter account number: ";
cin >> accountNumber;
cout << "Enter initial balance: ";
cin >> initialBalance;
BankAccount myAccount(accountNumber, initialBalance);
myAccount.displayAccountDetails();
cout << "Enter deposit amount: ";
cin >> depositAmount;
myAccount.deposit(depositAmount);
cout << "Enter withdrawal amount: ";
cin >> withdrawAmount;
myAccount.withdraw(withdrawAmount);
myAccount.displayAccountDetails();
return 0;
}
C++ Employee Salary Based on Performance
#include <iostream>
using namespace std;
// sets employee salary according to performance grade using a class
class Employee {
private:
string name;
int employeeID;
double salary;
public:
Employee(string empName, int empID) {
name = empName;
employeeID = empID;
salary = 0;
}
void setSalaryBasedOnPerformance(char performanceGrade) {
if (performanceGrade == 'A') {
salary = 100000;
} else if (performanceGrade == 'B') {
salary = 75000;
} else if (performanceGrade == 'C') {
salary = 50000;
} else if (performanceGrade == 'D') {
salary = 30000;
} else {
cout << "Invalid performance grade" << endl;
}
}
void displayEmployeeDetails() {
cout << "\nEmployee ID: " << employeeID << endl;
cout << "Employee Name: " << name << endl;
cout << "Salary: " << salary << endl;
}
};
int main() {
string name;
int employeeID;
char performanceGrade;
cout << "Enter employee name: ";
cin >> name;
cout << "Enter employee ID: ";
cin >> employeeID;
Employee emp(name, employeeID);
cout << "Enter performance grade (A, B, C, D): ";
cin >> performanceGrade;
emp.setSalaryBasedOnPerformance(performanceGrade);
emp.displayEmployeeDetails();
return 0;
}
C++ Date Class with Validation
#include <iostream>
using namespace std;
// validates a date using class methods and leap year check
class Date {
private:
int day;
int month;
int year;
bool isLeapYear(int y) {
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}
public:
Date() : day(1), month(1), year(2000) {}
void setDate(int d, int m, int y) {
day = d;
month = m;
year = y;
}
void getDate() {
cout << "Date: " << day << "/" << month << "/" << year << endl;
}
bool isValidDate() {
if (year < 1 || month < 1 || month > 12 || day < 1)
return false;
int daysInMonth[] = { 31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 };
if (isLeapYear(year))
daysInMonth[1] = 29;
return day <= daysInMonth[month - 1];
}
};
int main() {
Date d;
int day, month, year;
cout << "Enter day: ";
cin >> day;
cout << "Enter month: ";
cin >> month;
cout << "Enter year: ";
cin >> year;
d.setDate(day, month, year);
if (d.isValidDate()) {
cout << "Valid date entered." << endl;
d.getDate();
} else {
cout << "Invalid date entered." << endl;
}
return 0;
}
C++ Student Class with Grade Calculation
#include <iostream>
#include <string>
using namespace std;
// calculates student grade based on marks using a class
class Student {
private:
string name;
string className;
int rollNumber;
float marks;
char grade;
void calculateGrade() {
if (marks >= 90)
grade = 'A';
else if (marks >= 75)
grade = 'B';
else if (marks >= 60)
grade = 'C';
else if (marks >= 50)
grade = 'D';
else
grade = 'F';
}
public:
void inputDetails() {
cout << "Enter student name: ";
getline(cin, name);
cout << "Enter class: ";
getline(cin, className);
cout << "Enter roll number: ";
cin >> rollNumber;
cout << "Enter marks (out of 100): ";
cin >> marks;
cin.ignore(); // clear newline from buffer
calculateGrade();
}
void displayDetails() {
cout << "\nStudent Details:\n";
cout << "Name: " << name << endl;
cout << "Class: " << className << endl;
cout << "Roll Number: " << rollNumber << endl;
cout << "Marks: " << marks << endl;
cout << "Grade: " << grade << endl;
}
};
int main() {
Student s1;
s1.inputDetails();
s1.displayDetails();
return 0;
}
C++ Shape Class Hierarchy with Area & Perimeter
#include <iostream>
#include <cmath>
using namespace std;
// demonstrates runtime polymorphism for circle, rectangle, and triangle
class Shape {
public:
virtual void input() = 0;
virtual void calculateArea() = 0;
virtual void calculatePerimeter() = 0;
virtual ~Shape() {}
};
class Circle : public Shape {
private:
float radius;
public:
void input() override {
cout << "Enter radius of circle: ";
cin >> radius;
}
void calculateArea() override {
cout << "Area of circle: " << 3.14159 * radius * radius << endl;
}
void calculatePerimeter() override {
cout << "Perimeter (Circumference) of circle: " << 2 * 3.14159 * radius << endl;
}
};
class Rectangle : public Shape {
private:
float length, width;
public:
void input() override {
cout << "Enter length and width of rectangle: ";
cin >> length >> width;
}
void calculateArea() override {
cout << "Area of Rectangle: " << length * width << endl;
}
void calculatePerimeter() override {
cout << "Perimeter of Rectangle: " << 2 * (length + width) << endl;
}
};
class Triangle : public Shape {
private:
float a, b, c;
public:
void input() override {
cout << "Enter the three sides of the triangle: ";
cin >> a >> b >> c;
}
void calculateArea() override {
float s = (a + b + c) / 2;
float area = sqrt(s * (s - a) * (s - b) * (s - c));
cout << "Area of Triangle: " << area << endl;
}
void calculatePerimeter() override {
cout << "Perimeter of Triangle: " << (a + b + c) << endl;
}
};
int main() {
Shape* shape;
cout << "\n--- Circle ---\n";
shape = new Circle();
shape->input();
shape->calculateArea();
shape->calculatePerimeter();
delete shape;
cout << "\n--- Rectangle ---\n";
shape = new Rectangle();
shape->input();
shape->calculateArea();
shape->calculatePerimeter();
delete shape;
cout << "\n--- Triangle ---\n";
shape = new Triangle();
shape->input();
shape->calculateArea();
shape->calculatePerimeter();
delete shape;
return 0;
}
C++ Complex Number Class with Add & Subtract
#include <iostream>
using namespace std;
// implements basic complex number operations using a class
class Complex {
private:
float real, imag;
public:
void getData() {
cout << "Enter real part: ";
cin >> real;
cout << "Enter imaginary part: ";
cin >> imag;
}
void display() {
cout << real << " + " << imag << "i" << endl;
}
Complex add(Complex c) {
Complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
Complex subtract(Complex c) {
Complex temp;
temp.real = real - c.real;
temp.imag = imag - c.imag;
return temp;
}
};
int main() {
Complex c1, c2, sum, diff;
cout << "Enter first complex number:\n";
c1.getData();
cout << "\nEnter second complex number:\n";
c2.getData();
sum = c1.add(c2);
diff = c1.subtract(c2);
cout << "\nSum of the two complex numbers: ";
sum.display();
cout << "Difference of the two complex numbers: ";
diff.display();
return 0;
}
C++ Laptop Class Example
#include <iostream>
#include <string>
using namespace std;
// defines a Laptop class with name, price, and processor
class Laptop {
private:
string name;
float price;
string processor;
public:
Laptop(string n, float p, string proc) {
name = n;
price = p;
processor = proc;
}
void display() {
cout << "Laptop Name: " << name << endl;
cout << "Price: $" << price << endl;
cout << "Processor: " << processor << endl;
}
};
int main() {
Laptop l1("Dell Inspiron", 750.50, "Intel i5");
Laptop l2("HP Pavilion", 820.75, "AMD Ryzen 5");
cout << "Laptop 1 Details:" << endl;
l1.display();
cout << "\nLaptop 2 Details:" << endl;
l2.display();
return 0;
}
C++ Shape Class with Circle & Rectangle
#include <iostream>
#define PI 3.14
using namespace std;
// abstract Shape class with color and area; Circle & Rectangle implement it
class Shape {
private:
string color;
float area;
public:
void setColor(string c) {
color = c;
}
string getColor() {
return color;
}
void setArea(float a) {
area = a;
}
float getArea() {
return area;
}
virtual void calculateArea() = 0;
};
class Circle : public Shape {
private:
float radius;
public:
void setRadius(float r) {
radius = r;
}
void calculateArea() {
float a = PI * radius * radius;
setArea(a);
}
};
class Rectangle : public Shape {
private:
float length, breadth;
public:
void setDimensions(float l, float b) {
length = l;
breadth = b;
}
void calculateArea() {
float a = length * breadth;
setArea(a);
}
};
int main() {
Circle c;
c.setColor("Red");
c.setRadius(5);
c.calculateArea();
cout << "Circle Color: " << c.getColor() << endl;
cout << "Circle Area: " << c.getArea() << endl;
Rectangle r;
r.setColor("Blue");
r.setDimensions(4, 6);
r.calculateArea();
cout << "Rectangle Color: " << r.getColor() << endl;
cout << "Rectangle Area: " << r.getArea() << endl;
return 0;
}
AWD Practicals Source Codes
Use them to learn, tweak, or just survive the lab sessions without losing your sanity.
!NOTE :
If you copy this blindly and your teacher roasts you, that’s between you and your karma.
About Page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>About Page</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 40px;
}
</style>
</head>
<body>
<h1>About Us</h1>
<p>This is the About page. We are learning Html lnks!</p>
<p><a href="index.html">Back to home</a></p>
</body>
</html>
Extintlink - Links Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Links Example</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 40px;
line-height: 1.6;
}
a {
color: #3366cc;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
section {
margin-top: 50px;
}
</style>
</head>
<body>
<h1>Types of links in html</h1>
<h2>External Links</h2>
<p>
Visit
<a href="https://www.wikipedia.org" target="_blank">Wikipedia</a> for more
information.
</p>
<h2>Internal Link</h2>
<p>Go to the <a href="about.html">About Page</a>.</p>
<p style="color:gray;font-size:14px;">
(Note: Create a separate file named <code>about.html</code> in the same
folder for this link to work.)
</p>
<h2>Link Within Same Page</h2>
<p>Jump to the <a href="#bottom">bottom of this page</a>.</p>
<section style="height:400px;">
<p>Scroll down to see the anchor target below.</p>
</section>
<h3 id="bottom">Bottom of the page</h3>
<p>This is the target for the same-page link.</p>
</body>
</html>
Types of Lists in HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Types of Lists in HTML</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 40px;
}
</style>
</head>
<body>
<h2>Ordered List</h2>
<ol>
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ol>
<h2>Unordered List</h2>
<ul>
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ul>
<h2>Description List</h2>
<dl>
<dt>HTML</dt>
<dd>A markup language for creating web pages.</dd>
<dt>CSS</dt>
<dd>A style sheet language for designing web pages.</dd>
<dt>JavaScript</dt>
<dd>A programming language for adding interactivity to web pages.</dd>
</dl>
</body>
</html>
Student marks table
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Student marks table</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 40px;
}
table {
border-collapse: collapse;
width: 70%;
}
th,
td {
border: 1px solid #333;
padding: 10px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
caption {
caption-side: top;
margin-bottom: 10px;
font-size: 18px;
font-weight: bold;
text-align: left;
}
.average-row td {
background-color: #e6f7ff;
font-weight: bold;
text-align: left;
}
</style>
</head>
<body>
<table>
<caption>
Students Marks Table
</caption>
<tr>
<th>Name</th>
<th>Subject</th>
<th>Marks</th>
</tr>
<tr>
<td rowspan="2">Rajashree</td>
<td>Adv Web</td>
<td>75</td>
</tr>
<tr>
<td>OS</td>
<td>60</td>
</tr>
<tr>
<td rowspan="2">Kiran</td>
<td>Adv Web</td>
<td>80</td>
</tr>
<tr>
<td>OS</td>
<td>75</td>
</tr>
<tr class="average-row">
<td></td>
<td colspan="2">Average of all marks:72.5</td>
</tr>
</table>
</body>
</html>
Nested Table Example
<!DOCTYPE html>
<html>
<head>
<title>Nested Table Example</title>
<style>
table {
border-collapse: collapse;
margin: 10px;
}
td,
th {
border: 2px solid black;
padding: 10px;
text-align: center;
}
.outer {
background-color: #f0f8ff;
}
.inner {
background-color: #ffe4e1;
}
</style>
</head>
<body>
<h2>Nested Table Example</h2>
<table class="outer">
<tr>
<th>Outer Table - Column 1</th>
<th>Outer Table - Column 2</th>
</tr>
<tr>
<td>Row 1, Col 1</td>
<td>
<!--Nested Table Starts Here-->
<table class="inner">
<tr>
<th>Inner Table - Col 1</th>
<th>Inner Table - Col 2</th>
</tr>
<tr>
<td>Nested Row 1</td>
<td>Nested Row 2</td>
</tr>
<tr>
<td colspan="2">Nested Footer</td>
</tr>
</table>
<!--Nested Table Ends Here-->
</td>
</tr>
</table>
</body>
</html>
Form in HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Form in HTML</title>
</head>
<body>
<h2>Registration Form</h2>
<form>
<fieldset>
<legend>User Personal Information</legend>
<label>Enter your full name</label><br />
<input type="text" name="name" /><br />
<label>Enter your email</label><br />
<input type="email" name="email" /><br />
<label>Enter your password</label><br />
<input type="password" name="pass" /><br />
<label>Confirm your password</label><br />
<input type="password" name="pass" /><br />
<br /><label>Enter your gender</label><br />
<input type="radio" id="gender" name="gender" value="male" />Male<br />
<input
type="radio"
id="gender"
name="gender"
value="female"
/>Female<br />
<input
type="radio"
id="gender"
name="gender"
value="others"
/>others<br />
<br />Enter your Address:<br />
<textarea></textarea><br />
<input type="submit" value="sign-up" />
</fieldset>
</form>
</body>
</html>
User Registration Form
<!DOCTYPE html>
<html>
<head>
<title>User Registration Form</title>
<style>
h2 {
color: orange;
}
form {
border: 1px solid #ccc;
padding: 20px;
width: 300px;
background-color: #f9f9f9;
}
label {
display: block;
margin-top: 10px;
font-weight: bold;
}
input {
width: 100%;
padding: 8px;
margin-top: 5px;
box-sizing: border-box;
}
input[type="submit"] {
background-color: #4caf50;
color: white;
border: none;
margin-top: 15px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<h2>User Registration Form</h2>
<form>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required />
<label for="age">Age:</label>
<input type="number" id="age" name="age" required />
<label for="appointment">Date of Appointment:</label>
<input type="date" id="appointment" name="appointment" required />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Pure CSS Login Form
<!DOCTYPE html>
<html lang="en">
<head>
<title>Pure CSS Login Form</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div class="container">
<div class="center">
<h1>Login</h1>
<form action="" method="POST">
<div class="txt_field">
<input type="text" name="text" required />
<span></span>
<label>Username</label>
</div>
<div class="txt_field">
<input type="password" name="password" required />
<span></span>
<label>Password</label>
</div>
<div class="pass">Forget Password?</div>
<input name="submit" type="button" value="Submit" />
<div class="signup_link">
Not a member?<a href="signup.php">Signup</a>
</div>
</form>
</div>
</div>
</body>
</html>
BCA Table
<!DOCTYPE html>
<html>
<head>
<title>BCA Table</title>
<style>
table {
border-collapse: collapse;
width: 60%;
text-align: center;
}
th,
td {
border: 1px solid black;
padding: 8px;
}
.center-text {
text-align: center;
font-weight: bold;
}
</style>
</head>
<body>
<table>
<tr>
<th colspan="5" class="center-text">BCA</th>
</tr>
<tr>
<td rowspan="2">SEM I &II</td>
<th>Java</th>
<th>CSS</th>
<th>HTML</th>
<th>C</th>
</tr>
<tr>
<td>55</td>
<td>63</td>
<td>62</td>
<td>89</td>
</tr>
<tr>
<td colspan="5" class="center-text">Thank You</td>
</tr>
</table>
</body>
</html>
Student Grades
<!DOCTYPE html>
<html>
<head>
<title>Student Grades</title>
<style>
table {
border-collapse: collapse;
width: 50%;
}
th,
td {
border: 1px solid black;
padding: 8px;
text-align: center;
}
tfoot td {
font-weight: bold;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>Name</th>
<th>Sub</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="2">Gautam</td>
<td>Maths1</td>
<td>A</td>
</tr>
<tr>
<td>Maths2</td>
<td>A+</td>
</tr>
<tr>
<td rowspan="2">Sachin</td>
<td>Science1</td>
<td>B+</td>
</tr>
<tr>
<td>Science2</td>
<td>A</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3">SYBCA</td>
</tr>
</tfoot>
</table>
</body>
</html>
3x3 Table with rowspan and colspan
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>3x3 Table with rowspan and colspan</title>
<style>
table {
border-collapse: separate;
border: 2px solid black;
}
td {
border: 1px solid #000;
padding: 10px;
text-align: center;
}
</style>
</head>
<body>
<h2>3x3 Table Example with cellspacing,cellpadding,rowspan,colspan</h2>
<table border="1" cellspacing="5" cellpadding="10">
<tr>
<td rowspan="2">Row 1 & Row 2<br />Col 1</td>
<td>Row 1 <br />Col 2</td>
<td>Row 1 <br />Col 3</td>
</tr>
<tr>
<td colspan="2">Row 2<br />Col 2 & 3 merged</td>
</tr>
<tr>
<td>Row 3<br />Col 1</td>
<td>Row 3<br />Col 2</td>
<td>Row 3<br />Col 3</td>
</tr>
</table>
</body>
</html>
Hyperlink Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Hyperlink Example</title>
</head>
<body>
<h2>Hyperlink Examples</h2>
<!--i)Text as hyperlink-->
<p>
Click this
<a href="https://www.example.com" target="_blank">text hyperlink</a> to go
to Example.com.
</p>
<!--ii)Image as hyperlink-->
<p>
<a href="https://www.example.com" target="_blank">
<img
src="https://via.placeholder.com/150"
alt="Placeholder Image"
style="border:1px solid #000;"
/>
</a>
</p>
<!--iii)Hyperlink to yahoo.com-->
<p>Go to <a href="https://www.yahoo.com" target="_blank">Yahoo</a></p>
</body>
</html>
Inline CSS Example
<!DOCTYPE html>
<html>
<head>
<title>Inline CSS Example</title>
</head>
<body>
<h2 style="color: orange; text-align: center;">
Welcome to Inline CSS Demo
</h2>
<p style="font-size: 18px; color: blue;">
This paragraph uses inline CSS to make the text blue and increase the font
size.
</p>
<div style="background-color: lightgray; padding: 10px;">
<p style="color: green;">This is a paragraph inside a styled div.</p>
<p style="color: red; font-weight: bold;">
This is a bold red paragraph.
</p>
</div>
<button
style="background-color: green; color: white; padding: 8px 16px; border: none;"
>
Click Me
</button>
</body>
</html>
Types of Lists in HTML
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Types of Lists in HTML</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>HTML List Example</h1>
<section>
<h2>Unordered List</h2>
<ul>
<li>Apples</li>
<li>Oranges</li>
<li>Bananas</li>
</ul>
</section>
<section>
<h2>Ordered List</h2>
<ol>
<li>Wake up</li>
<li>Brush Teeth</li>
<li>Have Breakfast</li>
</ol>
</section>
<section>
<h2>Descriptiton List</h2>
<dl>
<dt>HTML</dt>
<dd>A markup language for web pages.</dd>
<dt>CSS</dt>
<dd>A language to style HTML content.</dd>
<dt>Javascript</dt>
<dd>A language to add interactivity to websites.</dd>
</dl>
</section>
<section>
<h2>Nested Lists</h2>
<ul>
<li>
Fruits
<ul>
<li>Apple</li>
<li>Banana</li>
</ul>
</li>
<li>
Vegtables
<ul>
<li>Carrot</li>
<li>Spinach</li>
</ul>
</li>
</ul>
</section>
</body>
</html>
CSS
body {
font-family: Arial, sans-serif;
margin: 20px;
line-height: 1.6;
}
h1 {
color: #333;
}
section {
margin-bottom: 30px;
padding: 10px;
border: 1px solid#ddd;
border-radius: 6px;
}
ul,
ol,
dl {
margin-left: 20px;
}
dt {
font-weight: bold;
}
dd {
margin-left: 20px;
margin-bottom: 10px;
}
All Types of Lists
<!DOCTYPE html>
<html>
<head>
<title>All Types of Lists</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h2 {
color: orange;
}
ul {
list-style-type: square;
margin-bottom: 20px;
}
ol {
list-style-type: upper-roman;
margin-bottom: 20px;
}
dl {
background-color: #f9f9f9;
padding: 10px;
border-left: 4px solid #ccc;
}
dt {
font-weight: bold;
margin-top: 10px;
}
dd {
margin-left: 20px;
}
</style>
</head>
<body>
<h2>Unordered List</h2>
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Orange</li>
</ul>
<h2>Ordered List</h2>
<ol>
<li>Wake up</li>
<li>Brush Teeth</li>
<li>Have Breakfast</li>
</ol>
<h2>Description List</h2>
<dl>
<dt>HTML</dt>
<dd>HyperText Markup Language used to structure web pages.</dd>
<dt>CSS</dt>
<dd>Cascading Style Sheets used to style HTML elements.</dd>
<dt>JavaScript</dt>
<dd>A scripting language used to make web pages interactive.</dd>
</dl>
</body>
</html>
Collage Information
<!DOCTYPE html>
<html>
<head>
<title>College Information</title>
<style>
.college-name {
font-family: "Times New Roman", Times, serif;
color: blue;
background-color: yellow;
font-size: 24px;
padding: 10px;
}
.college-info {
color: green;
font-size: 18px;
}
</style>
</head>
<body>
<div class="college-name">ABC College of Science and Technology</div>
<div class="college-info">
ABC College is located in XYZ city and offers undergraduate and
postgraduate programs in Science, Technology, Engineering, and
Mathematics. The college is affiliated with a reputed university and is
known for its excellent faculty and infrastructure.
</div>
</body>
</html>
Nested List With Colors
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Nested List With Colors</title>
<style>
ol {
color: green;
font-weight: bold;
}
ol li ul {
color: red;
list-style-type: disc;
font-weight: normal;
}
ol li ul li {
color: red;
}
</style>
</head>
<body>
<h2>Nested list Example</h2>
<ol>
<li>
Fruits
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Orange</li>
</ul>
</li>
<li>
Vegetables
<ul>
<li>Carrot</li>
<li>Broccoli</li>
<li>Spinach</li>
</ul>
</li>
<li>
Grains
<ul>
<li>Rice</li>
<li>Wheat</li>
<li>Barley</li>
</ul>
</li>
</ol>
</body>
</html>
Simple CSS Page
<!DOCTYPE html>
<html>
<head>
<title>Simple CSS Page</title>
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
color: red;
}
ol {
margin-top: 10px;
padding-left: 20px;
}
li {
margin-bottom: 5px;
}
</style>
</head>
<body>
<h1>My Favorite Activities</h1>
<ol>
<li>Reading Books</li>
<li>Playing Football</li>
<li>Learning HTML & CSS</li>
<li>Watching Documentaries</li>
</ol>
</body>
</html>
Birthday Invitation
<!DOCTYPE html>
<html>
<head>
<title>Birthday Invitation</title>
<style>
body {
background-color: #ffe6f0;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
text-align: center;
margin: 0;
padding: 0;
}
.card {
background-color: #fff0f5;
width: 60%;
margin: 50px auto;
padding: 30px;
border-radius: 15px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
h1 {
color: #d63384;
font-size: 36px;
margin-bottom: 10px;
}
h2 {
color: #6f42c1;
font-size: 24px;
}
p {
color: #333;
font-size: 18px;
margin: 10px 0;
}
.footer {
margin-top: 30px;
font-style: italic;
color: #6c757d;
}
</style>
</head>
<body>
<div class="card">
<h1>You're Invited!</h1>
<h2>To My Birthday Party🎉</h2>
<p><strong>Date:</strong> Saturday, August 10th, 2025</p>
<p><strong>Time:</strong> 4:00PM - 8:00PM</p>
<p><strong>Venue:</strong> 123 Party Lane, Happy Town</p>
<p>There will be music, games, food, and lots of fun!</p>
<p>Come celebrate and make memories with me! 🎂🎈</p>
<div class="footer">
Please RSVP by August 5th<br />
Contact: (123)456-7890 or email@example.com
</div>
</div>
</body>
</html>
Function to get 5 numbers from the user and display only the odd numbers
function displayOddNumbers() {
let numbers = [];
// Accept 5 numbers from the user
for (let i = 0; i < 5; i++) {
let num = parseInt(prompt("Enter number $(i+1): "), 10);
if (!isNaN(num)) {
numbers.push(num);
} else {
alert("Please enter a valid number.");
i--; // Decrement i to repeat this iteration
}
}
let oddNumbers = numbers.filter((num) => num % 2 !== 0);
// Display the odd numbers
if (oddNumbers.length > 0) {
alert("Odd numbers are: " + oddNumbers.join(", "));
console.log("Odd numbers:", oddNumbers);
} else {
alert("No odd numbers were entered.");
console.log("No odd numbers were entered.");
}
}
displayOddNumbers();
Write a JS program to accept a number from user and check if the entered number is palindrome
function checkPalindrome(string) {
const len = string.lenght;
for (let i = 0; i < len / 2; i++) {
if (string[i] !== string[len - 1 - i]) {
return "It is not paloidrome";
}
}
}
const string = prompt("Enter a string : ");
const value = checkPalindrome(string);
console.log(value);