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

XII PBA Questions

Uploaded by

Ahmed Sohail
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

XII PBA Questions

Uploaded by

Ahmed Sohail
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 42

Anx-A

Ser SLO Sec A / B Questions Answer


1. Write some programs using: A Q.1 Write a program that #include <iostream>
• Cin finds out a sum of digits using namespace std;
• Cout of a 4 digit number, say int main() {
• Escape sequences 1234. int n, r1,r2,r3,r4,sum;
• Setw cout<<”Enter any four digit number:”;
cin>>n;
r1=n%10; n=n/10;
r2=n%10; n=n/10;
r3=n%10; n=n/10;
r4=n%10; n=n/10;
sum =r1+r2+r3+r4;
cout<<”Sum of 4 digits number is:”<<sum;
return 0;}
Q.2 This program #include <iostream>
calculates the Body Mass using namespace std;
Index (BMI) given weight int main() {
and height. float weight, height;
cout << "Enter your weight in kilograms: ";
cin >> weight;
cout << "Enter your height in meters: ";
cin >> height;
float bmi = weight / (height * height);
cout << "Your BMI is: " << bmi << endl;
return 0;}
Q.3 Write a program that #include <iostream>
calculates the volume of a using namespace std;
cylinder given its radius int main() {
and height. 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.4 Write a program to #include <iostream>
calculate the perimeter of using namespace std;
a triangle given the lengths int main() {
of its three sides. 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.5 What will be the OUTPUT:
output of following 25
program segment?
int main() {
int x = 5;
x *= 2 + 3; cout << x
<< endl;
return 0; }
2. i) Explain the use of the A Q.1 Write a program that #include <iostream>
following decision statements: should input a gender (F orusing namespace std;
• If M) and an age (1 to 100) int main() {
• If-else and output a message char gender;
• Else-if “Retirement Age”, if the int age;
• Switch-default input is female and over 50 cout << "Enter gender (F/M): ";
ii) Know the concept of nested if years of age or male and cin >> gender;
iii) Use break statement and exit over 65 years of age, cout << "Enter age (1-100): ";
function otherwise it should display cin >> age;
the message “Not if ((gender == 'F' || gender == 'f') && age > 50) {
Retirement Age” 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 #include <iostream>
that determines whether a using namespace std;
given year is a leap year. int main() {
A leap year is divisible by int year;
4, but not by 100, unless cout << "Enter a year: ";
it's also divisible by 400. 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 #include <iostream>
that asks the user for a using namespace std;
temperature in Celsius or int main() {
Fahrenheit and converts it int choice;
to the other scale based double t,f, celsius;
on user choice. 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) {
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 #include <iostream>
that converts a given using namespace std;
amount in US Dollars to
Rupees, EUR, GBP, or int main() {
INR based on user choice. double amount;
Use exchange rates: int choice;
1 USD = 0.85 EUR,
1 USD = 278 Rs cout << "Enter amount in USD: ";
1 USD = 3.76 Saudi Riyal cin >> amount;

cout << "Convert to:\n1. EUR\n2. RUPEES


\n3. Saudi Riyal\n Choose an option: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Amount in EUR: " << amount *0.85 <<
endl;
break;
case 2:
cout << "Amount in Rs: " << amount * 277 << endl;
break;
case 3:
cout << "Amount in Riyal: "<<amount *3.76 <<
endl;
break;
default:
cout << "Invalid option!" << endl;
}
return 0;
}
Q.5 Write a program to #include <iostream>
read a number and find using namespace std;
out whether it is a prime or int main() {
composite. int number;
bool isPrime = true;
cout << "Enter a positive integer: ";
cin >> number;

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


if (number % i == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
cout << number << " is a prime number." <<
endl;
else
cout << number << " is a composite number." <<
endl;
return 0;}
3. Explain the use of the following A Q.1 Write a C++ program #include <iostream>
looping structures: to find the factorial of a using namespace std;
• For given number using a int main() {
• While loop. int num, factorial = 1;
• Do-while cout << "Enter a number: ";
cin >> num;
for (int i = 1; i <= num; i++) {
factorial = factorial * i;
}
cout << "Factorial of " << num << " is: " << factorial
<< endl;
return 0;
}
Q.2 Write a C++ program # include <iostream>
to print natural numbers using namespace std;
from 1 to 10 in reverse int main( )
order { int i;
for (i=10; i>=1; i--)
cout<<i<<" ";
return 0; }
Q.3 Write C++ Program to #include<iostream>
print table of any number. #include<conio.h>
using namespace std;
int main()
{ int i,n;
cout<<"Enter number for which you want to generate
table:";
cin>>n;
cout<<"\n\n";
for(i=1;i<=10;++i) cout<<"\t"<<n<<"*"<<i<<"="<<n*i<<"\n";
return 0;}
Q.4 Write a program that #include <iostream>
takes an integer input and using namespace std;
outputs its reverse.
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 #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;

} while (choice == 'y' || choice == 'Y');


cout << "Calculator closed." << endl;
return 0;}
Q.10 Simulate an ATM #include <iostream>
machine where the user using namespace std;
can withdraw, deposit, or int main() {
check their balance. The double balance = 1000.00; // Initial balance
program should run until int choice;
the user chooses to exit. double amount;
do {
cout << "\nATM Menu:" << endl;
cout << "1. Check Balance" << endl;
cout << "2. Deposit Money" << endl;
cout << "3. Withdraw Money" << endl;
cout << "4. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
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 A Q.1 A one-dimensional array is a simple #include <iostream>
write at an index in an array list of elements. using namespace std;
2. Explain how to traverse an Write a program that initializes a one-
array using all loop structures dimensional array, calculates the sum int main() {
of its elements, and displays them. int arr[5] = {10, 20, 30, 40, 50};
int sum = 0;
for(int i = 0; i < 5; i++) {
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-dimensional using namespace std;
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 the #include <iostream>
temperatures for a whole week into an #include <string>
array and then determines the hottest day using namespace std;
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] << ": ";
cin >> temperatures[i];
}

double maxTemp = temperatures[0];


int hottestDayIndex = 0;

for (int i = 1; i < DAYS; i++)


{
if (temperatures[i] > maxTemp)
{
maxTemp = temperatures[i];
hottestDayIndex = 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 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] ;

// Bubble Sort algorithm for sorting


for(int i = 0; i < n-1; i++) {
for(int j = 0; j < n-i-1; j++) {
if(arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
cout << "Sorted numeric list: ";
for(int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0; }
5. 1. Explain how to define and A Q.1 Write a C++ program that initializes a #include <iostream>
initialize a two dimensional 2D array of integers, calculates the sum of using namespace std;
array of different sizes and its values, and displays the result on the
data types screen. int main()
2. Explain how to access and {
write at an index in a two int test[2][3] =
dimensional array {
{1, 2, 3}, // First row
{4, 5, 6} // Second row
};

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;

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


for (int j = 0; j < cols; j++) {
cout << sumArray[i][j] << " "; }
cout << endl;
}
return 0; }
6. 1.Explain how to define a string A Q.1 Write a C++ program to input any #include <iostream>
2. Explain the techniques of string and calculate its length using string #include <cstring>
initializing a string functions. using namespace std;
3. Explain the most commonly int main() {
used string functions char cString[100];
cout << "Enter a string: ";
cin.getline(cString, 100);
int lengthC = strlen(cString);
cout << "Length of the string is: " << lengthC << endl;
}
return 0; }
Q.2 Write a program to search a string #include <iostream>
item out of a list of strings #include <string>
using namespace std;
int main() {
string arr[5] = {"apple", "banana", "grape", "mango",
"cherry"};
int n = 5;
string searchItem = "mango";
bool found = false;

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


if(arr[i] == searchItem)
{
cout << "String item \"" << searchItem << "\"
found at index " << i << endl;
found = true;
break;
}
}

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);

// Searching the student name using Linear Search

for(int i = 0; i < 10; i++)


{
if(strcmp(students[i], searchName) == 0) {
cout << "Student " << searchName << " found at
index " << i<< endl;
found = true;
break;
}
}
if(!found) {
cout << "Student " << searchName << " not found
in the list." << endl;
}
return 0; }
Q.5 Write a program that demonstrates the #include <iostream>
concatenation of two strings using string #include <cstring>
function. using namespace std;

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];

// Input elements of the array from the user


cout << "Enter " << SIZE << " numbers: ";
for (int i = 0; i < SIZE; i++) {
cin >> numbers[i];
}

// Call the function and display the result


cout << "The sum of the array is: " <<
sumArray(numbers, SIZE) << endl;

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;

cout << "Enter three numbers: ";


cin >> a >> b >> c;

int sum = Sum(a, b, c);


cout << "Sum: " << sum << endl;
cout << "Average: " << average << endl;
return 0; }
Q.3 Predict the output: Sum: 15
int add(int a, int b) {
return a + b;
}

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; }

