University of Bahrain: 1.1 Creating A C++ Program

Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

1 BASIC ELEMENTS OF C++

University of Bahrain
College of Information Technology
Department of Computer Science
CSC100/ITCS101 Introduction to Computers and IT

1 Basic Elements of C++


Example 1 A Simple C++ Program: Printing a Line of Text.
// My f i r s t program i n C++

#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.

Dissection of the above program


1. The symbols // indicate that the remaining text is a comment. Programmers insert comments to document
programs and to improve program readability.

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.

3. int main() { ... }


Every program in C++ begins executing at the function main.
4. cout << "Welcome to C++ Programming." << endl;
This statement instructs the computer to print on the screen the string of characters marked by the
quotation marks. Every statement in C++ must be terminated by a semicolon (;). endl used to direct
the computer to go to the next line.

1.1 Creating a C++ Program


The syntax of the main function has the following form:

int main()
{
statement 1;
.
.
statement n;

return 0;
}

1.2 The Basics of a C++ Program


Example 2 Adding two numbers and display their results.
#i n c l u d e <i o s t r e a m >

u s i n g namespace s t d ;

ITCS101/CSC100 C++ Notes 1 Dr. Ali Alsaffar


1.3 Data Types 1 BASIC ELEMENTS OF C++

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 ;

c o u t << f i r s t << ” + ” << s e c o n d << ” = ” << t o t a l << e n d l ;

return 0;
}

Output:
34 + 19 = 53

1.2.1 Special Symbols


Some of the special symbols: Mathematical symbols + - * /
Punctuation marks . ; ? ,
Tokens of two characters + != == >=

1.2.2 Word Symbols


Reserved words (keywords): Some examples: int, float, double, const, void, return.
Identifiers (variables): Consists of letters, digits, and underscore ( ). Must not begin
with a digit and not a reserved. word.
Examples: payrate, first, letter1

1.2.3 Uppercase and Lowercase Letters


The C++ compiler is case sensitive. In other words, lowercase letters are treated different from uppercase
letters (and vice versa). For example, Rate, rate, RATE are viewed by the compiler as different identifiers.

1.3 Data Types


Simple Data Types:
• Integral: char, short, int, long bool, unsigned char, unsigned short, unsigned int, unsigned long.
int -2147483648 to 2147483647
bool true or false
char -128 to 127
• Floating-point: float, double, long double.
float −3.4 × 10+38 to −3.4 × 10+38
double −1.7 × 10+308 to 1.7 × 10+308

Example 3 An example of some simple data types.


char: ’a’ , ’+’, ’T’, ’$’
bool: true or false
int: 2, 0, -5, +453, -67, 36782
float: 75.924, -1.482, 0.0, 7800.0

1.4 Arithmetic Operators and Operator Precedence


+ addition - subtraction * multiplication / division % modulus.

ITCS101/CSC100 C++ Notes 2 Dr. Ali Alsaffar


1.5 Type Conversion (Casting) 1 BASIC ELEMENTS OF C++

Example 4 : Arithmetic Expression Result


2+5 7
13 + 89 102
34 - 20 14
2*7 14
14 / 7 2
34 % 5 4
-34 % 5 -4
34 % -5 -5
-34 % -5 4
4%6 4
5.0 + 3.5 8.5
16.3 - 5.2 11.1
4.2 * 2.5 10.5
5.0 / 2.0 2.5
Order of Precedence: Parenthesis → (∗, /, %) → (+, −).

Expressions: Integral 2+3*5


3+x-y/7
x + 2 * (y - z) + 18
floating-point 12.8 * 17.5 - 34.50
x * 10.5 + y - 16.2
Mixed Expressions: 2 + 3.5
6 / 4 + 3.9
5.4 * 2 - 13.6 + 18 / 2

1.5 Type Conversion (Casting)


static cast<dataTypeName>(expression) ⇐= expression is converted to dataTypename.
Example 5 : Expression Evaluates to
static cast<int>(7.9) 7
static cast<double>(259) 259.0
static cast<double>(15) / 2 15.0 / 2 = 7.5
static cast<double>(259) 259.0
static cast<int>(7.9) + static cast<int>(6.7) 7 + 6 = 13

1.6 string Type


A string is a sequence of zero or more characters. Strings in C++ are enclosed in double quotation marks. A
string containing no characters is called null or empty.
To use the string data type you must include #include <string> in your program.

1.7 Allocating Memory with Constants and Variables


Named constant: A memory location whose content is not allowed to change during program execution.
const dataType identifier = value;

Example 6 const double CONVERSION = 2.54;


const int NO OF STUDENTS = 20;
const double PAY RATE = 15.75;
const double PI = 3.141592653;
Variable: A memory location whose content may change during program execution.
dataType identifier, identifier, ..., identifier;

Example 7 double amountDue;


int counter;
char ch;
int x, y; string name;

ITCS101/CSC100 C++ Notes 3 Dr. Ali Alsaffar


1.8 Putting Data into Variables 1 BASIC ELEMENTS OF C++

1.8 Putting Data into Variables


You can place data into variables into two ways:
• Use C++ assignment’s statement (=).

• Use input (read) statements.

1.9 Assignment Statement


variable = expression

• 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.

1.10 Initializing Variables


A variable is said to be initialized the first time a value is placed in the variable.
You can initialize a variable in two ways:

• During declaration: dataType variablename = initialvalue;

• Using the Assignment Statement variable = initialValue;

ITCS101/CSC100 C++ Notes 4 Dr. Ali Alsaffar


1.11 Input (Read) Statement 1 BASIC ELEMENTS OF C++

Example 8 double a, b = -2.3;


char m, l = ’A’;
int counter = 0;
..
.
a = 4.5; m = ’S’;

1.11 Input (Read) Statement


Putting data into variables from the standard input device (Keyboard) is accomplished via the use of cin and
the operator >>.
cin >> variable >> variable >> ...;

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

c o u t << ” Enter f i r s t i n t e g e r \n” ; // prompt


c i n >> i n t e g e r 1 ; // read an i n t e g e r

c o u t << ” Enter s e c o n d i n t e g e r \n” ; // prompt


c i n >> i n t e g e r 2 ; // read an i n t e g e r

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

c o u t << ”Sum i s << sum << e n d l ; // p r i n t sum

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


}

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 ;

ITCS101/CSC100 C++ Notes 5 Dr. Ali Alsaffar


1.12 Increment and Decrement Operators 1 BASIC ELEMENTS OF C++

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

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


}

Output:
Enter the distance in miles> 45.9
That equals 73.8531 kilometers

1.12 Increment and Decrement Operators


Operator Example Explanation
Pre-increment ++a Increment a by 1 then use the new value of a.
Post-increment a++ Use the current value of a then increment a by 1.
Pre-decrement --a Decrement a by 1 then use the new value of a.
Post-decrement a-- Use the current value of a then decrement a by 1.

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

