You are on page 1of 94

P R E PAR E D B Y

I . A S M A A A B D U L L A H

D R . M O H A M M E D K H A D E R

A S U 2 0 1 3

FACULTY OF INFORMATION
TECHNOLOGY
Computer Science
Department

Structured Programming Lab Manual


V 3.0
Page 0
Text Book

Page 0
History of Changes

Version Date By Description


V0.0 September 7, Dr. Hazem Qatuos  Creation: Letter Document with
2012 margins Normal, that is 1 inch all
around
V1.0 September 9, Dr. Lab instructor  Modified the Exercises of Lab 1 by
2012 adding Q2
 Some editing in the introduction of
Lab 1
V2.0 Oct 31,2013 I.Asmaa Abdullah  Updated the manual from Lab 0 to
Lab 6
Dr.Mohammed  Updated the manual From Lab 7 to
Khader Lab 12

Page 0
Table of Contents

Page 0
Applied Science Private University – Jordan http://FIT.asu.edu.jo

0
Lab

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 1
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Lab 0:

The Basics of a C++ Programing Language

Lab Objectives:

After finishing lab 0 and lab 1 ,the student supposed to know the following :
o How to open the Microsoft visual studio , and the steps needed to write and execute a simple
program that print a simple statement ,after knowing The Basics of a C++ Program:
 Data types and identifiers
 Comments
 Special symbols
 data types
 Reserved words (key words)

o Find and correct the errors(syntax ,semantics ).


o Applying the escape characters like \n, \t,\r,\a.

0.1 Structured programming

Structured programming (sometimes known as modular programming) is a subset of procedural


programming that enforces a logical structure on the program being written to make it more efficient
and easier to understand and modify.

Structured programming frequently employs a top-down design model, in which developers map out
the overall program structure into separate subsections. A defined function or set of similar functions
is coded in a separate module or sub module, which means that code can be loaded into memory more
efficiently and that modules can be reused in other programs

Structured programming was first suggested by Corrado Bohm and Guiseppe Jacopini. The two
mathematicians demonstrated that any computer program can be written with just three structures:
decisions, sequences, and loops.

0.2 Comments

 Aim of comments to clear the program to reader, document then date when program is
written or modified

 The comments are ignored by the compiler

 There are two types of comments

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 2
Applied Science Private University – Jordan http://FIT.asu.edu.jo

o Single line //

o Multiple lines /* */

0.3 Special symbols

 Mathematical symbols + - * /

 Punctuation marks . ;(end statement) ? ,(spate items in list)

 Comparison symbols == != <= >=

0.4 Reserved words (key words)

 int, float, double, char, void, return

0.5 Identifi ers(case sensitive)

Identifiers are names of things that appear in program (ex: variables, constants, functions)

Some identifiers are predefined other are defined by user.

C++ identifiers consist of only: 1)Letters 2)Digits 3) underscore _ (no other symbols)

 It must begin with _ or letter (not digit)

Example of accepted identifiers : first _first fi_rst firts1

Example of unaccepted identifiers : fi rst first! First+ 1first

0.6 Data types

Data types are set of values together with a set of operations.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 3
Applied Science Private University – Jordan http://FIT.asu.edu.jo

0.6.1 Integral (simple) data type

0.6.2 Floating-Point (simple) Data Types


• C++ uses scientific notation to represent real numbers (floating-point notation)

• float: represents any real number

• Range: -3.4E+38 to 3.4E+38 (four bytes)

• double: represents any real number

• Range: -1.7E+308 to 1.7E+308 (eight bytes)

0.7 What is a Variable?

Computer programs manipulate (or process) data. A variable is used to store a piece of data for
processing. It is called variable because you can change the value stored.
More precisely, a variable is a named storage location, that stores a value of a particular data type. In
other words, a variable has a name, a type and stores a value of that type.

For example,

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 4
Applied Science Private University – Jordan http://FIT.asu.edu.jo

int sum; // Declare a variable named "sum" of the type "int" for storing
an integer.
// Terminate the statement with a semi-colon.
int number1, number2; // Declare two "int" variables named "number1" and "number2",
// separated by a comma.
double average; // Declare a variable named "average" of the type "double" for
storing a real number.
int height = 20; // Declare an int variable, and assign an initial value.

Once a variable is declared, you can assign and re-assign a value to a variable, via the assignment
operator "=".
For example,
int number; // Declare a variable named "number" of the type "int"
(integer)
number = 99; // Assign an integer value of 99 to the variable "number"
number = 88; // Re-assign a value of 88 to "number"
number = number + 1; // Evaluate "number + 1", and assign the result back to
"number"
int sum = 0; // Declare an int variable named sum and assign an initial
value of 0
sum = sum + number; // Evaluate "sum + number", and assign the result back to
"sum", i.e. add number into sum
int num1 = 5, num2 = 6; // Declare and initialize two int variables in one
statement, separated by a comma
double radius = 1.5; // Declare a variable name radius, and initialize to 1.5
int number; // ERROR: A variable named "number" has already been declared
sum = 55.66; // WARNING: The variable "sum" is an int. It shall not be
assigned a floating-point number
sum = "Hello"; // ERROR: The variable "sum" is an int. It cannot be assigned a
text string

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 5
Applied Science Private University – Jordan http://FIT.asu.edu.jo

1
Lab

Lab 1:

Using the Visual studio environment and Debugging


the Code.

1.1 Creating a new project :

We will create a sample project to help illustrate the use of Visual Studio. Note that this tutorial
assumes the use of Visual Studio 2012
.
1- After clicking on Visual Studio icon in Windows 8 scree n

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 6
Applied Science Private University – Jordan http://FIT.asu.edu.jo

2- Select New Project.

3- The dialog window that appears allows you to choose the type and name of your project. After
selecting Visual C++ in the list of templates on the left, choose Win32 Console Application
from the list of project types in the middle.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 7
Applied Science Private University – Jordan http://FIT.asu.edu.jo

4- Use the boxes at the bottom of this window to specify a name and location for your project.

Note :If you want to change the location of your project, click Browse ,choose the location you want,
create a new folder ,name it ,then save it .

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 8
Applied Science Private University – Jordan http://FIT.asu.edu.jo

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 9
Applied Science Private University – Jordan http://FIT.asu.edu.jo

5- After accepting these settings, a window appears that you can use to set application settings.
Click Next, then select the check box next to Empty project, which is under Additional
options, in the following window. Click Finish to create your project.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 10
Applied Science Private University – Jordan http://FIT.asu.edu.jo

6- The following screen will


appear

7- Then choose from view solution


explorer

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 11
Applied Science Private University – Jordan http://FIT.asu.edu.jo

7- To create your first C++ file, right click on Source Files, in the Solution Explorer window.
Choose Add New Item. In the list that appears, choose C++ file (.cpp), then name your
file.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 12
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Note that you can add existing files to your project, which can be useful when reusing code from
previous projects. Right click on the appropriate files folder (typically Source Files or Header Files),
then choose Add Existing Item. Find the desired file, then click Add to add it to the project.

1.2 Writing, Compiling, and Executing Programs


Let's create a simple application that handles basic input and output to illustrate the process of
creating a Visual Studio application. Enter the following in the code window:

// Week1 program
#include <iostream>
using name space std;

void main( )
{
int a;
cout << "Hello World!" << endl;
cin >> a;
cout << "a = " << a << endl;
}
Notice that Visual Studio color-codes parts of your program—C++ keywords are blue, strings
and library names are red, and comments are green.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 13
Applied Science Private University – Jordan http://FIT.asu.edu.jo

To compile your code, choose BuildBuild Solution in the main menu (or press F7).
To run your program, choose DebugStart Without Debugging (Ctrl+F5). This option forces
your program to pause when finished, allowing you to view all output, as shown in Figure 5. If you
simply press the green "play" button, which corresponds to Debug Start Debugging (F5),
your program will run until it encounters a breakpoint. If you have not set any breakpoints, the
program will run to completion and exit without allowing you to view the output.
Note that your program requires input—the statement cin >> a; causes the program to wait for the
user to enter at least one non-whitespace character and press Enter.

Output of basic program prior to user input

Final output of basic program. Note that the '7' is user input.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 14
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Note: Observe the use of int main() instead of void main(). Both are the same except that you
need to put return 0 at the end of the main function in case that you decided to use int main().
Remove return 0 if you decided to use void main().

1.2.1 Brief Explanation of the Program

#include<iostream>
usingnamespacestd;
The "#include" is called a preprocessor directive. A preprocessor directive begins with a # sign, and is
processed before compilation. The directive " #include <iostream>" tells the preprocessor to
include the "iostream" header file to support input/output operations. The " using namespace std;"
statement declares std as the default namespace used in this program. The names cout and endl,
which is used in this program, belong to the std namespace. These two lines shall be present in all
our programs. I will explain their meaning later.

voidmain(){ ...... }
defines the so-called main() function. The main() function is the entry point of program execution.
cout << "Hello, world!" << endl;
"cout" refers to the standard output (or Console OUTput). The symbol << is called the stream
insertion operator (or put-to operator), which is used to put the string "Hello, world!" to the console.
"endl" denotes the END-of-Line or newline, which is put to the console to bring the cursor to the
beginning of the next line.
cin >> a
"cin" refers to the standard input, The symbol >> is called the stream extraction operator.

1.3 C++ Terminology and Syntax


Programming language : a set of rules, symbols, and special words
Function: collection of statements; when executed, accomplishes something May be predefined or
standard

Statement : A programming statement performs a piece of programming action. It must be


