0% found this document useful (0 votes)
57 views

C++ Assignment

The document contains solutions to 9 programming problems involving C++ concepts like functions, structures, classes, and storage classes. Specifically, it provides the full source code for: 1. A program that prints a table using manipulators like setw and endl. 2. A program with an inline function to calculate circle area. 3. A program that reverses a string using a custom function. 4. A program that overloads the sort() function for different data types. 5. A program using a structure to represent distances with related functions. 6. A program passing Time objects to functions by value, address, and reference. 7. A program with a friend function to add

Uploaded by

Yogendra Kshetri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

C++ Assignment

The document contains solutions to 9 programming problems involving C++ concepts like functions, structures, classes, and storage classes. Specifically, it provides the full source code for: 1. A program that prints a table using manipulators like setw and endl. 2. A program with an inline function to calculate circle area. 3. A program that reverses a string using a custom function. 4. A program that overloads the sort() function for different data types. 5. A program using a structure to represent distances with related functions. 6. A program passing Time objects to functions by value, address, and reference. 7. A program with a friend function to add

Uploaded by

Yogendra Kshetri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

C++ Lab Assignment 1

SOLUTIONS:

1. Write a C++ Program to print the following using cout and manipulators (endl, left, right, setw)

#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
cout<<left<<setw(10)<<"S.No."<<left<<setw(15)<<"City"<<left<<setw(15)<<"District"
<<left<<setw(15)<<"Province"<<right<<setw(10)<<"Population"<<endl;

cout<<left<<setw(10)<<"1."<<left<<setw(15)<<"Kathmandu"<<left<<setw(15)<<"Kathmandu"
<<left<<setw(15)<<"Bagmati"<<right<<setw(10)<<"500000"<<endl;

cout<<left<<setw(10)<<"2."<<left<<setw(15)<<"Pokhara"<<left<<setw(15)<<"Kaski"
<<left<<setw(15)<<"Gandaki"<<right<<setw(10)<<"50000"<<endl;

cout<<left<<setw(10)<<"3."<<left<<setw(15)<<"Butwal"<<left<<setw(15)<<"Rupandehi"
<<left<<setw(15)<<"Lumbini"<<right<<setw(10)<<"100000"<<endl;

cout<<left<<setw(10)<<"4."<<left<<setw(15)<<"Dharan"<<left<<setw(15)<<"Sunsari"
<<left<<setw(15)<<"prov 1"<<right<<setw(10)<<"80000"<<endl;
return 0;
}

2. Write a Program defining an inline function to compute the area of circle with radius as input.

#include<iostream>
#define PI 3.14
using namespace std;
inline float area(float r){
return PI*r*r;
}

int main(){
float r;
cout<<"Enter the radius of the circle :\n";
cin>>r;
cout<<"The area of the circle :"<<area(r);

return 0;
}

3. Write a program to get input a string and print the string and its reverse. Define your own
function to reverse the string in your program.