Q.5 Predict the output OUTPUT


#include <iostream>
using namespace std; Square of 4: 16
inline int square(int x) { Square of 5: 25
return x * x;
}
int main() {
cout << "Square of 4: " << square(4) <<
endl;
cout << "Square of 5: " << square(5) <<
endl;
return 0; }
9. Understand the use of function B Q.1 Write a program to sum two and three #include <iostream>
overloading with: numbers of different data types using using namespace std;
• Number of arguments function overloading.
• Data types of arguments int sum(int a, int b)
• Return types {
return a + b;
}

float sum(float a, float b)


{
return a + b;
}

int sum(int a, int b, int c)


{
return a + b + c;
}

float sum(float a, float b, float c)


{
return a + b + c;
}

int main()
{
int x = 5, y = 10;
float p = 3.5, q = 4.5;
cout << "Sum of two integers: "
<< sum(x, y) << endl;

cout << "Sum of two floats: "


<< sum(p, q) << endl;

int a = 1, b = 2, c = 3;
cout << "Sum of three integers: "
<< sum(a, b, c) << endl;

float m = 1.1, n = 2.2, o = 3.3;


cout << "Sum of three floats: "
<< sum(m, n, o) << endl;
return 0;}
Q.2 Write a program that overloads a #include <iostream>
function max() to find the maximum of two using namespace std;
numbers and three numbers.
int max(int a, int b)
{
return (a > b) ? a : b;
}