terminated by a semi-colon (;) (just like an English sentence is ended with a period
.
Preprocessor Directive : The #include is a preprocessor directive and NOT a programming
statement. A preprocessor directive begins with hash sign ( #). It is processed before compiling the
program. A preprocessor directive is NOT terminated by a semicolon - Take note of this rule.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 15
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Block : A block is a group of programming statements enclosed by braces { }. This group of


statements is treated as one single unit. There is one block in this program, which contains
the body of the main() function. There is no need to put a semi-colon after the closing brace.

Comments : A multi-line comment begins with /* and ends with */. An end-of-line comment
begins with // and lasts till the end of the line. Comments are NOT executable statements and are
ignored by the compiler. But they provide useful explanation and documentation. Use comments
liberally.

Whitespaces : Blank, tab, and newline are collectively called whitespaces. Extra whitespaces are
ignored, i.e., only one whitespace is needed to separate the tokens. But they could help you and your
readers better understand your program. Use extra whitespaces liberally.

Case Sensitivity : C++ is case sensitive - a ROSE is NOT a Rose, and is NOT a rose.

Syntax: rules that specify which statements (instructions) are legal

Semantic rule : meaning of the instruction

1.4 The Process of Writing a C++ Program

Step 1: Write the source codes (.cpp) and header files (.h).
Step 2: Pre-process the source codes according to the preprocessor directives. The preprocessor
directives begin with a hash sign ( #), such as #include and #define. They indicate that certain
manipulations (such as including another file or replacement of symbols) are to be performed
BEFORE compilation.
Step 3: Compile the pre-processed source codes into object codes ( .obj, .o).
Step 4: Link the compiled object codes with other object codes and the library object codes
(.lib, .a) to produce the executable code (.exe).
Step 5: Load the executable code into computer memory.
Step 6: Run the executable code.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 16
Applied Science Private University – Jordan http://FIT.asu.edu.jo

If you missed the semicolon ( ; ) at the end of statement, this what will happen, when
you compile and run your file:

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 17
Applied Science Private University – Jordan http://FIT.asu.edu.jo

1.5 Debugging in Visual Studio


Executing Code Line-by-Line

You have two basic options for line-by-line code execution: Step Into (F11) or Step Over (F10).
For most code, these operations will behave the same . Step Into can be used to enter and step
through functions, which can then be exited using a third option: Step Out (Shift+F11). Step
Over will execute each line without entering any functions. All three options can be found in the
Debug menu; note that Step Out is only available when actively debugging a program.

The Debug menu. Note that the Step Out


command is not shown because no program is
being actively debugged

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 18
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Lab Exercises

1. Print each of the following patterns. Use one " cout <<" statement for each line of outputs.
End each line by printing an "endl".

* * * * * * * * * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * * * * *

(a) (b) (c)

2. Write a program to print the following picture. Take note that you need to use escape sequences
to print special characters.

'__'
(oo)
+========\/
/ || %%% ||
* ||-----||
"" ""

3. Suppose x,y and z are int variables and x=2,y=5 and z=6 what is the output of:

1. cout<<”x=”<<x<<”y=”<<y<<”,z=”<<z<<endl;
2. cout<<”x+y=”<<x+y<<endl;

4. Write a c++ program that prints the string “welcome to c++”; 7 times; each time in a single line;
each line includes one of the following notations
1) \n 2)\t 3)\b 4)\r 5)\\ 6)\’ 7)\”

Escape Sequence Description


\n New-line (or Line-feed)
\r Carriage-return
\t Tab

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 19
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Escape Sequence Description


\" Double-quote (needed to include " in double-quoted
string)
\' Single-quote
\\ Back-slash (to resolve ambiguity)

5.Write a program (called "Add2Numbers.cpp") that prompts user for two integers and prints their
sum ,fill the spaces to complete your program .
1 /*
2 * Prompt user for two integers and print their sum (Add2Integers.cpp)
3 */
4 #include <iostream>
5 using namespace std;
6
7 void main() {
8 .................; // Declare a variable named integer1 of the type integer
9 .................; // Declare a variable named integer2 of the type integer
10 .................; // Declare a variable named sum of the type integer
11
12 cout << "Enter first integer: "; // Display a prompting message
13 .................; // Read input from keyboard (cin) into integer1
14 cout << "Enter second integer: "; // Display a prompting message
15 .................; // Read input into integer2
16
17 sum = integer1 + integer2; // Compute the sum
18
19 // Print the result
20 cout << "The sum of " << integer1 << " and " << integer2
21 << " is " << sum << endl;
22
23
24 }

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 20
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Exercises

1. Write a program to prompt user for 5 integers and print their sum. Use
five int variables integer1 to integer5 to store the five integers.

2. Write a c++ program that prompts the user to input the time for an event; the user would enter
firstly the hour and then the minute, your program will print the entered time in format (hh:mm).
Example of the output:
“Enter a time for an event; at which hour and then at which minute”
05
30
Your event at 05:30
Press any key to continue

3. Write a C++ program that prompts the user to input the elapsed time for an event in seconds.
The program then outputs the elapsed time in hours, minutes, and seconds. (For example, if the
elapsed time is 9630 seconds, then the output is 2:40:30.)

4 . Write a C++ program that prompts the user to input the elapsed time for an event in hours,
minutes, and seconds. The program then outputs the elapsed time in seconds.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 21
Applied Science Private University – Jordan http://FIT.asu.edu.jo

References
1. http://civilium-ju.com/uploads/New/Science%20and%20other%20Engineering%20Materials
%20Section/C++/C++%20Programming%20From%20Problem%20Analysis%20to%20Program%20Design
%20[5th%20Edition]%20book.pdf

2. http://www.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introduction.html#zz-1.

My comments to modifying this Experiment


_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 22
Applied Science Private University – Jordan http://FIT.asu.edu.jo

2
Lab

Lab 2:Structured Programming:

Logical operators and logical selection

Lab Objectives:
After finishing the lab ,the student supposed to know the following :

 Identifying mathematical/ logical operations

 Knowing the precedence of operations

 Type casting

Operations
2.1 Arithmetic Operators

Type Example Operation


int 2 + 3 int 2 + int 3 → int 5
double 2.2 + 3.3 double 2.2 + double 3.3 → double 5.5
mix 2 + 3.3 int 2 + double 3.3 → double 2.0 + double 3.3 → double 5.3
int 1 / 2 int 1 / int 2 → int 0
double 1.0 / 2.0 double 1.0 / double 2.0 → double 0.5
mix 1 / 2.0 int 1 / double 2.0 → double 1.0 + double 2.0 → double 0.5
C++ supports the following arithmetic operators for numbers: short, int, long, long
long, char (treated as 8-bit signed integer), unsigned short, unsigned int, unsigned
long, unsigned long long, unsigned char, float, double and long double.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 23
Applied Science Private University – Jordan http://FIT.asu.edu.jo

All the above operators are binary operators, i.e., they take two operands. The multiplication, division
and remainder take precedence over addition and subtraction. Within the same precedence level
(e.g., addition and subtraction), the expression is evaluated from left to right. For example, 1+2+3-4 is
evaluated as ((1+2)+3)-4.
It is important to take note that int/int produces an int, with the result truncated, e.g., 1/2 →
0 (instead of 0.5).

2.2 MIXED-TYPE OPERATIONS


If both the operands of an arithmetic operation belong to the same type, the operation is carried out
in that type, and the result belongs to that type.
For example, int/int → int; double/double → double .
However, if the two operands belong to different types, the compiler promotes the value of
the smaller type to the larger type (known as implicit type-casting). The operation is then carried out
in the largertype. For example, int/double → double/double → double . Hence, 1/2 → 0, 1.0/2.0
→ 0.5, 1.0/2 → 0.5, 1/2.0 → 0.5 .

For example,

Operator Description Usage Examples


* Multiplication expr1 * expr2 2 * 3 → 6; 3.3 * 1.0 → 3.3
/ Division expr1 / expr2 1 / 2 → 0; 1.0 / 2.0 → 0.5
% Remainder (Modulus) expr1 % expr2 5 % 2 → 1; -5 % 2 → -1

+ Addition expr1 + expr2 1 + 2 → 3; 1.1 + 2.2 → 3.3


- Subtraction expr1 - expr2 1 - 2 → -1; 1.1 - 2.2 → -1.1
2.3 COMPOUND ASSIGNMENT OPERATORS
Besides the usual simple assignment operator '=' described earlier, C++ also provides the so-
called compound assignment operators as listed:
Operator Usage Description Example
= var = expr Assign the value of the LHS to thex = 5;
variable at the RHS
+= var += expr same as var = var + expr x += 5; same as x = x + 5
-= var -= expr same as var = var - expr x -= 5; same as x = x - 5

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 24
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Operator Usage Description Example


*= var *= expr same as var = var * expr x *= 5; same as x = x * 5
/= var /= expr same as var = var / expr x /= 5; same as x = x / 5
%= var %= expr same as var = var % expr x %= 5; same as x = x % 5

2.4 INCREMENT/DECREMENT OPERATORS


C++ supports these unary arithmetic operators: increment '++' and decrement '--'.

For example,

1 /* Test on increment (++) and decrement (--) Operator (TestIncDec.cpp) */


2 #include <iostream>
3 using namespace std;
4Operator Example Result
5
++ void main() { ++x
x++; Increment by 1, same as x += 1
6 int mark = 76; // declare & assign
--
7 cout << x--; --xendl; // 76Decrement by 1, same as x -= 1
mark <<
8
9 mark++; // increase by 1 (post-increment)
10 cout << mark << endl; // 77
11
12 ++mark; // increase by 1 (pre-increment)
13 cout << mark << endl; // 78
14
15 mark = mark + 1; // also increase by 1 (or mark += 1)
16 cout << mark << endl; // 79
17
18 mark--; // decrease by 1 (post-decrement)
19 cout << mark << endl; // 78
20
21 --mark; // decrease by 1 (pre-decrement)
22 cout << mark << endl; // 77
23
24 mark = mark - 1; // also decrease by 1 (or mark -= 1)
25 cout << mark << endl; // 76
26
27 }

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 25
Applied Science Private University – Jordan http://FIT.asu.edu.jo

The increment/decrement unary operator can be placed before the operand (prefix operator), or after
the operands (postfix operator). They takes on different meaning in operations.

Operator Description Example Result


++var Pre-Increment y = ++x; same as x=x+1; y=x;
Increment var, then use the new value of var
var++ Post-Increment y = x++; same as oldX=x; x=x+1; y=oldX;
Use the old value of var, then
increment var
--var Pre-Decrement y = --x; same as x=x-1; y=x;
var-- Post-Decrement y = x--; same as oldX=x; x=x-1; y=oldX;

If '++' or '--' involves another operation, then pre- or post-order is important to specify the order of
the two operations. For examples,

x = 5;
cout << x++ << endl; // Save x (5); Increment x (=6); Print old x (5).
x = 5;
cout << ++x << endl; // Increment x (=6); Print x (6).
// This is confusing! Try to avoid! What is i=++i? What is i=i++?

Prefix operator (e.g, ++i) could be more efficient than postfix operator (e.g., i++) in some situations.

2.5 IMPLICIT TYPE-CONVERSION VS. EXPLICIT TYPE-CASTING


Converting a value from one type to another type is called type casting (or type conversion). There
are two kinds of type casting:
1. Implicit type-conversion performed by the compiler automatically, and
2. Explicit type-casting via an unary type-casting operator in the form of (new-
type)operand or new-type(operand).

2.5.1 IMPLICIT (AUTOMATIC) TYPE CONVERSION


When you assign a value of a fundamental (built-in) type to a variable of another fundamental type,
C++ automatically converts the value to the receiving type, if the two types are compatible. For
examples,
 If you assign an int value to a double variable, the compiler automatically casts
the int value to a double double (e.g., from 1 to 1.0) and assigns it to the double variable.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 26
Applied Science Private University – Jordan http://FIT.asu.edu.jo

 if you assign a double value of to an int variable, the compiler automatically casts
the double value to an int value (e.g., from 1.2 to 1) and assigns it to the int variable. The
fractional part would be truncated and lost. Some compilers issue a warning/error "possible loss
in precision"; others do not.

1 /*
2 * Test implicit type casting (TestImplicitTypeCast.cpp)
3 */
4 #include <iostream>
5 #include <iomanip>
6 using namespace std;
7
8 void main() {
9 int i;
10 double d;
11
12 // print floating point number in fixed format with 1 decimal place
13 cout << fixed << setprecision(1);
14
15 i = 3;
16 d = i; // Assign an int value to double
17 cout << "d = " << d << endl; // 3.0
18
19 d = 5.5;
20 i = d; // Assign a double value to int
21 cout << "i = " << i << endl; // 5 (truncated, no warning!)
22
23 i = 6.6; // Assign a double literal to int
24 cout << "i = " << i << endl; // 6 (truncated, no warning!)
25 }