1.13 Escape Sequences


Example 12 cout << "Welcome to C!\n";
The character \n inside the string is not printed. It is used to direct the computer to go to the next line. This
character is called an escape character.

Other escape sequences are listed below:

Common escape sequences


Escape Sequence Description
\n Newline. Position the cursor at the beginning of the next line.
\t Horizontal tab. Move the cursor to the next tab stop.
\r Carriage return. Locate the cursor to the beginning of the current line.
\a Alert. Sound the system bell.
\\ Backslash. Print a backslash character.
\" Double quote. Print a double quote character.
\’ Single quotation mark is printed

1.14 Compound Assignment Statements


Assume: int c = 3, d = 5, e = 4, f = 6, g = 12;
Assignment Sample
Operator Expression Explanation Assigns
+= c += 7 c = c + 7 10 to c
-= d -= 4 d = d - 4 1 to d
*= e *= 5 e = e * 5 20 to e
/= f /= 3 f = f / 3 2 to f
%= g %= 9 g = g % 9 3 to g

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

ITCS101/CSC100 C++ Notes 6 Dr. Ali Alsaffar


1.15 Exercises 1 BASIC ELEMENTS OF C++

sum = a + b + c; // a = 3 b = 5 c = 14.1 sum = 22


c /= a; // a = 3 b = 5 c = 4.7 sum = 22
b += c - a; // a = 3 b = 6 c = 4.7 sum = 22
a *= 2 * b + c; // a = 50 b = 6 c = 4.7 sum = 22

(b) Simple Assignment Statement Compound Assignment Statement


i = i + 5; i += 5;
counter = counter + 1; counter += 1;
sum = sum + number; sum += number;
amount = amount * (interest + 1); amount *= interest + 1;
x = x / ( y + 5 ); x /= y + 5;

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.

celsius = 5/9 (f ahrenheit − 32)

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.

Call 1: How many miles and minutes? 3 20


Call 2: How many miles and minutes? 2 15
Call 3: How many miles and minutes? 6 4
Call 1 costs BD. 6.045
Call 2 costs BD. 4.53
Call 3 costs BD. 1.29
Total cost is BD. 11.865

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:

ITCS101/CSC100 C++ Notes 7 Dr. Ali Alsaffar


2 INPUT/OUTPUT

Perimeter = 2(length + width)


Volume = length × width × depth
Surface Area = 2(length + width) × depth + length × width

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:

volume = π × radius2 × (200 − distance)

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

2.1.1 cin and the Extraction Operator >>


cin skips all white spaces (blanks and certain non-printable characters).

Example 14 Suppose you have the following variable declarations:


int a, b;
double z;
char ch, ch1, ch2;
# Statement Input Values Stored in Memory
1. cin >> ch; A ch = ’A’;
2. cin >> ch; AB ch = ’A’, ’B’ is held for later input.
3. cin >> a; 48 a = 48;
4. cin >> a; 46.35 a = 46, .35 is held for later input.
5. cin >> z; 74.35 z = 74.35
6. cin >> z; 39 z = 39.0
7. cin >> z >> a; 65.78 38 z = 65.78, a = 38
8. cin >> a >> b; 4 60 a = 4, b = 60
9. cin >> a >> ch >> z; 57 A 26.9 a = 57, ch = ’A’, z = 26.9

10. cin >> a >> ch >> z; 57 A a = 57, ch = ’A’, z = 26.9


26.9
11. cin >> a >> ch >> z; 57 a = 57, ch = ’A’, z = 26.9
A
26.9
12. cin >> a >> ch >> z; 57A26.9 a = 57, ch = ’A’, z = 26.9
13. cin >> z >> ch >> a; 36.78B34 z = 36.78, ch = ’B’, a = 34
14. cin >> z >> ch >> a; 36.78 z = 36.78, ch = ’B’, a = 34
B34
15. cin >> a >> b >> z; 11 34 a = 11, b = 34, computer waits for
the next number.
16. cin >> a >> z; 46 32.4 68 a = 46, z = 32.4, 68 is held for
later input.
17. cin >> a >> z; 78.49 a = 46, z = 0.49
18. cin >> ch >> a; 256 ch = ’2’, a = 56
19. cin >> a >> ch; 256 a = 256, computer waits for
the next number.

ITCS101/CSC100 C++ Notes 8 Dr. Ali Alsaffar


2.2 Output and Formatting Output 2 INPUT/OUTPUT

2.2 Output and Formatting Output


2.2.1 setprecision manipulator
It is used to control the output of floating-point number.
setprecision(n)
where n is the number of decimal places.

• The include statement #include <iomanip> is required in the program header.


• Use the setprecision with cout operator.

• Once the precision is determined, it is changed until a similar subsequent statement changes the precision.

Example 15 Consider the following statements:


double num = 3.1342456789;
...
cout << setprecision(3) << num << endl;

2.2.2 fixed, showpoint and setw Manipulators

• fixed is used to output floating-point numbers in a fixed decimal format.


Example: cout << fixed;

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

2.2.3 Unsetting manipulator


To unset a manipulator use:
cout.unsetf(ios::fixed)

Example 16 Setprecision, fixed, and showpoint manipulators


#i n c l u d e <i o s t r e a m >
#i n c l u d e <iomanip>
using namespace s t d ;
int main ( )
{
double s a l e = 1 8 9 0 . 7 ;

c o u t << s e t p r e c i s i o n ( 3 ) << f i x e d << showpoint ;

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 ;

ITCS101/CSC100 C++ Notes 9 Dr. Ali Alsaffar


2.3 File Input/Output 2 INPUT/OUTPUT

c o u t << l e f t << setw ( 2 6 ) << ” Pension Plan ”


<< r i g h t << setw ( 1 0 ) << 0 . 0 6 ∗ s a l e
<< e n d l ;
c o u t << l e f t << setw ( 2 6 ) << ” Health I n s u r a n c e ”
<< r i g h t << setw ( 1 0 ) << 7 5 . 0
<< e n d l ;
return 0 ;
}

Output:
Gross amount ---------------1890.700
Medicare/Mediaid Tax ---------51.994
Pension Plan ----------------113.442
Health Insurance -------------75.000

2.3 File Input/Output


File I/O is a five-step process:
1. Include the header file fstream in the program.
#include <fstream>
2. Declare the stream variables.
ifstream inData;
ofstream outData;
3. Associate the file stream variables with the input/output sources.
inData.open("prog.dat");
inData.open("c:\\prog.dat");
4. Use the file stream variables with >> and <<, or other input/output functions.
inData >> payRate;
outData << "The paycheck is: $" << pay << endl;
5. Close the files.
inData.close();
outData.close();
In skeleton form, a program uses file I/O usually takes the following form:
#i n c l u d e <i o s t r e a m >

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

