0% found this document useful (0 votes)
14 views42 pages

Cptr Science 12

The document provides a comprehensive set of programming questions and solutions for Class X Computer Science, focusing on C++ programming concepts such as input/output, decision statements, looping structures, and basic algorithms. It includes examples of programs for calculating sums, volumes, and conversions, as well as exercises on variable naming conventions and error handling. Overall, it serves as a guide for students to practice and understand fundamental programming skills.

Uploaded by

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

Cptr Science 12

The document provides a comprehensive set of programming questions and solutions for Class X Computer Science, focusing on C++ programming concepts such as input/output, decision statements, looping structures, and basic algorithms. It includes examples of programs for calculating sums, volumes, and conversions, as well as exercises on variable naming conventions and error handling. Overall, it serves as a guide for students to practice and understand fundamental programming skills.

Uploaded by

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

QIB FOR CLASS X - BIOLOGY PBA

Class: HSSC Subject: Computer Science


Total SLO: 14 Total Qs: 72
Ser SLO Questions Answer
1. Write some programs using: Q.1 Write a program in C++ that #include <iostream>
• Cin finds out a sum of digits of a 4 digit using namespace std;
• Cout n int main() {
• Escape sequences int n, r1,r2,r3,r4,sum;
• Setw umber, say 1234. 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 Write a program in C++ that #include <iostream>
calculates the Body Mass Index (BMI) using namespace std;
given weight and height. int main() {
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 You have the following code. The code has several issues with variable names:
Identify any issues with the variable 1. Variable names cannot start with a digit. So, 1number is invalid.
names according to C++ rules, and o Correction: Rename it to number1.
correct them: 2. Variable names can only contain letters, digits, and underscores, but not special
int 1number = 10; characters like %.
double %discount = 5.5; o Correction: Rename %discount to discount.
float price$ = 100.0; 3. Variable names cannot contain symbols like $ other than an underscore.
Correction: Rename price$ to price.

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;

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;

Page 4 of 42
Ser SLO Questions Answer
}

Q.5 Write a program to read a #include <iostream>


number and find out whether it is a using namespace std;
prime or composite. int main() {
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 Q.1 Write a C++ program to find the #include <iostream>
looping structures: factorial of a given number using a using namespace std;
• For loop. int main() {
• While 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 to print # include <iostream>
natural numbers from 1 to 10 in using namespace std;
Page 5 of 42
Ser SLO Questions Answer
reverse order int main( )
{ int i;
for (i=10; i>=1; i--)
cout<<i<<" ";
return 0; }
Q.3 Write C++ Program to print table #include<iostream>
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 takes an #include <iostream>
integer input and outputs its reverse. using namespace std;

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

cout << "GCD = " << num1 << endl;

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;

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


cout << "Calculator closed." << endl;
return 0;}
Q.10 Simulate an ATM machine #include <iostream>
where the user can withdraw, using namespace std;
deposit, or check their balance. The int main() {
program should run until the user double balance = 1000.00; // Initial balance
chooses to exit. int choice;
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;

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

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

// 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 Q.1 Write a C++ program that #include <iostream>
initialize a two dimensional initializes a 2D array of integers, using namespace std;
array of different sizes and data calculates the sum of its values, and
types displays the result on the 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
Page 13 of 42
Ser SLO Questions Answer
};

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

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 using namespace std;
a third two-dimensional array to int main() {
store the result of 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++)

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;

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 Q.1 Write a C++ program to input #include <iostream>
2. Explain the techniques of any string and calculate its length #include <cstring>
initializing a string using 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 #include <iostream>
string 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;

// Linear search algorithm for string items


Page 17 of 42
Ser SLO Questions Answer
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 #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);

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

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

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

Q.6 Predict the output OUTPUT


#include <iostream>
using namespace std; Square of 4: 16
Page 24 of 42
Ser SLO Questions Answer

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 Q.1 Write a program to sum two and #include <iostream>
overloading with: three numbers of different data types using namespace std;
• Number of arguments using 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;

Page 25 of 42
Ser SLO Questions Answer
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 using namespace std;
of two 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;}

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

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 using namespace std;
square of one number and the cube
of two numbers. int calculate(int num) {
return num * num;
}

int calculate(int num1, int num2) {

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

10. Know the use of reference


Q1.Write a program to display the #include <iostream>
operator ( & ) address and the value of a variable using namespace std;
Know the use of dereference using pointer
operator ( * ) int main() {
Declare variables of pointer types
int num = 25;
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 include <iostream>
pointer variable and modify value using namespace std;
int main() {
of variable using pointer.
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 OUTPUT:
following:
Value of num: 10
int main() { Value of ptr: 0x7fffd0000000 (address of num)

Page 28 of 42
Ser SLO Questions Answer

int num = 10; 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;}

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 = &num;
int num = 7;
*ptr += 5
cout << "Before increment: " <<
num << endl; cout << "After increment: " << num << endl;
int* ptr = &num;
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

Q2. Write a program to create and #include <iostream>


display student object with data using namespace std;
members as 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 #include <iostream>
private data members for length using namespace std;
and width. Write public member
functions to set the dimensions class Rectangle {
and calculate the area. private:

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

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:

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

Page 34 of 42
Ser SLO Questions Answer

Q2. Write a program to create a #include <iostream>


class Circle with a data member using namespace std;
radius. Use a parameterized
constructor to initialize the radius. class Circle {
Also, create a function to calculate private:
and display the area of the circle. 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 #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;
}

// 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 #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;

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

// 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.
Q1. Write a program to open a file #include <iostream>
• Open the file named and write the following
• Modes of opening file #include <fstream>
lines into a file:
• Know the concept of using namespace std;
• BOF Hello, World!
int main() {
• EOF Welcome to file handling in C++.
ofstream file("output.txt", ios::out);
if (file.is_open())
{
file << "Hello, World!" << endl;
file << "Welcome to file handling in C++." << endl;
file.close();

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

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

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

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


string 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 #include <iostream>


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

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

You might also like