C++ will not perform automatic type conversion, if the two types are not compatible.

2.5.2 EXPLICIT TYPE-CASTING

You can explicitly perform type-casting via the so-called unary type-casting operator in the form
of (new-type)operand or new-type(operand). The type-casting operator takes one operand in the
particular type, and returns an equivalent value in the new type. Take note that it is an operation that
yields a resultant value, similar to an addition operation although addition involves two operands.
For example,
// Print floating-point number in fixed format with 1 decimal point (need <iomanip>)

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 27
Applied Science Private University – Jordan http://FIT.asu.edu.jo

cout << fixed << setprecision(1);

cout << (double)5 << endl; // int 5 → double 5.0


cout << (int)5.5 << endl; // double 5.5 → int 5

double aDouble = 5.6;


int anInt = (int)aDouble; // return 5 and assign to anInt. aDouble does not change!

// C++ also supports function-style type cast.


cout << double(5) << endl; // 5.0
cout << int(5.5) << endl; // 5
cout << int(aDouble) << endl; // 5

Example :
1 /* Test Type Casting (TestTypeCast.cpp) */
2 #include <iostream>
3 #include <iomanip>
4 using namespace std;
5
6 int main() {
7 // Print floating-point number in fixed format with 1 decimal place
8 cout << fixed << setprecision(1);
9
10 // Test explicit type casting
11 int i1 = 4, i2 = 8;
12 cout << i1 / i2 << endl; // 0
13 cout << (double)i1 / i2 << endl; // 0.5
14 cout << i1 / (double)i2 << endl; // 0.5
15 cout << (double)(i1 / i2) << endl; // 0.0
16
17 double d1 = 5.5, d2 = 6.6;
18 cout << (int)d1 / i2 << endl; // 0
19 cout << (int)(d1 / i2) << endl; // 0
20
21 // Test implict type casting
22 d1 = i1; // int implicitly casts to double
23 cout << d1 << endl; // 4.0
24 i2 = d2; // double truncates to int! (Warning?)
25 cout << i2 << endl; // 6
26 }

2.5.3 OPERATOR STATIC-CAST<TYPE>

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 28
Applied Science Private University – Jordan http://FIT.asu.edu.jo

C++ introduces a new operator called static_cast<type> to perform type conversion (because the
regular cast mentioned earlier is too lax and could produce expected results). static_cast signal an
error if conversion fails. For example,

double d = 5.5;
int i = static_cast<int>(d);
float f = static_cast<float>(i);
long l = static_cast<logn>(d);

2.6 Relational operators in c++ :

There are six comparison (or relational) operators:

Operator Meaning Example


== Equal to x == y

!= Not equal to x != y

> Greater than x > y

>= Greater than or equal to x >= y

< Less than x < y

<= Less than or equal to x <= y

Take note that the comparison operator for equality is a double-equal sign (==); whereas a single-
equal sign (=) is the assignment operator.

2.7 RELATIONAL AND LOGICAL OPERATORS


Very often, you need to compare two values before deciding on the action to be taken, e.g., if mark
is more than or equal to 50, print "PASS".
C++ provides six comparison operators (or relational operators

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 29
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Operator Description Usage Example (x=5, y=8)


== Equal to expr1 == expr2 (x == y) → false
!= Not Equal to expr1 != expr2 (x != y) → true
> Greater than expr1 > expr2 (x > y) → false
>= Greater than orexpr1 >= expr2 (x >= 5) → true
equal to
< Less than expr1 < expr2 (y < 8) → false
<= Less than or equalexpr1 >= expr2 (y <= 8) → true
to

in C++, these comparison operations returns a bool value of either false (0) or true (1 or a non-
zero value).
Each comparison operation involves two operands, e.g., x <= 100. It is invalid to write 1 < x <
100 in programming. Instead, you need to break out the two comparison operations x > 1, x < 100,
and join with with a logical AND operator, i.e., (x > 1) && (x < 100), where && denotes AND
operator.

C++ provides four logical operators (which operate on boolean operands only):

Operator Description Usage


&& Logical AND expr1 && expr2
|| Logical OR expr1 || expr2
! Logical NOT !expr
^ Logical XOR expr1 ^ expr2

The truth tables are as follows:

AND (&&) true false

True true false


false false false

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 30
Applied Science Private University – Jordan http://FIT.asu.edu.jo

OR (||) true false

True true true


False true false

NOT (!) true false

false true
Example:
// Return true if x is between 0 and 100 (inclusive)
(x >= 0) && (x <= 100)
// wrong to use 0 <= x <= 100

// Return true if x is outside 0 and 100 (inclusive)


(x < 0) || (x > 100) //or
!((x >= 0) && (x <= 100))

// Return true if year is a leap year


// A year is a leap year if it is divisible by 4 but not by 100, or it is divisible
by 400.
((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)

2.8 ORDER OF PRECEDENCE

1. ()
2. ++Pre-increment, --pre-decrement, ! not (unary operators)
3. *,/,%
4. +,-
5. <,<=,>=,>
6. &&
7. ||
8. ==,!=
9. Compound operators
10. = assignment
11. ++Post-increment,-- post –decrement

LAB EXERCISES
1- What is the value of x, if we suppose that int x=3 * 7 - 6 + 2 * 5 / 4 + 6;

2- What is the output of the following :


bool x=(14 >= 5) || ('A' > 'B') ; bool x=(24 >= 35) || ('A' > 'B');

Cout<<x; Cout<<x;

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 31
Applied Science Private University – Jordan http://FIT.asu.edu.jo

bool x=('A' <= 'a') || (7 != 7); bool x=(11 > 5 || 6 < 15 && 7 >= 8 ) ;

cout<<x; cout<<x;

bool x= 3>4 || 2 ; bool x=3 < (4||2);

cout<<x<<endl; cout<<x;

bool x= 3 >(0||0); bool x= 3 <(0||0);

cout<<x; cout<<x;

int x= 3 + (4>1); bool x=4>(5||3);

cout<<x; cout<<x;

bool x= 3+(4>1); bool x=3>4 || 2<3;

cout<<x; cout<<x;

bool x=3<(4||2); bool x= !4>5 && 6<7 ||4>2;

cout<<x; cout<<x;

bool x= !4>5 && 6<7 ||4<2; bool x= !4>5 ;

cout<<x; cout<<x;

bool x= !4<5 ; int x=(3+2)*4 - 2%3 + 4/2;

cout<<x; cout<<x;

int x=3; int x=3;

cout<<x+1; int y=x+1;

cout<<x; cout<<x;

cout<<y;

int x=3; int x=3;

cout<<x++; int y=3 + ++x – x++ + x++;

cout<<x; cout<<y;

cout<<x;

int x=3;

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 32
Applied Science Private University – Jordan http://FIT.asu.edu.jo

cout<<x++ + 3;

cout<<x;

EXERCISES

1. Write a program that takes as input given lengths expressed in feet and inches. The

program should then convert and output the lengths in centimeters. Assume that the

given lengths in feet and inches are integers. One inch is equal to 2.54 centimeters, and 1 foot is equal
to 12 inches.

2- Write C++ statement(s) that accomplish the following:

a. Declare int variables x and y. Initialize x to 25 and y to 18.

b. Declare and initialize an int variable temp to 10 and a char variabl ch to 'A'.

c. Update the value of an int variable x by adding 5 to it.

d. Declare and initialize a double variable payRate to 12.50.

e. Swap the contents of the int variables x and y. (Declare additional variables, if necessary.)

g. Suppose x and y are double variables. Output the contents of x, y, and the expression

x + 12 / y - 18.

3 - Suppose x, y, z, and w are int variables. What value is assigned to each of these variables after the last
statement executes?

x = 5; z = 3;

y = x - z;

z = 2 * y + 3;

w = x - 2 * y + z;

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 33
Applied Science Private University – Jordan http://FIT.asu.edu.jo

z = w - x;

w++;

4. Suppose a, b, and c are int variables and a = 5 and b = 6. What value is assigned to each variable after
each statement executes? If a variable is undefined at a particular statement, report UND
(undefined).

a b c

a = (b++) + 3; __ __ __

c = 2 * a + (++b); __ __ __

b = 2 * (++c) - (a++); __ __ __

5- Consider the following program segment:

//include statement(s)

//using namespace statement

void main()

//variable declaration

//executable statements

//return statement

a. Write C++ statements that include the header files iostream and string.

b. Write a C++ statement that allows you to use cin, cout, and endl without the prefix std::.

c. Write C++ statements that declare the following variables: name of type string and studyHours of type
double.

d. Write C++ statements that prompt and input a string into name and a double value into studyHours.

e. Write a C++ statement that outputs the values of name and studyHours with the appropriate text. For
example, if the value of name is "Donald" and the value of studyHours is 4.5, the output is: Hello,
Donald! on Saturday, you need to study 4.5 hours for the exam.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 34
Applied Science Private University – Jordan http://FIT.asu.edu.jo

3
Lab

REFERENCES
3. http://civilium-ju.com/uploads/New/Science%20and%20other%20Engineering%20Materials
%20Section/C++/C++%20Programming%20From%20Problem%20Analysis%20to%20Program%20Design
%20[5th%20Edition]%20book.pdf

4. http://www.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introduction.html#zz-1.

MY COMMENTS TO MODIFYING THIS EXPERIMENT


_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

Lab 3: Structured Programming:


Selection: if and if …else

Lab objectives:
After finishing the lab ,the student supposed to know the following :
 selection concept in programming

 if statement-if-else- nested if

3.1 Flow Control


There are three basic flow control constructs - sequential, conditional (or decision),
and loop (or iteration), as illustrated below.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 35
Applied Science Private University – Jordan http://FIT.asu.edu.jo

3.1.1 Sequential Flow Control


A program is a sequence of instructions. Sequential flow is the most common and straight-forward,
where programming statements are executed in the order that they are written - from top to bottom
in a sequential manner.

3.1.2 Conditional (Decision) Flow Control


There are a few types of conditionals, if-then, if-then-else, nested-if (if-elseif-elseif-...-else).

Syntax Example Flowchart

if (mark >= 50) {


// if-then cout << "Congratulation!"
if ( booleanExpression ) { << endl;
true-block ; cout << "Keep it up!" <<
} endl;
}

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 36
Applied Science Private University – Jordan http://FIT.asu.edu.jo

if (mark >= 50) {


cout << "Congratulation!"
// if-then-else
<< endl;
if ( booleanExpression ) {
cout << "Keep it up!" <<
true-block ;
endl;
} else {
} else {
false-block ;
cout << "Try Harder!" <<
}
endl;
}

// nested-if
if ( booleanExpr-1 ) {
if (mark >= 80) {
block-1 ;
cout << "A" << endl;
} else if ( booleanExpr-2 )
} else if (mark >= 70) {
{
cout << "B" << endl;
block-2 ;
} else if (mark >= 60) {
} else if ( booleanExpr-3 )
cout << "C" << endl;
{
} else if (mark >= 50) {
block-3 ;
cout << "D" << endl;
} else if ( booleanExpr-4 )
} else {
{
cout << "F" << endl;
......
}
} else {
elseBlock ;
}

Conditional Operator :
A conditional operator is a ternary (3-operand) operator, in the form
of booleanExpr ? trueExpr : falseExpr. Depending on the booleanExpr, it evaluates and returns
the value of trueExpr or falseExpr.

Syntax Example

booleanExpr ? trueExpr : falseExpr cout << (mark >= 50) ? "PASS" : "FAIL" << endl;
// return either "PASS" or "FAIL", and put to cout
max = (a > b) ? a : b; // RHS returns a or b
abs = (a > 0) ? a : -a; // RHS returns a or -a

Braces: You could omit the braces { }, if there is only one statement inside the block. For example,

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 37
Applied Science Private University – Jordan http://FIT.asu.edu.jo

if (mark >= 50)


cout << "PASS" << endl; // Only one statement, can omit { } but not recommended
else { // more than one statements, need { }
cout << "FAIL" << endl;
cout << "Try Harder!" << endl;
}

However, I recommend that you keep the braces, even though there is only one statement in the
block, to improve the readability of your program.

LAB EXERCISES

1- The following C++ program finds the absolute value of an integer.


//Program: Absolute value of an integer
#include <iostream>
using namespace std;
void main( )
{
--------------

--------------

--------------

2- The following program determines an employee’s weekly wages. If the hours worked
exceed 40, wages include overtime payment.

//Program: Weekly wages


#include <iostream>
#include <iomanip>
using namespace std;
void main()
{
double wages, hours;
const double rate = 1.5;
--------------

--------------

--------------

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 38
Applied Science Private University – Jordan http://FIT.asu.edu.jo

3 - Suppose that balance and interestRate are variables of type double, and
if (balance > 50000.00) interestRate = 0.07
if (balance >= 25000.00) interestRate = 0.05;
if (balance >= 1000.00) interestRate = 0.03;
interestRate = 0.00;
write a c++ program to determine the interestRate depending on the value of the balance.

EXERCISES
1- Write a program that prompts the user to input an integer between 0 and 35. If the number is less
than or equal to 9, the program should output the number; otherwise, it should output A for 10, B for 11,
C for 12. . . and Z for 35. (Hint: Use the cast operator, static_cast<char>( ), for numbers >= 10.)

2- In a right triangle, the square of the length of one side is equal to the sum of the squares of the
lengths of the other two sides. Write a program that prompts the user to enter the lengths of three
sides of a triangle and then outputs a message indicating whether the triangle is a right triangle.

3- A box of cookies can hold 24 cookies, and a container can hold 75 boxes of cookies. Write a
program that prompts the user to enter the total number of cookies, the number of cookies in a box,
and the number of cookie boxes in a container. The program then outputs the number of boxes and
the number of containers to ship the cookies. Note that each box must contain the specified number
of cookies, and each container must contain the specified number of boxes. If the last box of cookies
contains less than the number of specified cookies, you can discard it and output the number of
leftover cookies. Similarly, if the last container contains less than the number of specified boxes, you
can discard it and output the number of leftover boxes.

4- Write a program that mimics a calculator. The program should take as input two integers and the
operation to be performed. It should then output the numbers, the operator, and the result. (For
division, if the denominator is zero, output an appropriate message.) Some sample outputs follow:

3+4=7

13 * 5 = 65

REFERENCES
1) http://civilium-ju.com/uploads/New/Science%20and%20other%20Engineering%20Materials
%20Section/C++/C++%20Programming%20From%20Problem%20Analysis%20to%20Program%20Design
%20[5th%20Edition]%20book.pdf

2) http://www.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introduction.html#zz-1.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 39
Applied Science Private University – Jordan http://FIT.asu.edu.jo

4
Lab

MY COMMENTS TO MODIFYING THIS EXPERIMENT


_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

Lab 4: Structured Programming:

Switch Structures

LAB OBJECTIVE
After finishing the lab ,the student supposed to know the following :

 Recognizing switch –case

 Changing nested if to switch and vise versa

SWITCH STRUCTURES
"switch-case" is an alternative to the "nested-if". In a switch-case statement, a break statement is
needed for each of the cases. If break is missing, execution will flow through the following case. You
can use either an int or char variable as the case-selector.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 40
Applied Science Private University – Jordan http://FIT.asu.edu.jo

char oper; int num1, num2, result;


/ switch-case
......
switch ( selector ) {
switch (oper) {
case value-1:
case '+':
block-1; break;
result = num1 + num2; break;
case value-2:
case '-':
block-2; break;
result = num1 - num2; break;
case value-3:
case '*':
block-3; break;
result = num1 * num2; break;
......
case '/':
case value-n:
result = num1 / num2; break;
block-n; break;
default:
default:
cout << "Unknown operator" <<
default-block;
endl;
}
}
switch structure gives the computer the power to choose from among many alternatives.

switch, case, break and default are reserved words


 Firstly, the expression is evaluated. The value of the expression is then used to perform
the action specified in the statements that follows the reserved word case.
 break statement is optional, cause immediate exit from the switch structure. ;
 the expression is called selector it is value determines which statement to select for
execution
 case value should appear only once
 one or more statement may follow the case label, you do not need {}
 When the value if expression is matched against a case value (called label) the statements
executed until either a break statement or the end of the switch structure is reached }.
 When the value of the expression does not match any of the case values, the statements
following the default label execute.
 If the value of the expression does not match any of the case values and no default lable,
the entire switch statements is skipped
Write this code in a new project and run it …. See the output :

switch(grade/10)
{
case10:
case 9:
cout<<”A”;
cout<<”excellent”;
break;

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 41
Applied Science Private University – Jordan http://FIT.asu.edu.jo

case 8:
cout<<”B”;
break;
case 7:
cout<<”C”;
break;
case 6:
cout<<”D”;
break;
default:
cout<<”F”;
}

 Now delete ( break ) statement, run the code again ,is there any differences
between the two output?

LAB EXERCISES

1- Consider the following statements. What is the output ?

#include <iostream>
using namespace std;
void main()
{
int x=2;
int y=3, z;
switch(z)
{
case 0:
Cout<<”Zero”<<endl;
break;
case 1:
cout<<”one”<<endl;
break;
cae 2:
cout<<”two”<<endl;
break;
case 3:
cout<<”three”<<endl;
break;} }

2- Consider the following statements, in which grade is a variable of type char.:

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 42
Applied Science Private University – Jordan http://FIT.asu.edu.jo

#include <iostream>
using namespace std;
void main()

char grade;
cout<<”please enter the grade “<,endl;
cin>>grade;

switch (grade)
{
case 'A':
cout << "The grade point is 4.0.";
break;
case 'B':
cout << "The grade point is 3.0.";
break;
case 'C':
cout << "The grade point is 2.0.";
break;
case 'D':
cout << "The grade point is 1.0.";
break;
case 'F':
cout << "The grade point is 0.0.";
break;
default:
cout << "The grade is invalid.";
}
}

