University of Bahrain: 1.1 Creating A C++ Program
University of Bahrain: 1.1 Creating A C++ Program
University of Bahrain: 1.1 Creating A C++ Program
University of Bahrain
College of Information Technology
Department of Computer Science
CSC100/ITCS101 Introduction to Computers and IT
#i n c l u d e <i o s t r e a m >
using namespace s t d ;
int main ( )
{
c o u t << ”Welcome t o C++ Programming . ” << e n d l ” ;
return 0;
}
Output:
Welcome to C++ Programming.
2. #include <iostream>
It is a directive to the C++ preprocessor. This directive tells the preprocessor to include header file
contains information and declarations used by the compiler when compiles standard input/output library
functions such as cout.
int main()
{
statement 1;
.
.
statement n;
return 0;
}
u s i n g namespace s t d ;
i n t main ( )
{
i n t f i r s t , second , t o t a l ; // d e c l a r a t i o n
f i r s t = 34;
second = 1 9 ;
t o t a l = f i r s t + second ;
return 0;
}
Output:
34 + 19 = 53
• The value of expression should match the data type of the variable.
• The expression on the right side is evaluated and its value is assigned to the variable on the left side.
#i n c l u d e <i o s t r e a m >
#i n c l u d e <s t r i n g >
using namespace s t d ;
int main ( )
{
int i , j ;
double s a l e ;
char f i r s t ;
string str ;
i = 4;
c o u t << ” i = ” << i << e n d l ;
j = 4 ∗ 5 − 11;
c o u t << ” j = ” << j << e n d l ;
s al e = 0.02 ∗ 1000;
c o u t << ” s a l e = ” << s a l e << e n d l ;
f i r s t = ’D ’ ;
c o u t << ” f i r s t = ” << f i r s t << e n d l ;
s t r = ” I t i s a sunny day . ” ;
c o u t << ” s t r = ” << s t r << e n d l ;
return 0 ;
}
Output:
i=4
j=9
sale = 20
first = D
str = It is a sunny day.
Example 9 Write a program that reads two integers and prints their sum on screen.
// A d d i t i o n program
#i n c l u d e <i o s t r e a m >
using namespace s t d ;
int main ( )
{
int i n t e g e r 1 , i n t e g e r 2 , sum ; // d e c l a r a t i o n
sum = i n t e g e r 1 + i n t e g e r 2 ; // a s s i g n m e n t o f sum
Output:
Enter first integer 23
Enter second integer -12
Sum is 11
Example 10 Write a program that converts a distance measure from Miles to Kilometers. Note that one mile
is equal to 1.609 centimeters.
// C o n v e r t s d i s t a n c e s from m i l e s t o k i l o m e t e r s .
#i n c l u d e <i o s t r e a m >
using namespace s t d ;
int main ( )
{
double m i l e s , kms ; // d e c l a r a t i o n
// Get t h e d i s t a n c e i n m i l e s .
c o u t << ” Enter t h e d i s t a n c e i n m i l e s > ” ;
c i n >> m i l e s ;
// Convert t h e d i s t a n c e t o k i l o m e t e r s .
kms = m i l e s ∗ 1 . 6 0 9 ;
// D i s p l a y t h e d i s t a n c e i n k i l o m e t e r s .
c o u t << ”That e q u a l s ” << kms << ” k i l o m e t e r s ” << e n d l ;
Output:
Enter the distance in miles> 45.9
That equals 73.8531 kilometers
Example 11 Suppose a, b, and c are int and a = 5 and b = 6. What value is assigned to each variable
after each statement executes?
a = (b++) + 3; // a = 9 b = 7 c = 8
c = 2 * a + (++b); // a = 9 b = 8 c = 26
b = 2 * (++c) - (a++); // a = 10 b = 45 c = 27
Example 13
(a) Suppose a, b, and sum are int and c is a double variable. What value is assigned to each variable after
each statement executes? Suupose a = 3, b = 5, and c = 14.1
1.15 Exercises
1. Write a program that converts a distance measure from inches to cents. Note that one inch is equal to
2.54 centimeters?
2. Write a program to convert a temperature in degrees Fahrenheit to degrees Celsius.
3. tudents are awarded points toward their grades based upon the average of three quizzes (Q1 , Q2 , Q3 ), the
midterm exam (M T ), and half the final exam (F inal). Quizzes are on scale from 0 to 100, the midterm
is on scale from 0 to 50, and the final is on scale from 0 to 100. Compute the total points using a C++
program and print the result out of 100.
4. ABC Phone Company, Inc., charges for phone calls by distance (miles) and length of time (minutes). The
cost of a call (in Bahrain Dinar) is computed as 30% of the call weight, where the call weight is computed
by adding the time with 5% of the distance.
Design a C++ program that reads the distance and length of time for three phone calls. The program
must calculate and display the cost for each of the three calls and the total cost of all three calls.
A sample Input/Output of your program is shown below.
5. Write a program to read three resistance values R1 , R2 , and R3 in Ohms and compute their combined
resistance Rc when they are arranged in parallel. The value of Rc is computed using the following formula.
1
Rc =
1 1 1
+ +
R1 R2 R3
Your program should print the values of R1 , R2 , R3 and Rc .
For example, if R1 = 2.3 Ohms, R2 = 6.21 Ohms, and R3 = 4.58 Ohms, then Rc = 1.228269131 Ohms.
6. One large chemical company pays its salespeople on a commission basis. The salespeople receive BD.
75/600 per week plus 9% of their gross sales for that week. For example, a salesperson who sells BD.
1890/— worth of chemicals in a week receives BD. 75/600 plus 9% of 1890/—, or a total of 75/600 +
170/100 = 245/700. Develop a program that will input each salesperson’s gross sales for last week and
will calculate and display that salesperson’s earnings?
7. The Perimeter, Surface Area, and Volume of an in-ground pool are given by the following formulas:
Using these formulas as a basis, write a C++ program that accepts the length, width, and depth mea-
surements and then calculates the perimeter, volume, and surface area of the pool.
8. The volume of oil stored in an underground 200-foot-deep cylindrical tank is determined by measuring
the distance from the top of the tank to the surface of the oil. Knowing this distance and the radius of
the tank the volume of oil in the tank can be determined using the formula:
Using this formula, write a C++ program that accepts the radius and the distance measures, calculates
the volume of the oil in the tank, and displays the two input values and calculates the volume.
2 Input/Output
2.1 I/O Streams and Standard I/O Devices
Input stream: A sequence of characters from an input device (keyboard, file) to the computer.
Output stream: A sequence of characters from the computer to the output device (screen, printer).
• Once the precision is determined, it is changed until a similar subsequent statement changes the precision.
• showpoint is used to force the output to show the decimal point and trailing zeros.
Example: cout << fixed << showpoint;
• setw(n) is used to output the value of an expression in a specified number of columns. The output is
by default right-justified.
Example: cout << setw(5) << x << endl;
• setfill(ch) is used to fill the unused columns in setw() with a character other than a space.
Example: cout << setfill(’-’) << setw(5) << x << endl;
• left is used to left-justified the output of setw(). The output is by default right-justified.
Example: cout << left << setw(5) << "Hi" << endl;
• right is used to right-justified the output of setw(). The output is by default right-justified.
Example: cout << right << setw(5) << "Hi" << endl;
c o u t << s e t f i l l ( ’− ’ ) ;
c o u t << l e f t << setw ( 2 6 ) << ” Gross amount ”
<< r i g h t << setw ( 1 0 ) << s a l e
<< e n d l ;
c o u t << l e f t << setw ( 2 6 ) << ” Medicare / Mediaid Tax ”
<< r i g h t << setw ( 1 0 ) << 0 . 0 2 7 5 ∗ s a l e
<< e n d l ;
Output:
Gross amount ---------------1890.700
Medicare/Mediaid Tax ---------51.994
Pension Plan ----------------113.442
Health Insurance -------------75.000
using namespace s t d ;
int main ( )
{
// D e c l a r e f i l e stream v a r i a b l e s such as t h e f o l l o w i n g
i f s t r e a m inData ;
o f s t r e a m outData ;
.
.
// Open t h e f i l e s
inData . open ( ” c : \ \ prog . dat ” ) ;
outData . open ( ” c : \ \ prog . out ” ) ;
// Code f o r d a t a m a n i p u l a t i o n
// C l o s e t h e f i l e s
inData . c l o s e ( ) ;
outData . c l o s e ( ) ;
return 0 ;
}
using namespace s t d ;
int main ( )
{
ifstream inFile ;
ofstream outFile ;
double t e s t 1 , t e s t 2 , t e s t 3 , t e s t 4 , t e s t 5 ;
double a v e r a g e ;
s t r i n g f i r s t N a m e , lastName ;
i n F i l e . open ( ” t e s t . t x t ” ) ;
o u t F i l e . open ( ” t e s t a v g . t x t ” ) ;
average = ( t e s t 1 + t e s t 2 + t e s t 3 + t e s t 4 + t e s t 5 ) / 5 . 0 ;
Input File
2.4 Exercises
1. Write a program to calculate the property tax. Property tax is calculated on 92% of the assessed value of
the property. For example, if the assessed value is $100000, the property tax is on $92000. Assume the
property tax is $1.05 for each $100 of the assessed value. Your program should prompt the user to enter
the assessed value of the property.
A sample Input/Output Screen.
2. Write a program that calculates and prints the monthly paycheck for an employee. The net pay is
calculated after the following deductions:
• Medicare/Medicaid Tax: 2.75%
• Pension Plan: 6%
• Health Insurance: BD. 75
Your program should prompt the user to enter the gross amount and print the net pay. A sample
Input/Output is shown below:
3. The manager of a football stadium wants you to write a program that calculates the total ticket sales for
a game. There are four types of tickets – Box, Sideline, Premium, and general Admission. Data is stored
as shown below:
250 5750
100 28000
50 35750
25 18750
The first line indicates the ticket price is $250 and that 5750 tickets were sold at that price. Output the
number of tickets sold and the total sale amount. Format your output with two decimal places.
Example 19 If student’s grade is greater than or equal to 60, then print “Passed”, otherwise print “Failed”
In C++, the above statement may be written as
if ( grade >= 60 )
cout << "Passed\n";
else
cout << "Failed\n";
Example 20 Write a program to read an integer value, then accordingly determine if it is positive or negative?
#include <i o s t r e a m >
using namespace s t d ;
int main ( )
{
int number ;
c o u t << ” Enter an i n t e g e r ? ” ;
c i n >> number ;
i f ( number >= 0 )
c o u t << number << ” i s p o s i t i v e \n” ;
else
return 0;
}
{
Statement 1;
Statement 2;
...
}
2. if ( numItems == 0 )
cout << "Invalid number of items.\n";
else
{
average = sum / numItems;
cout << "Average is " << average << "\n";
}
3. if ( transType == ’c’ )
{
cout << "Check for " << transAmount << endl;
balance = balance - transAmount;
}
else
{
cout << "Deposite of " << transAmount << endl;
balance = balance + transAmount;
}
if ( x >= 0 ) if ( x > 0 )
numPos = numPos + 1; numPos = numPos + 1;
else else if ( x < 0 )
if ( x < 0 ) numNeg = numNeg + 1;
numNeg = numNeg + 1; else
else numZero = numZero + 1;
numZero = numZero + 1;
Example 22 The table below describes the assignment of grades based on an exam score.
Write a program segment to print the grade, according to the exam score?
if ( score >= 90 )
cout << "A";
else if ( score >= 80 )
cout << "B";
else if ( score >= 70 )
cout << "C";
else if ( score >= 60 )
cout << "D";
else
cout << "F";
2. Display one of five messages based on the value next char (type char).
If next char = ‘a’ or ‘A’ display “Excellent”.
If next char = ‘b’ or ‘B’ display “Good”.
If next char = ‘c’ or ‘D’ display “O.K.”.
If next char = ‘d’ or ‘D’ or ‘f’ or ‘F’
Other value display “Invalid letter grade”. display “Student on probation.”.
switch (next_char)
{
case ’a’: case ’A’:
cout << "Excellent.);
break;
case ’b’: case ’B’:
cout << "Good.";
break;
case ’c’: case ’C’:
cout << "O.K.";
break;
case ’d’: case ’D’: case ’f’: case ’F’:
cout << "Student on probation.";
break;
default: cout << "Invalid letter grade.";
}
3.9 Exercises
1. Write a program to find the ideal weight for a given height. The height must be given in centimeters
between 140 cm and 240 cm. The ideal weight is the height minus 100. Before calculating the height
check that the input is valid?
2. ACE balloon shop sells balloons to customers at 10 fils each. If the customer buys 500 − 1000 balloons,
the price is 8 fils each. If the customer buys over 1000 balloons, the price is 6 fils each. Write a program
that reads the number of balloons to purchase and prints the amount of the bill?
3. A part time employee is paid BD. 2/000 per hour for the first 20 hours in a week. Additional hours are
paid BD. 2/500 per hour. In addition the company deducts 5% of the total weekly income for health
insurance. Find how much (s)he will be paid for any given number of hours?
4. The Pythagorean theorem states that the sum of squares of the sides of a right triangle is equal to the
square of the hypotenuse. For example, if two sides of a triangle have lengths of 3 and 4, then the
hypotenuse must have a length of 5. Together the integers 3, 4, and 5 form a Pythagorean triple. There
are an infinite number of such triples. Given two positive integers, m and n, where m > n, a Pythagorean
triple can be generated by the following formulas:
side1 = m2 − n2
side2 = 2mn
hypotenuse = m2 + n2
Write a program that takes values for m and n as input and displays the values of the Pythagorean triple
generated by the formula above?
5. In this problem you are required to write a program that solves for the values of x and y in the following
equations
a1 x + b2 y = c1
a2 x + b2 y = c2
where a1 , a2 , b1 , b2 , c1 , and c2 are float constants. To solve for x and y, the following formulas are used:
1
x= × (b2 c1 − b1 c2 ) (1)
D
1
y= × (a1 c2 − a2 c1 ) (2)
D
where D = (a1 b2 − a2 b1 ).
Write a program that reads a1 , b1 , c1 , a2 , b2 , and c2 . If D = 0 then display the message “No solution
exists”. Otherwise, find and display the values of x and y.
6. Write a program that takes the x–y coordinates of a point in the Cartesian plane and prints a message
either an axis on which the point lies or the quadrant in which it is found.
8. Write a program that determines the gross pay for employees in a company according to the following
rules:
• The company pays “straight- time” for the first 50 hours worked by each employee and pays “time-
and-a-quarter” for hours worked in between 51 and 60 hours (inclusive) and pays “time-and-a-half”
for all hours worked in excess of 60 hours.
• In addition, the company pays $30 as social allowance for single employees and $50 for married
employees. (Hint: use ‘S’ or ‘s’ to indicate single employees and ‘M’ or ’m’ to indicate married
employees).
• Furthermore, the company deducts from the total gross salary of each employee 5% for the insurance
company.
Here is a sample Input/Output of your program:
9. The relative gravity of some of the planets in the solar system are shown below:
Write a complete C++ program that accepts as input the user’s weight on Earth, and the first letter of
the planet name. If the first letter does not uniquely identify the planet such as S (Sun and Saturn), then
the program should ask the user to enter the second letter in the planet name. The program then prints
the weight on the planet.
The formula for calculating the weight of an object in the planet is:
Weight of the object on a planet = weight of the object on Earth * Relative Gravity
Sample Input/Output
10. Write a C++ program that asks the user to enter two float numbers and a character which represents
a code for an arithmetic operation. The program performs arithmetic operations (addition, subtraction,
multiplication, and division) on those two numbers depending on the value of code as follows:
You must use the switch statement to determine the arithmetic operation. If the code character that is
entered by the user is not one of those specified above, print a message saying “invalid code”.
Sample Input/Output #1
Invalid character.
Sample Input/Output #2
11. Write a program that will calculate and prints bills for the city power company. The rates vary depending
on whether the use is residential, commercial, or industrial. A code of R means residential use, a code of C
means commercial use, and a code I means industrial use. Any other code should be treated as an error.
The rates are computed as follows:
R: $6.00 plus $0.052 per kwh used.
C: $60.00 for the first 1000 kwh and 0.045 for each additional kwh.
I: Rate varies depending on time of usage:
Peak hours: $76.00 for first 1000 kwh and $0.065 for each additional kwh
Off-peak hours: $40.0 for first 1000 kwh and $0.028 for each additional kwh.
Your program should prompt the user to enter an integer account number, the use code (type char), and
the necessary consumption figures in whole numbers of kilowatt-hours. Your program should display the
amount due from the user?
12. Based on automobiles’s model year and weight (in lbs), the government determines the car’s weight class
and registration fee using the following schedule:
Weight Registration
Model Year Weight Class Fee
1970 or earlier Less than 2700 lbs 1 16.500
2700 to 3800 lbs 2 25.500
More than 3800 lbs 3 46.500
14. Write a program that reads two points on a line and another two points on another line. Your program
should determine whether these two lines are parallel or they intersect. If they intersect, you need further
to state whether they are perpendicular or not.
Two lines are parallel if their slopes are equal, otherwise they intersect. Two intersected lines are per-
pendicular if the product of their slopes is -1. Use the formula below to compute the slopes of the two
lines.
y2 − y1
Slope of (x1 , y1 ) and (x2 , y2 ) is .
x2 − x1
Here are examples of two input/output samples.
First run Second run
i f ( s 1 == s 2 )
c o u t << ” \nThe two l i n e s are p a r a l l e l . ” ;
else
{
c o u t << ” \nThe two l i n e s intersect .”;
i f ( s 1 ∗ s 2 == −1 )
c o u t << ” \nThey a r e perpendicular . ” ;
e l s e c o u t << ” \nThey a r e not p e r p e n d i c u l a r . ” ;
}
return 0 ;
}
Explanation: The loop repetition condition is tested; if it is true, the statement (loop body) is
executed, and the loop condition is retested. When this condition is tested and found
to be false, the while loop is exited and the next program statement after the while
is executed.
int i = 0;
while ( i <= 20 )
{
cout << i << " ";
i += 5;
}
// Counter−C o n t r o l l e d w h i l e l o o p
counter = 0; // i n i t i a l i z e t h e l o o p c o n t r o l v a r i a b l e
// Counter−C o n t r o l l e d R e p e t i t i o n
#i n c l u d e <i o s t r e a m >
u s i n g namespace s t d ;
int main ( )
{
int i = 0 , power = 1 ; // d e c l a r a t i o n
while ( i <= 6 )
{
c o u t << i << ” \ t ” << power << e n d l ;
power ∗= 2 ;
}
return 0 ;
}
// Counter−C o n t r o l l e d w h i l e l o o p
c i n >> v a r i a b l e ; // i n i t i a l i z e t h e l o o p c o n t r o l v a r i a b l e
while ( v a r i a b l e != s e n t i n e l ) // Test t h e l o o p c o n t r o l v a r i a b l e
{
...
c i n >> v a r i a b l e ; // u p d a t e t h e l o o p c o n t r o l v a r i a b l e
...
}
Example 25 Write a program to find the product of all nonzero data items — stops at first 0?
/∗ S e n t i n e l −C o n t r o l l e d R e p e t i t i o n ∗/
#i n c l u d e <i o s t r e a m >
u s i n g namespace s t d ;
int main ( )
{
double product , item ; // d e c l a r a t i o n
product = 1 ;
c o u t << ” Enter a number o r 0 t o s t o p : ” ;
c i n >> item ;
while ( item != SENTINEL )
{
p r o d u c t = p r o d u c t ∗ item ;
c o u t << ” Next number o r 0 t o s t o p : ” ;
c i n >> item ;
}
return 0 ;
}
// Flag−C o n t r o l l e d w h i l e l o o p
found = f a l s e ; // i n i t i a l i z e t h e l o o p c o n t r o l v a r i a b l e
Example 26 Write a program that counts the number of digits of an input positive integer. Make sure that
the input integer is not negative, otherwise convert it to positive.
/∗ Flag−C o n t r o l l e d R e p e t i t i o n ∗/
#i n c l u d e <i o s t r e a m >
u s i n g namespace s t d ;
int main ( )
{
int num , count ;
b o o l done ;
c o u t << ” Enter a p o s i t i v e i n t e g e r : ” ;
c i n >> num ;
count = 0 ;
done = f a l s e ;
while ( ! done )
{
i f ( num != 0 )
{
count++;
num /= 1 0 ;
}
else
done = t r u e ;
}
// EOF−C o n t r o l l e d w h i l e l o o p
ifstream i n f i l e ;
i n f i l e >> v a r i a b l e ; // i n i t i a l i z e t h e l o o p c o n t r o l v a r i a b l e
while ( ! i n f i l e . e o f ( ) ) // Test t h e l o o p c o n t r o l v a r i a b l e
{
...
i n f i l e >> v a r i a b l e ; // u p d a t e t h e l o o p c o n t r o l v a r i a b l e
...
}
Example 27 Write a program that reads a set of integers stored in ”num.dat” file. The program should find
the sum of these integers and display it on screen.
#i n c l u d e <i o s t r e a m >
#i n c l u d e <f s t r e a m >
u s i n g namespace s t d ;
int main ( )
{
ifstream inFile ;
int num , sum ;
i n F i l e . open ( ” t e s t . t x t ” ) ;
sum = 0 ;
while ( ! i n F i l e . e o f ( ) )
{
4.1.5 Examples
1. Predict the output of this program fragment:
// Counter-Controlled Repetition
i = 0;
while ( i <= 5 )
{
cout << i << "\t" << 10 - i;
i = i + 1;
}
2. A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available
to you. Determine the class average on the quiz?
// Counter−C o n t r o l l e d R e p e t i t i o n
#i n c l u d e <i o s t r e a m >)
int main ( )
{
int c o u n t e r , grade , t o t a l ;
double a v e r a g e ;
total = 0;
counter = 1;
while ( c o u n t e r <= 10 )
{
c o u t << ” Enter g r a d e : ” ;
c i n >> g r a d e ;
t o t a l = t o t a l + grade ;
counter = counter + 1;
}
average = t o t a l / 1 0 . 0 ;
c o u t << ” C l a s s a v e r a g e i s ” << a v e r a g e << e n d l ) ;
return 0 ;
}
Explanation: First initial is executed. Then, the condition is tested. If it is true, the statement is
executed and the update is evaluated; otherwise the for loop is exited.
4.2.1 Examples
1. Trace the execution of the loop that follows for n = 8.
sum = 0;
for ( odd = 1; odd < n; odd += 2 )
sum = sum + odd;
j = 10;
for ( i = 1; i <= 5; ++i )
{
cout << i << "\t" << j;
j -= 2;
}
3. #include <iostream>
#include <cmath>
const int N = 6;
int main()
{
int number, cube;
4.3.1 Examples
1. // Find first even number input
do
{
cout << "Enter a number: ";
cin >> num;
}
while ( num % 2 != 0);
cout << endl << "The first even number is " << num;
2. What does the following code segment display? Try each of these inputs: 345, 82, 6.
num /= 10;
} while (num > 0);
cout << endl;
• Use the continue statement in while, for, and do...while repetition loops to skip the remaining
statements in the loop and proceeds with the next iteration of the loop.
4.4.1 Examples
1. Using break statement.
int x ;
f o r ( x = 1 ; x <= 1 0 ; x++)
{
i f ( x == 5 ) break ;
c o u t >> x >> ” \ t ” ) ;
}
c o u t << ” \ nUsed c o n t i n u e . ” ;
continue ;
}
sum += num ;
c i n >> num ;
}
4.6 Exercises
1. Blood sugar is considered normal if its rate is less than 140 and greater than 70, it is considered high its rate
is greater than or equal to 140, and it is considered low its rate is less than or equal to 70.
Write a C++ program that asks the user to input the rate of blood sugar of each patient in a hospital (-1 to
indicate the end of the data.) The program should calculate and print the number of patients with normal
blood sugar, number of patients with high blood sugar, number of patients with low blood sugar, and the
total number of patients entered by the user.
2. Write a complete C++ program that accepts a set of positive integer numbers. Your program should count
the odd numbers and find the maximum of these odd integer numbers. Use -1 to indicate end of data.
Sample Input/Output
9
6
2
3
17
-1
3. Write a program that reads a positive integer number of any digit size and do the following:
(a) Print the sum of its digits.
(b) Print the average of its digits.
(c) Print the leftmost digit.
(d) Print the maximum digit.
If the input number is negative, convert it to positive. Here is a sample Input/Output of your program:
Enter a positive integer: 1246
The Sum is 13
The average is 3.25
The leftmost digit is 1
The maximum is 6
4. Wind speed is classified according to their velocity into not a strong wind, strong wind, gale wind, whole gale
wind and hurricane. Write a program that asks the user to enter a wind speed which is an integer number
and then display the wind category depending on that value. Your program should continue asking for a
wind speed and displaying its category until the user enters a negative value. The wind speed is classified as
follows:
Wind Speed Category
Below 25 Not a strong wind
25–38 Strong wind
39-54 Gale
55-72 Whole gale
Above 72 Hurricane
Sample Input/Output
5. The interest rate used on funds deposited in bank is determined by the amount of time the money is left on
deposit. For a particular bank, the following schedule is used.
Write a C++ program that accepts the time that funds are left on deposit continuously until -1 is entered
and displays the interest rate corresponding to the time entered.
6. Write a program that reads ages of students in a community and counts the number of students in each class
according to the following table:
Age Class
1 – 5 Preschool
6 – 12 Primary
13 – 15 Intermediate
16 – 18 Secondary
Your program must continuously read ages in the range 1 – 18 until -1 is entered. It should ignore all ages
that are outside this range. Here is a sample Input/Output of your program.
8. Students who finish the semester get a message on their transcript from the registration department according
to their GPA. The following table shows the list of messages:
Write a C++ program that asks the user to enter a student’s GPA and decide which category he/she should
be in. The program should continue asking the user to enter the student’s GPA until the user enter a negative
number.
Note that if the student is in the first category (0.00–1.99) you should ask the student how many previous
semesters has failed and decide whether he/she should be on probation or suspension.
9. Write a program that reads student GPA’s on a 4.0 scale. The number of students is not known in advance.
Therefore, you must read the GPA’s until a negative number is entered.
Your program should display the number of students with GPA of 4.0 and their corresponding percentage.
Sample Input/Output
10. A sport club wants to update the information about its members. Write a complete C++ program that asks
the user to input member’s ID (integer) and status S or M to indicate single or married (char). Use -1 for
the ID number to stop entering the data. The program should then output the following:
• The total number of members in the club.
• The total number if single members.
Excellent students: 11
Very-Good students: 8
Good students: 6
12. A prime number is defined as a number that is divisible by 1 and itself only. Write a C++ program that
asks the user to input an integer number N . It should then find the largest prime number less than N and
the smallest prime number greater than N .
Sample Input/Output
Enter an integer: 20
void main() {
unsigned long int current, previous, next, i;
current = 1; previous = 1;
for ( i = 1; i <= SIZE; i++)
{
next = current + previous;
printf("%15lu", next);
if ( i % 5 == 0 ) printf("\n");
previous = current;
current = next;
}
}
#include <stdio.h> #define SIZE 1000 #include <stdio.h> #define SIZE 1000
term = x; term = x;
sum = x; sum = x;
for ( i = 2; i <= SIZE; i++) for ( i = 1; i <= SIZE; i++)
{ {
term = -term * x; term = -term * x * x / ( (2*i+1)*(2*i) );
sum = sum + (term / i); sum = sum + term;
} }
printf("ln(1+%f) = %.10f.\n",x, sum); printf("sin (%f) = %.10f.\n",x, sum);
} }
15. Write a program that reads from the keyboard a positive integer M and generates a triangle of numbers (as
shown below). You must make sure the number is entered is positive before making the triangle.
For example, if the input for M is 6, the output triangle should be
scanf("%M", M);
6 5 4 3 2 1 for ( i = M; i > 0; --i) {
5 4 3 2 1 for ( j = i; j > 0; --j)
4 3 2 1 printf("%-5d", j);
3 2 1 printf("\n");
2 1 }
1
17. Write a program that reads a nonnegative number n in the range 1–9. The program should display the
numbers from 1 to n in a payramid form. For example, if n = 5, the following pattern is displayed:
1
222
33333
4444444
555555555
#include <stdio.h>
int main() {
int i, j, n;
scanf("%d", &n);
while ( n < 1 && n > 9 )
{
printf("Invalid input.\n");
printf("Enter n (1-9):? ");
scanf("%d", &n);
}
return 0;
}
5 User-Defined Functions
In C++, the concept of a function, either predefined or userdefined, is similar to that of a function in algebra.
int main ( )
{
int x ;
double u , v ;
c o u t << ” Uppercase a i s ”
<< s t a t i c c a s t <char>( t o u p p e r ( ’ a ’ ) ) << e n d l ;
c o u t << ” 5 t o t h e power o f 4 = ”
<< pow ( 5 , 4 ) << e n d l ;
return 0 ;
}
Output:
Uppercase a is A
5 to power of 4 = 625
Input parameters
↓ ... ↓
Function
Name
↓
Return value
(Type of the function)
The first four properties formed the heading of the function (function header); the fifth property is called
the body of the function. Together, these five properties is called the definition of the function.
Example 29 Write a program that uses a function called larger that finds the larger of two double variables.
#include <i o s t r e a m >
u s i n g namespace s t d ;
// Function Header ( p r o t o t y p e )
double l a r g e r ( double , double ) ;
int main ( )
{
double one , two , maxNum ;
return 0 ;
}
// Function body
2. Write a function plaindrome() that tests if an input variable is a plaindrome (you can read it from both
sides left and right). For example, 5, 44, 181, 3344, 7865687 are plaindrome.
#i n c l u d e <i o s t r e a m >
u s i n g namespace s t d ;
b o o l p l a i n d r o m e ( int ) ;
int main ( )
{
int number ;
c i n >> number ;
return 0 ; // i n d i c a t e s t h a t program ended s u c c e s s f u l l y
}
b o o l p l a i n d r o m e ( int num)
{
// S t o r e t h e number i n r e v e r s e o r d e r i n revNum
int tempNum = num ;
int revNum = 0 ;
while (tempNum != 0 )
{
revNum = revNum ∗ 10 + tempNum % 1 0 ;
tempNum /= 1 0 ;
}
// Compare t h e number and i t s r e v e r s e
i f ( num == revNum )
return t r u e ;
else
return f a l s e ;
}
void p r i n t S t a r s ( ) ;
int main ( )
{
printStars ();
c o u t << ” ∗∗∗∗∗∗∗∗∗∗ Annual ∗∗∗∗∗∗∗∗∗∗∗ ” << e n d l ;
printStars ();
c o u t << ” ∗∗∗∗∗∗∗ S p r i n g S a l e ∗∗∗∗∗∗∗∗∗∗ ” << e n d l ;
printStars ();
return 0 ;
}
void p r i n t S t a r s ( )
{
f o r ( int s t a r = 1 ; s t a r <= 3 0 ; s t a r ++)
c o u t << ” ∗” ;
c o u t << e n d l ;
f o r ( int s t a r = 1 ; s t a r <= 3 0 ; s t a r ++)
c o u t << ” ∗” ;
c o u t << e n d l ;
}
int main ( )
{
int l i n e s ;
c o u t << ”How many l i n e s : ” ;
c i n >> l i n e s ;
printChar ( ’ ’ , l i n e s − L ) ;
p r i n t C h a r ( ’ ∗ ’ , 2∗L−1);
c o u t << e n d l ;
}
return 0 ;
}
int main ( ) {
int num1 = 1 0 , num2 = 1 5 ;
char ch = ’A ’ ;
funTwo (num2 , 2 5 , ch ) ;
return 0 ;
}
Output:
Inside main: num1 = 10, num2 = 15, and ch = A
Inside funOne: a = 11, b = 30, c = B, and one = 10
After funOne: num1 = 10, num2 = 30, and ch = A
Inside funTwo: x = 31, y = 50, and w = G
After funtwo: num1 = 10, num2 = 31, and ch = G
// G l o b a l v a r i a b l e
int z = 6 ;
void f ( int ) ;
int main ( )
{
int y ;
y = z + 5;
z += y ;
c o u t << ” z = ” << z << e n d l ;
f (z );
c o u t << ” z = ” << z << e n d l ;
c i n >> z ;
return 0 ;
}
void f ( int x )
{
// L o c a l v a r i a b l e
int y = 3 ;
x −= y ;
x += x ;
c o u t << ”x = ” << x << e n d l ;
z = x − 4;
}
Output:
z = 17
x = 28
z = 24
5.7 Exercises
1. The Gaussian density function is commonly used in engineering statistics. This function is defined in the
equation that follows:
1 2
Y = √ e−0.5x
2π
where π = 3.14159. Write a program to read a value for x and compute the corresponding value of Y . Print
the values in the following form:
The standard normal density function evaluated
at xxx.xx gives a value of xx.xxxx
2. Two positive integers i and j are considered to be relatively prime if there exists no integer greater than 1
that divides them both. Write a function replm that has two input parameters, i and j, and returns a value
of 1 if and only if i and j are relatively prime. Otherwise, replm should return a value 0.
min = i
if ( j < min ) min = j;
3. Write a function that finds all factors of any particular number. For example,
9 = 3 × 3, 17 = 17 (prime), 52 = 2 × 2 × 13
void factors(int n)
{
int i;
for (; n % 2 == 0; n /= 2)
cout << setw(5) << 2;
for( i = 3; n != 1; i+=2)
for(; n % i == 0; n /= i)
cout << setw(5) << i;
}
4. Given the lengths a, b, c of the sides of a triangle, write a function to compute the area A of the triangle.
The formula for computing A is given by
p
A = s(s − a)(s − b)(s − c)
where s = 21 (a + b + c) is the semiperimeter of the triangle. Write a driver program to get values for a, b,
and c and call your function to compute A. The driver should print A, a, b, and c.
5. Write a function multiple that determines for a pair of integers whether the second integer is a multiple of
the first. The function should take two integer arguments and return 1 (true) if the second is a multiple of
the first, and 0 (false) otherwise. Use this function in a program that inputs a series of pairs of integers.
else return 0;
}
6. Write a function that takes an integer value and returns the number with its digits reversed. For example,
given the number 7631, the function should return 1367.
int reverse(int n)
{
int rnum = 0;
for(; n != 0; n /= 10)
rnum = rnum * 10 + n % 10;
return rnum;
}
7. Write a function that takes the Cartesian coordinates of two points (x1 , y1 ) and (x2 , y2 ) and returns the
distance between them computed using the following formula:
p
dist = (x1 − x2 )2 + (y1 − y2 )2
8. Write a program that inputs a series of integers and passes them one at a time to function even which uses
the modulus operator to determine if an integer is even. The function should take an integer argument and
return 1 if the integer is even and 0 otherwise.
The set of values that you specify for the data type must be identifers.
Example 36 Define an enumeration type sports and define a variable of this type.
enum sports {BASKETBALL, FOOTBALL, HOCKEY, BASEBALL, SOCCER, VOLLEYBALL};
...
sports mySport;
6.3 Assignment
Once a variable is declared, you can store value sin it.
Example 37
1. Illegal Operations.
mySport = favSport + 1;
favSport = BASKETBALL + FOOTBALL;
mySport++;
favSport--;
2. Legal Operations.
mySport = FOOTBALL;
// Assign next value to a variable
favSport = static_cast<sports>(favSport + 1); // HOCKEY is stored in favSport
6.7 Exercises
1. (a) Define an enumeration type, triangleType, that has the values scalene, sosceles, equilateral, and
noTriangle.
(b) Write a function, triangleShape, that takes as parameters three numbers, each of which represents the
length of a side of the triangle. The function should return the shape of the triangle. (Note: In a
triangle, the sum of the lengths of any two sides is greater than the length of the third side.) A scalene
triangle is a triangle that has three unequal sides. An isosceles triangle is a triangle with (at least) two
equal sides. An equilateral triangle is a triangle with all three sides of equal length.
(c) Write a program that prompts the user to input the length of the sides of the triangle and outputs the
shape of the triangle.
7 Arrays
An array is a group of memory locations related by the fact that they all have the same name and the same
type. To refer to a particular location or element in the array, we specify the name of the array and the position
number of the particular element in the array.
cout << setpresion(1) << x[0]; Display the value of x[0], which is 16.0
sum = x[0] + x[1]; Stores the sum of x[0] and x[1], which is 28.0
in the variable sum.
x[2] = x[0] + x[1]; Stores the sum of x[0] and x[1] in x[2]. The
new x[2] is 28.0
int prime[10];
...
prime[0] = 2; prime[1] = 3; prime[2] = 5;
prime[3] = 7; prime[4] = 11; prime[5] = 13;
prime[6] = 17; prime[7] = 19; prime[8] = 23;
prime[9] = 29;
...
int num[120];
int count = 0;
...
cout << "How many integers? ";
3. During declaration:
a. Initializing an array: The following loop initializes every component of the array sales to 0.0
for (index = 0; index < 10; index++)
sales[index] = 0.0;
b. Reading data into an array: The following loop inputs the data into the array sales.
for (index = 0; index < 10; index++)
cin >> sales[index];
c. Reading data ended by a sentinel. Store data into sales ended by a sentinel.
• Declaring strings.
#include <string>
.....
string str1, str2;
• Initializing strings.
string name = "William Jacob";
string str1, str2
str1 = "Hello There";
str2 = name; //Copies the value of name into str2
• Using the operator + with strings.
string str1 = "William";
str1 = str1 + " " + "Jacob";
• Relational Operators and the string Type.
string str1 = "Hello", str2 = "Hi", str3 = "Air";
string str4 = "Bill", str4 = "Big";
str1 < str2 true The first character of str1 and str2 are the same, but the second
character ‘e’ of str1 is less than the second character ’i’ of str2.
str1 > "Hen" false The first two characters of str1 and ”Hen” are the same, but the
third character ‘l’ of str1 is less than the third character ’n’ of
”Hen”.
str1 > "hello" false The first character ’H’ of str1 is less than the first character ’h’ of
”hello”, because the ASCII code of ’H’ is 72 and the ASCII code
of ’h’ is 104.
str1 == "hello false The first character of str1 and str2 are not the same, they have
different ASCII codes.
strVer.length()
This function searches for the string expression strExp in the string strVar and returns an unsigned
integer value. If the search is successful, the function returns the position in strVar where the match
begins. If the search is unsuccessful, the function returns the special value string::npos.
– strVar.find(strExp, pos)
In this form pos specifies the position in the string where to begin the search.
Example 40 string str = "Outside it is cloudy and warm.";
string str1;
Statement Effect
• swap Function
strVar1.swap(strVar2)
This function is used to swap the contents of two string variables. After execution the contents of strVar1
and strVar2 are swapped.
string str1 = "warm", str2 = "cold"; str1.swap(str2); cout << str1; // Output is: cold
• substr Function
strVar.substr(expr1, expr2)
This function returns a particular substring of a string. expr1 and expr2 are unsigned integers expressions.
The expression expr1 specifies a position within the string and expr2 specifies the length of the substring
to be returned.
#include <stdio.h>
#define SIZE 5
void main()
{
int a[SIZE] = {0, 1, 2, 3, 4}, i;
modifyArray( a, SIZE );
for( i=0; i <= SIZE - 1; i++)
printf("%3d", a[i]);
printf("\n");
modifyElement( a[3] );
printf("The value of a[3] is %3d\n", a[3]);
}
cur_large = list[0];
for( i = 1; i < n; ++i )
if ( list[i] > cur_large ) cur_large = list[i];
return cur_large;
}
#include <stdio.h>
void main() {
int array1[2][3]={ {1,2,3}, {4,5,6} },
array2[2][3]={ 1, 2, 3, 4, 5 },
array3[2][3]={ {1,2}, {4} };
2. Write a function that displays the values on the diagonal of its 10 × 10 matrix parameter.
#define SIZE 10
...
void printDiagonal( int a[][SIZE] )
{
int i;
for ( i = 0; i < SIZE; i++)
printf("%d ", a[i][i]);
}
3. Write a function that determines who won a game of tic-tac-toe. The function should return a value of 0
if no winner, 1 if x wins, and 2 if o wins.
#include <stdio.h>
#define SIZE 3
void main() {
char ticTacToe[SIZE][SIZE] = { "oxo" ,
"xxo" ,
"oox"};
int result;
result = winner(ticTacToe);
if (result == 1) printf("\nx has won.\n");
else if (result == 2) printf("\no has won.\n");
else printf("\nNo winner.\n");
}
return 0;
}
7.7 Problems
1. Write a statement that assigns to seg len the length of a line segment from xi yi to xi+1 yi+1 using the
formula p
(xi+1 − xi )2 + (yi+1 − yi )2
Assume that xi represents the ith element of array x, that yi represents the ith element of array y, and
that the minimum i is 0.
2. Write a for loop that sums the even values from the LIST SIZE-element array list. For example, the
sum for this list would be 104 (30 + 12 + 62).
30 12 51 17 45 62
3. Write a program to store an input list of 10 integers in an array; then display a table similar to the
following showing each data value and what percentage each value is of the total of all 10 values.
n % of total
8 4.00
12 6.00
18 9.00
25 12.50
24 12.00
30 15.00
28 14.00
22 11.00
23 11.50
10 5.00
4. Use a single-subscripted array to read in 20 numbers, each of which is between 10 and 100, inclusive. As
each number is read, print it only if it is not a duplicate of a number already read. Use the smallest
possible array to solve this problem.
5. Write a C++ function called CheckArray that determines if a one-dimensional array of integers is sorted
(ordered) or not. If sorted, then is it sorted in increasing order or decreasing order.
Your function should return -1 if the array is unsorted, 0 if sorted in ascending order, and 1 if sorted
in descending order. The main function that calls CheckArray is given below. You should write the
prototype of the function first and then the function CheckArray itself.
6. Assume that the reservation for an airplane flight have been stored in a file called FLIGHT.DAT. The
plane contains 38 rows with 6 seats in each row. The seats in each row are numbered 1–6 as follows:
The file FLIGHT.DAT contains 38 lines of information corresponding to the 38 rows. Each line contains
6 values corresponding to the 6 seats. The value for any seat is either 0 or 1, representing an empty or
occupied seat.
Write a complete program to read the FLIGHT.DAT information into a two-dimensional array called seat.
Find and print all pairs of adjacent (next to each other) seats that are empty. Adjacent aisle seats should
not be printed. If all three seats on one side of the plane are empty, then two pairs of adjacent seats
should be printed. Print this information in the following manner.
7. Write a program that reads the temperatures for one week in different cities. Define a 2-dimensional array
of size 5 rows and 7 columns that will store the temperature readings. Ask the user to input the required
data, then print all those days in which the temperatures are the same (i.e. it should find all identical
columns in the 2-dimensional array).
For example, if the numbers in the array are as follows,
Days
0 1 2 3 4 5 6
city0 23.0 27.1 23.0 26.9 28.0 29.0 26.9
city1 22.4 28.0 22.4 30.5 24.0 24.0 30.5
city2 25.0 31.7 25.0 26.4 30.0 31.2 26.4
city3 23.6 30.6 23.6 32.3 26.0 26.0 32.3
city4 21.1 28.0 21.1 30.2 34.0 29.5 30.2
D o o o D o o o D o o o o o
x D o o x D o o x D o o o o
x x D o x x D o x x D o o o
x x x D x x x D x x x D o o
x x x x
x x x x
Name your function LowerSum and write it in a way such that it can be called by the main function
given below.
8 File Processing
8.1 Problems
1. Write a program that reads a data file containing a C++ program and writes it to another file after
removing all comments. Comments in C++ are either one-line comments that start with // or multi-line
comments that are started by /* and terminated by */.
2. Write a C++ program that opens two output files “ODD.DAT” and “EVEN.DAT”. The program then
generates 100 random integers between 1 and 500. It should write the odd numbers to the file ODD.DAT
and the even numbers to EVEN.DATA.
3. Write a C++ program that reads an unknown number of integers from an input file “NUMS.DAT”. It
should produce a second file “SORTED.OUT” with the same set of numbers sorted in descending order.
Assume that the input file can contain a maximum of 200 numbers.
4. Consider the following C++ program.
The above program reads an unknown number of positive integers. It stops when it reads 0. If the number
is even it prints the number on the screen multiplied by 10, if the number is odd it prints it multiplied by
2.
Rewrite the above program such that it reads the numbers from a file and writes the output to two different
ouput files. Assume that the numbers are read from a file called ‘INPUT.DAT’, the even numbers are
written to an output file ‘EVEN.TXT’, and the odd numbers are written to ‘ODD.TXT’.
5. For research purposes and to better help students, the admission office of your local university wants to
know how well female and male students perform in certain courses. You receive a file that contains female
and male students GPA’s for certain courses. The letter code f is used for female and the letter code m
is used for male students. Every file entry consists of a letter code followed by a GPA. Each line has one
entry. The number of entries in the file is unknown. Write a program that computes and outputs the
average GPA for both female and male students.
6. A programmer wants to write a program to copy a text file called “ORIGINAL.TXT” to another file
called “COPY.TXT” so that finally he/she ends up with two files having exactly the same content.
Assuming that the input file has at least one character, the programmer writes the following code:
#include<stdio.h>
void main() {
char x;
FILE *infile, *outfile;
while( feof(infile) )
{
scanf("%c",&x);
fprintf(outfile,"%c",&x);
}
fclose(infile);
fclose(outfile);
return 0;
}
The above program has 5 errors in it! What are they? Mension the error and how to correct it.
(a) Error: infile = fopen(”ORIGINAL.TXT”, ”w”);
Correction: infile = fopen(”ORIGINAL.TXT”, ”r”);
(b) Error: while( feof(infile) ) Correction: while( !feof(infile) ) OR while( feof(infile) == 0 )
(c) Error: scanf(”%c”,&x);
Correction: scanf(infile, ”%c”,&x);
(d) Error: fprintf(outfile,”%c”, & x); Correction: fprintf(outfile,”%c”, x);
(e) Error: return 0;
Correction: Delete return 0; OR return;