int max(int a, int b, int c)


{
return (a > b && a > c) ? a : (b > c ? b : c);
}

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;
}

double area(double length, double width)

{
return length * width;
}

double area(double base, double height, int dummy)


{
return (0.5 * base * height);
}

int main() {

double radius = 5.0, length = 10.0, width = 4.0, base =


6.0, height = 3.0;

cout << "Area of circle: " << area(radius);


cout << "Area of rectangle: "
<< area(length, width);
cout << "Area of triangle: " << area(base, height, 0);
return 0; }
Q.4 Write a program that overloads a #include <iostream>
function calculate() to calculate the square using namespace std;
of one number and the cube of two
numbers. int calculate(int num) {
return num * num;
}

int calculate(int num1, int num2) {


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; }
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 = &num;
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 = &num;
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:

int main() { Value of num: 10


int num = 10; Value of ptr: 0x7fffd0000000 (address of num)
Value pointed to by ptr: 10
int *ptr = &num;
cout << "\n Value of num: " << num ;
cout << "\ n Value of ptr: " << ptr;
cout << "\ nValue pointed to by ptr: " <<
*ptr
}
Q4. Predict the output: OUTPUT:

int main() { Before increment: 7


int num = 7; After increment: 8:
int* ptr = &num;
cout << "Before increment: " << num <<
endl;
(*ptr)++;
cout << "After increment: " << num <<
endl;
return 0;}