3- change the following nested if to switch

if (month == 1)

cout << "January" << endl;

else if (month == 2)

cout << "February" << endl;

else if (month == 3)

cout << "March" << endl;

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 43
Applied Science Private University – Jordan http://FIT.asu.edu.jo

else if (month == 4)

cout << "April" << endl;

else if (month == 5)

cout << "May" << endl;

else if (month == 6)

cout << "June" << endl;

4- change the following nested if to switch

#include <iostream>
using namespace std;
void main()
{
int age;
Cout<<”please enter the age “<<endl;
Cin>>age;

If (age >= 18)


{

cout << "Old enough to be drafted." << endl;


cout << "Old enough to vote." << endl;
}
else
cout << "Not old enough to be drafted." << endl;
cout << "Not old enough to vote." << endl;

5- Write a c++ that ask the user to enter the score of an exam (out of 100) for a student , the output
will be either A,B,C,D or F according to the following

100-91 ----A

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 44
Applied Science Private University – Jordan http://FIT.asu.edu.jo

90-81----B

80-71----C

70-81----D

60-80----E

49-0----F ?

By using SWITCH Statement??

6- Complete the following code:


#include <iostream>
using namespace std;
void main()
{
int testScore;
cout << "Enter the test score: ";
cin >> testScore;
cout << endl;
switch ( . . . . . . . . . . . . . . . . . . . . . )
{
.....................
.....................
.....................
. . . . . . . . . . . . . . . . . . . . .}
}

EXERCISES

1- Write a program that mimics a calculator. The program should take as input two integers and the
operation to be performed. It should then output the numbers, the operator, and the result. (For
division, if the denominator is zero, output an appropriate message.) By using SWITCH
Statement??

2- Demonstrates a program that calculates a customer’s bill for a local cable company. There are
two types of customers: residential and business. There are two rates for calculating a cable bill:

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 45
Applied Science Private University – Jordan http://FIT.asu.edu.jo

one for residential customers and one for business customers. For residential customers, the
following rates apply:

• Bill processing fee: $4.50

• Basic service fee: $20.50

• Premium channels: $7.50 per channel.

Programming Example: Cable Company Billing | 225For business customers, the following rates
apply:

• Bill processing fee: $15.00

• Basic service fee: $75.00 for first 10 connections, $5.00 for each additional connection

• Premium channels: $50.00 per channel for any number of connections

The program should ask the user for an account number (an integer) and a customer code. Assume
that R or r stands for a residential customer, and B or b stands for a business customer

Input The customer’s account

3- Write a program that calculates and prints the bill for a cellular telephone company. The
company offers two types of service: regular and premium.
Its rates vary, depending on the type of service. The rates are computed as follows:
Regular service: $10.00 plus first 50 minutes are free. Charges for over 50 minutes are $0.20 per
minute.
Premium service: $25.00 plus:
a. For calls made from 6:00 a.m. to 6:00 p.m., the first 75 minutes are free;
charges for more than 75 minutes are $0.10 per minute.
b. For calls made from 6:00 p.m. to 6:00 a.m., the first 100 minutes are
free; charges for more than 100 minutes are $0.05 per minute
Your program should prompt the user to enter an account number, a service code (type char), and
the number of minutes the service was used.
A service code of r or R means regular service; a service code of p or P means premium service
For the premium service, the customer may be using the service during the day and the night.
Therefore, to calculate the bill, you must ask the user to input the number of minutes the service was
used during the day and the number of minutes the service was used during the night.

4- You have several pictures of different sizes that you would like to frame. A local picture-framing
store offers two types of frames—regular and fancy.
The frames are available in white and can be ordered in any color the customer desires. Suppose that
each frame is 1 inch wide. The cost of coloring the frame is $0.10 per inch. The cost of a regular
frame is $0.15 per inch, and the cost of a fancy frame is $0.25 per inch. The cost of putting a

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 46
Applied Science Private University – Jordan http://FIT.asu.edu.jo

cardboard paper behind the picture is $0.02 per square inch, and the cost of putting glass on top of
the picture is $0.07 per square inch. The customer can also choose to put crowns on the corners,
which costs $0.35 per crown.
Write a program that prompts the user to input the following information and then output the cost
of framing the picture:
a. The length and width, in inches, of the picture
b. The type of the frame
c. Customer’s choice of color to color the frame
d. If the user wants to put the crowns, then the number of crowns

REFERENCES
1) http://civilium-ju.com/uploads/New/Science%20and%20other%20Engineering%20Materials
%20Section/C++/C++%20Programming%20From%20Problem%20Analysis%20to%20Program%20Design
%20[5th%20Edition]%20book.pdf