ITCS101/CSC100 C++ Notes 10 Dr. Ali Alsaffar


2.3 File Input/Output 2 INPUT/OUTPUT

return 0 ;
}

Example 17 program to calculate the average test scores


#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 >
#i n c l u d e <s t r i n g >
#i n c l u d e <iomanip>

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

o u t F i l e << f i x e d << showpoint ;


o u t F i l e << s e t p r e c i s i o n ( 2 ) ;

c o u t << ” P r o c e s s i n g data ” << e n d l ;

i n F i l e >> f i r s t N a m e >> lastName ;


o u t F i l e << ” Student name : ” << f i r s t N a m e
<< ” ” << lastName << e n d l ;

i n F i l e >> 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 ;


o u t F i l e << ” Test s c o r e s : ” << setw ( 8 ) << t e s t 1
<< setw ( 8 ) << t e s t 2 << setw ( 8 ) << t e s t 3
<< setw ( 8 ) << t e s t 4 << setw ( 8 ) << t e s t 5
<< e n d l ;

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 ;

o u t F i l e << ” Average t e s t s c o r e : ” << setw ( 8 )


<< a v e r a g e << e n d l ;

inFile . close ();


outFile . close ( ) ;
return 0 ;
}

Input File

Layla Ali 867.50 89 65.75 37 98.50


Output File
Student name: Layla Ali
Test scores: 87.50 89.00 65.75 37.00 98.50
Average test score: 75.55

ITCS101/CSC100 C++ Notes 11 Dr. Ali Alsaffar


2.4 Exercises 3 CONTROL STRUCTURES I (SELECTION)

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.

Enter the assessed value: 100000

Taxable amount: 92000.00


Property tax: 966.00

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:

Enter gross amount (BD): 650

---------- Paycheck -----------


Gross amount: 650.000
Medicare/Medicaid Tax: 17.875
Pension Plan: 39.000
Health Insurance: 75.000
-------------------------------
Net Pay: 518.125

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.

3 Control Structures I (Selection)


In C++, a condition is represented by a logical (Boolean) expression. An expression that has a value of
either true or false is called a logical (Boolean) expression. A relational operator allows you to make
comparisons in your program.

In Math In C++ Description Example 1 Example 2


= == Equal to age == 15 str == "Ali"
6= != Not equal to age != 15 str < "Hi"
< < Less than month < 13 str1 < str2
≤ <= Less than or equal month <= 12 str1 <= str2
> > Greater than day > 0 str > "Hasan"
≥ >= Greater than or equal day >= 1 str >= "Mona"

ITCS101/CSC100 C++ Notes 12 Dr. Ali Alsaffar


3.1 Logical (Boolean) Operators and Logical Expressions 3 CONTROL STRUCTURES I (SELECTION)

3.1 Logical (Boolean) Operators and Logical Expressions


Logical (Boolean) operators enable you to combine logical expressions.

Operator Description Example


! not !(age < 13)
&& and (month >=1 && (month <= 12)
|| or (day == 1) || (day == 2)

3.2 Precedence Rule


Precedence Operators
1. ()
2. !, + , − (Unary)
3. ∗, / , %
4. +, −
5. < , <= , > , >=
6. == , ! =
7. &&
8. ||
9. =

3.3 The if Selection Structure


The if structure is called a single-selection structure because it selects or ignores a single action.

Example 18 If student’s grade is greater than or equal to 60, then print“Passed”


In C++, we can implement the above statement as
if ( grade >= 60 )
cout << "Passed\n";

3.4 The if/else Selection Structure


The if/else structure is called a double-selection structure because it selects between two different actions.

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

ITCS101/CSC100 C++ Notes 13 Dr. Ali Alsaffar


3.5 Compound Statement 3 CONTROL STRUCTURES I (SELECTION)

c o u t << number << ” i s n e g a t i v e \n” ; \ n” ;

return 0;
}

3.5 Compound Statement


If according to a Boolean expression we would like to execute multiple statements instead of a single statement,
we use the compound statement rule:

{
Statement 1;
Statement 2;
...
}

Example 21 Examples of if and if/else statements.


1. if ( x > y )
{
temp = x;
x = y;
y = temp;
}
else
cout << "Don’t swap data\n";

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

3.6 Nested if statements


A nested if statement occurs when the true or false statement of an “if” statement is itself an “if” statement.
It can be used to implement decisions with several alternatives. For example,
// Increment numPos, numNeg, or numZero based on x

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;

ITCS101/CSC100 C++ Notes 14 Dr. Ali Alsaffar


3.7 Conditional Operator (?:) 3 CONTROL STRUCTURES I (SELECTION)

1. The conditions are evaluated in sequence.


2. Only one statement will be executed among all the statements.
3. If all conditions are false, then the last statement in the last “else” is executed.

Example 22 The table below describes the assignment of grades based on an exam score.

Exam score Grade Assigned


90 and above A
80 – 89 B
70 – 79 C
60 – 69 D
below 60 F

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

3.7 Conditional Operator (?:)


C++ provides the conditional operator (?:). The format is condition ? statement1 : statement2;
For example,
cout << grade >= 60 ? "Passed : "Failed";
grade >= 60 ? cout << "Passed\n" : cout << "Failed\n";

3.8 The switch Statement


3.8.1 Examples
1. // Determine life expectancy of a standard light bulb
switch (watts)
{
case 25: life = 2500;
break;
case 40:
case 60: life = 1000;
break;
case 75:
case 100: life = 750;
break;
default: life = 0;
}

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.”.

ITCS101/CSC100 C++ Notes 15 Dr. Ali Alsaffar


3.9 Exercises 3 CONTROL STRUCTURES I (SELECTION)

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

As an example, in the following equations:


2x − y = 8.3
4x + 3y = 10.1

ITCS101/CSC100 C++ Notes 16 Dr. Ali Alsaffar


3.9 Exercises 3 CONTROL STRUCTURES I (SELECTION)

a1 = 2.0, b1 = −1.0, c1 = 8.3, a2 = 4.0, b2 = 3.0, and c2 = 10.1.


D = (2.0 × 3.0 + 1.0 × 4.0) = 10
x = (1/10) × (3.0 × 8.3 + 1.0 × 10.1) = 3.5 and
y = (1/10) × (2.0 × 10.1 − 4.0 × 8.3) = −1.3.

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.

A sample Input/Output Screen.

Enter a1, b1, and c1: 2.0 -1.0 8.3


Enter a2, b2, and c2: 4.0 3.0 10.1

The value of x = 3.5


The value of y = -1.3

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.

Sample lines of output:


(-1.0, -2.5) is in quadrant three.
(0.0, 4.8) is on the y axis.
7. The National Earthquake Information Center has asked you to write a program implementing the following
decision table to characterize an earthquake based on its Richter scale number.
Richter Scale
Number (n) Characterization
n < 5.0 Little or no damage.
5.0 ≤ n < 5.5 Some damage.
5.5 ≤ n < 6.5 Serious damage: walls may crack or fall.
6.5 ≤ n < 7.5 Disaster: houses and buildings destroyed.
higher Catastrophe: most buildings destroyed.

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:

Enter No. of hours worked: 40


Enter hourly rate: 4.5
Enter Marital Status: M

Gross Pay is $218.50

9. The relative gravity of some of the planets in the solar system are shown below:

ITCS101/CSC100 C++ Notes 17 Dr. Ali Alsaffar


3.9 Exercises 3 CONTROL STRUCTURES I (SELECTION)

Planet Relative Gravity


Sun 27.5
Venus 0.88
Jupiter 2.64
Saturn 1.15

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

Enter the weight? 50


Enter the first letter of the planet? S
Enter the second letter? A

Weight in planet is 57.50

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:

Code Arithmetic Operation


A or a +
S or s -
M or m *
D or d /

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

Enter two float numbers> 6 7


Enter a character to perform arithmetic operation> g

Invalid character.

Sample Input/Output #2

Enter two float numbers> 5.0 2.0


Enter a character to perform arithmetic operation> M

5.0 * 2.0 = 10.0

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:

ITCS101/CSC100 C++ Notes 18 Dr. Ali Alsaffar


3.9 Exercises 3 CONTROL STRUCTURES I (SELECTION)

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

1971 to 1979 Less than 2700 lbs 4 27.000


2700 to 3800 lbs 5 30.500
More than 3800 lbs 6 52.500

1980 or later Less than 3500 lbs 7 19.500


3500 or more lbs 8 52.500
Using this information, write a C++ program that accepts the year and weight of an automobile and
determines and displays the weight class and registration fee for the car.
13. Write a C++ program that accepts a number followed by one space and then a letter. If the letter
following the number is ‘f’ or ‘F’, the program is to treat the number entered as a temperature in degrees
Fahrenheit, convert the number to the equivalent degrees Celsius, and print the result. If the letter
following the number is ‘c’ or ‘C’, the program is to treat the number entered as a temperature in degrees
Celsius, convert the number to the equivalent degrees Fahrenheit, and print the result. If the letter is
neither ‘f’, ‘F’, ‘c’, nor ‘C’, the program is to print a message that the input is invalid and terminate.
The formulas for conversion are:
Celsius = (5/9)(F ahrenheit − 32)
F ahrenheit = (9/5)(Celsius + 32)

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

--- First Line --- --- First Line ---


Enter first point: 1.3 6.2 Enter first point: 6.4 8.3
Enter second point: 4.3 -4.5 Enter second point: -3.1 2.3

--- Second Line --- --- Second Line ---


Enter first point: -3.12 5.34 Enter first point: 2.8 5.32
Enter second point: -4.8 5.6 Enter second point: -6.7 -0.68

The two lines intersect. The two lines are parallel.


They are not perpendicular.

ITCS101/CSC100 C++ Notes 19 Dr. Ali Alsaffar


3.9 Exercises 3 CONTROL STRUCTURES I (SELECTION)

#include <i o s t r e a m >


using namespace s t d ;
int main ( )
{
f l o a t L1x1 , L1y1 , L1x2 , L1y2 ,
L2x1 , L2y1 , L2x2 , L2y2 ,
s1 , s 2 ;

c o u t << ”−−− F i r s t Li ne −−−” << e n d l ;


c o u t << ” Enter f i r s t p o i n t : ” ;
c i n >> L1x1 >> L1y1 ;
c o u t << ” Enter Second p o i n t : ” ;
c i n >> L1x2 >> L1y2 ;
c o u t << e n d l ;
c o u t << ”−−− Second L ine −−−” << e n d l ;
c o u t << ” Enter f i r s t p o i n t : ” ;
c i n >> L2x1 >> L2y1 ;
c o u t << ” Enter Second p o i n t : ” ;
c i n >> L2x2 >> L2y2 ;

s 1 = ( L1y2 − L1y1 ) / ( L1x2−L1x1 ) ;


s 2 = ( L2y2 − L2y1 ) / ( L2x2−L2x1 ) ;

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

ITCS101/CSC100 C++ Notes 20 Dr. Ali Alsaffar


4 CONTROL STRUCTURES II (REPETITION)

4 Control Structures II (Repetition)


4.1 The while Looping (Repetition) Structure
Syntax: while ( loop repetition condition )
statement;

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.

Example 23 Consider the following C++ program segment.

int i = 0;
while ( i <= 20 )
{
cout << i << " ";
i += 5;
}

4.1.1 Case 1: Counter-Controlled while Loops

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

while ( c o u n t e r < N) // Test t h e l o o p c o n t r o l v a r i a b l e


{
...
c o u n t e r ++; // 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 24 Write a program fragment that produces this output:


0 1
1 2
2 4
3 8
4 1
5 3
6 6

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

ITCS101/CSC100 C++ Notes 21 Dr. Ali Alsaffar


4.1 The while Looping (Repetition) Structure 4 CONTROL STRUCTURES II (REPETITION)

4.1.2 Case 2: Sentinel-Controlled while Loops

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

const int SENTINEL = 0 ;

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

4.1.3 Case 3: Flag-Controlled while Loops

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

while ( ! found ) // Test t h e l o o p c o n t r o l v a r i a b l e


{
...
if ( expression )
found = t r u 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 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 ( )

ITCS101/CSC100 C++ Notes 22 Dr. Ali Alsaffar


4.1 The while Looping (Repetition) Structure 4 CONTROL STRUCTURES II (REPETITION)

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

i f (num < 0 ) num ∗= −1;

count = 0 ;
done = f a l s e ;
while ( ! done )
{
i f ( num != 0 )
{
count++;
num /= 1 0 ;
}
else
done = t r u e ;
}

c o u t << e n d l << ”The number o f d i g i t s i s ” << count ;


return 0 ;
}

4.1.4 Case 4: EOF-Controlled while Loops

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

c o u t << ” t h e sum o f t h e i n t e g e r s ” << e n d l ;


i n F i l e >> num ;

while ( ! i n F i l e . e o f ( ) )
{

ITCS101/CSC100 C++ Notes 23 Dr. Ali Alsaffar


4.2 for Looping (Repetition) Structure 4 CONTROL STRUCTURES II (REPETITION)

c o u t << num << e n d l ;


sum += num ;
i n F i l e >> num ;
}

c o u t << ” i s ” << sum << e n d l ;

inFile . close ();


return 0 ;
}

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

4.2 for Looping (Repetition) Structure


Syntax: for ( initial; condition; update )
statement;

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.

ITCS101/CSC100 C++ Notes 24 Dr. Ali Alsaffar


4.3 do...while Looping (Repetition) Structure 4 CONTROL STRUCTURES II (REPETITION)

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;

2. Trace the following

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;

cout << "number\t\tnumber^3\n\n";


for( number = 0; number <= N; number++)
{
cube = pow(number, 3);
cout << number << "\t\t" << cube;
}
return 0;
}

