Set 1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

C++ Set-1 Basic Programs Practicals

1. Takes two integer operands and one operator from the user, performs the
operation, and then print the result.
#include <iostream>
using namespace std;

int main() {
char op;
int num1, num2, result;

cout << "Enter first number: ";


cin >> num1;

cout << "Enter second number: ";


cin >> num2;

cout << "Enter operator (+, -, *, /): ";


cin >> op;

switch (op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
cout << "Error! Division by zero is not allowed.";
return 1; // Exit the program with an error code
}
break;
default:
cout << "Error! Invalid operator.";
return 1; // Exit the program with an error code
}

cout << "Result: " << result << endl;


return 0;
}

1
Prepared by :Prof.Menka Lilani
C++ Set-1 Basic Programs Practicals
2.Write a C++ program to Generate all the prime numbers between 1 and n, where n is a
value supplied by the user.
#include <iostream> Using Function
int main() { #include <iostream>
int n; using namespace std;
// Get user input for the upper limit 'n'
std::cout << "Enter a value for n: "; // Function to check if a number is prime
int isPrime(int num) {
std::cin >> n;
int i;
if (num <= 1) return 0;
// Check and generate prime numbers for (i = 2; i * i <= num; i++) {
between 1 and n if (num % i == 0) {
std::cout << "Prime numbers between 1 and return 0;
" << n << " are: "; }
}
for (int i = 2; i <= n; ++i) return 1;
{ }
int isPrime = 1; // Assume i is prime
int main() {
for (int j = 2; j < i; ++j) { int n;
if (i % j == 0) { cout << "Enter a positive integer value for
n: ";
isPrime = 0; // i is divisible by j, not
cin >> n;
prime
break; cout << "Prime numbers between 1 and "
} << n << " are: ";
}
// Check and print prime numbers
if (isPrime) { between 1 and n
std::cout << i << " "; for (int i = 2; i <= n; i++) {
} if (isPrime(i)) {
} cout << i << " ";
}
std::cout << std::endl; }

return 0;
return 0;
}
}

2
Prepared by :Prof.Menka Lilani
C++ Set-1 Basic Programs Practicals
3.Searching an element in an array.
#include <iostream> Taking Values from users
using namespace std; #include <iostream>
using namespace std;
// Function to search for an element in the
array // Function to search for an element in the
int searchElement(int arr[], int size, int key) { array
for (int i = 0; i < size; ++i) { int searchElement(int arr[], int size, int key) {
if (arr[i] == key) { for (int i = 0; i < size; ++i) {
return i; // Return the index if element if (arr[i] == key) {
found return i; // Return the index if the
} element is found
} }
return -1; // Return -1 if element not found }
} return -1; // Return -1 if the element is not
found
int main() { }
int arr[] = { 3, 7, 1, 9, 4, 6 };
int size = sizeof(arr) / sizeof(arr[0]); int main() {
int size;
int elementToFind = 9; cout << "Enter the size of the array: ";
int result = searchElement(arr, size, cin >> size;
elementToFind);
int arr[size];
if (result != -1) { cout << "Enter elements of the array:" <<
cout << "Element found at index: " << endl;
result << endl; for (int i = 0; i < size; ++i) {
} cin >> arr[i];
else { }
cout << "Element not found in the array." int key;
<< endl; cout << "Enter the element to search: ";
} cin >> key;

return 0; int foundIndex = searchElement(arr, size, key);


} if (foundIndex != -1) {
cout << "Element found at index " <<
foundIndex << endl;
} else {
cout << "Element not found in the array" <<
endl;
}
return 0;
}

3
Prepared by :Prof.Menka Lilani
C++ Set-1 Basic Programs Practicals
4. To find the factorial of a given integer.

#include<iostream.h> Prints Table


#include<conio.h> #include <iostream>
using namespace std;
void main()
{ int main()
{
int n,f=1,i=1;
int n;
clrscr();
cout << "Enter a number: ";
cin >> n;
cout<<"\n Enter The Number:";
cin>>n; cout << "Factorial Table for " << n << ":" <<
endl;
//LOOP TO CALCULATE THE FACTORIAL OF for (int i = 1; i <= n; ++i)
A NUMBER {
while(i<=n) int factorial = 1;
{ for (int j = 1; j <= i; ++j)
f=f*i; {
i++; factorial *= j;
} }
cout << i << "! = " << factorial << endl;
}
cout<<"\n The Factorial of "<<n<<" is "<<f;
getch(); return 0;
} }