2) http://www.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introduction.html#zz-1.

MY COMMENTS TO MODIFYING THIS EXPERIMENT


_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 47
Applied Science Private University – Jordan http://FIT.asu.edu.jo

5
Lab

Lab 5:Structured Programming:

While looping (repetition) structure

LAB OBJECTIVES
After finishing the lab ,the student supposed to know the following :

 Why repletion is needed

 while structure

 where to use break and continue

5.1 WHY IS REPETITION NEEDED?


Suppose you want to add five numbers to find their average. From what you have learned

so far, you could proceed as follows (assume that all variables are properly declared):

cin >> num1 >> num2 >> num3 >> num4 >> num5; //read five numbers

sum = num1 + num2 + num3 + num4 + num5; //add the numbers

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 48
Applied Science Private University – Jordan http://FIT.asu.edu.jo

average = sum / 5; //find the average

But suppose you want to add and average 100, 1000, or more numbers. You would have

to declare that many variables and list them again in cin statements and, perhaps, again in

the output statements. This takes an exorbitant amount of space and time. Also, if you

want to run this program again with different values or with a different number of values,

you have to rewrite the program.

Suppose you want to add the following numbers:

53794

Consider the following statements, in which sum and num are variables of type int:

1. sum = 0;

2. cin >> num;

3. sum = sum + num;

The first statement initializes sum to 0. Let us execute statements 2 and 3. Statement 2

stores 5 in num; statement 3 updates the value of sum by adding num to it. After statement

3, the value of sum is 5.

Let us repeat statements 2 and 3. After statement 2 (after the programming code reads the

next number):

num = 3

After statement 3:

sum = sum + num = 5 + 3 = 8

At this point, sum contains the sum of the first two numbers. Let us again repeat statements

2 and 3 (a third time). After statement 2 (after the code reads the next number):

num = 7

After statement 3:

sum = sum + num = 8 + 7 = 15

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 49
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Now, sum contains the sum of the first three numbers. If you repeat statements 2 and 3

two more times, sum will contain the sum of all five numbers.

If you want to add 10 numbers, you can repeat statements 2 and 3 ten times. And if you want to

add100 numbers, you can repeat statements 2and3 one hundred times. In either case, you do not

have to declare any additional variables, as you did in the first code. You can use this C++ code to

add any set of numbers, whereas the earlier code requires you to drastically change the code.

There are many other situations in which it is necessary to repeat a set of statements. For

example, for each student in a class, the formula for determining the course grade is the same.

C++ has three repetition, or looping, structures that let you repeat statements over and over

until certain conditions are met.

5.2 WHILE LOOPING (REPETITION) STRUCTURE

Syntax Example Flow chart

int sum = 0, number = 1;


while (number <= 1000) {
// while-do sum += number;
while ( condition ) { ++number;
body ; }
}

 while is a reserved word


 Expression act as a decision maker, and usually logical expression
 Parentheses around the expression part of the syntax
 Expression provides an entry condition, if the initial value is true the statement executes
 The loop condition (expression)then reevaluated if it again true, the statement executes again
 The statement continue execute until the expression is no longer true
 The loop continues to execute endlessly is called infinite loop

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 50
Applied Science Private University – Jordan http://FIT.asu.edu.jo

EXAMPLES

i=0;
while(i<=20) Output:
{ 0 --- ---- ---- --
cout<<i<<” “;
i+=5;// if omitted, you will have infinite loop
}

int x=0;
While(x<=5)
{
Cout<<x<<endl;
x++;

}
i=0;
while(i<=20) Output:
5 --- ---- ---- --
{
i=i+5;// if omitted, you will have infinite loop
cout<<i<<” “;
}

i=20
while(i<=20) Output:
25
{
i+=5;// if omitted, you will have infinite loop
cout<<i<<” “;
}

i=20
while(i<20) Output:
{
i+=5;// if omitted, you will have infinite loop
cout<<i<<” “;}

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 51
Applied Science Private University – Jordan http://FIT.asu.edu.jo

5.3 INTERRUPTING LOOP FLOW - "BREAK" AND "CONTINUE"


The break statement breaks out and exits the current (innermost) loop.
The continue statement aborts the current iteration and continue to the next iteration of the current
(innermost) loop.
break and continue are poor structures as they are hard to read and hard to follow. Use them only if
absolutely necessary. You can always write the same program without using break and continue.

Example (break and continue): Study the following program.


1 /* A mystery series (Mystery.cpp) */
2 #include <iostream>
3 using namespace std;
4
5 void main() {
6 int number = 1;
7 while (true) {
8 ++number;
9 if ((number % 3) == 0) continue;
10 if (number == 133) break;
11 if ((number % 2) == 0) {
12 number += 3;
13 } else {
14 number -= 3;
15 }
16 cout << number << " ";
17 }
18 cout << endl;
19
20 }

LAB EXERCISES

1- Suppose the input is:


8 9 2 3 90 38 56 8 23 89 7 2
Suppose you want to add these numbers and find their average. Complete the following
program:

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 52
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Sample Run: In this sample run, the user input is shaded.


Enter the number of integers in the list: 12
: Enter 12 integers.
8 9 2 3 90 38 56 8 23 89 7 2
The sum of the 12 numbers = 335
The average = 27

//Program: Counter-Controlled Loop


#include <iostream>
using namespace std;
void main()
{
int limit; //store the number of data items
int number; //variable to store the number
int sum; //variable to store the sum
int counter; //loop control variable
cout << " Enter the number of "<< "integers in the list: ";

---------------------------------------
--------------------------------------
--------------------------------------
-------------------------------------- }

2- Example (Sentinel-Controlled Loop):


Prompt user for positive integers, and display the count, maximum, minimum and average.
Terminate when user enters -1. Complete this example ..
1 /* Prompt user for positive integers and display the count, maximum,
2 minimum and average. Terminate the input with -1 (StatNumbers.cpp) */
3 #include <iostream>
4 using namespace std;
5
6 void main() {
7 int numberIn; // input number (positive integer)
8 int count = 0; // count of inputs, init to 0
9 int sum = 0; // sum of inputs, init to 0
10 int max = 0; // max of inputs, init to minimum
11 int min = INT_MAX; // min of inputs, init to maximum
12 int sentinel = -1; // Input terminating value
13
14 // Read Inputs until sentinel encountered
15 cout << "Enter a positive integer or " << sentinel << " to exit: ";
16 while (--------------------- )
17 {
18 // Check input for positive integer
19
20 ---------------------------------------
21 --------------------------------------

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 53
Applied Science Private University – Jordan http://FIT.asu.edu.jo

22
--------------------------------------
23
---------------------------------------
24
25 --------------------------------------
26 --------------------------------------
27 cout << "Count is " << count << endl;
28
29 if (count > 0)
30 {
31 cout << "Maximum is " << max << endl;
32 cout << "Minimum is " << min << endl;
33 cout << "Average is " << (double)sum / count << endl;
34 }
35 }
36

EXERCISES

1- Following is a C++ program that uses awhile loop to find aFibonacci number.
Consider the following sequence of numbers:
1, 1, 2, 3, 5, 8, 13, 21, 34, ....
Given the first two numbers of the sequence (say, a1 and a2), the nth number an, n>= 3,
of this sequence is given by:
a n = a n-1 + a n-2
Thus:

a 3 = a 2 + a 1 = 1+ 1=2;
a 4 = a 3 + a 2 = 2+1 =3;
and so on

Such a sequence is called a Fibonacci sequence. In the preceding sequence, a 2 = 1 and a1 = 1.


However, given any first two numbers, using this process, you can determine the nth number,
an,n >= 3, of the sequence. The number determined this way is called the nth Fibonacci number.
Suppose a2 = 6 and a1 = 3.

Next, we write a program that determines the nth Fibonacci number given the first two numbers.
Input : The first two Fibonacci numbers and the desired Fibonacci number.
Output : The nth Fibonacci number

2- This program reads a given set of integers and then prints the number of odd and even integers.
It also outputs the number of zeros. The program reads 20 integers.
Input 20 integers—positive, negative, or zeros.
Output The number of zeros, even numbers, and odd numbers.

3- Write a program that prompts the user to input an integer and then outputs both the individual
digits of the number and the sum of the digits. For example, it should output the individual digits
of 3456 as 3 4 5 6, output the individual digits of 8030 as 8 0 3 0, output the individual digits of

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 54
Applied Science Private University – Jordan http://FIT.asu.edu.jo

2345526 as 2 3 4 5 5 2 6, output the individual digits of 4000 as 4 0 0 0, and output the individual
digits of -2345 as 2 3 4 5.

4- Write a program that uses while loops to perform the following steps:
a. Prompt the user to input two integers: firstNum and secondNum
(firstNum must be less than secondNum).
b. Output all odd numbers between firstNum and secondNum.
c. Output the sum of all even numbers between firstNum and
secondNum.
d. Output the numbers and their squares between 1 and 10.
e. Output the sum of the square of the odd numbers between firstNum
and secondNum.
f. Output all uppercase letters.

REFERENCES
1) http://civilium-ju.com/uploads/New/Science%20and%20other%20Engineering%20Materials
%20Section/C++/C++%20Programming%20From%20Problem%20Analysis%20to%20Program%20Design
%20[5th%20Edition]%20book.pdf

2) http://www.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introduction.html#zz-1.

MY COMMENTS TO MODIFYING THIS EXPERIMENT


_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 55
Applied Science Private University – Jordan http://FIT.asu.edu.jo

6
Lab

Lab 6: Structured Programming:

do..While (repetition) structure

LAB OBJECTIVES
After finishing the lab ,the student supposed to know the following :
 Knowing the structure of do-while
 The difference between while and do-while

6.1 DO- WHILE (REPETITION) STRUCTURE

In C++, do is a reserved word.


The statement executes first, and then the expression is evaluated. If the expression
evaluates to true, the statement executes again. As long as the expression in a
do...while statement is true, the statement executes. To avoid an infinite loop, you
must, once again, make sure that the loop body contains a statement that ultimately makes
the expression false and assures that it exits properly.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 56
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Syntax Example Flow chart

// do-while
do { int sum = 0, number = 1;
body ; do {
} sum += number;
while ( condition ) ; ++number;
} while (number <= 1000);

6.2 FOR LOOPING (REPETITION) STRUCTURE


The while loop discussed in the previous section is general enough to implement most forms of
repetitions. The C++ for looping structure discussed here is a specialized form of the while loop.
Its primary purpose is to simplify the writing of counter-controlled loops. For this reason, the for
loop is typically called a counted or indexed for loop .
The initial statement, loop condition, and update statement (called for loop control statements)
enclosed within the parentheses control the body (statement) of the for statement.

