Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C File

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

INDEX

S.No. Experiment Name Page Date Sign


Date-17/07/24

Experiment 1

Write a program in C++ to print the name and address.

Theory- The provided C++ program prints the name and the address by using the “cout”
statement.

Program-

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

1
Experiment 2

Write a program in C++ to find the sum of three numbers.

Theory- The provided C++ program gives us the sum of three numbers which are taken from
the user. First, we declare the three variables for three numbers, then we take the input by
“cin” and finally calculate the sum and print it.

Program-

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

2
Experiment 3

Write a program in C++ to find the greatest of two numbers.

Theory- The provided C++ gives us the greatest of two numbers given by the user. First, we
declare the variables for the two numbers, and then we use the if statement with the greater
than operator to find which number is greater. Then we print the greatest number.

Program-

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

3
Experiment 4

Write a program in C++ to find whether the number is even or odd.

Theory- The provided C++ tells us whether the number is even or odd. Firstly we declare the
variable for the number. Then we check if the remainder after division by 2 is 0 then the
given number is even otherwise the given number is odd.

Program-

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

4
Experiment 5

Write a program in C++ to find whether the number is palindrome.

Theory- The provided C++ tells us whether the number is palindrome or not. We read the
integer then reverse it using a loop and compare it with the original number. If they are equal
then the number is palindrome, if not then the number is not palindrome.

Program-

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

5
Date-24/07/24
Experiment 6

Write a program in C++ to use math operators using functions.

Theory- This C++ program performs basic arithmetic operations (addition, subtraction,
multiplication, and division) based on user input. It prompts the user for two numbers and an
operation, then calculates and displays the result using a switch statement.

Program-

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

6
Experiment 7

Write a program in C++ to find the factorial of a number using function.

Theory- This C++ program calculates the factorial of a positive integer entered by the user
using a recursive function. It prompts the user for the integer and displays the factorial result
by calling the `factorial` function, which uses recursion to compute the factorial value.

Program-

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

7
Experiment 8

Write a program in C++ to find the days of the week using the switch statement.

Theory- This C++ program displays the day of the week based on user input. It prompts the
user to enter a number from 1 to 7, then uses a switch statement to print the corresponding
day of the week.

Program-

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

8
Date-31/07/24
Experiment 9

Write a program in C++ using the four categories of function.

a)

Theory- This C++ program defines a `say_hello` function that prints "Byee" to the console
and calls this function from the `main` function. It demonstrates basic function declaration,
definition, and usage.

Program-

#include <iostream>
using namespace std;

void say_hello();

int main() {
say_hello();
return 0;
}

void say_hello() {
cout << "Byee";
}

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

9
b)

Theory- This C++ program asks for the user's name and passes it to the `say_hello` function,
which then prints a personalised greeting. It demonstrates user input handling and function
usage with parameters.

Program-

#include<iostream>
using namespace std;

void say_hello(string name);

int main() {
cout << "Enter your name: ";
string name;
cin >> name;

// pass argument num function prime()


say_hello(name);

void say_hello(string name) {


cout << "Hello " << name ;
}

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

10
c)

Theory- This C++ program prompts the user to enter their username through the
`get_username` function, which returns the inputted name. The main function then prints a
personalised greeting using this username.

Program-

#include <iostream>
using namespace std;
string get_username();

int main() {
string user_name = get_username();

cout << "Hello, " << user_name;


}
string get_username() {
string name;
cout << "Enter your user name : ";
cin >> name;

return name;
}

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

11
d)

Theory- This C++ program checks if a user-inputted positive integer is a prime number using
the `check_prime` function, which returns `true` if the number is prime and `false` otherwise.
The main function then outputs whether the number is prime based on the function's result.

Program-

#include <iostream>
using namespace std;
bool check_prime(int n);
int main() {
int num;
cout << "Enter a positive integer to check: ";
cin >> num;
int is_prime = check_prime(num);
if (is_prime == true)
cout << num << " is a prime number.";
else
cout << num << " is not a prime number.";
return 0;
}
bool check_prime(int n) {

for (int i = 2; i <= n/2; ++i) {


if (n % i == 0)
return false;
}
return true;
}

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

12
Experiment 10

Write a program in C++ for call by value.

Theory- This C++ program demonstrates swapping the values of two integers using a `swap`
function, but since it passes arguments by value, the swap only affects the local copies within
the function. The main function handles user input and displays the values before and after
the (local) swap.

