Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
36 views16 pages

C++ Programs: Prime, Palindrome, Sort & More

Uploaded by

Vasu Goyal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views16 pages

C++ Programs: Prime, Palindrome, Sort & More

Uploaded by

Vasu Goyal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 16

#c++ programs of chatgpt made c++ course

#Checking prime number program


#include <iostream>
using namespace std;
int main() {
int num;
cout << "enter a number";
cin >> num;
bool isprime = true;

if (num <= 1) {
isprime = false;
}
else {
for (int i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
isprime = false;
break;

}
}

if (isprime) {
cout << "num is prime no.";

}
else {
cout << "not prime";
}
return 0;
}

#Palindrome checker
#include <iostream>
using namespace std;
int main() {
char str[100];
cout << "enter a string";
cin.getline(str, 100);

int len = strlen(str);


bool ispalindrome = true;
for (int i = 0; i <= len / 2; ++i) {
if (str[i] != str[len - i - 1]) {
ispalindrome = false;
break;
}
}

if (ispalindrome) {
cout << "Its a palindrome";
}
else {
cout << "not a palindrome";
}
return 0;
}
#day of the year checker
#include <iostream>
using namespace std;

int main() {
int day, month, year;
cout << "Enter date (DD MM YYYY): ";
cin >> day >> month >> year;

bool isleapyear = false;


if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {
isleapyear = true;
}

int daysinmonth[] = { 31,28 + isleapyear,31,30,31,30,31,31,30,31,30,31 };

if (month < 1 || month>12 || year < 1 || day < 1 || day>daysinmonth[month - 1])


{
cout << "Invalid date entered!\n";
return 1;
}

int totaldays = 0;
for (int i = 1; i < month; ++i) {
totaldays += daysinmonth[i - 1];
}
totaldays += day;

int dayofweek = totaldays % 7;

cout << "Day of the week: ";


switch (dayofweek) {
case 0:
cout << "Sunday\n";
break;
case 1:
cout << "Monday\n";
break;
case 2:
cout << "Tuesday\n";
break;
case 3:
cout << "Wednesday\n";
break;
case 4:
cout << "Thursday\n";
break;
case 5:
cout << "Friday\n";
break;
case 6:
cout << "Saturday\n";
break;
}

return 0;
}
#Reversing number
#include <iostream>
using namespace std;
int main() {
int num, reversedNumber = 0;
cout << "Enter a number: ";
cin >> num;

while (num != 0) {
int remainder = num % 10;
reversedNumber= reversedNumber*10+ remainder;
num /= 10;
}

cout << "Reversed number: " << reversedNumber;


return 0;
}