// for-loop
for (init; test; post-
proc) { // Sum from 1 to 1000
body ; int sum = 0;
} for (int number = 1;
number <= 1000; ++number)
{
sum += number;

The for loop executes as follows:


1. The initial statement executes.
2. The loop condition is evaluated. If the loop condition evaluates to true:
i. Execute the for loop statement.
ii. Execute the update statement (the third expression in the parentheses).
3. Repeat Step 2 until the loop condition evaluates to false.
The initial statement usually initializes a variable (called the for loop control, or
for indexed, variable).
In C++, for is a reserved word.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 57
Applied Science Private University – Jordan http://FIT.asu.edu.jo

EXAMPLES

i=0;
do { Output:
cout<<i<<” “; 0 --- --- ----- ----- ----
i=i+5;
}
while(i<=20)

i=0; Output:
do { -----
cout<<i<<” “;
i=i+5;
}
while(i>=20)

) i=0;
while (i<=20){ Output:
cout<<i<<” “; --- --- ----- ----- ----
i=i+5;
}

i=0;
while (i>=20){
cout<<i<<” “; Output:
i=i+5; -----
}

__________________________________________________________________________________
i=0;
do {
i=i+5; Output:
cout<<i<<” “; --- --- ----- ----- ----
}
while(i<=20)
__________________________________________________________________________________

for (i = 0; i < 10; i++) Output:


cout << i << " "; --- --- ----- ----- ----
cout << endl;

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 58
Applied Science Private University – Jordan http://FIT.asu.edu.jo

__________________________________________________________________________________

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


Output:
{ --- --- ----- ----- ----
cout << "Hello!" << endl;
cout << "*" << endl;
}
__________________________________________________________________________________
Output:
for (i = 1; i <= 5; i++) --- --- ----- ----- ----
cout << "Hello!" << endl;
cout << "*" << endl;
__________________________________________________________________________________

Output:
for (i = 0; i < 5; i++) ;
--- --- ----- ----- ----
cout << "*" << endl;

__________________________________________________________________________________

Output:
for (i = 10; i >= 1; i--) --- --- ----- ----- ----
cout << " " << i;
cout << endl;
__________________________________________________________________________________

for (i = 1; i <= 20; i = i + 2) Output:


--- --- ----- ----- ----
cout << " " << i;
cout << endl;
__________________________________________________________________________________

The initial statement, i = 0;, initializes the int variable i to 0. Next, the loop
condition, i < 10, is evaluated. Because 0 < 10 is true, the print statement executes and
outputs 0. The update statement, i++, then executes, which sets the value of i to 1.
Once again, the loop condition is evaluated, which is still true, and so on. When i
becomes 10, the loop condition evaluates to false, the for loop terminates, and
the statement following the for loop executes

In a while and for loop, the loop condition is evaluated before executing the body of the loop.
Therefore, while and for loops are called pretest loops. On the other hand, the loop condition in a
do...while loop is evaluated after executing the body of the loop. Therefore, do...while loops are
called posttest loops.
Because the while and for loops both have entry conditions, these loops may never activate. The
do...while loop, on the other hand, has an exit condition and therefore always executes the statement
at least once.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 59
Applied Science Private University – Jordan http://FIT.asu.edu.jo

A do...while loop can be used for input validation. Suppose that a program prompts a user
to enter a test score, which must be greater than or equal to 0 and less than or equal to 50. If
the user enters a score less than 0 or greater than 50, the user should be prompted to re-enter
the score. The following do...while loop can be used to accomplish this objective:
int score;
do
{
cout << "Enter a score between 0 and 50: ";
cin >> score;
cout << endl;
}
while (score < 0 || score > 50);

LAB EXERCISES

1- Divisibility Test by 3 and 9


Suppose that m and n are integers and m is nonzero. Then m is called a divisor of n
if n = mt for some integer t; that is, when m divides n, the remainder is 0.

An integer is divisible by 3 and 9 if and only if the sum of its digits is divisible by 3 and 9.
For example, suppose n= 27193257. Then s= 2 + 7 + 1 + 9 + 3 + 2 + 5 + 7 = 36. Because
36 is divisible by both 3 and 9, it follows that 27193257 is divisible by both 3 and 9.
Next, we write a program that determines whether a positive integer is divisible by 3 and 9
by first finding the sum of its digits and then checking whether the sum is divisible by 3 and 9

//Program: Divisibility test by 3 and 9


#include <iostream>
using namespace std;
void main()
{
int num, temp, sum;
cout << "Enter a positive integer: ";
cin >> num;

------------------
------------------
------------------
------------------
------------------
}

2- The following C++ program finds the sum of the first n positive integers.

//Program to determine the sum of the first n positive integers.


#include <iostream>

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 60
Applied Science Private University – Jordan http://FIT.asu.edu.jo

using namespace std;


void main()
{
int counter; //loop control variable
int sum; //variable to store the sum of numbers
int n; //variable to store the number of first positive integers to be added
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------

3- Write C++ program to print out n! . n!=n x (n-1) x (n-2) ……. x 2 x 1 n>=1

void main()
{
int num ;
cout << "Enter a positive integer: ";
cin >> num;

------------------
------------------
------------------
------------------
------------------
}

EXERCISES

1- Write a program that reads a set of integers and then finds and prints the sum of the even
and odd integers.

2- Write c++ program enables user to enter 10 grades, then finds the average of passed
student grades and the average for the failed student grades and prints the result.

3- Write c++ program enables user to enter unknown number of grades until the user enter
grade=-1, then finds the number of passed grades (the program counts the number of
passed students)
4- Write c++ program enables user to enter an integer, the output will be 2 n.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 61
Applied Science Private University – Jordan http://FIT.asu.edu.jo

5- Write c++ program enables user to enter two integers n, m, where n>=0 the output will be
mn.

REFERENCES
1) http://civilium-ju.com/uploads/New/Science%20and%20other%20Engineering%20Materials
%20Section/C++/C++%20Programming%20From%20Problem%20Analysis%20to%20Program%20Design
%20[5th%20Edition]%20book.pdf

2) http://www.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introduction.html#zz-1.

MY COMMENTS TO MODIFYING THIS EXPERIMENT


_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 62
Applied Science Private University – Jordan http://FIT.asu.edu.jo

7
Lab

Lab 7: Structured Programming:

Nested Loops

LAB OBJECTIVES
After finishing the lab, the student supposed to know the following:
 Knowing the need of using nested loop techniques
 Learning different nested loops techniques.

6.1 NESTED LOOPS

The following diagram illustrates a nested for-loop, i.e., an inner for-loop within an outer for-
loop.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 63
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Try out the following program, which prints a 8-by-8 checker box pattern using nested loops, as
follows:

# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
/*
1 * Print square pattern (PrintSquarePattern.cpp).
2 */
3 #include <iostream>
4 using namespace std;
5
6 int main() {
7 int size = 8;
8 for (int row = 1; row <= size; ++row) { // Outer loop to print all
9 the rows
10 for (int col = 1; col <= size; ++col) { // Inner loop to print all
11 the columns of each row
12 cout << "# ";
13 }
14 cout << endl; // A row ended, bring the cursor to the next line
15 }
16
17 return 0;
}

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 64
Applied Science Private University – Jordan http://FIT.asu.edu.jo

This program contains two nested for-loops. The inner loop is used to print a row of eight "# ",
which is followed by printing a newline. The outer loop repeats the inner loop to print all the
rows.

Suppose that you want to print this pattern instead (in program called
PrintCheckerPattern.cpp):

# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #

You need to print an additional space for even-number rows. You could do so by adding the
following statement before Line 8.

if ((row % 2) == 0) { // print a leading space for even-numbered rows


cout << " ";
}
Example : The following program input n marks and print their average. If the user
input an invalid mark then the program keeps asking the user to reenter a valid mark.

1. include <iostream>
2. using namespace std;
3. int main ()
4. {
5. int sum =0, mark, n;
6. cout<<"enter the number of marks"<<endl;
7. cin>>n;
8.
9. for(int i=1; i<=n; i++) {
10. cout<<"enter the next mark between (0..100) ";
11. cin>> mark;
12. while(mark<0 || mark>100)
13. {
14. cout<<"Invalid mark please renter the mark ";
15. cin>> mark;
16. }
17.
18. sum = sum + mark;
19. }
20. cout<<"average is "<<(double)sum/n;
21. return 0;
22. }

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 65
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Example: The following program lists the non-prime numbers between 2 and an upperbound.
1 /*
2 * List non-prime from 1 to an upperbound (NonPrimeList.cpp).
3 */
4 #include <iostream>
5 #include <cmath>
6 using namespace std;
7
8 void main() {
9 int upperbound;
10 cout << "Enter the upperbound: ";
11 cin >> upperbound;
12 for (int number = 2; number <= upperbound; ++number) {
13 // Not a prime, if there is a factor between 2 and sqrt(number)
14 int maxFactor = (int)sqrt(number);
15 for (int factor = 2; factor <= maxFactor; ++factor) {
16 if (number % factor == 0) { // Factor?
17 cout << number << " ";
18 break; // A factor found, no need to search for more factors
19 }
20 }
21 }
22 cout << endl;
23
24 }

Let's rewrite the above program to list all the primes instead. A boolean flag called isPrime is
used to indicate whether the current number is a prime. It is then used to control the printing.

1 /*
2 * List primes from 1 to an upperbound (PrimeListWithBreak.cpp).
3 */
4 #include <iostream>
5 #include <cmath>
6 using namespace std;
7
8 void main() {
9 int upperbound;
10 cout << "Enter the upperbound: ";
11 cin >> upperbound;
12 for (int number = 2; number <= upperbound; ++number) {
13 // Not a prime, if there is a factor between 2 and sqrt(number)
14 int maxFactor = (int)sqrt(number);
15 bool isPrime = true; // boolean flag to indicate whether number is a prime
16 for (int factor = 2; factor <= maxFactor; ++factor) {
17 if (number % factor == 0) { // Factor?

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 66
Applied Science Private University – Jordan http://FIT.asu.edu.jo

18 isPrime = false; // number is not a prime


19 break; // A factor found, no need to search for more factors
20 }
21 }
22 if (isPrime) cout << number << " ";
23 }
24 cout << endl;
25
26 }

Let's rewrite the above program without using break statement. A while loop is used
(which is controlled by the boolean flag) instead of for loop with break.
1 /*
2 * List primes from 1 to an upperbound (PrimeList.cpp).
3 */
4 #include <iostream>
5 #include <cmath>
6 using namespace std;
7
8 void main() {
9 int upperbound;
10 cout << "Enter the upperbound: ";
11 cin >> upperbound;
12
13 for (int number = 2; number <= upperbound; ++number) {
14 // Not prime, if there is a factor between 2 and sqrt of number
15 int maxFactor = (int)sqrt(number);
16 bool isPrime = true;
17 int factor = 2;
18 while (isPrime && factor <= maxFactor) {
19 if (number % factor == 0) { // Factor of number?
20 isPrime = false;
21 }
22 ++factor;
23 }
24 if (isPrime) cout << number << " ";
25 }
26 cout << endl;
27
28 }

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 67
Applied Science Private University – Jordan http://FIT.asu.edu.jo

LAB EXERCISES

1- Write a program to print the times table “multiplication table” for numbers 1...12.
2- Write a C++ program to print the factorial of numbers from 1 to n.
As example: the following is a sample run.
Enter n: 5
1!=1
2!=2
3!=6
4!=24
5!=120
3-

