PF Lab Assignment #1
PF Lab Assignment #1
Assignment # 1
Submitted to:-
Sir ghulam Mustafa
Submitted by:-
Ayyan Ahmad
2024-BS-CYS-027
Topic: Functions in C++
Question 01
Write a program getting two numbers from the user using the function and function
named 'performOperation_yourName', and do the following:
• If the second number is greater than 0, divide them
• If the second number is less than 0, multiply them
• If the second number is equal to 0, add them
Program:
#include <iostream>
double result;
string operation;
if(num2>0){
operation = "division";
}else if (num2<0){
result = num1*num2;
operation = "multiplication";
}else{
operation = "addition";
}
cout<<"the result of the:"<<operation<<"is"<<result<<endl;
int main(){
double num1,num2;
cin>> num1;
cin>> num2;
performoperation_Ayyan(num1,num2);
return 0;
Output:
Explanation:
This program accepts two numbers and performs different operations based on
the value of the second number:
If the second number is greater than 0, it divides the first number by the second.
If the second number is less than 0, it multiplies them.
If the second number is equal to 0, it adds the two numbers.
Question 02
Write a C++ program that utilizes a function named 'displayCityInfo_yourName' to
display the city name based on their zip code. Assume there are only three and five
cities in the system.
Program:
#include <iostream>
void displayCityInfo_yourName()
int zipCode;
if (zipCode == 38000) {
} else {
cout << "City not found for this zip code!" << endl;
int main() {
return 0;
Output:
Explanation:
This program accepts a zip code from the user and uses a function to display the
corresponding city name based on the zip code. The city names are predefined
in the program for specific zip codes.
Question 03
Write a C++ program that utilizes a function named 'convertTemperature_yourName' to
find the temperature in Celsius or Fahrenheit from the given temperature and conversion
type. Ensure that the precision of the result is set using the setprecision() function.
Conversion Type Description Formula:
1. Celsius: 32 + (temperature * 1.8)
2. Fahrenheit: (temperature - 32) / 1.8
3. Kelvin: 273.15 + temperature
4. Rankine: Temperature * 5/9
Program:
#include <iostream>
switch(conversionType)
{
case 1:// For Celsius
break;
break;
cout<<273.15 + Temprature;
break;
break;
default:
int main()
double Temprature;
int conversionType;
cin>>Temprature;
cin>>conversionType;
return 0;
Output:
Explanation:
The program converts a given temperature into different units (Celsius,
Fahrenheit, Kelvin, and Rankine) based on a user-selected conversion type. It
uses predefined formulas for each conversion and ensures that the result is
printed with the appropriate precision using the setprecision() function.
Question 04
Write a C++ program that utilizes a function named 'calculateElectricityBill_yourName' to
calculate the Electricity Bill by taking units from the user and calculating the total bill
according to the following criteria:
• units <=100 → Rs.4/
• units > 100 and <=300 units → Rs.4.50/
• units >300 and <=500 units → Rs.4.75/
• units >500 units → Rs.5/units
Add a fuel surcharge of 20% and Govt. Tax 10% on the bill to calculate the total bill and
display it.
Program:
#include <iostream>
cout << "Fuel Surcharge (20%): Rs." << fuelSurcharge << endl;
cout << "Government Tax (10%): Rs." << govtTax << endl;
int main() {
int units;
// Ask the user to enter the number of units
calculateElectricityBill_Ayyan(units);
return 0;
Output:
Explanation:
This program calculates the electricity bill based on the number of units
consumed, applying different rates for different consumption ranges. It adds a
fuel surcharge of 20% and a government tax of 10% on the total bill.
Question 05
Design a program, which can calculate Call Cost, based on Call duration and Call
Charges per minute. When your program executes, ask the user for Call Duration and
then calculate the Call Cost based on Table 1. If the user enters any wrong value, your
program must print, 'Wrong Value entered'.
Table 1:
Call Duration | Call Charges / Minutes
Greater than 0 and less than or equal to 2 | Rs 12 per minute
Greater than 2 and less than or equal to 5 | Rs 10 per minute
Greater than 5 and less than or equal to 8 | Rs 7 per minute
Greater than 8 and less than or equal to 10 | Rs 5 per minute
Greater than 10 | Rs 3 per minute
Program:
#include <iostream>
// Check if the call duration is valid and calculate the call cost
} else {
return;
cout << "Call Duration: " << callDuration << " minutes" << endl;
int main() {
double callDuration;
} else {
calculateCallCost_yourName(callDuration);
return 0;
Output:
Explanation:
This program calculates the cost of a call based on the call duration and the
corresponding rates. The user enters the call duration, and the program
calculates the cost using a rate table. If the input is invalid, it prints an error
message.
Question 06
Write a function named 'replaceCharacter_yourName' that accepts a string and a
character from the user, and then replaces all occurrences of that character in the string
with the '*' symbol.
Program:
#include <iostream>
int main() {
string inputString;
char characterToReplace;
getline(cin, inputString);
replaceCharacter_Ayyan(inputString, characterToReplace);
return 0;
Output:
Explanation:
This program replaces all occurrences of a given character in a string with
asterisks ('*'). It accepts a string and a character from the user and modifies the
string accordingly.
Question 07
Write a C++ program that utilizes a function to generate a random number between 1
and 100.
Program:
#include <iostream>
#include <cstdlib>
#include <ctime>
int generateRandomNumber() {
int main() {
srand(static_cast<unsigned>(time(0)));
cout << "Random number between 1 and 100: " << randomNumber << endl;
return 0;
Output:
Explanation:
This program generates and displays a random number between 1 and 100. It
uses the random number generation functions available in C++.
Question 08
Write a program to check whether a given year is a leap year using the function.
Program:
#include <iostream>
return true;
return false;
int main() {
int year;
if (isLeapYear(year)) {
} else {
cout << year << " is not a leap year." << endl;
return 0;
}
Output:
Explanation:
This program checks whether a given year is a leap year or not. A leap year is
divisible by 4, but not divisible by 100 unless also divisible by 400. The program
checks these conditions and displays the result.
Question 09
Write a function called 'getFirstUppercaseLetter' that prompts the user to enter a string.
The function should then scan the string and return the first uppercase letter it
encounters. If no uppercase letter is found, the function should return '0' and if found first
character is uppercase then return that character.
Program:
#include <iostream>
#include <string>
char getFirstUppercaseLetter() {
string input;
if (isupper(c)) {
return c;
}
return '0';
int main() {
if (result == '0') {
} else {
cout << "The first uppercase letter is: " << result << endl;
return 0;
Output:
Explanation:
This program scans a string provided by the user and returns the first uppercase
letter it encounters. If no uppercase letter is found, it returns '0'. The program
uses a loop to iterate through the string and check each character.
Question 10
Implement a function named quadRoots(…) that accepts parameters for the coefficients
of a quadratic equation (a, b, and c), and returns the roots as a pair of complex numbers.
Test the function by accepting input coefficients from the user and displaying the roots.
Program:
#include <iostream>
#include <complex>
using namespace std;
double discriminant = b * b - 4 * a * c;
int main() {
double a, b, c;
cout << "Enter coefficients a, b, and c for the quadratic equation (ax^2 + bx + c = 0): ";
return 0;
Output:
Explanation:
This program calculates the roots of a quadratic equation (ax^2 + bx + c = 0). It
uses the quadratic formula to find the roots. If the discriminant (b^2 - 4ac) is
negative, it returns complex roots. Otherwise, it returns real roots.
Question 12
Design a function called calculateSalary to compute the monthly salary of an employee.
The function should accept three parameters: baseSalary, bonus, and deductions. The
baseSalary parameter is required, but bonus and deductions are optional and default to
0. The function should calculate the total salary by adding the baseSalary, and bonus,
and subtracting deductions. In the main function, the calculateSalary function is called
with different parameters to test its functionality. Formula: Salary = baseSalary + bonus
– deductions
Program:
#include <iostream>
int main() {
cout << "Salary (Base: 5000): " << calculateSalary(5000) << endl;
cout << "Salary (Base: 5000, Bonus: 500): " << calculateSalary(5000, 500) << endl;
cout << "Salary (Base: 5000, Bonus: 500, Deductions: 200): " <<
calculateSalary(5000, 500, 200) << endl;
return 0;
}
Output:
Explanation:
This program calculates an employee's monthly salary. It accepts a base salary
and optional bonus and deduction values (which default to 0). The program
calculates and displays the total salary by adding the bonus and subtracting the
deductions.
Question 13
Create a function named calculateTax that calculates the tax amount for a given income.
The function should accept one parameter: income (required), and an optional
parameter taxRate which defaults to 0.1 (10%). In the main function, the calculateTax
function is called with different parameters to test its functionality. If the tax rate is not
provided, it defaults to 10%.
Program:
#include <iostream>
int main() {
cout << "Tax (Income: 50000, Default Rate): " << calculateTax(50000) << endl;
cout << "Tax (Income: 50000, Tax Rate: 15%): " << calculateTax(50000, 0.15) <<
endl;
return 0;
Output:
Explanation:
This program calculates the tax on a given income based on a user-provided tax
rate. If the user does not provide a tax rate, the program uses a default tax rate
of 10%. The program computes the tax as a percentage of the income.
Question 14
Write a function called hms_to_sec() that takes three int values for hours, minutes, and
seconds as arguments and returns the equivalent time in seconds. Create a program
that exercises this function by obtaining a time value in hours, minutes, and seconds
from the user (format 12:59:59), calling the function, and displaying the value of seconds
it returns.
Program:
#include <iostream>
int main() {
cout << "Total seconds: " << hms_to_sec(hours, minutes, seconds) << endl;
return 0;
}
Output:
Explanation:
This program converts a time specified in hours, minutes, and seconds into total
seconds. It multiplies hours by 3600 (seconds in an hour), minutes by 60
(seconds in a minute), and adds them to the seconds input.
Question 15
Write a general-purpose function to convert any given year into its Roman equivalent.
The following table shows the Roman equivalents of decimal numbers:
Decimal Roman Decimal Roman
1000 M 40 XL
900 CM 10 X
500 D 9 IX
400 CD 5 V
100 C 4 IV
90 XC 1 I
50 L
Example: Enter a year: 1988
Roman equivalent of 1988 is: MCMLXXXVIII
Program:
#include <iostream>
};
roman += val.second;
year -= val.first;
return roman;
int main() {
int year;
cout << "Roman equivalent of " << year << " is: " << toRoman(year) << endl;
return 0;
Output:
Explanation:
This program converts a given year (in decimal) into its Roman numeral
equivalent. It uses a mapping of decimal values to Roman symbols and builds
the Roman numeral string by subtracting the largest applicable decimal value at
each step.
Question 16
Write a function named swapNumbers that takes two integer references as parameters
and swaps their values. Create a program to test this function.
Program:
#include <iostream>
int temp = a;
a = b;
b = temp;
int main() {
int x, y;
cout << "Before swapping: x = " << x << ", y = " << y << endl;
swapNumbers(x, y);
cout << "After swapping: x = " << x << ", y = " << y << endl;
return 0;
Output:
Explanation:
This program swaps two integer values using reference parameters. By passing
the integers by reference, the function modifies the actual values in the main
function without needing to return them.
Question 17
Write a function that determines whether the 'year is a leap year or not'. Pass the value
from main; also returning the value in main.
Program:
#include <iostream>
int main() {
int year;
if (isLeapYear(year)) {
} else {
cout << year << " is not a leap year." << endl;
return 0;
}
Output:
Explanation:
This program checks whether a given year is a leap year using the call-by-
reference method. The year value is passed by reference, and the function
checks if the year meets the criteria for a leap year and returns the result.
Question 18
Write a function that determines whether the given string is palindrome or not. For
example, rar is a palindrome. Take the string input from the user in main () and pass it
as an argument to the function.
Program:
#include <iostream>
#include <string>
if (str[start] != str[end]) {
return false;
start++;
end--;
return true;
}
int main() {
string input;
if (isPalindrome(input)) {
} else {
return 0;
Output:
Explanation:
This program checks if a string is a palindrome. A palindrome is a string that
reads the same forwards and backwards. The program compares characters
from both ends of the string and confirms if they are equal, indicating a
palindrome.