#secondlargestelement
#include <iostream>
using namespace std;
int main() {
int arr[5] = { 1,2,3,4,5 };
int max = arr[0]; int secondmax = INT_MIN;
for (int i = 1; i < 5; ++i) {
if(arr[i]>max) {
secondmax = max;
max=arr[i];

} else if (arr[i]>secondmax && arr[i]!=max) {


secondmax = arr[i];
}

cout << "secondlargestelelement " << secondmax;


return 0;

#removing duplication from an array


#include <iostream>
using namespace std;
int main() {
int arr[] = { 1,2,2,3,4,4,5 };
int n = 7;

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


for (int j = i + 1; j < n;) {
if (arr[i] == arr[j]) {
for (int k = j; k < n - 1; ++k) {
arr[k] = arr[k + 1];

}
--n;
}
else {
j++;
}
}
}

cout << "array after duplicates";


for (int i = 0; i < n; ++i) {
cout << arr[i];

}
return 0;

#bubble sort algorithm(using functions)


#include <iostream>
using namespace std;
void bubblesort(int arr[], int size) {
for (int i = 0; i < size - 1; ++i) {
for (int j = -0; j < size - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
}
}
}

int main() {
int arr[] = { 5,6,8,2,9 };
int size = sizeof(arr) / sizeof(arr[0]);
bubblesort(arr, size);

cout << "Sorted ARRAY: ";


for (int i = 0; i < size ; ++i) {
cout << arr[i];
}
}

#recursive function to find sum of digits


#include <iostream>
using namespace std;

// Function definition
int sumOfDigits(int n) {
if (n == 0) {
return 0;
}
return (n % 10) + sumOfDigits(n / 10);
}

int main() {
int num = 12345;
cout << "Sum of digits of " << num << ": " << sumOfDigits(num);
return 0;
}

#recursive function to find greater common divisor(euclidian algorithm)


#include <iostream>
using namespace std;

// Function definition
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}

int main() {
int num1 = 36, num2 = 48;
cout << "GCD of " << num1 << " and " << num2 << ": " << gcd(num1, num2);
return 0;
}

#structure with function in it finding largest number


#include <iostream>
using namespace std;
struct numbers {
int num1;
int num2;
int num3;

};

int findlargest(numbers nums) { //nums is the parameter whos type is numbers which
is structure which is defined above
int largest = nums.num1; // nums.num1 means that it is accessing num1
object from nums structure
if (nums.num2 > largest) {
largest = nums.num2;
}
if (nums.num3 > largest) {
largest = nums.num3;
}
return largest;
}
int main() {
numbers nums = { 10,20,30 }; //object is an array which is called nums
cout <<"largest number: "<< findlargest(nums); //calling function which
has nums as its parameter which is the array of 10,20,30 which is also the object
of the structure.
return 0;
}

#nested structure(structure within structure


#include <iostream>
using namespace std;
struct Address {
string city;
string state;
};

struct employee {
int age;
string name;
Address address; //makes the type of address as what is in Address structure
};

int main() {
employee emp1;
emp1.name ="vasu";
emp1.age = 45;
emp1.address = { "g", "har" };

cout << emp1.name << emp1.age << emp1.address.city<<emp1.address.state;


}

#average marks calculator


#include <iostream>
using namespace std;
struct student{
string name;
int marks[3];
};

float calculateaverage(int marks[], float size){


float sum = 0;
for (int i = 0; i < size; ++i) {
sum += marks[i];
}
return sum / size;
}

int main() {
student student1[2] = { { "vasu",{10,70,80}}, {"saanvi",{20,5,90}} };
for (int i = 0; i < 2; ++i) {
float avg = calculateaverage(student1[i].marks, 3);
cout << "Student " << student1[i].name << ": Total Marks - " <<
student1[i].marks[0] + student1[i].marks[1] + student1[i].marks[2] << ", Average
Marks - " << avg;

return 0;
}

#using getline, memory allocation using pointer, cin.ignore in structures


struct Book {
string title;
string author;
float price;
};

int main() {
int n;
cout << "Enter the number of books: ";
cin >> n;
Book* books = new Book[n];
for (int i = 0; i < n; ++i) {
cout << "Enter details for Book " << i + 1 << ":" << endl;
cout << "Title: ";
cin.ignore();
getline(cin, books[i].title);
cout << "Author: ";
getline(cin, books[i].author);
cout << "Price: ";
cin >> books[i].price;
}

cout << "Details of Books:" << endl;


for (int i = 0; i < n; ++i) {
cout << "Book " << i + 1 << ": Title - " << books[i].title << ", Author - "
<< books[i].author << ", Price - $" << books[i].price << endl;
}

delete[] books;
return 0;
}

#encapsulation using classes, functions


#include <iostream>
using namespace std;

class circle {
private:
double radius;
public:
void setradius(double r) {
if (r >= 5) {
radius = r;

}
else {
cout << "radius not fefined";

}
}
int getradius() {
return radius;
}

int calculatearea() {
return 3.14*radius*radius;
}
};

int main() {

circle circles;
circles.setradius(5);

cout << "radius:"<<circles.getradius()<<endl;


cout << "area of circle:" << circles.calculatearea();
return 0;
}
#base class and derived class using inheritance
#include <iostream>
using namespace std;

// Base class
class Shape {
public:
void display() {
cout << "This is a shape.";
}
};

// Derived class
class Rectangle : public Shape {
public:
void displayRectangle() {
cout << "This is a rectangle.";
}
};

int main() {
Rectangle rect;
rect.display(); // Accessing base class method
rect.displayRectangle(); // Accessing derived class method
return 0;
}

#polymorphism using function overloading


#include <iostream>
using namespace std;

class Math {
public:
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}
};

int main() {
Math math;
cout << "Sum of integers: " << math.add(5, 3)<<endl;
cout << "Sum of doubles: " << math.add(5.6, 7.9);
return 0;
}

#polymorphism with override,pointer,virtual function, delete pointer(by


destructor).
#include <iostream>
using namespace std;

class Animal {
public:
virtual void speak() { //virtual functions are based on type of the object
and can be overrriden by derived classes like in this program.
cout << "animal speaks";
}
};

class Dog : public Animal {


public:
void speak() override { //override is used to indicate that this function is
overriding the virtual function speak() defined in the base class.
cout << "Dog barks";

}
};