EXERCISES

4- Print these patterns using nested loop (in a program called PrintPattern1x). Use a variable called
size for the size of the pattern and try out various sizes. You should use as few printing statements as
possible.

Hints:
The equations for major and opposite diagonals are row = col and row + col = size + 1. Decide on what
to print above and below the diagonal.

5- Write a program to compute sinx for given x. The user should supply x and a positive integer n. We
compute the sine of x using the series and the computation should use all terms in the series up
through the term involving xn.
sin x = x - x3/3! + x5/5! - x7/7! + x9/9!......xn/n!

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 68
Applied Science Private University – Jordan http://FIT.asu.edu.jo

REFERENCES
3) http://civilium-ju.com/uploads/New/Science%20and%20other%20Engineering%20Materials
%20Section/C++/C++%20Programming%20From%20Problem%20Analysis%20to%20Program%20Design
%20[5th%20Edition]%20book.pdf

4) http://www.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introduction.html#zz-1.

MY COMMENTS TO MODIFYING THIS EXPERIMENT


_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 69
Applied Science Private University – Jordan http://FIT.asu.edu.jo

8
Lab

Lab 8: Structured Programming:

Predefined Functions:

Predefined functions
Function Header file Purpose Parameter type Result type
abs(x) <cstdlib> Absolute value Int int
abs(-5)=5
ceil(x) <cmath> Smallest number double int
not less than x
ceil(56.3)=57
cos(x) <cmath> Cosine of angle double int
cos(0.0)=1
exp(x) <cmath> ex double double
exp(1.0)=2.718
fab(x) <cmath> Absolute value double double
fab(-5.6)=5.6
floor(x) <cmath> Largest number not double int
greater than x
floor(45.6)=45
pow(x,y) <cmath> xy double int
32 =9 POW(3,2) = 9
tolower(x) <cctype> Lowercase int int
toupper(x) uppercase

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 70
Applied Science Private University – Jordan http://FIT.asu.edu.jo

 To use these predefined functions you must include the header file that contains the function
specifications
 #include <cmath>
 The function abs might have the following definition
int abs(int number) //number is called formal parameter
{
if (number<0)
number=-number;
return number;
}

 Example 1:
#include<iostream>
#include<cmatch>
#include<cstdlib>
using namespace std;
int main()
{
int x=-15, y;
double u=4.2, v=3.0;
cout<<u<<”to the power of ”<<v<<pow(u,v)<<endl; //u,v are called actual parameters
cout<<”absolute value of”<<x<<”=”<<abs(x); //x is called actual parameter
y=abs(x);//x is called actual parameter
cout<<y;
return 0;
}

 Formal parameter: variable declared in the function heading


 Actual parameter: variable or expression listed in a call to the function
 The number and the data types of actual parameter list should match the formal parameter list
When using predefined function, you need to be concerned with:

1. Name of the function


2. Number of parameters
3. Data type of each parameter
4. Data type of the value computed (returned)called the type of the function

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 71
Applied Science Private University – Jordan http://FIT.asu.edu.jo

abs(x) ; pow(x, y) ; floor(x) ; ceil(x)

#include <iostream>

#include<cmath>
using namespace std;
void main()
{
cout<<pow(4.0,2.0)<<endl; // 16
cout<<sqrt(4.0)<<endl; //2
cout<<floor(4.9)<<endl; //4
cout<<ceil(4.2) <<endl; //5
cout<<abs(-10)<<endl; //10
cout<<abs(10.0)<<endl; //10
}

#include <iostream>
#include<cmath>
using namespace std;0
void main() 17
{
double x= sqrt(16.0);
double y= x++ + ++ x –floor(3.8) + ceil(9.1)<<endl;
}

LAB EXERCISES

1- Write a C++ program to find the roots of the quadratic equation .


1- First you need to find the discriminate
2- If d > 0 then the equation has 2 real roots and can be found as follows:

You need to use the function pow from the cmath library to find the square root.

3- If d = 0 then the equation has a single root and can be found as follows:

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 72
Applied Science Private University – Jordan http://FIT.asu.edu.jo

4- If d < 0 then print "The equation has no real roots".

Q2)

My comments to modifying this Experiment


_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 73
Applied Science Private University – Jordan http://FIT.asu.edu.jo

9
Lab

_____________________________________________________________________________________
_____________________________________________________________________________________

Lab 9: Structured Programming:

User Defined Functions


Lab objectives:
After finishing the lab, the student supposed to know the following:
 How to define a function.

 How to call a function.

WHY FUNCTIONS?

At times, a certain portion of codes has to be used many times. Instead of re-writing the codes
many times, it is better to put them into a "subroutine", and "call" this "subroutine" many time -
for ease of maintenance and understanding. Subroutine is called method (in Java) or function (in
C/C++).
The benefits of using functions are:
1. Divide and conquer: construct the program from simple, small pieces or components.
Modularize the program into self-contained tasks.
2. Avoid repeating codes: It is easy to copy and paste, but hard to maintain and synchronize all
the copies.
3. Software Reuse: you can reuse the functions in other programs, by packaging them into
library codes.

Two parties are involved in using a function: a caller who calls the function, and the function
called. The caller passes argument(s) to the function. The function receives these argument(s),
performs the programmed operations within the function's body, and returns a piece of result
back to the caller.

USING FUNCTIONS

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 74
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Get Started with an Example


Suppose that we need to evaluate the area of a circle many times, it is better to write a function
called getArea(), and re-use it when needed.

/* Test Function (TestFunction.cpp) */


1 #include <iostream>
2 using namespace std;
3 const int PI = 3.14159265;
4
5 // Function Prototype (Function Declaration)
6 double getArea(double radius);
7
8
9 int main() {
10 double radius1 = 1.1, area1, area2;
11 // call function getArea()
12 area1 = getArea(radius1);
13 cout << "area 1 is " << area1 << endl;
14 // call function getArea()
15 area2 = getArea(2.2);
16 cout << "area 2 is " << area2 << endl;
17 // call function getArea()
18
cout << "area 3 is " << getArea(3.3) << endl;
19
20 }
21
22 // Function Definition
23 // Return the area of a circle given its radius
24 double getArea(double radius) {
25 return radius * radius * PI;
}
area 1 is 3.63
area 2 is 14.52
area 3 is 32.67

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 75
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Function Definition
The "return"
Function Statement
Prototype
Function Naming Convention

The syntax for function definition is as follows:


returnValueType functionName ( parameterList ) {
functionBody ;
}

 The parameterList consists of comma-separated parameter-type and parameter-name,


i.e., param-1-type param-1-name, param-2-type param-2-name,...
 The returnValueType specifies the type of the return value, such as int or double. An
special return type called void can be used to denote that the function returns no value. In
C++, a function is allowed to return one value or no value (void). It cannot return
multiple values.

Inside the function's body, you could use a return statement to return a value (of the
returnValueType declared in the function's header) and pass the control back to the caller. The
syntax is:
return expression; // Evaluated to a value of returnValueType declared in
function's signature
return; // For function with return type of void
Take note that invoking a function (by the caller) transfers the control to the function. The
return statement in the function transfers the control back to the caller.

A function's name shall be a verb or verb phrase (action), comprising one or more words. The
first word is in lowercase, while the rest are initial-capitalized (known as camel-case). For
example, getArea(), setRadius(), moveDown(), isPrime(), etc.

In C++, a function must be declared before it can be called. It can be achieved by either placing
the function definition before it is being used, or declare a so-called function prototype.
A function prototype tells the compiler the function's interface, i.e., the return-type, function
name, and the parameter type list (the number and type of parameters). The function can now be
defined anywhere in the file. For example,
// Function prototype - placed before the function is used.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 76
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Another Example
double getArea(double); // without the parameter name
int max(int, int);
You could optionally include the parameter names in the function prototype. The names will be
ignored by the compiler, but serve as documentation. For example,
// Function Prototype
double getArea(double radius); // parameter names are ignored, but serve as
documentation
int max(int number1, int number2);
Function prototypes are usually grouped together and placed in a so-called header file. The
header file can be included in many programs. We will discuss header file later.

We have a function called max(int, int), which takes two int and return their maximum. We
invoke the max() function from the main().

/* Testing max function (TestMaxFunction.cpp) */


1
#include <iostream>
2
using namespace std;
3
4
int maximum(int, int); // Function prototype (declaration)
5
6
int main() {
7
cout << maximum(5, 8) << endl; // Call maximum() with literals
8
9
int a = 6, b = 9, c;
10
c = maximum(a, b); // Call maximum() with variables
11
cout << c << endl;
12
13
cout << maximum(c, 99) << endl; // Call maximum()
14
}
15
16
// Function definition
17
// A function that returns the maximum of two given int
18
int maximum(int num1, int num2) {
19
return (num1 > num2) ? num1 : num2;
20
}
21

The "void" Return Type

Suppose that you need a function to perform certain actions (e.g., printing) without a need to
return a value to the caller, you can declare its return-value type as void. In the function's body,
you could use a "return;" statement without a return value to return control to the caller. In this
case, the return statement is optional. If there is no return statement, the entire body will be
executed, and control returns to the caller at the end of the body.
 Write C++ program that finds and prints the maximum grade among five students, the user
will enter (first, second, final and participation) marks for each student the program should
use a function to find the total and another function to print it for each student.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 77
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Actual of
Scope Parameters
Function'svs. Formal
Local Parameters
Variables and Parameters
#include<iostream>
using namespace std;

int total (int ft,int se, int fi, int part);


void printTotal (int ft,int se, int fi, int part);

void main()
{
int x1,x2,x3,x4;
int max=0,a;
for(int i=1;i<=5;i++)
{
cout<<"please enter first, second, final and other works
marks\n";
cin>>x1>>x2>>x3>>x4;
cout<<"student"<<i<<" totla mark is";
printTotal(x1,x2,x3,x4);
a=total(x1,x2,x3,x4);
if(a>max)
max=a;

}
cout<<"\nthe maximum mark is = "<<max;

int total (int ft,int se, int fi, int part)


{
return ft+se+fi+part;
}

void printTotal (int ft,int se, int fi, int part)


{
cout<<"Total is "<<ft+se+fi+part<<endl;
}

Recall that a function receives arguments from its caller, performs the actions defined in the
function's body, and return a value (or nothing) to the caller.
In the above example, the variable (double radius) declared in the signature of
getArea(double radius) is known as formal parameter. Its scope is within the function's
body. When the function is invoked by a caller, the caller must supply so-called actual
parameters (or arguments), whose value is then used for the actual computation. For example,
when the function is invoked via "area1 = getArea(radius1)", radius1 is the actual
parameter, with a value of 1.1.

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 78
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Boolean Functions
All variables, including function's parameters, declared inside a function are available only to the
function. They are created when the function is called, and freed (destroyed) after the function
returns. They are called local variables because they are local to the function and not available
outside the function. They are also called automatic variables, because they are created and
destroyed automatically - no programmer's explicit action needed to allocate and deallocate
them.

A boolean function returns a bool value (of either true or false) to the caller.
Suppose that we wish to write a function called isOdd() to check if a given number is odd.
1 /*
2 * Test Boolean function (BooleanfunctionTest.cpp).
3 */
4 #include <iostream>
5 using namespace std;
6
7 // Function Prototype
8 bool isOdd(int);
9
10 int main() {
11 cout << boolalpha; // print bool as true or false
12 cout << isOdd(5) << endl; // true
13 cout << isOdd(6) << endl; // false
14 cout << isOdd(-5) << endl; // false
15 }
16
17 bool isOdd(int number) {
18 if (number % 2 == 1) {
19 return true;
20 } else {
21 return false;
22 }
23 }

This seemingly correct codes produces false for -5, because -5%2 is -1 instead of 1. You may
rewrite the condition:
bool isOdd(int number) {
if (number % 2 == 0) {
return false;
} else {
return true;
}
}
The above code produces the correct answer, but is poor. For boolean function, you should
simply return the resultant bool value of the comparison, instead of using a conditional
statement, as follow:
bool isEven(int number) {
return (number % 2 == 0);
}

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 79
Applied Science Private University – Jordan http://FIT.asu.edu.jo

bool isOdd(int number) {


return !(number % 2 == 0); // OR return !isEven(number);
}

int main() {
int number = -9;
if (isEven(number)) { // Don't write (isEven(number) == true)
cout << "Even" << endl;
}
}

LAB EXERCISES

Q1) Write C++ program to read three marks and find their average, maximum and minimum. Declare
a function for each task.