#include <iostream>
#include <string.h>
using namespace std;
void reverse_string(char s[]) {
int i, j;
char temp;
for (i = 0, j = strlen(s) - 1; i < j; i++, j--) {
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}

int main() {
char string_input[100];
cout<<"Enter a string: "<<endl;
cin>>string_input;
string_input[strcspn(string_input, "\n")] = '\0'; // remove newline character from
input
cout<<"Original string: \n"<<string_input<<endl;
reverse_string(string_input);
cout<<"Reversed string: \n"<<string_input<<endl;
return 0;
}

4. Write a program overloading function sort() to sort an array of integers, characters as well as
floating point numbers(Use any sorting algorithm).

#include<iostream>
using namespace std;
#define N 10
void sort(int arr[], int SIZE);
void sort(float arr[], int SIZE);
void sort(char arr[], int SIZE);

int main(){
int int_array[N];
float float_array[N];
char char_array[N];
cout<<"Enter integer array elements:"<<endl;
for (int i = 0; i < N; i++)
{
cin>>int_array[i];
}
cout<<"Enter floating array elements:"<<endl;
for (int i = 0; i < N; i++)
{
cin>>float_array[i];
}
cout<<"Enter character array elements:"<<endl;
for (int i = 0; i < N; i++)
{
cin>>char_array[i];
}
sort(int_array,N);
sort(float_array, N);
sort(char_array, N);
cout<<"After sorting integer array:"<<endl;
for (int i = 0; i < N; i++)
{
cout<<int_array[i]<<", ";
}
cout<<endl;
cout<<"After sorting float array:"<<endl;
for (int i = 0; i < N; i++)
{
cout<<float_array[i]<<", ";
}
cout<<endl;
cout<<"After sorting character array:"<<endl;
for (int i = 0; i < N; i++)
{
cout<<char_array[i]<<", ";
}
return 0;
}

//for int
void sort(int arr[], int SIZE){
for (int i = 0; i < SIZE; i++)
{
for (int j = i+1; j < SIZE; j++)
{
if (arr[i] > arr[j])
{
int temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}

//for float
void sort(float arr[], int SIZE){
for (int i = 0; i < SIZE; i++)
{
for (int j = i+1; j < SIZE; j++)
{
if (arr[i] > arr[j])
{
float temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
// for char
void sort(char arr[], int SIZE){
for (int i = 0; i < SIZE; i++)
{
for (int j = i+1; j < SIZE; j++)
{
if (arr[i] > arr[j])
{
char temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}

5. Write a program that uses a structure Distance with data members meter and centimeter. Add
functions in structure to take input and output as well as the function to add the two variables of
Distance and return the sum. Your program should display the result.

#include <iostream>
using namespace std;
// Structure to represent distance
struct Distance {
int meter;
int centimeter;
};

// Function to take input for distance


void inputDistance(Distance& d) {
cout << "Enter meters: ";
cin >> d.meter;
cout << "Enter centimeters: ";
cin >> d.centimeter;
}

// Function to display distance


void displayDistance(const Distance& d) {
cout << "Distance: " << d.meter << " meters, " << d.centimeter << " centimeters" <<
endl;
}

// Function to add two distances and return the sum


Distance addDistances(const Distance& d1, const Distance& d2) {
Distance sum;
sum.meter = d1.meter + d2.meter;
sum.centimeter = d1.centimeter + d2.centimeter;

if (sum.centimeter >= 100) {


sum.meter += sum.centimeter / 100;
sum.centimeter %= 100;
}

return sum;
}

int main() {
Distance distance1, distance2, sum;

// Take input for two distances


cout << "Enter distance 1: " << endl;
inputDistance(distance1);
cout << "Enter distance 2: " << endl;
inputDistance(distance2);

// Add the distances


sum = addDistances(distance1, distance2);

// Display the result


cout << "Sum of distances:" << endl;
displayDistance(sum);
return 0;
}

6. Write a program with objects as function(to add time) argument by passing by value, passing
by address and passing by reference defining a class Time with data member hour, minute,
second as integers. Write member functions to read the data for objects and to show the value
of objects of Time.

#include <iostream>
using namespace std;
class Time {
public:
int hour;
int minute;
int second;

// Member function to read data for Time object


void readTime() {
cout << "Enter hour: ";
cin >> hour;
cout << "Enter minute: ";
cin >> minute;
cout << "Enter second: ";
cin >> second;
}

// Member function to display the value of Time object


void showTime() {
cout << "Time: " << hour << " hours, " << minute << " minutes, " << second << "
seconds" << endl;
}
};

// Function to add two Time objects by passing by value


Time addTimeByValue(Time t1, Time t2) {
Time sum;
sum.hour = t1.hour + t2.hour;
sum.minute = t1.minute + t2.minute;
sum.second = t1.second + t2.second;
if (sum.second >= 60) {
sum.minute += sum.second / 60;
sum.second %= 60;
}
if (sum.minute >= 60) {
sum.hour += sum.minute / 60;
sum.minute %= 60;
}

return sum;
}

// Function to add two Time objects by passing by address


void addTimeByAddress(Time* t1, Time* t2, Time* sum) {
sum->hour = t1->hour + t2->hour;
sum->minute = t1->minute + t2->minute;
sum->second = t1->second + t2->second;

if (sum->second >= 60) {


sum->minute += sum->second / 60;
sum->second %= 60;
}
if (sum->minute >= 60) {
sum->hour += sum->minute / 60;
sum->minute %= 60;
}
}

// Function to add two Time objects by passing by reference


void addTimeByReference(Time& t1, Time& t2, Time& sum) {
sum.hour = t1.hour + t2.hour;
sum.minute = t1.minute + t2.minute;
sum.second = t1.second + t2.second;

if (sum.second >= 60) {


sum.minute += sum.second / 60;
sum.second %= 60;
}
if (sum.minute >= 60) {
sum.hour += sum.minute / 60;
sum.minute %= 60;
}
}

int main() {
Time time1, time2, sum;

// Read data for time1 and time2


cout << "Enter time 1:" << endl;
time1.readTime();
cout << "Enter time 2:" << endl;
time2.readTime();

// Add time1 and time2 using pass by value


sum = addTimeByValue(time1, time2);
cout << "Sum using pass by value:" << endl;
sum.showTime();

// Add time1 and time2 using pass by address


addTimeByAddress(&time1, &time2, &sum);
cout << "Sum using pass by address:" << endl;
sum.showTime();

// Add time1 and time2 using pass by reference


addTimeByReference(time1, time2, sum);
cout << "Sum using pass by reference:" << endl;
sum.showTime();

return 0;
}

7. Define a friend function addtime() with objects as arguments and return the sum of two
objects. Show the values of each object and their sum as output.

#include <iostream>
using namespace std;

class Time {
private:
int hour ,minute,second;
public:
Time(int h = 0, int m = 0, int s = 0) : hour(h), minute(m), second(s) {}

// Member function to display the value of Time object


void showTime() {
cout << "Time: " << hour << " hours, " << minute << " minutes, " << second << "
seconds" << endl;
}
// Declare the friend function
friend Time addTime(const Time& t1, const Time& t2);
};
// Friend function to add two Time objects and return the sum
Time addTime(const Time& t1, const Time& t2) {
int h = t1.hour + t2.hour;
int m = t1.minute + t2.minute;
int s = t1.second + t2.second;

if (s >= 60) {
m += s / 60;
s %= 60;
}
if (m >= 60) {
h += m / 60;
m %= 60;
}

return Time(h, m, s);


}

int main() {
Time time1(2, 30, 45);
Time time2(1, 15, 20);

// Display the values of time1 and time2


cout << "Time 1:" << endl;
time1.showTime();
cout << "Time 2:" << endl;
time2.showTime();

// Add time1 and time2 using the friend function


Time sum = addTime(time1, time2);

// Display the sum


cout << "Sum of time1 and time2:" << endl;
sum.showTime();

return 0;
}

8. Write different programs to implement passing by reference and passing by value in C++.

A.passing by reference

#include <iostream>
using namespace std;

// Function to swap two integers using pass-by-reference


void swapByReference(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}

int main() {
int x = 10;
int y = 20;

cout << "Before swap: x = " << x << ", y = " << y << endl;

// Call the swapByReference function


swapByReference(x, y);

cout << "After swap: x = " << x << ", y = " << y << endl;

return 0;
}
B. pass by value

#include <iostream>

using namespace std;

// Function to calculate the square of a number using pass-by-value


int squareByValue(int num) {
return num * num;
}

int main() {
int number = 5;

cout << "Number: " << number << endl;

// Call the squareByValue function


int square = squareByValue(number);

cout << "Square: " << square << endl;

return 0;
}

9. Write different programs to implement different storage classes (auto, register, extern and
static) in C++ with its output.

A.Auto Storage Class:


#include <iostream>

int main() {
auto int x = 5; // auto storage class (optional, can be omitted)

std::cout << "The value of x: " << x << std::endl;

return 0; }
B.Register storage class

#include <iostream>

int main() {
register int y = 10; // register storage class

std::cout << "The value of y: " << y << std::endl;

return 0;
}

C. Extern storage class

#include <iostream>

extern int z; // extern storage class (variable declaration)

int main() {
std::cout << "The value of z: " << z << std::endl;

return 0;
}

int z = 15; // extern storage class (variable definition)

D.Static storage class

#include <iostream>

void increment() {
static int count = 0; // static storage class

count++;

std::cout << "Count: " << count << std::endl;


}

int main() {
increment();
increment();
increment();

return 0;
}

10. Write a C++ program to illustrate dynamic allocation and deallocation of memory using new
and delete.

#include <iostream>

int main() {
int* ptr = new int; // Dynamically allocate memory for an integer
*ptr = 42; // Assign a value to the dynamically allocated memory
std::cout << "Value stored in dynamically allocated memory: " << *ptr << std::endl;
delete ptr; // Deallocate the dynamically allocated memory
return 0;
}

11. Write a program using dynamic memory allocation to input an array of numbers and find the
sum of N numbers stored in the array using a function to compute the sum.

#include <iostream>

int computeSum(int* arr, int size) {

int sum = 0;

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

sum += arr[i];

}
return sum;

int main() {

int N;

std::cout << "Enter the number of elements in the array: ";

std::cin >> N;

// Dynamically allocate memory for the array

int* arr = new int[N];

std::cout << "Enter " << N << " numbers:" << std::endl;

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

std::cin >> arr[i];

// Calculate the sum using the computeSum function

int sum = computeSum(arr, N);

std::cout << "Sum of the " << N << " numbers: " << sum << std::endl;

// Deallocate the dynamically allocated memory

delete[] arr;

return 0;

}
12. Write a program to implement user defined constructor and copy constructor.

#include <iostream>

class MyClass {
private:
int value;

public:
// User-defined constructor
MyClass(int val) {
value = val;
std::cout << "User-defined constructor called with value: " << value << std::endl;
}

// Copy constructor
MyClass(const MyClass& other) {
value = other.value;
std::cout << "Copy constructor called with value: " << value << std::endl;
}

int getValue() {
return value;
}
};

int main() {
// Create an object using the user-defined constructor
MyClass obj1(42);
std::cout << "Value of obj1: " << obj1.getValue() << std::endl;

// Create a new object using the copy constructor


MyClass obj2(obj1);
std::cout << "Value of obj2: " << obj2.getValue() << std::endl;

return 0;
} 13. Write a program to illustrate constructor overloading in
C++.

13. Write a program to illustrate constructor overloading in C++.

#include <iostream>

class MyClass {
private:
int value1;
int value2;

public:
// Default constructor
MyClass() {
value1 = 0;
value2 = 0;
}

// Constructor with one parameter


MyClass(int val) {
value1 = val;
value2 = 0;
}

// Constructor with two parameters


MyClass(int val1, int val2) {
value1 = val1;
value2 = val2;
}

void displayValues() {
std::cout << "Value1: " << value1 << ", Value2: " << value2 << std::endl;
}
};

int main() {
// Create objects using different constructors
MyClass obj1; // Default constructor
MyClass obj2(10); // Constructor with one parameter
MyClass obj3(20, 30); // Constructor with two parameters

// Display the values of objects


std::cout << "Object 1: ";
obj1.displayValues();

std::cout << "Object 2: ";


obj2.displayValues();

std::cout << "Object 3: ";


obj3.displayValues();

return 0;
}

To Be Continued…

You might also like