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

PF Lab Assignment #1

This document contains a C++ programming assignment with multiple questions focusing on functions. Each question requires the implementation of a specific function to perform tasks such as mathematical operations, temperature conversion, electricity bill calculation, call cost calculation, character replacement in strings, random number generation, leap year checking, and finding the first uppercase letter in a string. The document provides code examples and explanations for each question.

Uploaded by

Saad Butt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

PF Lab Assignment #1

This document contains a C++ programming assignment with multiple questions focusing on functions. Each question requires the implementation of a specific function to perform tasks such as mathematical operations, temperature conversion, electricity bill calculation, call cost calculation, character replacement in strings, random number generation, leap year checking, and finding the first uppercase letter in a string. The document provides code examples and explanations for each question.

Uploaded by

Saad Butt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

C++ Programming Fundamental

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>

using namespace std;

// Function to perform operations based on conditions

void performoperation_Ayyan(double num1,double num2)

double result;

// Perform the operation based on the value of the second number

string operation;

if(num2>0){

result = num1 /num2;

operation = "division";

}else if (num2<0){

result = num1*num2;

operation = "multiplication";

}else{

result = num1 + num2;

operation = "addition";

}
cout<<"the result of the:"<<operation<<"is"<<result<<endl;

int main(){

// Getting two numbers from the user

double num1,num2;

cout<<"enter the first number:";

cin>> num1;

cout<<"enter the second number:";

cin>> num2;

// Call the function to perform the operation

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>

using namespace std;

void displayCityInfo_yourName()

int zipCode;

// Ask the user for a zip code

cout << "Enter zip code: ";

cin >> zipCode;

// Display the city name based on zip code

if (zipCode == 38000) {

cout << "City: Faisalabad" << endl;

} else if (zipCode == 50700) {

cout << "City: Gujrat" << endl;

} else if (zipCode == 44000) {

cout << "City: Islamabad" << endl;

} else if (zipCode == 54000) {

cout << "City: Lahore" << endl;

} else if (zipCode == 25000) {

cout << "City: Peshawar" << endl;

} else {

cout << "City not found for this zip code!" << endl;

int main() {

// Call the function to display city info based on zip code.


displayCityInfo_yourName();

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>

#include <iomanip>// For sepration()

using namespace std;

// Function to convert temperature based on conversion type

void convertTemprature_Ayyan(double Temprature, int conversionType)

switch(conversionType)

{
case 1:// For Celsius

cout<< 32 + (Temprature * 1.8);

break;

case 2:// For Fahrenheit

cout<<(Temprature - 32) / 1.8;

break;

case 3:// For Kelvin

cout<<273.15 + Temprature;

break;

case 4:// For Rankine

cout<<Temprature * 5.0 / 9.0;

break;

default:

cout<<"invalid conversion type."<<endl;

int main()

double Temprature;

int conversionType;

// Get temperature and conversion type from the user

cout<<"Enter the temprature : ";

cin>>Temprature;

cout<<"Enter conversion type : ";

cin>>conversionType;

// Call the function


convertTemprature_Ayyan(Temprature , conversionType);

cout<< fixed <<setprecision(2);

if(conversionType>= 1 && conversionType<= 4)

cout<<" converted temprature: "<<endl;

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>

using namespace std;


void calculateElectricityBill_Ayyan(int units) {

double billAmount = 0.0;

// Calculate the bill based on the units

if (units <= 100) {

billAmount = units * 4.0;

} else if (units > 100 && units <= 300) {

billAmount = units * 4.50;

} else if (units > 300 && units <= 500) {

billAmount = units * 4.75;

} else if (units > 500) {

billAmount = units * 5.0;

// Add fuel surcharge (20%) and government tax (10%)

double fuelSurcharge = billAmount * 0.20;

double govtTax = billAmount * 0.10;

// Calculate the total bill

double totalBill = billAmount + fuelSurcharge + govtTax;

// Display the calculated total bill

cout << "Electricity Bill Breakdown:" << endl;

cout << "Base Bill: Rs." << billAmount << endl;

cout << "Fuel Surcharge (20%): Rs." << fuelSurcharge << endl;

cout << "Government Tax (10%): Rs." << govtTax << endl;

cout << "Total Bill: Rs." << totalBill << endl;

int main() {

int units;
// Ask the user to enter the number of units

cout << "Enter the number of units consumed: ";

cin >> 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>

using namespace std;


void calculateCallCost_yourName(double callDuration) {

double callCost = 0.0;

// Check if the call duration is valid and calculate the call cost

if (callDuration > 0 && callDuration <= 2) {

callCost = callDuration * 12.0;

} else if (callDuration > 2 && callDuration <= 5) {

callCost = callDuration * 10.0;

} else if (callDuration > 5 && callDuration <= 8) {

callCost = callDuration * 7.0;

} else if (callDuration > 8 && callDuration <= 10) {

callCost = callDuration * 5.0;

} else if (callDuration > 10) {

callCost = callDuration * 3.0;

} else {

cout << "Wrong value entered" << endl;

return;

cout << "Call Duration: " << callDuration << " minutes" << endl;

cout << "Call Cost: Rs." << callCost << endl;

int main() {

double callDuration;

// Ask the user for call duration

cout << "Enter the call duration (in minutes): ";

cin >> callDuration;


if (cin.fail() || callDuration <= 0) {

cout << "Wrong value entered" << endl;

} else {

// call the function to calculate call cost

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>

using namespace std;

void replaceCharacter_Ayyan(string &str, char ch) {

// Loop through the string and replace occurrences of ch with '*'

for (char &c : str) {


if (c == ch) c = '*';

// Display the modified string

cout << "Modified string: " << str << endl;

int main() {

string inputString;

char characterToReplace;

// Ask the user to enter a string

cout << "Enter a string: ";

getline(cin, inputString);

// Ask the user for the character to replace

cout << "Enter the character to replace: ";

cin >> characterToReplace;

// Call the function to replace the character

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>

using namespace std;

// Function to generate a random number between 1 and 100

int generateRandomNumber() {

return rand() % 100 + 1;

int main() {

// Seed the random number generator with the current time

srand(static_cast<unsigned>(time(0)));

// Generate and display the random number

int randomNumber = generateRandomNumber();

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>

using namespace std;

// Function to check whether a year is a leap year

bool isLeapYear(int year) {

// A year is a leap year if it is divisible by 4, but not divisible by 100, unless it is


divisible by 400

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {

return true;

return false;

int main() {

// Ask the user to enter a year

int year;

cout << "Enter a year: ";

cin >> year;

// Check and display if the year is a leap year

if (isLeapYear(year)) {

cout << year << " is a leap year." << endl;

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

using namespace std;

// Function to get the first uppercase letter from the string

char getFirstUppercaseLetter() {

string input;

// Scan the string for the first uppercase letter

cout << "Enter a string: ";

cin >> input;

for (char c : input) {

if (isupper(c)) {

return c;

}
return '0';

int main() {

// Get the first uppercase letter from the user input

char result = getFirstUppercaseLetter();

// Display the result

if (result == '0') {

cout << "No uppercase letter found." << endl;

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

// Calculate the discriminant

pair<complex<double>, complex<double>> quadRoots(double a, double b, double c) {

double discriminant = b * b - 4 * a * c;

complex<double> root1, root2;

// Compute the roots using complex numbers

root1 = (-b + sqrt(complex<double>(discriminant))) / (2 * a);

root2 = (-b - sqrt(complex<double>(discriminant))) / (2 * a);

return {root1, root2};

int main() {

double a, b, c;

// Get coefficients from the user

cout << "Enter coefficients a, b, and c for the quadratic equation (ax^2 + bx + c = 0): ";

cin >> a >> b >> c;

// Call the function and get the roots

auto roots = quadRoots(a, b, c);

cout << "The roots of the equation are:" << endl;

cout << "Root 1: " << roots.first << endl;

cout << "Root 2: " << roots.second << endl;

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>

using namespace std;

// Function to calculate salary

double calculateSalary(double baseSalary, double bonus = 0, double deductions = 0) {

return baseSalary + bonus - deductions;

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>

using namespace std;

// Function to calculate tax

double calculateTax(double income, double taxRate = 0.1) {

return income * taxRate;

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>

using namespace std;

// Function to convert hours, minutes, and seconds to total seconds

int hms_to_sec(int hours, int minutes, int seconds) {

return (hours * 3600) + (minutes * 60) + seconds;

int main() {

// Get time from user

int hours, minutes, seconds;

cout << "Enter time in format (HH MM SS): ";

cin >> hours >> minutes >> seconds;

// Display total seconds

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>

using namespace std;

// Function to convert a year to Roman numerals

string toRoman(int year) {

string roman = "";

pair<int, string> values[] = {

{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"},

{100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"},


{10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}

};

for (auto &val : values) {

while (year >= val.first) {

roman += val.second;

year -= val.first;

return roman;

int main() {

int year;

cout << "Enter a year: ";

cin >> 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>

using namespace std;

// Function to swap two numbers

void swapNumbers(int &a, int &b) {

int temp = a;

a = b;

b = temp;

int main() {

int x, y;

cout << "Enter two numbers: ";

cin >> 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>

using namespace std;

// Function to determine if a year is a leap year

bool isLeapYear(int year) {

return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

int main() {

int year;

cout << "Enter a year: ";

cin >> year;

if (isLeapYear(year)) {

cout << year << " is a leap year." << endl;

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

using namespace std;

// Function to check if a string is a palindrome

bool isPalindrome(const string &str) {

int start = 0, end = str.length() - 1;

while (start < end) {

if (str[start] != str[end]) {

return false;

start++;

end--;

return true;

}
int main() {

string input;

cout << "Enter a string: ";

cin >> input;

if (isPalindrome(input)) {

cout << input << " is a palindrome." << endl;

} else {

cout << input << " is not a palindrome." << endl;

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.

You might also like