Program-

#include <iostream>
using namespace std;
int swap(int a, int b) {
int temp;
temp = a;
a = b;
b = temp;
cout<<"value of 'a' after swap is "<<a<<endl;
cout<<"value of 'b' after swap is "<<b<<endl;
return 0;
}
int main()
{
int a,b;
cout<<"Enter first no. :";
cin>>a;
cout<<"Enter second no. :";
cin>>b;

cout<<"value of 'a' before swap is "<<a<<endl;


cout<<"value of 'b' before swap is "<<b<<endl;
swap(a,b);
return 0;
}

13
Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

Experiment 11

Write a program in C++ for call by reference.


Theory-
This C++ program swaps the values of two user-inputted integers using a `swap` function
that takes references to the integers and prints their values before and after the swap. The
main function handles user input and displays the results.

Program-

#include <iostream>
using namespace std;
int swap(int &a, int &b) {
int temp;
temp = a;
a = b;
b = temp;

cout<<"value of 'a' after swap is "<<a<<endl;


cout<<"value of 'b' after swap is "<<b<<endl;
return 0;
}
int main()

14
{
int a,b;
cout<<"Enter first no. :";
cin>>a;
cout<<"Enter second no. :";
cin>>b;

cout<<"value of 'a' before swap is "<<a<<endl;


cout<<"value of 'b' before swap is "<<b<<endl;
swap(a,b);
return 0;
}

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

15
Date-07/08/24
Experiment 12

Write a program in C++ for inline function.

Theory- This C++ program uses an inline function `area` to calculate the area of a rectangle
by multiplying its length and breadth. The user inputs the rectangle's dimensions, and the
program outputs the calculated area.

Program-

#include<iostream>
using namespace std;
inline int area(int length, int breadth)
{
return length * breadth ;
}
int main()
{
int length, breadth, result;
cout << "Enter the length of the rectangle: ";
cin >> length;
cout << "\nEnter the breadth of the rectangle: ";
cin >> breadth;
result = area(length , breadth);
cout << "\nThe area of the rectangle is: " << result;
cout << "\n\n";
return 0 ;
}

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

16
Experiment 13

Write a program in C++ using friend function.

Theory- This C++ program demonstrates the use of friend functions to add private members
of two different classes, `ClassA` and `ClassB`. The `add` function, declared as a friend in
both classes, accesses the private members `numA` and `numB` to compute and return their
sum.

Program-

#include <iostream>
using namespace std;
class ClassB;
class ClassA {
public:
ClassA() : numA(12) {}
private:
int numA;
friend int add(ClassA, ClassB);
};
class ClassB {
public:
ClassB() : numB(1) {}
private:
int numB;
friend int add(ClassA, ClassB);
};
int add(ClassA objectA, ClassB objectB) {
return (objectA.numA + objectB.numB);
}
int main() {
ClassA objectA;
ClassB objectB;
cout << "Sum: " << add(objectA, objectB);
return 0;
}

Output-

17
Conclusion-
The program has been compiled and run successfully and the output has been verified.

Experiment 14

Write a program in C++ passing objects as function.

Theory- This C++ program defines a class `A` with two public members: an integer `age` and
a character `ch`. The `display` method takes a reference to an object of class `A` and prints
the values of `age` and `ch`. In the `main` function, an object `obj` of class `A` is created, and
the `display` method is called to output the object's `age` and `ch` values.

Program-

#include <iostream>
using namespace std;
class A {
public:
int age = 20;
char ch = 'A';
void display(A &a) {
cout << "Age = " << a.age << endl;
cout << "Character = " << a.ch << endl;
}
};
int main() {
A obj;
obj.display(obj);
return 0;
}

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

18
Date-14/08/24
Experiment 15

Create a class, which keeps track of the number of instances. Use static data
members, constructors and destructors to maintain updated information about
active objects.

Theory- This C++ class `InstanceCounter` tracks the number of active instances using a static
data member `instanceCount`. The constructor increments `instanceCount` whenever a new
object is created, and the destructor decrements it when an object is destroyed. The
`getInstanceCount()` function returns the current number of active instances.

Program-

