Computer Lab Project
Computer Lab Project
ROLL NO. : 31
PROGRAM : BSCS
SECTION : 6B
FALL 2023
Chapter # 4
Exercise
4.11: (Correct the Code Errors) Identify and correct the error(s) in each of the following:
a) if ( age >= 65 );
cout << "Age is greater than or equal to 65" << endl;
else
cout << "Age is less than 65 << endl";
b) if ( age >= 65 ) cout << "Age is greater than or equal to 65" << endl;
else;
cout << "Age is less than 65 << endl";
c) unsigned int x = 1;
unsigned int total;
while ( x <= 10 )
{
total += x;
++x;
}
d) While ( x <= 100 )
total += x;
++x;
e) while ( y > 0 )
{
cout << y << endl;
++y;
}
Answer:
A)
In this exercise, we need to find errors in the given code. The first error is in line 1, a semicolon
is not written after the if statement. The second error is in line 6, if we want a new line, we
need to write endl outside of the string.
The correct code is:
if (age >= 65)
cout << "Age is greater than or equal to 65" << endl;
else
cout << "Age is less than 65 << endl";
B)
In this exercise, we need to find errors in the given code. The first error is in line 4, a semicolon
is not written after The second error is in line 5, if we want a new line, we need to write endl
outside of the string.
The correct code is:
if (age >= 65)
cout << "Age is greater than or equal to 65" <<endl;
else
cout << "Age is less than 65" << endl;
C)
In this exercise, we need to find errors in the given code. In this code, the variable total is not
initialized with a value. It is a good practice to assign value to variables.
The correct code is:
unsigned int x(1);
unsigned int total(0);
4.14
(Credit Limits) Develop a C++ program that will determine whether a department-store
customer has exceeded the credit limit on a charge account. For each customer, the following
facts are available:
a) Account number (an integer)
b) Balance at the beginning of the month
c) Total of all items charged by this customer this month
d) Total of all credits applied to this customer's account this month
e) Allowed credit limit
The program should use a while statement to input each of these facts, calculate the new
balance (= beginning balance + charges – credits) and determine whether the new balance
exceeds the customer’s credit limit. For those customers whose credit limit is exceeded, the
program should display the customer’s account number, credit limit, new balance and the
message “Credit Limit Exceeded.”
Answer:
In this exercise, we need to create a program that determines whether a customer has
exceeded the credit limit. The program prompts the user to enter the customer's account
number, balance at the beginning of the month, a total of all item's charged this month, total
credits applied to the customer's account, and allowed credit limit. After that, the program
calculates new balances and checks if the customer has exceeded the credit limit. The program
is executed until the user enters the sentinel.
First, let's write a pseudocode.
Determine whether a customer has exceeded the credit limit
Initalize the variables
Prompt user to enter account number Input the first account number (possibly the sentinel)
While the user has not entered the sentinel
Prompt user to enter balance at the beginning of the month
Input the balance
Prompt user to enter the total of all items charged this month Input the total charges
4.15
Pseudocode
Let's first write a pseudocode.
Determine salesperson's salary
Initalize the variables
Prompt user to enter sales in dollars
Input the first sales (possibly the sentinel)
While the user has not entered the sentinel
Calculate salary as 200+ 0.09 sales
Output salary
Prompt user to enter sales in dollars
Input sales (possibly the sentinel)
C++ Code:
#include <iostream>
using namespace std;
int main()
{
double sales;
cout<<"Enter sales in dollars (-1 to end): ";
cin>>sales;
while(sales != -1)
{
cout<<"Salary is: $"<<200+ 0.09* sales<<endl;
cout<<"\nEnter sales in dollers (-1 to end): ";
cin>>sales;
}
return 0;
}
Output:
4.16.
Pseudocode:
First, let's write a pseudocode.
Determine salary Initalize the variables
Prompt user to enter worked hours
Input the first hours (possibly the sentinel)
While the user has not entered the sentinel
Prompt use to enter hourly rate
Input hourly rate salary hours rate
If hours > 40
salary + 0.5 (hours 40)
Output salary
Prompt user to enter worked hours
Input the hours (possibly the sentinel)
C++ Code:
#include <iostream>
using namespace std;
int main()
{
int hours;
double rate,salary;
cout<<"Enter hours worked(or -1 to end): ";
cin>>hours;
while(hours!=-1)
{
cout<<"Enter hourly rate: ";
cin>>rate;
if(hours>40)
{
salary=salary+0.5*(hours-40)*rate;
cout<<"Salary is $ "<<salary;
}
salary=hours*rate;
cout<<"Salary is $ "<<salary;
cout<<"\nEnter hours worked (or -1 to end): ";
cin>>hours;
}
return 0;
}
Output:
4.17
C++ Code
#include<iostream>
using namespace std;
int main()
{
int N=1;
cout<<"N\t10*N\t100*N\t1000*N"<<endl;
while (N <= 5)
{
cout<<N<<"\t"<<10*N<<"\t"<<100*N<<"\t"<<1000*N<<"\n";
N += 1;
}
return 0;
}
Output:
4.19
(Find the Two Largest Numbers)
C++ Code:
#include <iostream>
using namespace std;
int main()
{ int num, largest1 = 0, largest2 = 0;
int n = 1;
while (n <= 10)
{
cout << "Enter a number: ";
cin >> num;
if (num > largest1)
{
largest2 = largest1;
largest1 = num; }
else if (num > largest2)
{
largest2 = num; }
n++; }
cout << "The two largest numbers are: " << largest1 << " and " << largest2 << endl;
return 0;
}
Output:
4.20
(Validating User Input)
Answer:
In this exercise, we need to modify the given code so that if the user enters the wrong number,
the program loops until the user enters the correct number. For that, we use while loop.
C++ Code:
#include <iostream>
using namespace std;
int main()
{
int result, passes = 0, failures = 0;
int studentCounter = 1;
{
while (studentCounter <= 10)
{
cout <<"Enter the result (1 = pass, 2 = fail) : ";
cin >> result;
while(result != 1 && result != 2)
{
cout<<"Please enter correct result (1 = pass, 2 = fail) : ";
cin>>result;
}
if (result == 1)
passes+=1;
else if (result == 2)
failures+=1;
studentCounter += 1;
}
}
cout <<"Number of students who passed: "<< passes<<endl;
cout <<"Number of students who failed: "<< failures<<endl;
if(passes > 8)
cout<<"Bonus to Instructor!";
return 0;
}
Output:
4.21
(What Does this Program Do?) What does the following program print?
#include <iostream>
using namespace std;
int main()
{
int count = 1;
while ( count <= 10 )
{
cout << ( count % 2 ? "****" : "+++++++++" ) << endl;
++count;
}
}
Answer:
The given program checks if the counter is a multiple of 2 or not. If the counter is not multiple
of 2 then the program outputs ****, otherwise it outputs ++++++++.
The output of the given program is:
****
++++++++
****
++++++++
****
++++++++
****
++++++++
****
++++++++
Output:
4.26
(Square of Asterisks)
C++ Code:
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Please Enter the number between 1 & 20: ";
cin >> num;
// input validation to ensure size is between 1 and 20
while (num < 1 || num > 20) {
cout << "Invalid number. Please enter a number between 1 and 20: ";
cin >> num;
}
int i = 1;
while(i <= num){
int j = 1;
while(j <= num){
if( i == 1 || i == num || j == 1 || j == num)
cout << "* ";
else
cout << " ";
j++;
}
cout << endl;
i++;
}
return 0;
}
Output:
4.27
(Palindromes)
C++ Code:
#include <iostream>
using namespace std;
int main()
{
int num=0;
int x;
while (num < 9999 || num > 99999)
{
cout<<"Please enter five digit number : ";
cin >> num;
}
x=num;
if(x/10000==x%10)
{
x=num%10000;
if(x/1000==x%10)
cout<<num<<" is palindrom.";
else
cout<<num<<" is not palindrom.";
}
else
{
cout<<num<<" is not a palindrom.";
}
return 0;
}
Output:
4.28
(Printing the Decimal Equivalent of a Binary Number)
C++ Code:
#include<iostream>
using namespace std;
int main()
{
int binaryNumber;
int base = 1;
int decimal = 0;
cout << "Please enter the binary number: ";
cin>> binaryNumber;
while (binaryNumber>0)
{
decimal +=base*(binaryNumber % 10);
binaryNumber /= 10;
base *=2;
}
cout << decimal;
return 0;
}
Output:
4.29
(Checkerboard Pattern of Asterisks) Write a program that displays the following checkerboard
pattern. Your program must use only three output statements, one of each of the following
forms:
cout << "* ";
cout << ' ';
cout << endl;
C++ Code:
#include<iostream>
using namespace std;
int main()
{
int count=0;
for (int i=0; i < 8; i++)
{
if(i % 2 == 1)
{
cout << " ";
}
for (int j=0; j< 8; j++)
{
cout <<"* ";
}
cout << endl;
}
return 0;
}
Output:
4.30
Step 1
In this exercise, we need to write an infinite while loop that prints out the multiples of 22. The
while loop is infinite if the condition of the loop is always true.
Step 2
C++Code:
The following program is the infinite while loop that prints out the multiples of 22.
#include<iostream>
using namespace std;
int main()
{ int i=2;
while (true)
{
cout<<i<<", ";
i*=2;
}
return 0;
}
Output:
4.31
(Calculating a Sphere’s Circumference, Area, and Volume)
C++ Code
The following code prompts the use user to input the radius of the circle and print out the
diameter of the circle, the circumference, and the area of the circle.
#include<iostream>
using namespace std;
int main()
{
double PI=3.14159;
double radius;
cout<<"Please enter the radius of the circle: ";
cin>>radius;
cout<<"The diameter of the circle: "<<2*radius<<endl;
cout<<"The circumference of the circle: "<<2*radius*PI<<endl;
cout<<"The area of the circle: "<<radius*radius*PI<<endl;
return 0;
}
Output:
4.32
What’s wrong with the following statement? Provide the correct statement to accomplish what
the programmer was probably trying to do.
cout << ++( x + y );
Step 1
The statement uses the prefix form of the increment operator incorrectly.
The operator can only be used upon one variable at a time.
Step 2
If the programmer wanted to increment the variables, we can write the solution this way:
cout << ++ + ++y; This way, the variables get incremented properly.
Step 3
If the programmer wanted to increment the sum of the two variables:
cout << x + y + 1;
4.33
(Sides of a Triangle) Write a program that reads three nonzero double values and determines
and prints whether they could represent the sides of a triangle.
Step 1
In this exercise, we need to write a program that prompts the user to input three nonzero
numbers and print out if these numbers could represent the sides of a triangle. To determine if
the numbers could represent the sides of a triangle we use if- else statement. There is a rule
that says that the sum of the two sides of the triangle has to be greater than the size of the
third side of the triangle for all three combinations of the sides. Otherwise, it is not a triangle.
Step 2
C++ Code:
#include<iostream>
using namespace std;
int main()
{
double a,b,c;
cout << "Please enter three nonzero values: " << endl;
cin >> a >> b >> c;
if((a+b>c))
{
if(a+c>b)
{
if(b+c>a)
cout << "This can be sides of a triangle." <<endl;
else
cout << "This can not be sides of a triangle."<<endl;
}
else
cout << "This can not be sides of a triangle." <<endl;
}
return 0;
}
Output:
4.34
(Sides of a Right Triangle)
C++ Code
The following program prompts the user to input three values and determines and prints out if
this is a right triangle.
#include<iostream>
using namespace std;
int main()
{
int a,b,c;
cout << "Enter three nonzero values: " << endl;
cin >> a >> b >> c;
if(a*a + b*b ==c*c)
{ cout << "This is a right angle triangle." <<endl;
}
else if(a*a+c*c==b*b)
{
cout << "This is a right angle triangle." <<endl;
}
else if(b*b+c*c==a*a)
{
cout << "This is a right angle triangle."<<endl;
}
else
cout << "This is not a right angle triangle." <<endl;
return 0;
}
Output:
4.35
(Factorial)
a)
C++ Code
#include<iostream>
using namespace std;
int main()
{
int n,factorial;
cout<<"Please enter the positive integer: ";
cin>>n;
for(int i=1;i<=n;i++) {
if(i==1) {
factorial=1; }
else
{
factorial*=i; }
}
cout<<n<<"! = "<<factorial<<endl;
return 0;
}
Output:
b)
C++ Code
#include<iostream>
using namespace std;
int main()
{
int n;
double e,term;
cout<<"Please enter the accuracy of e: ";
cin>>n;
for(int i=0;i<n;i++)
{
if(i==0)
{
e=1.0;
}
else
{
for( int j=1;j<=i;j++)
{
if(j==1)
{
term=1.0;
}
else
{
term *=(1.0/j);
}
}
e+=term;
}
}
cout<<"e = "<<e<<endl;
return 0;
}
Output:
4.36
(Modified Account Class)
C++ Code
#include <iostream>
#include <iomanip>
using namespace std;
class Account {
private:
double balance;
public:
Account(double initialBalance) {
if (initialBalance >= 0) {
balance = initialBalance;
} else {
balance = 0;
cout << "Error: Initial balance cannot be negative. Balance set to 0." << endl;
}
}
void credit(double amount) {
balance += amount;
}
void debit(double amount) {
if (amount > balance) {
cout << "Error: Debit amount exceeded account balance." << endl;
} else {
balance -= amount;
}
}
double getBalance() {
return balance;
}
void display() {
cout << "Account balance: $" <<fixed <<setprecision(2) << getBalance() <<endl;
}
};
int main() {
Account account1(100.50);
account1.display();
account1.credit(20.25);
account1.display();
account1.debit(30.75);
account1.display();
return 0;
}
Output:
4.37
(Enforcing Privacy with Cryptography)
C++ Code
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter a four-digit integer: ";
cin >> number;
int a, b, c, d;
a = number / 1000;
b = (number % 1000) / 100;
c = (number % 100) / 10;
d = number % 10;
a = (a + 7) % 10;
b = (b + 7) % 10;
c = (c + 7) % 10;
d = (d + 7) % 10;
return 0;
}
Output:
4.38
(World Population Growth)
C++ Code
#include <iostream>
using namespace std;
int main()
{
double currentPopulation;
double growthRate;
cout << "Enter the current world population: ";
cin >> currentPopulation;
cout << "Enter the growth rate (as a decimal): ";
cin >> growthRate;
cout << "Year\tPopulation\tIncrease" << endl;
for (int year = 1; year <= 75; year++) {
double increase = currentPopulation * growthRate;
currentPopulation += increase;
cout << year << "\t" << currentPopulation << "\t\t" << increase << endl;
}
int doublePopulationYear = 0;
for (int year = 1; year <= 75; year++) {
if (currentPopulation >= 2 * currentPopulation) {
doublePopulationYear = year;
break;
}
}
cout << "The population would be double what it is today in year: " << doublePopulationYear
<< endl;
return 0;
}
Output:
4.39
(School Nutrition Programs)
C++ Code:
#include <iostream>
using namespace std;
int main() {
int servings;
double ingredient1Calories;
double ingredient2Calories;
double ingredient3Calories;
double ingredient4Calories;
double ingredient5Calories;
double totalCalories;
double caloriesPerServing;
4.40
(Homebuilding)
C++ Code:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double height;
double width;
double area;
double volumeOfMortar;
double cementBags;
double bricks;
double wasteMortar = 0.05;
double wasteBricks = 0.025;
while (true) {
cout << "Enter the height of the wall in meters (-1 to exit): ";
cin >> height;
if (height == -1) {
break;
}
cout << "Enter the width of the wall in meters: ";
cin >> width;
area = height * width;
bricks = ceil(area * 104 * (1 + wasteBricks));
volumeOfMortar = ceil(area * 0.00034 * (1 + wasteMortar));
cementBags = ceil(volumeOfMortar * 7);
cout << "Number of bricks required: " << bricks << endl;
cout << "Number of cement bags required: " << cementBags << endl;
}
return 0;
}
Output:
CHAPTER # 5
5.1:
#include <iostream>
using namespace std;
int main()
{
unsigned int counter{1}; // declare and initialize control variable
while (counter <= 10)
{
cout<<counter<<" ";
++counter;
}
cout<<endl;
return 0;
}
Output:
5.2:
#include<iostream>
using namespace std;
int main()
{
for (unsigned int counter{1}; counter <= 10; ++counter)
{
cout << counter << " ";
}
cout<<endl;
return 0;
}
Output:
5.5:
using namespace std;
int main()
{
unsigned int total{0};
for (unsigned int number{2}; number <= 20; number += 2)
{
total+=number;
}
cout << "Sum is " << total << endl;
return 0;
}
Output:
5.6:
#include <iostream>
#include <iomanip>
#include <cmath> // for pow function
using namespace std;
int main()
{
// set floating-point number format
cout << fixed << setprecision(2);
double principal{1000.00}; // initial amount before interest
double rate{0.05}; // interest rate
cout << "Initial principal: " << principal << endl;
cout << " Interest rate: " << rate << endl;
// display headers
cout << "\nYear" << setw(20) << "Amount on deposit" << endl;
// calculate amount on deposit for each of ten years
for (unsigned int year{1}; year <= 10; year++)
{
double amount = principal * pow(1.0 + rate, year);
cout << setw(4) << year << setw(20) << amount << endl;
}
return 0;
}
Output:
5.9:
#include <iostream>
using namespace std;
int main() {
unsigned int counter{1};
do {
cout << counter << " ";
++counter;
} while (counter <= 10); // end do...while
cout << endl;
}
Output:
5.11:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int total{0}; // sum of grades
unsigned int gradeCounter{0}; // number of grades entered
unsigned int aCount{0}; // count of A grades
unsigned int bCount{0}; // count of B grades
unsigned int cCount{0}; // count of C grades
unsigned int dCount{0}; // count of D grades
unsigned int fCount{0}; // count of F grades
cout << "Enter the integer grades in the range 0-100.\n"
<< "Type the end-of-file indicator to terminate input:\n"
<< " On UNIX/Linux/Mac OS X type <Ctrl> d then press Enter\n"
<< " On Windows type <Ctrl> z then press Enter\n";
int grade;
while (cin >> grade) {
total += grade; // add grade to total
++gradeCounter; // increment number of grades
switch (grade / 10) {
case 9: // grade was between 90
case 10: // and 100, inclusive
++aCount;
break; // exits switch
5.13:
#include <iostream>
using namespace std;
int main()
{
unsigned int count; // control variable also used after loop
for (count = 1; count <= 10; count++) { // loop 10 times
if (count == 5) {
break; // terminates loop if count is 5
}
cout << count << " ";
}
cout << "\nBroke out of loop at count = " << count << endl;
}
Output:
5.14:
#include <iostream>
using namespace std;
int main() {
for (unsigned int count{1}; count <= 10; count++) { // loop 10 times
if (count == 5) {
continue; // skip remaining code in loop body if count is 5
}
cout << count << " ";
}
cout << "\nUsed continue to skip printing 5" << endl;
}
Output:
5.18:
#include <iostream>
using namespace std;
int main() {
cout << boolalpha << "Logical AND (&&)"
<< "\nfalse && false: " << (false && false)
<< "\nfalse && true: " << (false && true)
<< "\ntrue && false: " << (true && false)
<< "\ntrue && true: " << (true && true) << "\n\n";
cout << "Logical OR (||)"
<< "\nfalse || false: " << (false || false)
<< "\nfalse || true: " << (false || true)
<< "\ntrue || false: " << (true || false)
<< "\ntrue || true: " << (true || true) << "\n\n";
cout << "Logical negation (!)"
<< "\n!false: " << (!false)
<< "\n!true: " << (!true) << endl;
}
Output:
Exercise Programs
5.1
#include <iostream>
using namespace std;
int main() {
int n, num, smallest;
cout << "Enter the number of values: ";
cin >> n;
cout << "Enter " << n << " integers: ";
cin >> smallest;
for (int i = 2; i <= n; i++) {
cin >> num;
if (num < smallest) {
smallest = num;
}
}
cout << "The smallest integer is: " << smallest << endl;
return 0;
}
Output:
5.12
#include <iostream>
using namespace std;
int main() {
int product = 1;
for (int i = 3; i <= 50; i += 3) {
product *= i;
}
cout << "The product of the multiples of 3 in the range 3 to 50 is: " << product << endl;
return 0;
}
Output:
5.13
#include <iostream>
using namespace std;
int main() {
const int N = 20;
long factorial = 1;
cout << " n n!" << endl;
cout << "--- --------" << endl;
for (int n = 1; n <= N; n++) {
factorial *= n;
cout << n << " " << factorial << endl;
}
return 0;
}
Output:
5.14
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
double amount;
double principal = 1000.0;
int rate;
cout << "Year" << setw(20) << "Amount on deposit" << endl;
cout << fixed << setprecision(2);
for (rate = 5; rate <= 10; rate++) {
cout << "\nInterest rate: " << rate << "%" << endl;
cout << "-----------------" << endl;
for (int year = 1; year <= 10; year++) {
amount = principal * pow(1.0 + static_cast<double>(rate) / 100.0, year);
cout << setw(4) << year << setw(20) << amount << endl;
}
}
return 0;
}
Output:
5.16
#include <iostream>
using namespace std;
int main() {
int num[5];
int i, j;
for (i = 0; i < 5; i++) {
do {
cout << "Enter a number between 1 and 9: ";
cin >> num[i];
} while (num[i] < 1 || num[i] > 9);
}
for (i = 0; i < 5; i++) {
for (j = 0; j < num[i]; j++) {
cout << num[i];
}
cout << endl;
for (j = 0; j < num[i]; j++) {
cout << num[i];
}
cout << endl << endl;
}
return 0;
}
Output:
5.17
#include <iostream>
using namespace std;
int main() {
const double PRODUCT1_PRICE = 2.98;
const double PRODUCT2_PRICE = 4.50;
const double PRODUCT3_PRICE = 9.98;
const double PRODUCT4_PRICE = 4.49;
const double PRODUCT5_PRICE = 6.87;
int productNumber;
int quantitySold;
double totalSales = 0.0;
cout << "Enter product number and quantity sold (-1 to exit):" << endl;
cin >> productNumber;
while (productNumber != -1) {
cin >> quantitySold;
switch (productNumber) {
case 1:
totalSales += PRODUCT1_PRICE * quantitySold;
break;
case 2:
totalSales += PRODUCT2_PRICE * quantitySold;
break;
case 3:
totalSales += PRODUCT3_PRICE * quantitySold;
break;
case 4:
totalSales += PRODUCT4_PRICE * quantitySold;
break;
case 5:
totalSales += PRODUCT5_PRICE * quantitySold;
break;
default:
cout << "Invalid product number. Please try again." << endl;
break;
}
cout << "Enter product number and quantity sold (-1 to exit):" << endl;
cin >> productNumber;
}
cout << "Total sales: $" << totalSales << endl;
return 0;
}
Output:
5.20
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int side1, side2, hypotenuse;
for (side1 = 1; side1 <= 500; side1++) {
for (side2 = 1; side2 <= 500; side2++) {
for (hypotenuse = 1; hypotenuse <= 500; hypotenuse++) {
if (pow(side1, 2) + pow(side2, 2) == pow(hypotenuse, 2)) {
cout << side1 << "\t" << side2 << "\t" << hypotenuse << endl;
}
}
}
}
return 0;
}
Output:
5.21
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; ++i) {
for (int j = 1; j <= i; ++j) {
cout << "*";
}
for (int k = 10; k > i; --k) {
cout << " ";
}
for (int j = 10; j > i; --j) {
cout << " ";
}
for (int k = 1; k <= i; ++k) {
cout << "*";
}
for (int j = 1; j < i; ++j) {
cout << " ";
}
for (int k = 10; k >= i; --k) {
cout << "*";
}
for (int j = 1; j < i; ++j) {
cout << " ";
}
for (int k = 1; k <= i; ++k) {
cout << " ";
}
for (int j = 10; j >= i; --j) {
cout << "*";
}
for (int k = 1; k < i; ++k) {
cout << " ";
}
for (int j = 1; j <= i; ++j) {
cout << "*";
}
cout << endl;
}
return 0;
}
Output:
5.23
#include <iostream>
using namespace std;
int main() {
const int HEIGHT = 9;
const int WIDTH = 21;
for (int row = 0; row < HEIGHT; row++) {
for (int col = 0; col < WIDTH; col++) {
if (row == 0 || row == HEIGHT - 1 || col == 0 || col == WIDTH - 1) {
cout << "#";
} else if (col >= row && col < WIDTH - row) {
cout << "*";
} else {
cout << " ";
}
}
cout << endl;
}
return 0;
}
Output:
5.24
#include <iostream>
using namespace std;
int main() {
int height;
do {
cout << "Enter an odd number in the range 1-29: ";
cin >> height;
} while (height % 2 == 0 || height < 1 || height > 29);
int halfHeight = height / 2;
for (int i = 0; i <= halfHeight; i++) {
for (int j = 0; j < i; j++) {
cout << " ";
}
for (int j = 0; j < (height - 2 * i); j++) {
cout << "*";
}
cout << endl;
}
for (int i = halfHeight - 1; i >= 0; i--) {
for (int j = 0; j < i; j++) {
cout << " ";
}
for (int j = 0; j < (height - 2 * i); j++) {
cout << "*";
}
cout << endl;
}
return 0;
}
Output:
5.28
#include <iostream>
using namespace std;
int main() {
string days[12] = {"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth",
"ninth", "tenth", "eleventh", "twelfth"};
string gifts[12] = {"a Partridge in a Pear Tree.", "Two Turtle Doves", "Three French Hens",
"Four Calling Birds", "Five Gold Rings", "Six Geese-a-Laying", "Seven Swans-a-Swimming", "Eight
Maids-a-Milking", "Nine Ladies Dancing", "Ten Lords-a-Leaping", "Eleven Pipers Piping",
"Twelve Drummers Drumming"};
for(int i=0; i<12; i++) {
cout << "On the " << days[i] << " day of Christmas, my true love gave to me:" << endl;
for(int j=i; j>=0; j--) {
switch(j) {
case 0:
if(i == 0) {
cout << "a Partridge in a Pear Tree." << endl;
} else {
cout << "and a Partridge in a Pear Tree." << endl;
}
break;
default:
cout << gifts[j] << endl;
break;
}
}
}
return 0;
}
Output:
5.29
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double principal = 24.00;
int years = 390;
double amount;
for(double rate=0.05; rate<=0.10; rate+=0.01) {
amount = principal * pow(1.0 + rate, years);
double interest = amount - principal;
cout << "Interest rate: " << rate*100 << "%" << endl;
cout << "Interest earned: $" << interest << endl;
cout << "Total amount: $" << amount << endl << endl;
}
return 0;
}
Output:
5.36
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double num = 123.02;
cout << setprecision(15) << num << endl;
cout << setprecision(16) << num << endl;
cout << setprecision(17) << num << endl;
return 0;
}
Output:
5.37
#include <iostream>
#include <string>
using namespace std;
int main() {
int score = 0;
string answer;
cout << "Question 1: What is global warming?\n";
cout << "1. An increase in the Earth's average temperature caused by human activities.\n";
cout << "2. A natural cycle of the Earth's climate that has been occurring for millions of
years.\n";
cout << "3. A hoax perpetrated by the government to control people.\n";
cout << "4. None of the above.\n";
cout << "Answer: ";
getline(cin, answer);
if (answer == "1") {
score++;
}
cout << "Question 2: What are some of the main causes of global warming?\n";
cout << "1. Deforestation and the burning of fossil fuels.\n";
cout << "2. Natural events such as volcanic eruptions and solar activity.\n";
cout << "3. Cow farts and other animal emissions.\n";
cout << "4. None of the above.\n";
cout << "Answer: ";
getline(cin, answer);
if (answer == "1") {
score++;
}
cout << "Question 3: What are some of the effects of global warming?\n";
cout << "1. Rising sea levels, melting glaciers, and more frequent and severe natural
disasters.\n";
cout << "2. No significant effects, as global warming is not a real issue.\n";
cout << "3. More pleasant weather and longer growing seasons.\n";
cout << "4. None of the above.\n";
cout << "Answer: ";
getline(cin, answer);
if (answer == "1") {
score++;
}
cout << "Question 4: What can individuals do to help reduce global warming?\n";
cout << "1. Use public transportation, switch to energy-efficient light bulbs, and reduce meat
consumption.\n";
cout << "2. Nothing, as individual actions have no impact on global warming.\n";
cout << "3. Use more plastic bags and drive more cars.\n";
cout << "4. None of the above.\n";
cout << "Answer: ";
getline(cin, answer);
if (answer == "1") {
score++;
}
cout << "Question 5: What is the scientific consensus on global warming?\n";
cout << "1. The vast majority of scientists agree that global warming is real and caused by
human activities.\n";
cout << "2. Scientists are evenly split on the issue.\n";
cout << "3. There is no scientific consensus on the issue.\n";
cout << "4. None of the above.\n";
cout << "Answer: ";
getline(cin, answer);
if (answer == "1") {
score++;
}
cout << "\nYour score is " << score << " out of 5.\n";
if (score == 5) {
cout << "Excellent!\n";
} else if (score == 4) {
cout << "Very good.\n";
} else {
cout << "Time to brush up on your knowledge of global warming.\n";
cout << "Some websites for further reading:\n";
cout << "- https://www.climate.gov/\n";
cout << "- https://www.epa.gov/climate-change-science/\n";
cout << "- https://climate.nasa.gov/\n";
}
return 0;
}
Output:
5.38
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const double FAIRTAX_RATE = 0.23;
int main() {
double housing, food, clothing, transportation, education, healthCare, vacations;
double totalExpenses, fairTax;
cout << "Enter your expenses in the following categories:\n";
cout << "Housing: $";
cin >> housing;
cout << "Food: $";
cin >> food;
cout << "Clothing: $";
cin >> clothing;
cout << "Transportation: $";
cin >> transportation;
cout << "Education: $";
cin >> education;
cout << "Health care: $";
cin >> healthCare;
cout << "Vacations: $";
cin >> vacations;
totalExpenses = housing + food + clothing + transportation + education + healthCare +
vacations;
fairTax = totalExpenses * FAIRTAX_RATE;
cout << fixed << setprecision(2);
cout << "\nTotal expenses: $" << totalExpenses << endl;
cout << "Estimated FairTax: $" << fairTax << endl;
return 0;
}
Output:
5.39
#include <iostream>
#include <string>
using namespace std;
int main() {
const int MAX_PAIRS = 5;
double exchangeRates[MAX_PAIRS];
string currencies[MAX_PAIRS];
string currency;
double rate;
int numPairs = 0;
while (numPairs < MAX_PAIRS) {
cout << "Enter a currency (or x to quit): ";
cin >> currency;
if (currency == "x") {
break;
}
cout << "Enter the exchange rate for 1 unit of " << currency << ": ";
cin >> rate;
currencies[numPairs] = currency;
exchangeRates[numPairs] = rate;
numPairs++;
}
double dollars;
cout << "Enter a dollar amount: ";
cin >> dollars;
for (int i = 0; i < numPairs; i++) {
double amount = dollars * exchangeRates[i];
cout << "Equivalent value in " << currencies[i] << ": " << amount << endl;
}
return 0;
}
Output:
Chapter # 7
Program 7.1
Write a program that inputs five integers from the user and stores them in an array. It then
displays all values in the array without using loops
Solution:
#include <iostream>
Using namespace std;
int main()
{
int arr[5)
cout<<"Enter five integers:” endl;
cin>>arr[0];
cin>>arr[1];
cin>>arr[2];
cin>>arr[3];
cin>>arr[4];
cout<<"The values in array are:\n”;
cout<<arr[0]<<endl;
cout<<arr[1]<<endl;
cout<<arr[2]<<endl;
cout<<arr[3]<<endl;
cout<<arr[4]<<end;
return 0;
}
Program 7.2
Write a program that inputs five integers from the user and stores them in an array. It then
display all values in the array using loops
Solution:
#include<iostream>
using namespace std;
int main()
{
int arr[5],i;
for(i=0; i<5; i++)
{
cout<<"enter an integar:";
cin>>arr[i];
}
cout<<"the values in array are:\n";
for(i=0; i<5; i++)
cout<<arr[i]<<endl;
return 0;
} Output:
Program 7.3
Write a program that inputs five integars from the user and stores them in an array.It then
displays all the values in the array using loops.
Solution:
#include<iostream>
using namespace std;
int main()
{
int arr[5],i, sum=0;
float avg = 0.0;
for(i=0; i<5; i++)
{
cout<<"Enter value:";
cin>>arr[i];
sum=sum + arr[i];
}
avg=sum/5.0;
cout<<"sum is"<<sum<<endl;
cout<<"average is"<<avg;
return 0;
} Output:
Program 7.4
Write a program that inputs current day and month from the user. It then calculates and
displays the total number of days in the current year till the entered date.
Solution:
#include<iostream>
using namespace std;
int main()
{
int day,month,total;
int days_per_month[12]={31,28,31,30,31,30,31,31,30,31,30,31};
cout<<"Enter the month number:";
cin>>month;
cout<<"enter the day number:";
cin>>day;
total=day;
for(int x=0; x<month-1; x++)
total += days_per_month[x];
cout<<"the number of days in this year till date =<< total <<endl:";
return 0;
} Output:
Program 7.5
Write a program that inputs the age of different persons and counts the number of persons in
the age group 50 and 60.
Solution:
#include<iostream>
using namespace std;
int main()
{
int age[150],i,n,count=0;
cout<<"enter the number of persons required";
cin>>n;
cout<<"enter ages of""<<n<<persons."<<endl;
for(i=0; i<n; i++)
{
cin>>age[i];
if(age[i]>=50 && age[i]<=60)
count=count + 1;
}
cout<<count<<"persons are in between 50 and 60:";
return 0;
} Output:
Programme 7.6
Write a program that uses four arrays numbers, squares, cubes and sums each consisting of 5
elements. The numbers array stores the value of its indexes, the squares array stores the
squares of its indexes, the cubes array stores the cubes of its indexes and sums array stores the
sum of corresponding indexes of three arrays. The program should display the values of all
arrays and the total of all values in sums array.
Solution:
#include<iostream>
using namespace std;
int main()
{
const int size = 5;
int numbers[size];
int squares[size];
int cubes[size];
int sums[size];
// store the numbers in the arrays
for(int i=0; i<size; i++)
{
numbers[i]=i;
squares[i]=i*i;
cubes[i]=i*i*i;
sums[i]=numbers[i]+squares[i]+cubes[i];
}
//output the sums array and add up all the sums...
int total = 0;
cout<<"numbers:\t";
for(i=0; i<size; i++)
cout<<numbers[i]<<"\t";
cout<<endl;
cout<<"squares:\t";
for(i=0; i<size; i++)
cout<<squares[i]<<"\t";
cout<<endl;
cout<<"cubes:\t\t;"
for(i=0; i<size; i++)
cout<<cubes[i]<<"\t";
cout<<endl;
cout<<"sums:\t\t";
for(i=0; i<size; i++)
{
cout<<sums[i]<<"\t";
total = total + sums[i];
}
Cout<<endl;
cout << "Grand total:"<<total<<endl;
return 0;
}
Program 7.7
Write a program that inputs ten numbers from the user in an array and displays the maximum
number.
Solution:
#include <iostream>
using namespace std;
int main()
{
int arr[10], i, max;
for(i=0; i<10; i++)
{
cout<<"Enter value: ";
cin>>arr[i];
}
max=arr[0];
for(i=0; i<10; i++)
if(max < arr[i])
max = arr[i];
cout<<"maximum value:"<<max;
return 0;
} Output:
Program 7.8
Write a program that inputs ten numbers from the user in an array and displays the minimum
number.
Solution:
#include <iostream>
using namespace std;
int main()
{
int arr[10],i,min;
for(i=0; i<10; i++)
{
cout<<"Enter value:";
cin>>arr[i];
}
min=arr[0];
for(i=0; i<10; i++)
if(min > arr[i])
min = arr[i];
cout<<"Minimun value: "<<min;
return 0;
} Output:
Program 7.9
Write a program that inputs five numbers in an array and displays them in actual and reverse
order.
Solution:
#include <iostream>
using namespace std;
int main ()
{
int num[5], i;
for(i=0; i<5; i++)
{
cout<<"Enter an integer: ";
cin>>num[i];
}
cout<<"\n The array in actual order:\n";
for(i=0; i<5; i++)
cout<<num[i]<<" ";
cout<<"\n The array in reverse order:\n";
for(i=4; i>=0; i--)
cout<<num[i]<<"";
return 0;
} Output:
Program 7.10
Write a program that initializes an array. It inputs a value from the user and searches the
number in the array.
Solution:
#include <iostream>
using namespace std;
int main()
{
int arr[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int i, n, loc =- 1;
cout<<"Enter value to find:";
cin>>n;
for(i=0; i<10; i++)
if(arr[i] == n)
loc = i;
if(loc == -1)
cout<<"Value not found in the array:";
else
cout<<"Value found at index"<<loc;
return 0;
} Output:
Program 7.11
Write a program that initializes an array of ten integers. It inputs an integer from the user and
searches the value in the array using binary search.
Solution:
#include <iostream>
using namespace std;
int main()
{
int arr[10]={10,20,30,40,50,60,70,80,90,100};
int n, i, mid, start, end, loc;
loc = -1;
start = 0;
end = 9;
cout<<"Enter any number to find:";
cin>>n;
while(start<=end)
{
mid = (start + end)/2;
if(arr[mid] == n)
{
loc = mid;
break;
}
else if(n<arr[mid])
end = mid - 1;
else
start = mid + 1;
}
if(loc == -1)
cout<<n<<"not found"<<endl;
else
cout<<n<<"found at index"<<loc<<endl;
return 0;
}
Output:
Program 7.12
Write a program that gets five inputs from the user in an array and then sorts this array in
ascending order.
Solution:
#include <iostream>
using namespace std;
int main()
{
int arr[5], i, j, min, temp;
for(i=0; i<5; i++)
{
cout<<"Enter value:";
cin>>arr[i];
}
cout<<"The original values in array:\n";
for(i=0; i<5; i++)
cout<<arr[i]<<" ";
for(i=0; i<4; i++)
{
min = i;
for(j=i+1; j<5; j++);
if(arr[j] < arr[min])
min = j;
if(min !=i)
{
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
cout<<"\nThe sorted array:\n";
for(i=0; i<5; i++)
cout<<arr[i]<<" ";
return 0;
}
Output:
Program 7.13
Write a program that stores five values in an array. It sorts the array using buble sort. It also
displays the values of unsorted and sorted array.
Solution:
#include <iostream>
using namespace std;
int main()
{
int arr[5], i, j, temp;
for(i=0; i<5; i++)
{
cout<<"enter value: ";
cin>>arr[i];
}
cout<<"The original values in array:\n";
for(i=0; i<5; i++)
cout<<arr[i]<<" ";
for(i=0; i<5; i++)
for(j=0; j<4; j++)
if(arr[j]>arr[j+1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
cout<<"\n The Sorted array:\n";
for(i=0; i<5; i++)
cout<<arr[i]<<" ";
return 0;
}
Output:
Program 7.14
Write a program that stores integer values in an array of 2 rows and 4 columns.
Solution:
#include <iostream>
using namespace std;
int main()
{
int arr[2][4],i,j;
for(i=0; i<2; i++)
for (j=0; j<4; j++)
{
cout<<"Enter an integer:";
cin>>arr[i][j];
}
for(i=0; i<2; i++)
{
for(j=0; j<4; j++)
cout<<arr[i][j]<<"\t";
cout<<endl;
}
return 0;
}
Output:
Program 7.15
Write a program that initializes a two dimensional array of 2 rows and 3 columns and
then displays its values.
Solution:
#include <iostream>
using namespace std;
int main()
{
int i,j, arr[2][3]= {15,21,9,84,33,72};
for(i=0; i<2; i++)
{
for(j=0; j<3; j++)
cout<<"arr["<<i<<"]["<<j<<"] = "<<arr[i][j]<<"\t";
cout<<endl;
}
return 0;
}
Output:
Program 7.16
Write a program that initializes a two-dimensional array of 2 rows and 4 columns and then
displays the minimum and maximum number in the array.
Solution:
#include <iostream>
using namespace std;
int main()
{
int i, j, max, min;
int arr [2][4] = {{15,21,9,84},{33,72,18,47}};
max = min = arr[0][0];
for(i=0; i<2; j++)
for(j=0; j<4; j++)
{
if(arr[i][j] > max)
max = arr[i][j];
if(arr[i][j] < min)
min = arr[i][j];
}
cout<<"Maximum= "<<max<<endl<<"Minimum = "<<min<<endl;
return 0;
}
Exercise Programs
7.1
Program:
#include <iostream>
using namespace std;
int main() {
int roll[5], marks[5], maxMarks = -1, maxRoll = 0;
cout << "Enter roll numbers and marks of five students:" << endl;
for (intcsSs i = 0; i < 5; i++) {
cout << "Student " << i + 1 << ": ";
cin >> roll[i] >> marks[i];
if (marks[i] > maxMarks) {
maxMarks = marks[i];
maxRoll = roll[i];
}
}
cout << endl << "Student with highest marks: Roll number = " << maxRoll << ", Marks = " <<
maxMarks;
return 0;
}
Output:
7.2
Program:
#include <iostream>
using namespace std;
int main() {
int roll[5], marks[5], maxMarks = -1, maxRoll = 0;
cout << "Enter roll numbers and marks of five students:" << endl;
for (int i = 0; i < 5; i++) {
cout << "Student " << i + 1 << ": ";
cin >> roll[i] >> marks[i];
if (marks[i] > maxMarks) {
maxMarks = marks[i];
maxRoll = roll[i];
}
}
cout << endl << "Student with highest marks: Roll number = " << maxRoll << ", Marks = " <<
maxMarks;
return 0;
}
Output:
7.3
Program:
#include <iostream>
using namespace std;
int main() {
const int SIZE = 10;
int numbers[SIZE], squares[SIZE], cubes[SIZE], sums[SIZE], totalSum = 0;
for (int i = 0; i < SIZE; i++) {
numbers[i] = i;
squares[i] = i * i;
cubes[i] = i * i * i;
}
for (int i = 0; i < SIZE; i++) {
sums[i] = numbers[i] + squares[i] + cubes[i];
totalSum += sums[i];
}
cout << "Sum array values: ";
for (int i = 0; i < SIZE; i++) {
cout << sums[i] << " ";
}
cout << endl << "Total sum: " << totalSum;
return 0;
}
Output:
7.4
Program:
#include <iostream>
#include <string>
using namespace std;
int main() {
const int NUM_EMPLOYEES = 10;
string names[NUM_EMPLOYEES];
double monthlySalaries[NUM_EMPLOYEES];
for (int i = 0; i < NUM_EMPLOYEES; i++) {
cout << "Enter name and monthly salary for employee " << i+1 << ": ";
cin >> names[i] >> monthlySalaries[i];
}
for (int i = 0; i < NUM_EMPLOYEES; i++) {
double annualSalary = monthlySalaries[i] * 12.0;
cout << names[i] << " has an annual salary of Rs " << annualSalary << " - ";
if (annualSalary >= TAX_THRESHOLD) {
cout << "Tax to be paid." << endl;
} else {
cout << "No tax." << endl;
}
}
return 0;
}
Output:
7.5
Program:
#include <iostream>
using namespace std;
int main() {
int arr[10];
int count[10] = {0};
for (int i = 0; i < 10; i++) {
cout << "Enter integer " << i+1 << ": ";
cin >> arr[i];
}
for (int i = 0; i < 10; i++) {
count[arr[i]]++;
}
for (int i = 0; i < 10; i++) {
if (count[i] > 0) {
cout << i << " is stored " << count[i] << " time(s) in array" << endl;
}
}
return 0;
}
Output:
7.6
#include <iostream>
using namespace std;
int main() {
int marks[10], countA = 0, countB = 0, countC = 0, countF = 0;
for (int i = 0; i < 10; i++) {
cout << "Enter the marks for student " << i+1 << ": ";
cin >> marks[i];
if (marks[i] >= 80) {
countA++;
} else if (marks[i] >= 60) {
countB++;
} else if (marks[i] >= 40) {
countC++;
} else {
countF++;
}
}
cout << "\nNumber of students with grade A: " << countA << endl;
cout << "Number of students with grade B: " << countB << endl;
cout << "Number of students with grade C: " << countC << endl;
cout << "Number of students with grade F: " << countF << endl;
return 0;
}
Output:
7.8
#include <iostream>
using namespace std;
int main()
{
const int SIZE = 10; // size of the array
float nums[SIZE]; // array to hold floating point numbers
float sum = 0, average;
// input the numbers and calculate the sum
for (int i = 0; i < SIZE; i++)
{
cout << "Enter a number: ";
cin >> nums[i];
sum += nums[i];
}
average = sum / SIZE;
cout << "The numbers greater than the average (" << average << ") are: ";
for (int i = 0; i < SIZE; i++)
{
if (nums[i] > average)
{
cout << nums[i] << " ";
}
}
return 0;
}
Output:
7.9
Program:
#include <iostream>
using namespace std;
int main() {
int scores[5][5] = {
{75, 80, 90, 85, 70},
{65, 70, 80, 75, 85},
{80, 75, 85, 90, 95},
{95, 90, 80, 85, 70},
{70, 75, 85, 90, 95}
};
int row, student;
cout << "Enter row number (1-5): ";
cin >> row;
cout << "Enter student number in row " << row << " (1-5): ";
cin >> student;
cout << "Score of student " << student << " in row " << row << " is: " << scores[row-1][student-
1] << endl;
return 0;
}
Output:
THE END