#include<iostream>
using namespace std;

double avg(int x,int y,int z);


double max(int x,int y,int z);
double min(int x,int y,int z);

int main()
{
int m1,m2,m3;
cout<<”enter three marks \n”;
cin>>a>>b>>c;
cout<<"Average is "<<avg(a,b,c);

return 0;
}

double avg(int x,int y,int z)


{

}
….
Q2) Write C++ program to enter a number and find its factorial and summation. Use a function for
each task.

As example if n = 5 then

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 80
Applied Science Private University – Jordan http://FIT.asu.edu.jo

EXERCISES

1- Write the definition of function courseGrade. This function takes as a parameter an int value
specifying the score for a course and returns the grade, a value of type char, for the course.
(We assume that the test score is a value between 0 and 100.inclusive.)

char courseGrade(int score)


{
switch (score / 10)
{
…..

Write a complete C++ program that read 10 students score and print their grades.

2- Consider the following function:

int mystery(int x, double y, char ch)


{
int u;
if ('A' <= ch && ch <= 'R')
return(2 * x + static_cast<int>(y));
else
return(static_cast<int>(2 * y) - x);
}

What is the output of the following C++ statements?


a. cout << mystery(5, 4.3, 'B') << endl;
b. cout << mystery(4, 9.7, 'v') << endl;
c. cout << 2 * mystery(6, 3.9, 'D') << endl;

3- Write a program that takes as input five numbers and outputs the mean “average” and
standard deviation of the numbers. If the numbers are x1, x2,x3, x4, and x5, then the mean is
x= (x1 + x2 + x3 + x4 + x5)/5 and the standard deviation is:

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 81
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Your program must contain at least the following functions: a function that calculates and returns the
mean and a function that calculates the standard deviation.

REFERENCES
1) http://civilium-ju.com/uploads/New/Science%20and%20other%20Engineering%20Materials
%20Section/C++/C++%20Programming%20From%20Problem%20Analysis%20to%20Program%20Design
%20[5th%20Edition]%20book.pdf

2) http://www.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introduction.html#zz-1.

MY COMMENTS TO MODIFYING THIS EXPERIMENT


_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 82
Applied Science Private University – Jordan http://FIT.asu.edu.jo

10
Lab

Lab 10: Structured Programming:

User Defined Functions(2)


Lab objectives:
After finishing the lab, the student supposed to know the following:
 Call by value.

 Call by reference.

Arguments passed by value and by reference:


Let's have a look at an example:

1 // function example
2 #include <iostream>
3 using namespace std;
4
5 int addition (int a, int b)
6 {
7 int r;
8 r=a+b;
9 return r;
10 }
11
12 int main ()
13 {
14 int z;
15 z = addition (5,3);
16 cout << "The result is " << z;
17 }

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 83
Applied Science Private University – Jordan http://FIT.asu.edu.jo

This program is divided in two functions: addition and main. Remember that no matter the order
in which they are defined, a C++ program always starts by calling main. In fact, main is the only
function called automatically, and the code in any other function is only executed if its function
is called from main (directly or indirectly).

In the example above, main begins by declaring the variable z of type int, and right after that, it
performs the first function call: it calls addition. The call to a function follows a structure very
similar to its declaration. In the example above, the call to addition can be compared to its
definition just a few lines earlier:

The parameters in the function declaration have a clear correspondence to the arguments passed
in the function call. The call passes two values, 5 and 3, to the function; these correspond to the
parameters a and b, declared for function addition.

At the point at which the function is called from within main, the control is passed to function
addition: here, execution of main is stopped, and will only resume once the addition function
ends. At the moment of the function call, the value of both arguments (5 and 3) are copied to the
local variables int a and int b within the function.

Then, inside addition, another local variable is declared (int r), and by means of the expression
r=a+b, the result of a plus b is assigned to r; which, for this case, where a is 5 and b is 3, means
that 8 is assigned to r.
The final statement within the function:

return r;

Ends function addition, and returns the control back to the point where the function was called;
in this case: to function main. At this precise moment, the program resumes its course on main
returning exactly at the same point at which it was interrupted by the call to addition. But
additionally, because addition has a return type, the call is evaluated as having a value, and this
value is the value specified in the return statement that ended addition: in this particular case, the
value of the local variable r, which at the moment of the return statement had a value of 8.

Therefore, the call to addition is an expression with the value returned by the function, and in
this case, that value, 8, is assigned to z. It is as if the entire function call (addition(5,3)) was
replaced by the value it returns (i.e., 8).

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 84
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Then main simply prints this value by calling:

cout << "The result is " << z;

In the functions seen earlier, arguments have always been passed by value. This means that, when
calling a function, what is passed to the function are the values of these arguments on the moment of
the call, which are copied into the variables represented by the function parameters. For example,
take:

1 int x=5, y=3, z;


2 z = addition ( x, y );

In this case, function addition is passed 5 and 3, which are copies of the values of x and y,
respectively. These values (5 and 3) are used to initialize the variables set as parameters in the
function's definition, but any modification of these variables within the function has no effect on
the values of the variables x and y outside it, because x and y were themselves not passed to the
function on the call, but only copies of their values at that moment.

In certain cases, though, it may be useful to access an external variable from within a function.
To do that, arguments can be passed by reference, instead of by value. For example, the function
duplicate in this code duplicates the value of its three arguments, causing the variables used as
arguments to actually be modified by the call:

1 // passing parameters by reference


2 #include <iostream>
3 using namespace std;
4
5 void duplicate (int& a, int& b, int& c)
6 {
7 a*=2;
8 b*=2;
9 c*=2; main Function Memory:
10 } x=2, y=6, z=14
11
12 int main ()
13 {
14 int x=1, y=3, z=7;
15 duplicate (x, y, z);
16 cout << "x=" << x << ", y=" << y << ", z=" << z;
17 return 0;
18 }

To gain access to its arguments, the function declares its parameters as references. In C++,
© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 85
Applied Science Private University – Jordan http://FIT.asu.edu.jo

references are indicated with an ampersand (&) following the parameter type, as in the
parameters taken by duplicate in the example above.

When a variable is passed by reference, what is passed is no longer a copy, but the variable itself,
the variable identified by the function parameter, becomes somehow associated with the
argument passed to the function, and any modification on their corresponding local variables
within the function are reflected in the variables passed as arguments in the call.

In fact, a, b, and c become aliases of the arguments passed on the function call (x, y, and z) and
any change on a within the function is actually modifying variable x outside the function. Any
change on b modifies y, and any change on c modifies z. That is why when, in the example,
function duplicate modifies the values of variables a, b, and c, the values of x, y, and z are
affected.

If instead of defining duplicate as:

void duplicate (int& a, int& b, int& c)

Was it to be defined without the ampersand signs as:

void duplicate (int a, int b, int c)

The variables would not be passed by reference, but by value, creating instead copies of their
values. In this case, the output of the program would have been the values of x, y, and z without
being modified (i.e., 1, 3, and 7).

For example:

Consider the following function to evaluate the solution of a quadratic equation using call by
reference:

// solves the quadratic equation a*x*x+b*x+c = 0.


// If the roots are real then the roots are
// returned in two parameters root1 and root2 and
// the function returns true, if they are complex
// then the function returns false.

bool quadsolve(float a, // IN coefficient


float b, // IN coefficient
float c, // IN coefficient
float& root1, // OUT root
float& root2) // OUT root

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 86
Applied Science Private University – Jordan http://FIT.asu.edu.jo

{
float disc; // local variable
disc = b * b - 4 * a * c;
if (disc < 0.0)
return false;
else
{
root1 = (-b + sqrt(disc))/(2 * a);
root2 = (-b - sqrt(disc))/(2 * a);
return true;
}
}

void main()
{
float c1, c2, c3;
float r1, r2;
char reply;
do {
cout << "Enter coefficients for a quadratic equation: ";
cin >> c1 >> c2 >> c3;
if (quadsolve(c1,c2,c3,r1,r2))
cout << "Solution of quadratic with coefficients "
<< c1 << " " << c2 << " " << c3 << " is "
<< r1 << " and " << r2 << endl;
else
cout << "Quadratic equation with coefficients "
<< c1 << " " << c2 << " " << c3
<< " has no real roots" << endl;
cout << "Another set? (y/n): ";
cin >> reply;
} while (reply == 'y');
}

LAB EXERCISES

Q1) What is the output?


int callMe(int x, int & y)
{
cout<<"inside "<< ++x + y++<<endl;
return x+y;
}
void main(){
int x = 10, z = 20;
cout<<"before call x = "<<x<<" z = "<<z<<endl;
cout<<“callMe "<< callMe(x,z)<<endl;
cout<<"after call x = "<<x<<" z = "<<z<<endl;
}

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 87
Applied Science Private University – Jordan http://FIT.asu.edu.jo

Q2) What is the output?

void callMe(int &x, int & y)


{
x+=2;
y--;
}
void main()
{
int x = 10, z = 20;
while(x<z)
{
cout<<"x="<<x<<" z="<<z<<endl;
callMe(x,z);
}
}

Q3) Write a function called swap that receives two integer numbers then swap them.

#include <iostream>
using namespace std;

// function declaration
void swap(int &x, int &y);

int main ()
{
// local variable declaration:
int a = 100;
int b = 200;

cout << "Before swap, value of a :" << a << endl;


cout << "Before swap, value of b :" << b << endl;

/* calling a function to swap the values using variable reference.*/


swap(a, b);

cout << "After swap, value of a :" << a << endl;


cout << "After swap, value of b :" << b << endl;

return 0;
}

// function definition to swap the values.


void swap(int &x, int &y)
{

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 88
Applied Science Private University – Jordan http://FIT.asu.edu.jo

//Code for swapping.


}

© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 89

You might also like