#include <iostream>
class InstanceCounter {
static int instanceCount;
public:
InstanceCounter() { instanceCount++; }
~InstanceCounter() { instanceCount--; }
static int getInstanceCount() { return instanceCount; }
};
int InstanceCounter::instanceCount = 0;
int main() {
InstanceCounter obj1, obj2;
std::cout << "Active instances: " << InstanceCounter::getInstanceCount() << std::endl;
{
InstanceCounter obj3;
std::cout << "Active instances: " << InstanceCounter::getInstanceCount() << std::endl;
}
std::cout << "Active instances: " << InstanceCounter::getInstanceCount() << std::endl;
return 0;
}

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

19
Experiment 16

Apply default arguments to define a function that finds the simple interest,
with arguments for principal, number of years and rate of interest. Let the
default values for principal be 1000, the number of years be 5 and the rate of
interest be 8. Write a suitable main ( ) that calls this function to demonstrate
all possible ways the function can be invoked.

Theory- This C++ code defines a function `calculateSimpleInterest` that calculates the simple
interest based on a given principal, number of years, and rate. It uses default values if specific
arguments are not provided. The `main` function demonstrates the calculation with various
combinations of arguments, printing the results to the console.

Program-
#include <iostream>
double calculateSimpleInterest(double principal = 1000, int years = 5, double rate = 8) {
return (principal * years * rate) / 100;
}
int main() {
double interest1 = calculateSimpleInterest();
std::cout << "Simple Interest (default values): " << interest1 << std::endl;

double interest2 = calculateSimpleInterest(2000);


std::cout << "Simple Interest (custom principal): " << interest2 << std::endl;

double interest3 = calculateSimpleInterest(3000, 3);


std::cout << "Simple Interest (custom principal and years): " << interest3 << std::endl;

double interest4 = calculateSimpleInterest(4000, 2, 10);


std::cout << "Simple Interest (custom principal, years, and rate): " << interest4 <<
std::endl;
return 0;
}

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

20
Experiment 17

Write a program in C++ Explaining with an example program the working of


function overloading..

Theory- This C++ code demonstrates function overloading by defining three `add` functions
that handle different types and numbers of parameters: two integers, two floating-point
numbers, and three integers. The `main` function then calls each version of the `add`
function, displaying the results for each scenario using `std::cout`. This allows for flexible
addition operations based on the types and number of arguments provided.

Program-
#include <iostream>
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
int main() {
int sum1 = add(10, 20);
std::cout << "Sum of 10 and 20 (int): " << sum1 << std::endl;
double sum2 = add(5.5, 3.2);
std::cout << "Sum of 5.5 and 3.2 (double): " << sum2 << std::endl;
int sum3 = add(1, 2, 3);
std::cout << "Sum of 1, 2, and 3 (int): " << sum3 << std::endl;
return 0;
}

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

21
Date-04/09/24
Experiment 18

Define Class named point which represents 2-D Point, i.e P(x, y). Define
Default constructor to initialize both data member value 5, Parameterized
constructor to initialize member according to the value supplied by the user and
Copy Constructor. Define Necessary Functions and Write a program to test class
Point.

Theory- This C++ code defines a `Point` class with two private member variables, `x` and
`y`, and provides three constructors: a default constructor that initializes the point to (5, 5), a
parameterized constructor for custom initialization, and a copy constructor that creates a new
object by copying an existing one. In the `main()` function, objects of the `Point` class are
instantiated using these constructors, and the coordinates are displayed using the `display()`
method. Each constructor also prints a message indicating when it is called, allowing the user
to observe the object creation process.

Program-

#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
Point() : x(5), y(5) {
cout << "Default constructor called. (" << x << ", " << y << ")" << endl;
}

Point(int x_val, int y_val) : x(x_val), y(y_val) {


cout << "Parameterized constructor called. (" << x << ", " << y << ")" << endl;
}

Point(const Point& other) : x(other.x), y(other.y) {


cout << "Copy constructor called. (" << x << ", " << y << ")" << endl;
}

void display() const {


cout << "Point(" << x << ", " << y << ")" << endl;
}
};

22
int main() {
Point p1;
p1.display();

Point p2(10, 15);


p2.display();

Point p3 = p2;
p3.display();

return 0;
}

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

23
Date-11/09/24
Experiment 19

Create a C++ class named `Employee` to model an employee in a company. The


class should use constructors to initialize its objects with specific attributes:
`employeeID` (integer), `name` (string), `position` (string), and `salary`
(double). Define the following methods:

1. Default Constructor: Initializes the employee with default values.