4
Prepared by :Prof.Menka Lilani
C++ Set-1 Basic Programs Practicals

5.Programs to understand storage specifiers.


#include<iostream> #include <iostream>
using namespace std; using namespace std;
// Global variable class Example {
int globalVariable = 10; public:
// Static data member
// Function with static variable static int staticVariable;
void staticExample()
{ // Const data member
// Static variable retains its value const int constVariable=8;
across function calls
static int staticVariable = 5; // Mutable data member
cout << "Static variable inside mutable int mutableVariable;
function: " <<
staticVariable << endl; //Member function to modify mutableVariable
staticVariable++; void modifyMutableVariable() const
} {
// Even though the function is const, we can
int main() modify mutableVariable
{ mutableVariable++;
// Local variable }
int localVar = 20; // Member function to display all variables
cout << "Global variable: " << void displayVariables() const {
globalVariable << endl; cout << "Static Variable: " << staticVariable << endl;
cout << "Const Variable: " << constVariable << endl;
// Accessing global variable within cout << "Mutable Variable: " << mutableVariable <<
the function endl;
//cout << "Global variable inside main }
function: " << globalVariable <<endl; };

// Accessing local variable // Initializing static data member outside the class
cout << "Local variable: " << localVar int Example::staticVariable = 10;
<< endl; int main() {
Example obj;
// Function call to demonstrate static // Trying to modify const variable will result in a
variable compilation error
// obj.constVariable = 5; // Uncommenting this line
staticExample(); will result in an error
obj.modifyMutableVariable(); // Call to modify the
// Accessing global variable again mutable variable
cout << "Global variable after function obj.displayVariables(); // Displaying all variables
call: " << globalVariable << std::endl;
return 0; return 0;
} }

5
Prepared by :Prof.Menka Lilani
C++ Set-1 Basic Programs Practicals
6. Write a Program using class to process Shopping List for a Departmental Store. The list
includes details such as the Code No and Price of each item and performs the operations like
Adding, Deleting Items to the list and Printing the Total value of an Order.

// Department Store Management System (DSMS) using c++


#include <conio.h>
#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <string>

using namespace std;

// class dept contains main function to perform add,update,view and delete operations
class dept {
public:
// control panel function is called which displays the options available to the user
void control_panel();
void add_item();
void display_item();
void check_item();
void update_item();
void delete_item();
};

// control panel
void dept ::control_panel()
{
cout << "**********************************************"
"**********************************";
cout << "\n\n\t\t\tDepartment Store Management System";
cout << "\n\n\t\t\t\t Control Panel\n";
cout << "\n********************************************"
"************************************\n";
cout << "\n\n 1. Add New Item";
cout << "\n 2. Display Items";
cout << "\n 3. Check Specific Item";
cout << "\n 4. Update Item";
cout << "\n 5. Delete Item";
cout << "\n 6. Exit";
}

6
Prepared by :Prof.Menka Lilani
C++ Set-1 Basic Programs Practicals
// add item
void dept ::add_item()
{

fstream file;
int no_item, Item_Id;
string itm_name;
string c_name;
cout << "\n\n\t\t\t\t Add New Item: \n";
cout << "----------------------------------------------"
"----------------------------\n";
cout << " Item Code : ";
cin >> Item_Id;
cout << "----------------------------------------------"
"----------------------------\n";
cout << "\n\n\t\t\t Item Name: ";
cin >> itm_name;
cout << "\n\n Company Name: ";
cin >> c_name;
cout << "\n\n\t\t\t No. Of Item: ";
cin >> no_item;
file.open("D://item.txt", ios::out | ios::app);
file << " " << Item_Id << " " << itm_name << " "
<< c_name << " " << no_item << "\n";
cout << "=============================================="
"============================"
<< endl;
file.close();
}

// display item
void dept ::display_item()
{
fstream file;
int no_item, Item_code;
string itm_name;
string c_name;
file.open("D://item.txt", ios::in);
if (!file) {
cout << "File Opening Error....";
}
else {
cout << "------------------------------------------"
"-----------------\n";
cout << " Item Code Item "
"Company No. of Item\n";
7
Prepared by :Prof.Menka Lilani
C++ Set-1 Basic Programs Practicals
cout << "------------------------------------------"
"-----------------"
<< endl;
file >> Item_code >> itm_name >> c_name
>> no_item; // To fetch data from file
while (!file.eof()) {
cout << " " << Item_code << " "
<< itm_name << " " << c_name
<< "\t " << no_item
<< "\n"; // to print fetched data from file
// cout<<"\t"<<no_item<<"\n";
file >> Item_code >> itm_name >> c_name
>> no_item; // again fetch next data from
// the file and the loop
// continues till eof
}
cout << "=========================================="
"================="
<< endl;

file.close();
}
}

// check specific item


void dept ::check_item()
{
fstream file;
int count = 0;
int Item_code;
int no_item;
string itm_name, c_name;
cout << "\n\n\t\t\t\t Check Specific Product\n";
cout << "----------------------------------------------"
"----------------------------------\n";
file.open("D://item.txt", ios ::in);
if (!file) {
cout << "File Opening Error....";
}
else {
int It_code;
cout << "\n\n Item Code: ";
cin >> It_code;
cout << "\n----------------------------------------"
"----------------------------------\n";
// again fetch next data from the
8
Prepared by :Prof.Menka Lilani
C++ Set-1 Basic Programs Practicals
// file and the loop continues till eof
file >> Item_code >> itm_name >> c_name >> no_item;
while (!file.eof()) {
if (It_code == Item_code) {
system("cls");
cout
<< "\n\n\t\t\t\tCheck Specific Product";
cout << "\n\n Item Code : " << Item_code;
cout << "\n\n\t\t\tItem Name : "
<< itm_name;
cout << "\n\n Company : " << c_name;
cout << "\n\n\t\t\tNo. of Item : "
<< no_item;
count++;
break;
}
// again fetch next data from the file and the loop continues till eof
file >> Item_code >> itm_name >> c_name
>> no_item;
}
file.close();
if (count == 0) {
cout << "Item Not Found....";
}
}
}
// update item
void dept ::update_item()
{
fstream file, file1;
int no_copy, no_co, count = 0;
string itm_name, b_na, a_name, a_na, newitm_idd,
newitm_id;
cout << "\n\n\t\t\t\tUpdate Item Record\n";
cout << "----------------------------------------------"
"----------------------------\n";
file1.open("D://book1.txt", ios::app | ios::out);
file.open("D://item.txt", ios::in);
if (!file)
cout << "\n\n File Opening Error...";
else {
cout << "\n\n Item Code : ";
cin >> newitm_id;
cout << "\n----------------------------------------"
"----------------------------------\n";
file >> newitm_idd >> itm_name >> a_name >> no_copy;
9
Prepared by :Prof.Menka Lilani
C++ Set-1 Basic Programs Practicals
while (!file.eof()) {
if (newitm_id == newitm_idd) {
system("cls");

cout << "\n\n\t\t\t\tUpdate Book Record";


cout << "\n\n New Item Name : ";

cin >> b_na;


cout << "\n\n\t\t\tCompany Name : ";

cin >> a_na;


cout << "\n\n No. of Items : ";

cin >> no_co;


file1 << " " << newitm_id << " " << b_na
<< " " << a_na << " " << no_co
<< "\n";
count++;
}
else
file1 << " " << newitm_idd << " "
<< itm_name << " " << a_name << " "
<< no_copy << "\n";

file >> newitm_idd >> itm_name >> a_name


>> no_copy;
}
if (count == 0)
cout << "\n\n Item Code Not Found...";
}

file.close();
file1.close();

remove("D://item.txt");
rename("D://book1.txt", "D://item.txt");
}

// delete item
void dept ::delete_item()
{
fstream file, file1;
int no_copy, count = 0;

string newitm_id, newitm_idd, itm_name, a_name;

10
Prepared by :Prof.Menka Lilani
C++ Set-1 Basic Programs Practicals
cout << "\n\n\t\t\t\tDelete Item Record";
cout << "\n--------------------------------------------"
"------------------------------\n";
file1.open("D://book1.txt", ios::app | ios::out);
file.open("D://item.txt", ios::in);

if (!file)
cout << "\n\n File Opening Error...";
else {
cout << "\n\n Item Code : ";
cin >> newitm_id;

cout << "\n----------------------------------------"


"----------------------------------\n";
file >> newitm_idd >> itm_name >> a_name >> no_copy;

while (!file.eof()) {
if (newitm_id == newitm_idd) {
system("cls");
cout << "\n\n\t\t\t\tDelete Item Record";
cout << "\n\n One Item is Deleted "
"Successfully...";
count++;
}
else
file1 << " " << newitm_idd << " "
<< itm_name << " " << a_name << " "
<< no_copy << "\n";
file >> newitm_idd >> itm_name >> a_name
>> no_copy;
}

if (count == 0)
cout << "\n\n Book ID Not Found...";
}
file.close();
file1.close();
remove("D://item.txt");
rename("D://temp.txt", "D://item.txt");
}

11
Prepared by :Prof.Menka Lilani
C++ Set-1 Basic Programs Practicals
// main function
int main()
{
dept d;
p:
d.control_panel();
int choice;

char x;
cout << "\n\n Your Choice : ";
cin >> choice;

switch (choice) {
case 1:
do {
d.add_item();
cout << "Do You Want To Add Another Item (y/n) "
": ";
cin >> x;
} while (x == 'y');
break;
case 2:
d.display_item();
break;
case 3:
d.check_item();
break;
case 4:
d.update_item();
break;
case 5:
d.delete_item();
break;
case 6:
exit(0);
break;

default:
cout << "\n\n Invalid Value....Please Try again";
}

cout << "\n";


getch();

goto p;
}
12
Prepared by :Prof.Menka Lilani
C++ Set-1 Basic Programs Practicals
7. Write a Program that creates & uses array of objects of a class (Eg. implementing the list of
Managers of a Company having details such as Name, Age, etc.).
#include <iostream>
using namespace std;

// Define the Manager class


class Manager {
public:
char name[50];
int age;
float salary;
};

int main()
{
const int numManagers = 2; // Number of managers in the company
Manager managers[numManagers]; // Array of Manager objects

// Input details for each manager


for (int i = 0; i < numManagers; i++)
{
cout << "Enter details for Manager " << i + 1 << ":\n";
cout << "Name: ";
cin.getline(managers[i].name, 50); // Reading name as a character array

cout << "Age: ";


cin >> managers[i].age;

cout << "Salary: ";


cin >> managers[i].salary;

// Consume the newline character left in the input buffer


cin.ignore();
}

// Display details of each manager


cout << "\nDetails of Managers:\n";
for (int i = 0; i < numManagers; i++)
{
cout << "Manager " << i + 1 << ":\n";
cout << "Name: " << managers[i].name << "\n";
cout << "Age: " << managers[i].age << "\n";
cout << "Salary: " << managers[i].salary << "\n\n";
}
return 0;
}
13
Prepared by :Prof.Menka Lilani
C++ Set-1 Basic Programs Practicals

8. Write a Program to find the Maximum out of Two Numbers using the friend function. Note:
Here one number is a member of one class and the other number is member of some other
class.

#include <iostream>
using namespace std;

class Number2; // Forward declaration to let the compiler know about the existence of Number2
class

class Number1 {
private:
int num1;

public:
void getNumber()
{
std::cout << "Enter the first number: ";
std::cin >> num1;
}

friend int findMax(Number1, Number2); // Friend function declaration


};

class Number2
{
private:
int num2;

public:
void getNumber()
{
cout << "Enter the second number: ";
cin >> num2;
}
friend int findMax(Number1, Number2); // Friend function declaration
};

14
Prepared by :Prof.Menka Lilani
C++ Set-1 Basic Programs Practicals
// Friend function definition
int findMax(Number1 n1, Number2 n2)
{
if (n1.num1 > n2.num2)
return n1.num1;
else
return n2.num2;
}

int main() {
Number1 obj1;
Number2 obj2;

obj1.getNumber();
obj2.getNumber();

int maxNumber = findMax(obj1, obj2);


cout << "Maximum number is: " << maxNumber << endl;

return 0;
}

15
Prepared by :Prof.Menka Lilani

You might also like