4.3 do...while Looping (Repetition) Structure


do
statement
while (expression);

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.

cout << "\nEnter a positive integer> ";


cin >> num;
do {
cout << num % 10 << " ";

ITCS101/CSC100 C++ Notes 25 Dr. Ali Alsaffar


4.4 The break and continue statements 4 CONTROL STRUCTURES II (REPETITION)

num /= 10;
} while (num > 0);
cout << endl;

4.4 The break and continue statements


• Use the break statement in while, for, and do...while repetition loops to immediately exit from the
loop.

• 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 << ” \ nBroke out a t x = ” << x ;

2. Using continue statement.


int x ;
f o r ( int x = 1 ; x <= 1 0 ; x++)
{
i f ( x == 5 ) continue ;
c o u t << x << ” \ t ” ;
}

c o u t << ” \ nUsed c o n t i n u e . ” ;

3. Using Break statement.


sum = 0 ;
c i n >> num ;
while ( c i n )
{
i f ( num < 0 )
{
c o u t << ” N e g a t i v e number found i n t h e data . ” << e n d l ;
break ;
}
sum += num ;
c i n >> num ;
}

4. Using continue statement.


sum = 0 ;
c i n >> num ;
while ( c i n )
{
i f ( num < 0 )
{
c o u t << ” N e g a t i v e number found i n t h e data . ” << e n d l ;
c i n >> num ;

ITCS101/CSC100 C++ Notes 26 Dr. Ali Alsaffar


4.5 Confusing == and = Operators 4 CONTROL STRUCTURES II (REPETITION)

continue ;
}
sum += num ;
c i n >> num ;
}

4.5 Confusing == and = Operators


– if ( payCode == 4 ) if ( payCode = 4 )
printf(‘‘You get a bonus’’); printf(‘‘You get a bonus’’);

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

There are 3 odd numbers. The maximum odd number is 17.

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

ITCS101/CSC100 C++ Notes 27 Dr. Ali Alsaffar


4.6 Exercises 4 CONTROL STRUCTURES II (REPETITION)

Sample Input/Output

Enter wind speed> 45


Gale
Enter wind speed> 19
Not a strong wind
Enter wind speed> -1

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.

Time on deposit Interest rate


Greater than or equal to 5 years 0.95
Less than 5 years but greater than or equal to 5 years 0.90
Less than 4 years but greater than or equal to 4 years 0.90
Less than 3 years but greater than or equal to 3 years 0.90
Less than 2 years but greater than or equal to 2 years 0.90
Less than 1 years but greater than or equal to 1 years 0.90
Less than 1 year 0.058

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.

Enter student ages in the range (1-18), -1 to stop:


6 4 16 2 22 11 17 3 -1

The number of Preschool students: 3


The number of Primary students: 2
The number of Intermediate students: 0
The number of Secondary students: 2
7. Write a program that computes and displays the GPA of a student in a specified semester. The program
should read the number of courses taken in that semester and for each course read the number of credits
(integer) and a grade letter (character). The GPA is computed as follows.
Credit1 × Points1 + Credit2 × Points2 + · · · + Creditn × Pointsn
GPA =
Total Credits
where n is the number of courses, Crediti is the number of credits for the ith course, and Pointsi is the points
received for the ith course. The value of Pointsi depends on the grade received for a course. It is obtained
as follows.

Grade Points Grade Points


A 4.0 C 2.0
B 3.0 D 1.0
C 2.0

ITCS101/CSC100 C++ Notes 28 Dr. Ali Alsaffar


4.6 Exercises 4 CONTROL STRUCTURES II (REPETITION)

As an example, if a student took 3 courses as shown below.


Credit Grade
2 C 2 × 2.0 + 4 × 4.0 + 3 × 3.0
then the GPA = = 3.22222
4 A 9
3 B

Here is a sample input/output of your program:

How many courses: 3


Enter credit and grade for each course
2C
4A
3B
Your GPA is 3.22222

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:

GPA Transcript Message


0.99–1.99 Ask the user for how many previous failed semesters. If the student failed on two
previous semesters then he/she is Suspended, otherwise he/she is On Probation.
2.00–2.99 Passed.
3.00–3.49 Dean’s Honor List.
3.50–4.00 President’s Honor List.

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

Enter student GPA’s, negative number to end:


3.11
2.25
4.0
1.95
3.05
4.0
2.35
-1

There are 2 students with a GPA 4.0.


They represent 28.57% of the students.

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.

ITCS101/CSC100 C++ Notes 29 Dr. Ali Alsaffar


4.6 Exercises 4 CONTROL STRUCTURES II (REPETITION)

• The total number of married members.


11. Write a program to process a collection of GPA’s of students collected from a survey. Your program should
count and print the number of Excellent students (3.5 ≤ GP A ≤ 4.0), the number of Very-Good students
(3.0 ≤ GP A < 3.5), and the number of Good students (2.5 ≤ GP A < 3.0). Any other GPA (less than 2.5)
is ignored. Here is a sample Input/Output of your program:

How many students? 26


Enter GPA for student#1: 3.5
Enter GPA for student #2: 2.8
Enter GPA for student #3: 2.1
.
.
.
Enter GPA for student #26: 3.99

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

The largest prime less than 20 is 19


The smallest prime greater than 20 is 23

13. Fibonacci (Italian mathematician) discovered the following series:


1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, . . .
As you see each next number is the sum of previous two numbers (except the first two numbers). Write a
complete C++ program to compute the first 88 numbers of this series, and print them 5 numbers per line.

#include <stdio.h> #define SIZE 88