2. Parameterized Constructor: Initializes the `employeeID`, `name`, `position`,
and `salary` with provided values.
3. Copy Constructor: Initializes a new `Employee` object as a copy of an
existing `Employee` object.
4. Setters: Provide setter methods to update the `employeeID`, `name`,
`position`, and `salary` of the employee.
5. Getters: Provide getter methods to retrieve the `employeeID`, `name`,
`position`, and `salary` of the employee.
6. Display: Implement a public method `display()` that prints the employee's
details in a readable format.

Theory- This C++ code defines an `Employee` class that models an employee with private
attributes (`employeeID`, `name`, `position`, and `salary`). It offers public constructors, along
with setter and getter methods for controlled access to these attributes. Additionally, the class
features a `display()` method to print the employee's details, ensuring encapsulation by
keeping the attributes private.

Program-

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

class Employee {
private:
int employeeID;
string name;
string position;
double salary;

public:
Employee() : employeeID(0), name("Unknown"), position("Unknown"), salary(0.0) {

24
cout << "Default constructor called." << endl;
}
Employee(int id, string empName, string empPosition, double empSalary)
: employeeID(id), name(empName), position(empPosition), salary(empSalary) {
cout << "Parameterized constructor called." << endl;
}
Employee(const Employee &other)
: employeeID(other.employeeID), name(other.name), position(other.position),
salary(other.salary) {
cout << "Copy constructor called." << endl;
}
void setEmployeeID(int id) {
employeeID = id;
}

void setName(string empName) {


name = empName;
}

void setPosition(string empPosition) {


position = empPosition;
}

void setSalary(double empSalary) {


salary = empSalary;
}

int getEmployeeID() const {


return employeeID;
}

string getName() const {


return name;
}

string getPosition() const {


return position;
}

double getSalary() const {


return salary;
}

void display() const {

25
cout << "Employee Details: " << endl;
cout << "ID: " << employeeID << endl;
cout << "Name: " << name << endl;
cout << "Position: " << position << endl;
cout << "Salary: $" << salary << endl;
}
};

int main() {
Employee emp1;
emp1.display();

Employee emp2(101, "John Doe", "Manager", 75000);


emp2.display();

Employee emp3 = emp2;


emp3.display();

emp1.setEmployeeID(102);
emp1.setName("Jane Smith");
emp1.setPosition("Developer");
emp1.setSalary(65000);
emp1.display();

return 0;
}

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

26
Date-25/09/24
Experiment 20

Define a class `Complex` with `real` and `imaginary` as two data members,
along with default and parameterized constructors. The class should include
functions to initialize and display the data. Additionally, overload the `+`
operator to add two complex objects. Write a complete C++ program to
demonstrate the use of the `Complex` class.

Theory- This C++ code defines a `Complex` class with two private member variables, `real`
and `imaginary`, and includes both default and parameterized constructors for initialization. It
overloads the `+` operator to enable the addition of two complex objects by summing their
real and imaginary parts. In the `main()` function, two complex numbers are created, added,
and displayed using the `display()` method, demonstrating the functionality of the class.

Program-

#include <iostream>
using namespace std;

class Complex {
private:
float real;
float imaginary;

public:
Complex() : real(0), imaginary(0) {}

Complex(float r, float i) : real(r), imaginary(i) {}

void display() const {


cout << real << " + " << imaginary << "i" << endl;
}

Complex operator+(const Complex& other) const {


Complex temp;
temp.real = real + other.real;
temp.imaginary = imaginary + other.imaginary;
return temp;
}
};

27
int main() {
Complex c1(3.5, 2.5), c2(1.5, 4.5);

cout << "First Complex Number: ";


c1.display();

cout << "Second Complex Number: ";


c2.display();

Complex c3 = c1 + c2;

cout << "Sum of Complex Numbers: ";


c3.display();

return 0;
}

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

28
Experiment 21

Design three classes: Student, Exam, and Result. The Student class has data
members such as roll number and name, etc. Create a class Exam by inheriting
the Student class. The Exam class adds data members representing the marks
scored in six subjects. Derive the Result class from the Exam class, which has
its own members such as total marks. Write an interactive program to model this
relationship. What type of inheritance does this model belong to?

Theory- This C++ code defines a Student class with attributes for roll number and name, an
Exam class that inherits from Student and adds marks for six subjects, and a Result class that
inherits from Exam to calculate and display the total marks. The program allows interactive
input of student details and marks, showcasing simple inheritance.