Q5. Modify the following code so that it int main() {


increments the value of num by 5 using a int num = 7;
cout << "Before increment: " << num << endl;
pointer:
int main() { int* ptr = &num;
int num = 7;
*ptr += 5
cout << "Before increment: " << num <<
endl; cout << "After increment: " << num << endl;
int* ptr = &num;
return 0; }
(*ptr)++;
cout << "After increment: " << num <<
endl;
return 0; }

11. Q1. Design a class called Circle with a #include <iostream>


 Declare object to access B
private data member for the radius. using namespace std;
• Data members
Include public member functions to set the
• Member functions class Circle {
radius, calculate the area, and display it.
 Understand and access
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;
}
Q2. Write a program to create and display #include <iostream>
student object with data members as using namespace std;
name, age and class. class Student {
private:
string name; // Data member for name
int age; // Data member for age
string studentClass; // Data member for class
public:
// Public member function to set student details
void setDetails(string n, int a, string c) {
name = n;
age = a;
studentClass = c;
}
// Public member function to display student details
void displayDetails() {
cout << "Student Name: " << name << endl;
cout << "Student Age: " << age << endl;
cout << "Student Class: " << studentClass <<
endl;
}
};
int main() {
Student student1; // Creating an object of class
Student

// Setting student details


student1.setDetails("Jawad", 16, "10th Grade");

// Displaying student details


student1.displayDetails();
return 0;
}
Q3. Create a class Rectangle with private #include <iostream>
data members for length and width. Write using namespace std;
public member functions to set the
dimensions and calculate the area. class Rectangle {
Demonstrate this with two objects of the private:
class. int length;
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 grades #include <iostream>
with data members for name, subject, and using namespace std;
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
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 setDetails(string name, double p, bool stock)


{
productName = name;
price = p;
inStock = stock;
}

// Function to display 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:

Box(double l, double w, double h)


{
length = l;
width = w;
height = h;
}

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; }
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;
}

// Constructor for name only (default age 18)


Student(string n) {
name = n;
age = 18; // Default age
}

// Function to display student details

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;

// Create an object using the parameterized


constructor
Rectangle rect2(4.0, 5.0);
cout << "Area of rectangle 2 (parameterized): " <<
rect2.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;
}

// Function to display the area of the triangle


void displayArea() {
cout << "Area of Triangle: " << (0.5 * base *
height) << endl;
}
};

int main() {
Triangle tri1; // Uses default values
Triangle tri2(6.0, 8.0); // Uses custom values

tri1.displayArea(); // Display area of tri1


tri2.displayArea(); // Display area of tri2
return 0;
}
13. B Q1. Write a program to open a file named #include <iostream>
 Open the file and write the following lines into a file: #include <fstream>
• Modes of opening file Hello, World! using namespace std;
 Know the concept of
• BOF Welcome to file handling in C++. int main() {
• EOF ofstream file("output.txt", ios::out);
if (file.is_open())
{
file << "Hello, World!" << endl;
file << "Welcome to file handling in C++." <<
endl;
file.close();
} else
{
cout << "Error opening the file!" << endl;
}
return 0; }
Q2. Write a C++ program that copies the #include <iostream>
contents of a file ABC.txt to another file #include <fstream>
XYZ.txt. using namespace std;

int main() {
string line;
ifstream inputFile("ABC.txt");
ofstream outputFile("XYz.txt");

// Check if the input file is open


if (!inputFile) {
cout << "Error opening ABC.txt!" << endl;
return 1; // Exit with error code
}

// Check if the output file is open


if (!outputFile) {
cout << "Error opening XYz.txt!" << endl;
return 1;
}
while (getline(inputFile, line))
{
outputFile << line << endl; // Copy each line from
ABC.txt to 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;}

Q3. Write a program that inputs a string #include <iostream>


and then writes string to a file. #include <fstream>
using namespace std;

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; }

Q4. Write a program to read string from a #include <iostream>


file and display it on a screen #include <fstream>
using namespace std;

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;
}

You might also like