XII PBA Questions
XII PBA Questions
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 #include <iostream>
calculate the sum of the using namespace std;
following series using int main() {
while loop: double sum = 0.0;
1/1+1/2+1/3+1/4+…+1/10 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 #include <iostream>
keep asking the user to using namespace std;
enter a positive number int main() {
until the user enters a int num;
valid number. 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 – #include <iostream>
Write a program that will #include <cstdlib> // For rand() and srand()
generate a random #include <ctime> // For time()
number, and the user has using namespace std;
to keep guessing until they int main()
get it right. {
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) {
cout << "Too high! Try again." << endl;
}
} while (guess != randomNumber);
cout << "Congratulations! You guessed the number!"
<< endl;
return 0; }
Q.8 Calculate the greatest #include <iostream>
common divisor (GCD) of using namespace std;
two numbers using a do- int main() {
while loop. int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
do {
if (num1 > num2)
num1 = num1 - num2;
else
num2 = num2 - num1;
} while (num1 != num2);
cout << "GCD = " << num1 << endl;
return 0;
}
Q.9 A simple text-based #include <iostream>
calculator that repeatedly using namespace std;
asks the user to perform int main() {
operations until they char choice;
choose to quit. double num1, num2, result;
do {
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
cout << "Choose operation (+, -, *, /): ";
char op;
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 << "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;
return 0; }
Q.4 Write a C++ program that reads 5 #include <iostream>
elements and reverses the elements of using namespace std;
an array using a for loop. int main()
{
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: ";
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 list in using namespace std;
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 input for #include <iostream>
the elements of two 3 x 3 matrices, perform using namespace std;
the multiplication, and display the result. int main() {
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++) {
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 matrix #include <iostream>
with rows and columns. using namespace std;
Write a program that initializes a 2D array int main() {
of 3x3 matrix, calculates the sum of int arr[3][3] = {
elements in each row, and displays the {1, 2, 3},
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;
}
return 0;}
Q.4 Write a program to compute the #include <iostream>
transpose of a 2D matrix. using namespace std;
int main() {
int matrix[3][3] = { {1, 2, 3}, {4, 5, 6},{7, 8, 9}};
cout << "Original matrix:" << endl;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
cout << "Transpose of the matrix:" << endl;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
cout << matrix[j][i] << " "; }
cout << endl;
}
return 0; }
Q.5 Write a program to add two 3 x 3 #include <iostream>
matrices and display the result. Use a third using namespace std;
two-dimensional array to store the result of int main() {
the addition. const int rows = 3;
const int cols = 3;
int sumArray[rows][cols];
int array1[rows][cols] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int array2[rows][cols] = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
sumArray[i][j] = array1[i][j] + array2[i][j];
}
}
cout << "Sum of the two 2D arrays:" << endl;
if(!found) {
cout << "String item \"" << searchItem << "\" not
found." << endl;
}
return 0; }
Q.3 Write a program to sort a list of string #include <iostream>
items using strcmp() and strcpy() #include <cstring>
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; }
Q.4 Write a C++ program that allows you to #include <iostream>
input 10 student names into a list (array) #include <cstring>
and then search for a particular student’s using namespace std;
name using Linear Search. The program int main() {
takes names as input from the user. The char students[10][50];
program should output name along with char searchName[50]; bool found = false;
index. cout << "Enter the names of the students:" << endl;
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);
int main() {
char str1[100], str2[100], char Str3[200];
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: B Q.1 Write a program that inputs two #include <iostream>
• Constants numbers and finds out the larger of two using namespace std;
• By value numbers using function. int findmax (int a, int b)
• By reference {
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 Celsius #include <iostream>
temperature into Fahrenheit temperature using namespace std;
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;
}
Q.3 Write a program to calculate the sum of #include <iostream>
an array of size n using function. A program using namespace std;
asks the user to enter the number of
elements and then passes it to the function // Function to calculate the sum of an array
as argument. int sumArray(int arr[], int size)
{
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 function. using namespace std;
int gcd(int a, int b)
{
while (b != 0)
{
int temp = b;
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 a int cube(int num)
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 global #include <iostream>
constant representing a tax rate. The using namespace std;
program should use a function that
calculates and prints the total price of an const float TAX_RATE = 0.05; // Global constant
item by adding the tax to the local variable
representing the price. void calculatePrice(float 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 that calculates #include <iostream>
the sum and average of three numbers using namespace std;
inside a function. The average is stored in
a global variable, and the sum is returned float average;
from the function. Both the sum and the
average are printed in the main () int Sum(int num1, int num2, int num3) {
function.. int sum = num1 + num2 + num3;
average = sum / 3.0
return sum;
}
int main( )
{
int a, b, c;
int main() {
int result = add(5, 10);
cout << "Sum: " << result << endl;
return 0;
}
Q.4 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;
float p = 3.5, q = 4.5;
cout << "Sum of two integers: "
<< sum(x, y) << endl;
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;}
Q.3 Write a program that overloads a #include <iostream>
function area() to calculate the area of a using namespace std;
circle, rectangle, and triangle.
double area(double radius)
{
return 3.14159 * radius * radius;
}
{
return length * width;
}
int main() {
return 0; }
Q.5
10. Know the use of reference B Q1.Write a program to display the #include <iostream>
operator ( & ) address and the value of a variable using using namespace std;
Know the use of dereference pointer
operator ( * ) int main() {
Declare variables of pointer
int num = 25;
types
Initialize the pointers int* ptr = #
cout << "Address of num: " << ptr << endl;
cout << "Value of num: " << *ptr << endl;
return 0;
}
Q2. Write a program to initialize pointer include <iostream>
variable and modify value of variable using namespace std;
using pointer. int main() {
int num = 15;
int* ptr = #
cout << "Original value of num: " << num << endl;
*ptr = 25; // Modifying the value of 'num' using
pointer
cout << "Value of num after modification: " << num
<< endl;
return 0;
}
Q3. Show the output of the following: OUTPUT:
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
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; }
Q5. Program to manage product details #include <iostream>
with data members for product name, using namespace std;
price, and stock status. use classes and class Product {
objects to model real-world situations, private:
string productName;
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;
}
};
int main() {
Product product1;
product1.setDetails("Wireless Headphones",
99.99, true);
product1.displayDetails();
return 0; }
12. Define constructor and Q1.. Write a C++ program that defines a #include <iostream>
destructor class Box that has a constructor to using namespace std;
• Default constructor/destructor initialize its dimensions and calculate its
• User defined constructor volume. class Box
• Constructor overloading {
private:
double length;
double width;
double height;
public:
double volume() {
return length * width * height;
}
};
int main() {
Box myBox(3.5, 2.0, 1.5);
return 0; }
Q2. Write a program to create a class #include <iostream>
Circle with a data member radius. Use a using namespace std;
parameterized constructor to initialize the
radius. Also, create a function to calculate class Circle {
and display the area of the circle. private:
double radius; // Data member for radius
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 class #include <iostream>
Student that can be initialized using two using namespace std;
different constructors: one for initializing
name and age, and another for initializing class Student {
only name (default age as 18). private:
string name;
int age;
public:
// Constructor for name and age
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 the area
of two rectangles using both a default #include <iostream>
constructor and a parameterized using namespace std;
constructor.
class Rectangle {
private:
double length;
double width;
public:
// 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 class #include <iostream>
Triangle with data members base and using namespace std;
height. Use a constructor with default
arguments to initialize the values. Also, class Triangle {
create a function to calculate and display private:
the area float base;
float height;
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
int main() {
string line;
ifstream inputFile("ABC.txt");
ofstream outputFile("XYz.txt");
inputFile.close();
outputFile.close();
return 0; }
14. Write a program to create and read B #include <iostream>
a data file
Q1. Write a program to write any five
single character to a file. #include <fstream>
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 the #include <fstream>
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;
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);
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;
}