Cptr Science 12
Cptr Science 12
Page 1 of 42
Ser SLO Questions Answer
Q.4 Write a program that calculates #include <iostream>
the volume of a cylinder given its using namespace std;
radius and height. int main() {
float radius, height;
const float PI = 3.14159;
cout << "\n Enter the radius of the cylinder: ";
cin >> radius;
cout << "\n Enter the height of the cylinder: ";
cin >> height;
float volume = PI * radius * radius * height;
cout << " \n The volume of the cylinder is: " << volume << endl;
return 0;}
Q.5 Write a program to calculate the #include <iostream>
perimeter of a triangle given the using namespace std;
lengths of its three sides. int main() {
float side1, side2, side3;
cout << "Enter the lengths of the three sides of the triangle: ";
cin >> side1 >> side2 >> side3;
float perimeter = side1 + side2 + side3;
cout << "The perimeter of the triangle is: " << perimeter << endl;
return 0;}
Q.6 What will be the output of OUTPUT:
following program segment? 25
int main() {
int x = 5;
x *= 2 + 3; cout << x << endl;
return 0; }
2. i) Explain the use of the following Q.1 Write a program that takes #include <iostream>
decision statements: gender (F or M) and age (1 to 100) as using namespace std;
• If input. The program should output int main() {
• If-else the message “Retirement Age” if the char gender;
• Else-if input indicates a female over 50 int age;
• Switch-default years old or a male over 65 years old. cout << "Enter gender (F/M): ";
ii) Know the concept of nested if Otherwise, it should display the cin >> gender;
iii) Use break statement and exit message “Not Retirement Age.” cout << "Enter age (1-100): ";
function cin >> age;
Page 2 of 42
Ser SLO Questions Answer
if ((gender == 'F' || gender == 'f') && age > 50) {
cout << "Retirement Age" << endl;
}
else if((gender == 'M' || gender == 'm') && age>65) {
cout << "Retirement Age" << endl;
} else {
cout << "Not Retirement Age" << endl;
}
return 0; }
Q.2 Write a C++ program that #include <iostream>
determines whether a given year is a using namespace std;
leap year. A leap year is divisible by 4, int main() {
but not by 100, unless it's also int year;
divisible by 400. cout << "Enter a year: ";
cin >> year;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
cout << year << " is a leap year." << endl;
else
cout << year << " is not a leap year." << endl;
return 0;
}
Q.3 Create a C++ program that asks #include <iostream>
the user for a temperature in Celsius using namespace std;
or Fahrenheit and converts it to the int main() {
other scale based on user choice. int choice;
double t,f, celsius;
cout << "Choose the conversion:\n
1. Celsius to Fahrenheit\n
2. Fahrenheit to Celsius\n";
cin >> choice;
if (choice == 1) {
cout << "Enter temperature in Celsius: ";
cin >>t;
f = (t * 9.0 / 5.0) + 32;
cout << "Temperature in Fahrenheit: " << f << endl;
} else if (choice == 2) {
Page 3 of 42
Ser SLO Questions Answer
cout << "Enter temperature in Fahrenheit: ";
cin >> t;
celsius = (t - 32) * 5.0 / 9.0;
cout << "Temperature in Celsius: " << celsius << endl;
} else {
cout << "Invalid choice!" << endl;
}
return 0;
}
Q.4 Write a C++ program that #include <iostream>
converts a given amount in US Dollarsusing namespace std;
to Rupees, EUR, GBP, or INR based on
user choice. int main() {
Use exchange rates: double amount;
1 USD = 0.85 EUR, int choice;
1 USD = 278 Rs
1 USD = 3.76 Saudi Riyal cout << "Enter amount in USD: ";
cin >> amount;
Page 4 of 42
Ser SLO Questions Answer
}
int main() {
int num, digit, reversed = 0;
cout << "Enter an integer: ";
cin >> num;
while (num != 0) {
digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
cout << "The reversed number is: " << reversed << endl;
return 0;
}
Q.5 Write a program to calculate the #include <iostream>
sum of the following series using using namespace std;
while loop: int main() {
1/1+1/2+1/3+1/4+…+1/10 double sum = 0.0;
Page 6 of 42
Ser SLO Questions Answer
int i = 1;
while (i <= 10) {
sum += 1.0 / i;
i++; }
cout << "The sum of the series is: " << sum << endl;
return 0; }
Q.6 Write a program to keep asking #include <iostream>
the user to enter a positive number using namespace std;
until the user enters a valid int main() {
number. int num;
do
{
cout << "Enter a positive number: ";
cin >> num;
if (num < 0)
cout << "Invalid input! Try again." << endl;
}
while (num < 0);
cout << "You entered: " << num << endl;
return 0; }
Q.7 Guessing Game – Write a #include <iostream>
program that will generate a random #include <cstdlib> // For rand() and srand()
number, and the user has to keep #include <ctime> // For time()
guessing until they get it right. using namespace std;
int main()
{
srand(time(0)); // Seed random number enerator
int randomNumber = rand() % 100 + 1; // Random number between 1 and 100
int guess;
do
{
cout << "Guess the number (between 1 and 100): ";
cin >> guess;
if (guess < randomNumber) {
cout << "Too low! Try again." << endl;
} else if (guess > randomNumber) {
Page 7 of 42
Ser SLO Questions Answer
cout << "Too high! Try again." << endl;
}
} while (guess != randomNumber);
cout << "Congratulations! You guessed the number!" << endl;
return 0; }
Q.8 Calculate the greatest common #include <iostream>
divisor (GCD) of two numbers using a using namespace std;
do-while loop. int main() {
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
do {
if (num1 > num2)
num1 = num1 - num2;
else
num2 = num2 - num1;
} while (num1 != num2);
return 0;
}
Q.9 A simple text-based calculator #include <iostream>
that repeatedly asks the user to using namespace std;
perform operations until they choose int main() {
to quit. char choice;
double num1, num2, result;
do {
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
cout << "Choose operation (+, -, *, /): ";
char op;
cin >> op;
Page 8 of 42
Ser SLO Questions Answer
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 << "Division by zero is not allowed!" << endl;
continue; // Skip to next iteration if division by zero
}
break;
default:
cout << "Invalid operation!" << endl;
continue; }
cout << "Result: " << result << endl;
cout << "Do you want to perform another operation (y/n)? ";
cin >> choice;
Page 9 of 42
Ser SLO Questions Answer
switch (choice) {
case 1:
cout << "Current balance: Rs << balance << endl;
break;
case 2:
cout << "Enter amount to deposit: Rs";
cin >> amount;
balance += amount;
cout << "Deposit successful! New balance: Rs." << balance << endl;
break;
case 3:
cout << "Enter amount to withdraw: Rs";
cin >> amount;
if (amount <= balance) {
balance -= amount;
cout << "Withdrawal successful! New balance: Rs" << balance << endl;
} else {
cout << "Insufficient balance!" << endl;
}
break;
case 4:
cout << "Thank you for using the ATM. Goodbye!" << endl;
break;
default:
cout << "Invalid choice! Please try again." << endl;
}
} while (choice != 4);
return 0;
}
4. 1. Explain how to access and Q.1 A one-dimensional array is a #include <iostream>
write at an index in an array simple list of elements. using namespace std;
2. Explain how to traverse an Write a program that initializes
array using all loop structures a one-dimensional array, int main() {
calculates the sum of its int arr[5] = {10, 20, 30, 40, 50};
elements, and displays them. int sum = 0;
for(int i = 0; i < 5; i++) {
Page 10 of 42
Ser SLO Questions Answer
sum = sum + arr[i]; }
cout << "Array elements: ";
for(int i = 0; i < 5; i++)
{
cout << arr[i] << " ";
}
cout << endl;
cout << "Sum of array elements: " << sum << endl;
return 0; }
Q.2 Write a program that finds the #include <iostream>
maximum element in a one- using namespace std;
dimensional array. int main() {
int arr[6] = {12, 45, 23, 78, 67, 89};
int max = arr[0];
for(int i = 1; i < 6; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
}
cout << "Maximum element in the array: " << max << endl;
return 0;
}
Q.3 Write a C++ program that reads #include <iostream>
the temperatures for a whole week #include <string>
into an array and then determines using namespace std;
the hottest day of the week.
int main() {
const int DAYS = 7; double temperatures[DAYS]; // Array to hold the temperatures
string daysOfWeek[DAYS] = {"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"};
cout << "Enter the temperatures for the week:" << endl;
for (int i = 0; i < DAYS; i++) {
cout << daysOfWeek[i] << ": ";
Page 11 of 42
Ser SLO Questions Answer
cin >> temperatures[i];
}
cout << "The hottest day of the week is " << daysOfWeek[hottestDayIndex]
<< " with a temperature of " << maxTemp << " degrees." << endl;
return 0; }
Q.4 Write a C++ program that reads #include <iostream>
5 elements and reverses the using namespace std;
elements of an array using a for int main()
loop. {
int arr[5] = {10, 20, 30, 40, 50};
int n = 5; // Size of the array
cout << "Original array: ";
for(int i = 0; i < n; i++)
{ cout << arr[i] << " "; }
cout << endl;
// Reversing the array using a for loop
for(int i = 0; i < n / 2; i++) {
int temp = arr[i];
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = temp;
}
cout << "Reversed array: ";
Page 12 of 42
Ser SLO Questions Answer
for(int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0; }
Q.5 Write a program that reads 10 #include <iostream>
elements in a list and then sorts the using namespace std;
list in ascending order. int main() {
int arr[10], n=10 ;
for(int i = 0; i < n; i++)
cin>> arr[i] ;
int sum = 0;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
sum += test[i][j];
}
}
cout << "The sum of the values in the 2D array is: " << sum << endl;
return 0; }
Q.2 Write a program that will take #include <iostream>
input for the elements of two 3 x 3 using namespace std;
matrices, perform the multiplication, int main() {
and display the result. int matrix1[3][3], matrix2[3][3], result[3][3];
cout << "Enter elements of first 3x3 matrix:" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cin >> matrix1[i][j];
}
}
cout << "Enter elements of second 3x3 matrix:" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cin >> matrix2[i][j];
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result[i][j] = 0;
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
Page 14 of 42
Ser SLO Questions Answer
for (int k = 0; k < 3; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
cout << "Result of 3x3 matrix multiplication:" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << result[i][j] << " ";
}
cout << endl;
}
return 0; }
Q.3 A two-dimensional array is like a #include <iostream>
matrix with rows and columns. using namespace std;
Write a program that initializes a 2D int main() {
array of 3x3 matrix, calculates the int arr[3][3] = {
sum of elements in each row, and {1, 2, 3},
displays the matrix. {4, 5, 6},
{7, 8, 9}
};
cout << "2D array elements (matrix):" << endl;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
cout << "Sum of each row:" << endl;
for(int i = 0; i < 3; i++) {
int rowSum = 0;
for(int j = 0; j < 3; j++) {
rowSum += arr[i][j];
}
cout << "Row " << i + 1 << ": " << rowSum << endl;
}
Page 15 of 42
Ser SLO Questions Answer
return 0;}
Page 16 of 42
Ser SLO Questions Answer
{
for (int j = 0; j < cols; j++)
{
sumArray[i][j] = array1[i][j] + array2[i][j];
}
}
cout << "Sum of the two 2D arrays:" << endl;
int main() {
string arr[5] = {"apple", "banana", "grape", "mango", "cherry"};
int n = 5;
string searchItem = "mango";
bool found = false;
if(!found) {
cout << "String item \"" << searchItem << "\" not found." << endl;
}
return 0; }
Q.3 Write a program to sort a list of #include <iostream>
string items using strcmp() and #include <cstring>
strcpy() functions. using namespace std;
int main() {
char arr[5][20] = {"banana", "apple", "grape", "mango", "cherry"};
int n = 5;
char temp[20];
for(int i = 0; i < n-1; i++)
{
for(int j = 0; j < n-i-1; j++)
{
if(strcmp(arr[j], arr[j+1]) > 0)
{
strcpy(temp, arr[j]);
strcpy(arr[j], arr[j+1]); strcpy(arr[j+1], temp);
}
}
}
cout << "Sorted string list: ";
for(int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0; }
Page 18 of 42
Ser SLO Questions Answer
Q.4 Write a C++ program that allows #include <iostream>
you to input 10 student names into a #include <cstring>
list (array) and then search for a using namespace std;
particular student’s name using int main() {
Linear Search. The program takes char students[10][50];
names as input from the user. The char searchName[50]; bool found = false;
program should output name along cout << "Enter the names of the students:" << endl;
with index. for(int i = 0; i < 10; i++)
{
cout << "Student " << i + 1 << ": ";
cin.get(students[i], 50);
}
cout << "Enter the name of the student to search: ";
cin.get(searchName, 50);
if(!found) {
cout << "Student " << searchName << " not found in the list." << endl;
}
return 0; }
Q.5 Write a program that #include <iostream>
demonstrates the concatenation of #include <cstring>
two strings using string function. using namespace std;
int main() {
char str1[100], str2[100], char Str3[200];
Page 19 of 42
Ser SLO Questions Answer
cout << "Enter the first string: ";
cin.getline(str1, 100);
cout << "Enter the second string: ";
cin.getline(str2, 100);
strcpy(Str3, str1);
strcat(Str3, str2);
cout << "Concatenated string: " <<Str3 ;
return 0; }
7. i)Pass the arguments: Q.1 Write a program that inputs #include <iostream>
• Constants two numbers and finds out the using namespace std;
• By value larger of two numbers using int findmax (int a, int b)
• By reference function. {
ii) Use default argument return (a > b) ? a : b;
iii) Use return statement }
int main()
{
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
cout << "The maximum number is: " << findmax(num1, num2) ;
return 0;
}
Q.2 Write program to convert the #include <iostream>
Celsius temperature into Fahrenheit using namespace std;
temperature using function.
double convertt(double celsius) {
return (celsius * 9.0 / 5.0) + 32;
}
int main() {
double celsius;
cout << "Enter temperature in Celsius: ";
cin >> celsius;
cout << celsius << " Degrees Celsius: "<< convert(celsius) <<" Degrees Fahrenheit.";
return 0;
}
Page 20 of 42
Ser SLO Questions Answer
Q.3 Write a program to calculate the #include <iostream>
sum of an array of size n using using namespace std;
function. A program asks the user to
enter the number of elements and // Function to calculate the sum of an array
then passes it to the function as int sumArray(int arr[], int size)
argument. {
int sum = 0;
for (int i = 0; i < size; i++)
{
sum += arr[i];
}
return sum;
}
int main() {
const int SIZE = 5;
int numbers[SIZE];
return 0;
}
Q.4 Write a program to find the Least #include <iostream>
Common Multiple (LCM) using a using namespace std;
function. int gcd(int a, int b)
{
while (b != 0)
{
int temp = b;
Page 21 of 42
Ser SLO Questions Answer
b = a % b;
a = temp;
}
return a;
}
int lcm(int a, int b)
{
return (a * b) / gcd(a, b);
}
int main( )
{
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
cout << "The LCM of " << num1 << " and " << num2 << " is: " << lcm(num1, num2) <<
endl;
return 0; }
Q.5 Write a program to find a cube of int cube(int num)
a number using function {
return num * num * num;
}
int main()
{
int number, c;
cout << "Enter a number: ";
cin >> number;
c= cube(number);
cout << "The cube of "<< number <<" is: " << c << endl;
return 0;
}
8. Use of local and global variables Q.1 Write a program that defines a #include <iostream>
global constant representing a tax using namespace std;
rate. The program should use a
function that calculates and prints const float TAX_RATE = 0.05; // Global constant
Page 22 of 42
Ser SLO Questions Answer
the total price of an item by adding
the tax to the local variable void calculatePrice(float price)
representing the price. {
float totalPrice = price + (price *TAX_RATE);
cout << "Price before tax: \n" << price;
cout << "Price after tax: \n"
<< totalPrice;
}
int main()
{
float price;
cout << "Enter the price of the item: ";
cin >> price;
calculatePrice(price);
return 0;}
Q.2 Write a C++ program to #include <iostream>
demonstrate the use of global and using namespace std;
local variables with the same name. int score = 50; // global variable
Explain how C++ differentiates int main() {
between the two. int score = 100; // local variable with the same name
cout << "Local score: " << score << endl;
cout << "Global score: " << ::score << endl;
return 0;
}
Q.3 Write a C++ program that #include <iostream>
calculates the sum and average of using namespace std;
three numbers inside a function.
The average is stored in a global float average;
variable, and the sum is returned
from the function. Both the sum int Sum(int num1, int num2, int num3) {
and the average are printed in the int sum = num1 + num2 + num3;
main () function.. average = sum / 3.0
return sum;
Page 23 of 42
Ser SLO Questions Answer
}
int main( )
{
int a, b, c;
int main() {
int result = add(5, 10);
cout << "Sum: " << result << endl;
return 0;
}
Q.5 What is the output? Value: 15
void printValue(int a, int b = 10) { Value: 20
cout << "Value: " << a + b << endl;
}
int main() {
printValue(5);
printValue(5, 15); arguments
return 0; }
int main()
{
int x = 5, y = 10;
Page 25 of 42
Ser SLO Questions Answer
float p = 3.5, q = 4.5;
int a = 1, b = 2, c = 3;
cout << "Sum of three integers: "
<< sum(a, b, c) << endl;
int main() {
int x = 5, y = 10, z = 3;
cout << "Maximum of " << x << " and " << y << " is: " << max(x, y) << endl;
cout << "Maximum of " << x << ", " << y << ", and " << z << " is: " << max(x, y, z) << endl;
return 0;}
Page 26 of 42
Ser SLO Questions Answer
Q.3 Write a program that overloads a #include <iostream>
function area() to calculate the area using namespace std;
of a circle, rectangle, and triangle.
double area(double radius)
{
return 3.14159 * radius * radius;
}
{
return length * width;
}
int main() {
double radius = 5.0, length = 10.0, width = 4.0, base = 6.0, height = 3.0;
Page 27 of 42
Ser SLO Questions Answer
return num1 * num2 * num2;
}
int main() {
int x = 3, y = 2;
cout << "Square of " << x << ": " << calculate(x) << endl;
cout << "Cube with " << y << " base: " << calculate(x, y) << endl;
return 0; }
Page 28 of 42
Ser SLO Questions Answer
int main() {
Q5. Modify the following code so
int num = 7;
that it increments the value of num
cout << "Before increment: " << num << endl;
by 5 using a pointer:
int main() { int* ptr = #
int num = 7;
*ptr += 5
cout << "Before increment: " <<
num << endl; cout << "After increment: " << num << endl;
int* ptr = #
Page 29 of 42
Ser SLO Questions Answer
return 0; }
(*ptr)++;
cout << "After increment: " <<
num << endl;
return 0; }
Q1. Design a class called Circle with #include <iostream>
11. • Declare object to access
a private data member for the using namespace std;
• Data members radius. Include public member
• Member functions functions to set the radius, calculate class Circle {
• Understand and access the area, and display it. private:
specifier:
• Private double radius;
• Public public:
• Know the concept of data hiding
void setRadius(double r)
{
radius = r; }
double calculateArea()
{
return 3.14 * radius * radius; }
void displayArea() {
cout << "Area of Circle: " << calculateArea() << endl;
}
};
int main() {
Circle c;
c.setRadius(5.0);
c.displayArea();
return 0;
}
Page 30 of 42
Ser SLO Questions Answer
Page 31 of 42
Ser SLO Questions Answer
Demonstrate this with two objects int length;
of the class. int width;
public:
void setDimensions(int l, int w) {
length = l;
width = w;
}
int calculateArea() {
return length * width; // Calculating area
}
};
int main() {
Rectangle rect1, rect2; // Creating two objects
rect1.setDimensions(5, 3);
rect2.setDimensions(7, 4);
cout << "Area of Rectangle 1: " << rect1.calculateArea() << endl;
cout << "Area of Rectangle 2: " << rect2.calculateArea() << endl;
return 0;
}
Q4. Program to manage student #include <iostream>
grades with data members for using namespace std;
name, subject, and grade. class Student {
private:
string name; // Student name
string subject; // Subject name
char grade; // Grade
public:
// Function to set student details
void setDetails(string n, string s, char g)
{
name = n;
subject = s;
grade = g;
}
// Function to display student details
Page 32 of 42
Ser SLO Questions Answer
void displayDetails() {
cout << "Student Name: " << name << endl;
cout << "Subject: " << subject << endl;
cout << "Grade: " << grade << endl;
}
};
int main() {
Student student1;
student1.setDetails("Alia", "Mathematics", 'A');
student1.displayDetails();
return 0; }
#include <iostream>
Q5. Program to manage product
using namespace std;
details with data members for
class Product {
product name, price, and stock
private:
status. use classes and objects to
string productName;
model real-world situations,
double price;
bool inStock; // Stock status
public:
// Function to set product details
void displayDetails() {
cout << "Product Name: " << productName << endl;
cout << "Price: $" << price << endl;
cout << "Availability: " << (inStock ? "In Stock" : "Out of Stock") << endl;
}
};
Page 33 of 42
Ser SLO Questions Answer
int main() {
Product product1;
product1.setDetails("Wireless Headphones", 99.99, true);
product1.displayDetails();
return 0; }
12. Define constructor and destructor #include <iostream>
Q1.. Write a C++ program that
• Default constructor/destructor using namespace std;
defines a class Box that has a
• User defined constructor
constructor to initialize its
• Constructor overloading class Box
dimensions and calculate its
{
volume.
private:
double length;
double width;
double height;
public:
double volume() {
return length * width * height;
}
};
int main() {
Box myBox(3.5, 2.0, 1.5);
cout << "Volume of the box: " << myBox.volume();
return 0; }
Page 34 of 42
Ser SLO Questions Answer
public:
// Parameterized constructor
Circle(double r)
{
radius = r; // Initializing radius
}
// Function to calculate and display area
void displayArea() {
double area = 3.14 * radius * radius;
cout << "Area of Circle: " << area << endl;
}
};
int main() {
Circle circle(5.0); // Creating an object with a radius of 5.0
circle.displayArea(); // Display the area
return 0;
}
Q3. Write a program to create a #include <iostream>
class Student that can be initialized using namespace std;
using two different constructors:
one for initializing name and age, class Student {
and another for initializing only private:
name (default age as 18). string name;
int age;
public:
// Constructor for name and age
Page 35 of 42
Ser SLO Questions Answer
Student(string n, int a) {
name = n;
age = a;
}
void displayDetails()
{
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main()
{
Student student1("Alia", 20); // Using 1st constructor
Student student2("Bushra"); // Using 2nd constructor
student1.displayDetails(); student2.displayDetails();
return 0; }
Q4. Write a program to calculate #include <iostream>
the area of two rectangles using using namespace std;
both a default constructor and a
parameterized constructor. class Rectangle {
private:
double length;
double width;
public:
Page 36 of 42
Ser SLO Questions Answer
// Default constructor
Rectangle() {
length = 1.0; // Default length
width = 1.0; // Default width
}
// Parameterized constructor
Rectangle(double l, double w) {
length = l;
width = w;
}
double area()
{
return length * width;
}
};
int main() {
// Create an object using the default constructor
Rectangle rect1;
cout << "Area of rectangle 1 (default): " << rect1.area() << endl;
return 0;
}
Q5. Write a program to create a #include <iostream>
class Triangle with data members using namespace std;
base and height. Use a constructor
with default arguments to initialize class Triangle {
the values. Also, create a function private:
to calculate and display the area float base;
float height;
Page 37 of 42
Ser SLO Questions Answer
public:
// Constructor with default arguments
Triangle(float b = 5.0, float h = 10.0) {
base = b;
height = h;
}
int main() {
Triangle tri1; // Uses default values
Triangle tri2(6.0, 8.0); // Uses custom values
Page 38 of 42
Ser SLO Questions Answer
} else
{
cout << "Error opening the file!" << endl;
}
return 0; }
Q2. Write a C++ program that #include <iostream>
copies the contents of a file ABC.txt #include <fstream>
to another file XYZ.txt. using namespace std;
int main() {
string line;
ifstream inputFile("ABC.txt");
ofstream outputFile("XYz.txt");
inputFile.close();
outputFile.close();
return 0; }
Page 39 of 42
Ser SLO Questions Answer
14. Write a program to create and #include <iostream>
Q1. Write a program to write any
read a data file #include <fstream>
five single character to a file.
Use the following streams using namespace std;
• Single character
• String int main() {
ofstream file("single_char.txt", ios::out);
if (file.is_open()) {
char ch;
cout << "Enter 5 characters to write to the file: " << endl;
for (int i = 0; i < 5; ++i) {
cin >> ch;
file.put(ch); // Write a single character to the file
}
file.close();
cout << "Characters written to file successfully." << endl;
} else {
cout << "Error opening the file!" << endl;
}
return 0;
}
Q2. Write a program to read a file #include <iostream>
character by character and display #include <fstream>
the read characters on screen. using namespace std;
int main() {
ifstream file("example.txt");
if (!file.is_open()) {
cout << "Error opening the file!" << endl;
return 1;
}
char ch;
cout << "Reading the file character by character:" << endl;
Page 40 of 42
Ser SLO Questions Answer
while (!file.eof())
{
file.get(ch);
cout << ch << " ";
}
file.close();
cout << endl << "End of file reached!" << endl;
return 0;}
int main() {
ofstream file("string.txt", ios::out);
if (file.is_open()) {
string input;
cout << "Enter a string to write to the file: ";
getline(cin, input);
file << input << endl;
file.close();
cout << "String written to file successfully." << endl;
} else {
cout << "Error opening the file!" << endl;
}
return 0; }
int main() {
ifstream file("string.txt", ios::in);
Page 41 of 42
Ser SLO Questions Answer
if (file.is_open()) {
string line;
cout << "Reading string from file: ";
while (getline(file, line))
{ cout << line << endl;
}
file.close();
cout << "File read successfully." << endl;
} else {
cout << "Error opening the file!" << endl;
}
return 0;
}
Page 42 of 42