int main() {
Animal* animal = new Dog();//animal is a pointer of type Animal. It is
initialized with a new instance of the Dog class. This is possible because of
polymorphism and inheritance in C++. Since Dog is derived from Animal, a pointer to
Dog can be implicitly converted to a pointer to Animal. This is called upcasting.
animal->speak();// calls the speak function of dog as we overrided it when we
mentioned override.
delete animal;// it deletes the memory allocated to the dog object by pointer
animal and basically is a destructor.
return 0;
}

#using memory allocation and deallocation using classes and constructor


#include <iostream>
using namespace std;

class Box {
private:
int* length; //length is the pointer to the integer

public:
Box() { //Box is a constructor
length = new int; //memory is allocated for int using new and the
address of it is stored in length
*length = 0; // value pointed by length is initialized to 0
}

void setlength(int l) {
*length = l; //the value of int l is stored in pointer length
}

int getlength() {
return *length; //it gives the value which is stored in the pointer
length
}

~Box() {
delete length; //~box is the destructor, the allocated memory or value
inside length is now deleted.
}
};

int main() {
Box* box = new Box();//a pointer box is created to Box and stored in another
Box object
box->setlength(5);//the function setlength is called which sets the length of
box to 5
cout << "Length of box: " << box->getlength(); //the length of the box is
retrieved using getlength
delete box;//memory allocated for Box object by using box is now deleted by
the destructor
return 0;

#Static data members and member functions belong to the class rather than
individual objects. They are shared among all objects of the class.
#include <iostream>
using namespace std;

class Counter {
private:
static int count;//static int is a function which has a member variable
called count and is used to count the number of counter objects created

public:
Counter() {// this is the constructor
count++; //each time a counter object is created the count variabvle is
incremented, also count is shared among all instances of the class as its a static
member
}

static int getcount() {//getcount is declared static and returns value of


count
return count;//as its a static function it can be called without
creating an instance of the class
}
};

int Counter::count = 0;//initializes static member variable count to 0 and is


necessary to provide a separate initialization for static member variables outside
the class definition.
int main() {
Counter c1, c2, c3;//objects created and each time an object created the
constructor increments static member count
cout << "Count:" << Counter::getcount();//The getCount() static member
function of the Counter class is called using the scope resolution operator ::.
This function returns the current count of Counter objects created.
return 0;
}

#program to demonstrate the use of friend functions in C++ classes


#include <iostream>
using namespace std;

class Number {
private:
int num;//private number num

public:
Number(int n) {//number is a constructor and has n has a parameter
num = n; //the value of n is assigned to num
}

friend void display(Number);//friend function declaration of display and has


Number in bracket to specify the Number class, this allows the function to access
private members of the number class.
};

void display(Number num1) {//takes Number class's object num1 as parameter


cout << "Number: " << num1.num;//displays value of its num member variable
}
int main() {
Number n(10);//a Number object n is crated with value of 10 by calling
constructor Numver (int n).
display(n);//Inside the display function, num1 represents a copy of the
Number object n that was passed as an argument. Thus, num1.num accesses and prints
the value of the num member variable of the n object.
}

#constructor using default and parameterized constructor


#include <iostream>
using namespace std;

class Rectangle {
private:
int length;
int width;

public:
// Default Constructor
Rectangle() {
length = 0;
width = 0;
}

// Parameterized Constructor
Rectangle(int l, int w) {
length = l;
width = w;
}

void display() {
cout << "Length: " << length << ", Width: " << width << endl;
}
};

int main() {
Rectangle rect1; // Calls default constructor
Rectangle rect2(5, 3); // Calls parameterized constructor
rect1.display();
rect2.display();
return 0;
}

#constructor and destructor


#include <iostream>
using namespace std;

class MyClass {
private:
int* data;// reserves memory for pointer data but doesnt really allocates
memory for actual data
public:
MyClass() {//This is the constructor of the MyClass class. It is automatically
called when an object of MyClass is created.
data = new int[5];//allocates memory for an array of 5 integers using new
and assigns the address of the allocated memory to the pointer data.
cout << "Constructor called." << endl;
}

~MyClass() {
delete[] data;// deletes the memory allocated for it for data
cout << "Destructor called." << endl;
}
};

int main() {
MyClass obj;// object "obj" is created and hence calls constructor
return 0;
}

#file reading
#include <iostream>
#include <fstream>
using namespace std;

int main() {
ifstream/ofstream file;//have to declare this line when using
ifstream/ofstream. ofstream is for writing to a file while ifstream is to read from
that particular file.
file.open("example.txt");

if (!file) {
cout << "error";
return 1;//return 1 so that it doesnt display wierd long ass errors
}

file.close();//to close file


return 0;

#reading line by line lines from a file


#include <iostream>
#include <fstream>
using namespace std;

int main() {
ifstream file;
file.open("example.txt");

if (!file) {
cout << "error";
return 1;
}

string line;//declares a variable line.


while (getline(file, line)) { //reads line by line through getline function
and stores it in file.
cout << line << endl;//prints every line, line by line which was stored
in file.
}

file.close();
return 0;

#try,catch,throw example
#include <iostream>
using namespace std;

int main() {
try {
int age = 15;
if (age >= 18) {
cout << "access granted";
}
else {
throw(age);
}
}
catch (int mynum) {//catches whatever is in throw, which is age,i.e. 15.
cout << "access denied-you must be 18 years old";
cout << "your age is: " << mynum;
}
return 0;
}

#vectors
#include <iostream>
#include <vector>
using namespace std;

int main() {
vector<int>numbers = { 1,2,3,4,5 };//declares a vector(type of array) of int
type named numbers.
cout << "first element: " << numbers[0] << endl;// prints first element i.e.
1.
for (auto it = numbers.begin(); it != numbers.end(); ++it) { //a for loop,
auto is a type which is based on whatever the vector has,
begin() takes the position of first element while end() takes the last. it!
=end ensures that the reading of vector is finished. and then increments it.
cout << *it << " "; //prints the value of 'it' and then derefences(kind
of delete) so that 'it' can have a new value when its incremented to next one.

}
return 0;
}

#adding elements to a vector and printing it


#include <iostream>
#include <vector>
using namespace std;

int main() {
vector<int> numbers;
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(3);
for (int i = 0; i < numbers.size(); ++i) {
cout << numbers[i] <<" "<< endl;
}
return 0;
}

#sets-dont allow duplicate elements and sorts whatever is inside it, printing and
declaring elements inside a set works exactly as vector.
#adding elements in a set(slight diff from vector)
#include <iostream>
#include <set>
using namespace std;

int main() {
set<int> numbers;
numbers.insert(1);
numbers.insert(2);
numbers.insert(3);
return 0;
}

#multiset(bag) has every syntax and everything else same as set but it allows
duplicate elements unlike set.

#lists has same syntax and everything as sets, vectors but insertion works
differently.
#include <iostream>
#include <list>
using namespace std;

int main() {
list<int>numbers = { 1,2,3,5,6 };
numbers.insert(numbers.begin(), 9);//puts value 9 in the beginnig of the list.
numbers.insert(numbers.end(), 7);//puts value 7 in the end of the list.
auto it = numbers.begin();//a variable "it" is pointing to first element
advance(it, 2);//adavances the iterator by 2 positions so it is pointing to 3rd
element of the list.
numbers.insert(it, 3);//inserts value of 3 to the position pointed by "it" i.e.
3.
return 0;
}

#queue insertion(note: in queues elements added are in a sequence like a normal


list unlike stacks which start from behind).
#include <iostream>
#include <queue>
using namespace std;
int main() {
queue <int> q;
q.push(1);
q.push(2);
q.push(3);
return 0;
}

#stacks(inserts elements from the end and not starting like usual)
#include <iostream>
#include <stack>
using namespace std;

int main() {
stack<int> s;
// Inserting elements into the stack
s.push(1);
s.push(2);
s.push(3);
// Printing elements by popping from the stack
cout << "Elements in the stack:" << endl;
while (!s.empty()) {
cout << s.top() << " "; // Print the top element of the stack
s.pop(); // Remove the top element
}
cout << endl;

return 0;
}

#map (works in key-value pair like a dictionary in python


#include <iostream>
#include <map>
using namespace std;

int main() {
map<int, string> students = { {101,"alice"},{102,"bob"},{103,"clinton"} };
cout << "student with roll number 102: " << students[102] << endl;//accessing
using normal method
cout << "student with roll number 103: " << students.at(103) <<
endl;//accessing using at method

return 0;
}

#multimap
#include <iostream>
#include <map>
using namespace std;

int main() {
multimap<int, string> students = { {101,"alice"},{102,"bob"},
{101,"clinton"} };//key can be overloaded in a multimap

for (auto it = students.begin(); it != students.end(); ++it{


cout<<"roll number: "<<it->first<<",name: "<<it->second<<endl;
}

return 0;
}

#deque
#include <iostream>
#include <deque>
using namespace std;

int main() {
deque<int> numbers = { 1, 2, 3, 4, 5 };
// Accessing elements using array-like syntax
cout << "First element: " << numbers[0] << endl;
// Accessing elements using iterators
for (auto it = numbers.begin(); it != numbers.end(); ++it) {
cout << *it << " ";
}
return 0;
}

You might also like