Program-
#include <iostream>
#include <string>
using namespace std;

class Student {
protected:
int rollNo;
string name;

public:
void inputStudentDetails() {
cout << "Enter Roll No: ";
cin >> rollNo;
cout << "Enter Name: ";
cin >> name;
}
};
class Exam : public Student {
protected:
float marks[6];

public:
void inputMarks() {
cout << "Enter marks for 6 subjects: ";
for (int i = 0; i < 6; i++) {
cin >> marks[i];
}

29
}

float totalMarks() {
float total = 0;
for (int i = 0; i < 6; i++) {
total += marks[i];
}
return total;
}
};
class Result : public Exam {
public:
void displayResult() {
cout << "Roll No: " << rollNo << ", Name: " << name << ", Total Marks: " <<
totalMarks() << endl;
}
};

int main() {
Result studentResult;
studentResult.inputStudentDetails();
studentResult.inputMarks();
studentResult.displayResult();

return 0;
}

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

30
Experiment 22

Write a program to swap two numbers (create two classes) using a friend
function.

Theory- This C++ program demonstrates how to swap two numbers using a friend function.
The swapNumbers() function has access to the private members of both classes Number1 and
Number2, allowing it to swap their values.

Program-
#include <iostream>
using namespace std;
class Number1;
class Number2;
class Number1 {
int num1;
public:
void setNumber(int n) { num1 = n; }
friend void swapNumbers(Number1 &n1, Number2 &n2);
void display() { cout << "Number1: " << num1 << endl; }
};
class Number2 {
int num2;
public:
void setNumber(int n) { num2 = n; }
friend void swapNumbers(Number1 &n1, Number2 &n2);
void display() { cout << "Number2: " << num2 << endl; }
};
void swapNumbers(Number1 &n1, Number2 &n2) {
int temp = n1.num1;
n1.num1 = n2.num2;
n2.num2 = temp;
}
int main() {
Number1 n1;
Number2 n2;
n1.setNumber(5);
n2.setNumber(10);

cout << "Before Swap:" << endl;


n1.display();
n2.display();

31
swapNumbers(n1, n2);

cout << "After Swap:" << endl;


n1.display();
n2.display();

return 0;
}

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

32
Experiment 23

Write a program to calculate the total marks of a student using the concept of a
virtual base class.

Theory- This program demonstrates the use of virtual base classes to avoid ambiguity in the
case of multiple inheritance. The class Result inherits from both Test and Sports, which
virtually inherit from Student. This avoids duplication of the rollNo attribute.

Program-
#include <iostream>
using namespace std;
class Student {
protected:
int rollNo;
public:
void getRollNo() {
cout << "Enter Roll No: ";
cin >> rollNo;
}
void displayRollNo() {
cout << "Roll No: " << rollNo << endl;
}
};
class Test : virtual public Student {
protected:
int marks;
public:
void getMarks() {
cout << "Enter Marks: ";
cin >> marks;
}
void displayMarks() {
cout << "Marks: " << marks << endl;
}
};
class Sports : virtual public Student {
protected:
int score;
public:
void getScore() {
cout << "Enter Sports Score: ";

33
cin >> score;
}
void displayScore() {
cout << "Sports Score: " << score << endl;
}
};
class Result : public Test, public Sports {
int total;
public:
void calculateTotal() {
total = marks + score;
}
void displayResult() {
displayRollNo();
displayMarks();
displayScore();
cout << "Total: " << total << endl;
}
};
int main() {
Result r;
r.getRollNo();
r.getMarks();
r.getScore();
r.calculateTotal();
r.displayResult();
return 0;
}

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

34
Experiment 23

Write a program to show the use of this pointer. Write the application of this
pointer.

Theory- This program demonstrates the use of the this pointer in C++. The this pointer is
used to refer to the current instance of the class. In this example, it is used to assign values to
the class members and return the address of the current object.

Program-
#include <iostream>
using namespace std;
class Demo {
int value;
public:
Demo(int value) {
this->value = value;
}
void display() {
cout << "Value: " << this->value << endl;
}
Demo* getThisPointer() {
return this;
}
};
int main() {
Demo d(10);
d.display();

cout << "Address of object d: " << d.getThisPointer() << endl;


return 0;
}

Output-

Conclusion-
The program has been compiled and run successfully and the output has been verified.

35

You might also like