void main() {
unsigned long int current, previous, next, i;

printf("The first %d Fibonacci numbers are:\n", SIZE);

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

14. Write a program to compute the following series:


x2 x3 x4 x5
ln(1 + x) = x − + − + + ······
2 3 4 5
x3 x5 x7 x9
sin(x) = x − + − + + ···
3! 5! 7! 9!

ITCS101/CSC100 C++ Notes 30 Dr. Ali Alsaffar


4.6 Exercises 4 CONTROL STRUCTURES II (REPETITION)

/* ln(1+x) = x - x^2/2 + .... */ /* Sin(x) = x - x^3/3! + .... */

#include <stdio.h> #define SIZE 1000 #include <stdio.h> #define SIZE 1000

void main() { void main() {


int i; int i;
double x, term, sum; double x, term, sum;

printf("Enter the value of x: "); printf("Enter the value of x: ");


scanf("%lf", &x); scanf("%lf", &x);

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

16. Write a program that displays the following table of integers:

for ( i = 3; i <= 20; i++) {


3 6 9 ··· 30 for ( j = i; j <= i * 10; j += i)
4 8 12 ··· 40 printf("%-5d", j);
.. .. .. .. .. printf("\n");
. . . . . }
20 40 60 ··· 200

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;

printf("Enter n (1-9):? ");

ITCS101/CSC100 C++ Notes 31 Dr. Ali Alsaffar


4.6 Exercises 4 CONTROL STRUCTURES II (REPETITION)

scanf("%d", &n);
while ( n < 1 && n > 9 )
{
printf("Invalid input.\n");
printf("Enter n (1-9):? ");
scanf("%d", &n);
}

for( i = 1; i <= n; i++)


{
for( j = 1; j<= n-i; j++)
printf(" ");
for( j = 1; j <= 2*i-1; j++)
printf("%d", i);
printf("\n");
}

return 0;
}

ITCS101/CSC100 C++ Notes 32 Dr. Ali Alsaffar


5 USER-DEFINED FUNCTIONS

5 User-Defined Functions
In C++, the concept of a function, either predefined or userdefined, is similar to that of a function in algebra.

5.1 Predefined Functions


In C++, predefined functions are organized into separate libraries. The table below lists some of the predefined
functions, the name of the header file, the data type of the parameters, and the function type.

Function Header File Purpose Parameters(s) Result


Type
abs(x) <cstdlib> Returns the absolute value of its argument: int int
abs(-7)=7
ceil(x) <cmath> Returns the smallest whole number that is not double double
less than x: ceil(56.34) = 57.0
cos(x) <cmath> Returns the cosine of angle x: cos(0.0)= double double
1.0 (radians)
exp(x) <cmath> Returns ex , where e = 2.718: exp(1.0) = double double
2.71828
fabs(x) <cmath> Returns the absolute value of its argument: double double
fabs(-5.67) = 5.67
floor(x) <cmath> Returns the largest whole number that is not double double
greater than x: floor(45.67) = 45.00
pow(x, y) <cmath> Returns xy ; if x is negative, y must be a whole double double
number: pow(0.16, 0.5) = 0.4
tolower(x) <cctype> Returns the lowercase value of x if x is upper- int int
case; otherwise, returns x
toupper(x) <cctype> Returns the uppercase value of x if x is lower- int int
case; otherwise, returns x
rand() <cstdlib> Returns a random number in the range 0 to none int
32768

Example 28 How to use predefined functions


#i n c l u d e <i o s t r e a m >
#i n c l u d e <cmath>
#i n c l u d e <cc typ e >

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

5.2 User-Defined Functions


User-defined functions in C++ are classified into two categories:

ITCS101/CSC100 C++ Notes 33 Dr. Ali Alsaffar


5.3 Value-returning functions 5 USER-DEFINED FUNCTIONS

• Value-returning functions – function that have a return type.


• Void functions – functions that do not have a return value.

5.3 Value-returning functions


To define your function you need to know the following:
1. The name of the function.
2. The number of parameters, if any.

3. The data type of each parameter.


4. The data type of the return value.
5. The code required to accomplish the task.

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.

5.3.1 Syntax: Value-Returning function

functionType functionName(formal parameter list)


{
statements
}

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 ;

c o u t << ” Enter two numbers : ” ;


c i n >> one >> two ;
c o u t << ”The l a r g e r i s ” << l a r g e r ( one , two ) ;

c o u t << ” Enter a n o t h e r two numbers : ” ;


c i n >> one >> two ;
maxNum = l a r g e r ( one , two ) ;

return 0 ;
}

// Function body

ITCS101/CSC100 C++ Notes 34 Dr. Ali Alsaffar


5.3 Value-returning functions 5 USER-DEFINED FUNCTIONS

double l a r g e r ( double x , double y )


{
double max ;
i f ( x >= y )
max = x ;
else
max = y ;
return max ;
}

Example 30 Examples on user-defined returning functions.


1. Write the necessary statements to find the larger of three double variables one, two and three using the
function larger() defined in the previous example.
(a) double maxNum = larger(one, two);
maxNum = larger(maxNum, two);

(b) double maxNum = larger(larger(one, two), three);


double maxNum = larger(maxNum, two);

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 o u t << ” Enter a number : ” ;


c i n >> number ;
i f ( p l a i n d r o m e ( number ) )
c o u t << number << ” i s a p l a i n d r o m e . ” ;
else
c o u t << number << ” i s not a p l a i n d r o m e . ” ;

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

ITCS101/CSC100 C++ Notes 35 Dr. Ali Alsaffar


5.4 Void Functions 5 USER-DEFINED FUNCTIONS

5.4 Void Functions


5.4.1 Void Functions Without Parameters
The general form (syntax) of the void function without formal parameters is:
void functionName()
{
statements
}

Example 31 An example of using void function without formal parameters.


#i n c l u d e <i o s t r e a m >
u s i n g namespace s t d ;

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

5.4.2 Void Functions With Parameters


The general form (syntax) of the void function with formal parameters is:
void functionName(formal parameter list)
{
statements
}

Example 32 An example of using void function with formal parameters.


#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 >
u s i n g namespace s t d ;

void p r i n t C h a r ( char ch , int c o u t ) ;

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 ;

f o r ( int L = 1 ; L <= l i n e s ; L++)


{

ITCS101/CSC100 C++ Notes 36 Dr. Ali Alsaffar


5.5 Reference Variables as Parameters 5 USER-DEFINED FUNCTIONS

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

void p r i n t C h a r ( char ch , int count )


{
f o r ( int s = 1 ; s <= count ; s++)
c o u t << ch ;
}

5.5 Reference Variables as Parameters


Reference parameters can pass one or more values for a function and can change the value of the actual
parameters.

Example 33 What is the output of the following program.


#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 >
u s i n g namespace s t d ;

void funOne ( int a , int& b , char c ) ;


void funTwo ( int& x , int y , char& w ) ;

int main ( ) {
int num1 = 1 0 , num2 = 1 5 ;
char ch = ’A ’ ;

c o u t << ” I n s i d e main : num1 = ” << num1


<< ” , num2 = ” << num2 << ” , and ch = ”
<< ch << e n d l ;

funOne (num1 , num2 , ch ) ;

c o u t << ” A f t e r funOne : num1 = ” << num1


<< ” , num2 = ” << num2 << ” , and ch = ”
<< ch << e n d l ;

funTwo (num2 , 2 5 , ch ) ;

c o u t << ” A f t e r funtwo : num1 = ” << num1


<< ” , num2 = ” << num2 << ” , and ch = ”
<< ch << e n d l ;

return 0 ;
}

void funOne ( int a , int& b , char c )


{
int one = a ;
a++;
b = b ∗ 2;
c = ’B ’ ;
c o u t << ” I n s i d e funOne : a = ” << a
<< ” , b = ” << b << ” , c = ” << c
<< ” , and one = ” << one << e n d l ;
}

ITCS101/CSC100 C++ Notes 37 Dr. Ali Alsaffar


5.6 Scope of an Identifier 5 USER-DEFINED FUNCTIONS

void funTwo ( int& x , int y , char& w)


{
x++;
y = y ∗ 2;
w = ’G ’ ;
c o u t << ” I n s i d e funTwo : x = ” << x
<< ” , y = ” << y << ” , and w = ”
<< w << e n d l ;
}

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

5.6 Scope of an Identifier


Local identifer. Identifiers declared within a function (or block). Local identifers are not accessible outside
of the function (block).

Global identifier. Identifiers declared outside of every function definition.

Example 34 What is the output of the following program.


#i n c l u d e <i o s t r e a m >
u s i n g namespace s t d ;

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

ITCS101/CSC100 C++ Notes 38 Dr. Ali Alsaffar


5.7 Exercises 5 USER-DEFINED FUNCTIONS

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

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.

int replm(int i, int j)


{
int min, count;

min = i
if ( j < min ) min = j;

for( count = 0; count < min; count++)


if ( i % count == 0 && j % count == 0
return 0;
return 1;
}

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.

int multipl(int n, int m)


{
if ( m % n == 0 )
return 1;

ITCS101/CSC100 C++ Notes 39 Dr. Ali Alsaffar


5.7 Exercises 5 USER-DEFINED FUNCTIONS

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.

ITCS101/CSC100 C++ Notes 40 Dr. Ali Alsaffar


6 USER-DEFINED SIMPLE DATA TYPES

6 User-Defined Simple Data Types


6.1 Enumeration Type
The syntax for enumeration type is:

enum typeName {value1, value2, ...};

The set of values that you specify for the data type must be identifers.

Example 35 Examples of enumeration type definitions.


// legal enumeration types
enum colors {BROWN, BLUE, RED, GREEN, YELLOW};
enum standing {FRESHMAN, SOPHOMORE, JUNIOR, SENIOR};
enum grades {A, B, C, D, F};
enum places {FIRST, SECOND, THIRD, FOURTH};
enum sports {BASKETBALL, FOOTBALL, HOCKEY, BASEBALL, SOCCER, VOLLEYBALL};

// illegal enumeration types


enum grades {’A’, ’B’, ’C’, ’D’, ’F’};
enum places {1ST, 2ND, 3RD, 4TH};

6.2 Declaring Variables


Once a data type is defined, you can declare variables of that type.

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.

enum sports {BASKETBALL, FOOTBALL, HOCKEY, BASEBALL, SOCCER, VOLLEYBALL};


...
sports mySport, favSport;
..
mySport = BASKETBALL;
favSport = mySport;

6.4 Operations on Enumeration Types


No arithmetic operations are allowed on the enumeration type.

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

// True if mysport is SOCCER or VOLLEYBALL

ITCS101/CSC100 C++ Notes 41 Dr. Ali Alsaffar


6.5 Declaring Variables When Defining the Enumeration Type 6 USER-DEFINED SIMPLE DATA TYPES

if (mysport >= BASEBALL) ..

//Using enumeration in loops


for(mySport = BASKETBALL; mySport <= SOCCER;
mysport = static_cast<sports>(mysport + 1))
...

// Functions and Enumeration Types


sports inFunction()
{
return FOOTBALL;
}

6.5 Declaring Variables When Defining the Enumeration Type


C++ Allows you to define an enumeration type and at the same time declare a variable of this type.

enum grades {A, B, C, D, F} courseGrades;


enum coins {PENNY, NICKEL, DIME, HALFDOLLAR, DOLLAR} change, usCoins.

6.6 typedef Statement


In C++, you can create an aliases to previously defined data type by using the typedef statement. The general
syntax is

typedef typeName newTypeName;

Example 38 Some examples on typedef.


typedef in integer;
typedef unsigned long int bigPositiveNumber;
...
bigPositiveNumber num;
cin >> num;

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.

ITCS101/CSC100 C++ Notes 42 Dr. Ali Alsaffar


7 ARRAYS

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.

7.1 Declaring and Referencing Arrays


The declaration double x[8]; instructs the compiler to associate eight memory cells with the name x; these
memory cells will be adjusted to each other in memory. Each element of array x may contain a single type
double value, so a total of eight such numbers may be stored and referenced using the array name x.
Example 39 Let x be the array shown below and declared as double x[8];

x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7]

16.0 12.0 6.0 8.0 2.5 12.0 14.0 -54.5

cout << setpresion(1) << x[0]; Display the value of x[0], which is 16.0

x[3] = 25.0; Stores the value 25.0 in x[3]

sum = x[0] + x[1]; Stores the sum of x[0] and x[1], which is 28.0
in the variable sum.

sum += x[2]; Adds x[2] to sum. The new x[2] is 34.0

x[3] += 1.0; Adds 1.0 to x[3]. The new x[3] is 26.0

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

The general form used for accessing an array component is:


arrayName[indexExp]
indexExp is called the index (subscript). The index value is either:
Constant. For example, x[0], x[3].
Variable. For example, x[i], x[index], where i and index must be a non-negative integer.
Expression. For example, x[2*i-1], x[rev-1], where the expression should be a none-negative expression.

7.2 Initializing Arrays


1. Using normal assignment statement:

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

2. Reading from the user:

int num[120];
int count = 0;
...
cout << "How many integers? ";

ITCS101/CSC100 C++ Notes 43 Dr. Ali Alsaffar


7.3 Examples Using Arrays 7 ARRAYS

cin >> count;


cout << Enter " << count << "integers:\n";
for(i = 0; i < count; i++)
cin >> num[i];

3. During declaration:

int prime[10] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};


int num[] = {1, 3, 7}; // num size is 3
int sales[10] = { 0 }; // all elements are initialized to 0
double salary[50] = {90.5, 80.6}; // salary[2]..salary[49] = 0

7.3 Examples Using Arrays


The following declaration is used through this example.
double sales[10];
int index;
double largestSale, sum, average;

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.

const int SENTINEL = -1;


const int SIZE = 100;
...
int count = 0;
double temp;
cin >> temp;
while ( (temp != SENTINEL) && ( count < SIZE )
{
sales[count++] = temp;
cin >> temp;
}

d. Printing an array: The following loop outputs the array sales.


for (index = 0; index < 10; index++)
cout >> sales[index] << "\t";
e. Finding the sum and average of an array: The following C++ code finds the sum of the elements of
the array sales and the average sale amount.
sum = 0.0;
for (index = 0; index < 10; index++)
sum += sales[index];
average = sum / 10.0;
f. Finding the largest element of the array: The following C++ code finds the the largest element in the
array sales.
int maxIndex = 0;
for (index = 1; index < 10; index++)

ITCS101/CSC100 C++ Notes 44 Dr. Ali Alsaffar


7.4 string Type 7 ARRAYS

if (sales[maxIndex] < sales[index])


maxIndex = index;
largestSale = sales[maxIndex]
g. Exchange first half with last half elements: the following C++ code exchange the first half with the
second half of the array.

#const int SIZE = 100;


...
for(int i = 0; i < n/2 - 1; ++i)
{
double temp = sales[ i ];
sales[ i ] = sales[ SIZE-i-1 ];
sales[ SIZE-i-1 ] = temp;
}

7.4 string Type


The data type string is a programmer-defined type and is not part of the C++ language. Before using the
data type string, the program must include the header file <string>.

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

Expression Value Explanation

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.

• Using the array index (subscript).


string str1 = "Hello there";
str1[6] = ‘T’; // Replaces the character ‘t’ with ‘T’

ITCS101/CSC100 C++ Notes 45 Dr. Ali Alsaffar


7.4 string Type 7 ARRAYS

7.4.1 Additional string Operators


• length Function

strVer.length()

This function returns the number of characters currently in the string.


string str = "It is sunny.";
cout << str.length(); // Displays 12
• size Function
strVar.size()
This function returns the same value as does the function length().
string str = "It is sunny.";
cout << str.size(); // Displays 12
• find Function
– strVar.find(strExp)

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

cout << str.find("is"); Outputs 11

cout << str.find("and"); Outputs 21

cout << str.find(’s’); Outputs 3

cout << str.find(’o’); Outputs 16

cout << str.find(str1); Outputs 14

cout << str.find("the"); Outputs string::nops

cout << str.find(’i’, 6); Outputs 8

• 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.

Example 41 string str = "Outside it is cloudy and warm.";


string str1;

ITCS101/CSC100 C++ Notes 46 Dr. Ali Alsaffar


7.5 Passing Arrays to Functions 7 ARRAYS

Statement Effect (Output)

cout << str.substr(0, 5); It is

cout << str.find("and"); Outputs 21

cout << str.find(’s’); Outputs 3

cout << str.find(’o’); Outputs 16

cout << str.find(str1); is clo

7.5 Passing Arrays to Functions


1. Passing Arrays and Individual array elements to functions

#include <stdio.h>
#define SIZE 5

vod modifyArray( int [], int );


void modifyElement( int );

void main()
{
int a[SIZE] = {0, 1, 2, 3, 4}, i;

for( i=0; i <= SIZE - 1; i++)


printf("%3d", a[i]);
printf("\n");

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

void modifyArray( int b[], int size)


{
int j;
for( j =0; j <= size-1; j++)
b[j] *= 2;
}

void modifyElement( int e )


{
printf("Value in modifyElement is %d\n", e *= 2);
}

2. Returns the largest of the first n values in array list

int get_max(const int list[], int n)


{
int i, cur_large;

cur_large = list[0];
for( i = 1; i < n; ++i )
if ( list[i] > cur_large ) cur_large = list[i];

ITCS101/CSC100 C++ Notes 47 Dr. Ali Alsaffar


7.6 Multiple-Subscripted Arrays 7 ARRAYS

return cur_large;
}

7.6 Multiple-Subscripted Arrays


1. Returns the largest of the first n values in array list

#include <stdio.h>

void printArray( const int [][ 3 ]);

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

printf("Values in array1 by row are:\n");


printArray( array1 );

printf("Values in array2 by row are:\n");


printArray( array2 );

printf("Values in array3 by row are:\n");


printArray( array3 );
}

void printArray( const int a[][ 3 ])


{
int i, j;
for( i = 0; i <= 1; i++) {
for( j = 0; j <= 2; j++ )
printf("%d ", a[i][j]);
printf( "\n" );
}
}

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

int winner( const char [][SIZE] );

void main() {
char ticTacToe[SIZE][SIZE] = { "oxo" ,
"xxo" ,

ITCS101/CSC100 C++ Notes 48 Dr. Ali Alsaffar


7.7 Problems 7 ARRAYS

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

int winner( const char T[][SIZE] ) {


int i,j, xcount, ocount;

for(i = 0; i < SIZE; i++) /* Check all rows */


{
for(j = 0, ocount = 0, xcount = 0; j < SIZE; j++)
if (T[i][j] == ’x’) xcount++;
else ocount++;
if ( xcount == 3 ) return 1;
if ( ocount == 3 ) return 2;
}

for(j = 0; j < SIZE; j++) /* Check all columns */


{
for(i = 0, ocount = 0, xcount = 0; i < SIZE; i++)
if (T[i][j] == ’x’) xcount++;
else ocount++;
if ( xcount == 3 ) return 1;
if ( ocount == 3 ) return 2;
}
/* Check left diagonal */
for ( i = 0, xcount = 0, ocount = 0; i < SIZE; ++i)
if (T[i][i] == ’x’) xcount++;
else ocount++;
if ( xcount == 3 ) return 1;
if ( ocount == 3 ) return 2;
/* Check right diagonal */
for ( i = SIZE-1, xcount = 0, ocount = 0; i >= 0; --i)
if (T[i][i] == ’x’) xcount++;
else ocount++;
if ( xcount == 3 ) return 1;
if ( ocount == 3 ) return 2;

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

list[0] list[1] list[2] list[3] list[4] list[5]

30 12 51 17 45 62

ITCS101/CSC100 C++ Notes 49 Dr. Ali Alsaffar


7.7 Problems 7 ARRAYS

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:

1 Window seat, left side 4 Aisle seat, right side


2 Center seat, left side 5 Center seat, right side
3 Aisle seat, left side 6 Window seat, right side

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.

AVAILABLE SEAT PAIRS


ROW SEATS
XX X,X
.
.
XX X,X

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

ITCS101/CSC100 C++ Notes 50 Dr. Ali Alsaffar


8 FILE PROCESSING

then your program should print the following:


days 0 and 2 are identical
days 3 and 6 are identical
8. Write a function that calculates and returns the sum of all elements on and below the “main diagonal”
of a rectangular matrix. Each rectangular matrix has one main diagonal. In the following three example
matrices, the elements on the main diagonal are labelled D. The elements below the main diagonal are
labelled x.

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.

#include<stdio.h> int main() {


int n;

printf("enter a positive integer, 0 to end");


scanf("%d", &n);
while( n != 0 )
{
if( n % 2 == 0 )
printf("%d\n", n*10);
else
printf("%d\n", n*2);

printf("enter a positive integer, 0 to end");


scanf("%d", &n);
}
return 0;
}

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

ITCS101/CSC100 C++ Notes 51 Dr. Ali Alsaffar


8.1 Problems 8 FILE PROCESSING

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;

infile = fopen("ORIGINAL.TXT", "w");


outfile= fopen("COPY.TXT","w");

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;

ITCS101/CSC100 C++ Notes 52 Dr. Ali Alsaffar

You might also like