Professional Documents
Culture Documents
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
Page 0
History of Changes
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:
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)
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
© 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 /* */
Mathematical symbols + - * /
Identifiers are names of things that appear in program (ex: variables, constants, functions)
C++ identifiers consist of only: 1)Letters 2)Digits 3) underscore _ (no other symbols)
© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 3
Applied Science Private University – Jordan http://FIT.asu.edu.jo
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:
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
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
© 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.
// 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 BuildBuild Solution in the main menu (or press F7).
To run your program, choose DebugStart 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.
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().
#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.
© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 15
Applied Science Private University – Jordan http://FIT.asu.edu.jo
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.
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
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.
© 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".
* * * * * * * * * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * * * * *
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)\”
© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 19
Applied Science Private University – Jordan http://FIT.asu.edu.jo
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.
© 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 Objectives:
After finishing the lab ,the student supposed to know the following :
Type casting
Operations
2.1 Arithmetic Operators
© 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).
For example,
© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 24
Applied Science Private University – Jordan http://FIT.asu.edu.jo
For example,
© 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.
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.
© 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.
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
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 }
© 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);
!= Not 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.
© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 29
Applied Science Private University – Jordan http://FIT.asu.edu.jo
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):
© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 30
Applied Science Private University – Jordan http://FIT.asu.edu.jo
false true
Example:
// Return true if x is between 0 and 100 (inclusive)
(x >= 0) && (x <= 100)
// wrong to use 0 <= x <= 100
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;
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;
cout<<x<<endl; cout<<x;
cout<<x; cout<<x;
cout<<x; cout<<x;
cout<<x; cout<<x;
cout<<x; cout<<x;
cout<<x; cout<<x;
cout<<x; cout<<x;
cout<<x; cout<<x;
cout<<y;
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.
b. Declare and initialize an int variable temp to 10 and a char variabl ch to 'A'.
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++); __ __ __
//include statement(s)
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.
Lab objectives:
After finishing the lab ,the student supposed to know the following :
selection concept in programming
if statement-if-else- nested if
© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 35
Applied Science Private University – Jordan http://FIT.asu.edu.jo
© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 36
Applied Science Private University – Jordan http://FIT.asu.edu.jo
// 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
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
--------------
--------------
2- The following program determines an employee’s weekly wages. If the hours worked
exceed 40, wages include overtime payment.
--------------
--------------
© 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
Switch Structures
LAB OBJECTIVE
After finishing the lab ,the student supposed to know the following :
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
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
#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;} }
© 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.";
}
}
if (month == 1)
else if (month == 2)
else if (month == 3)
© 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)
else if (month == 5)
else if (month == 6)
#include <iostream>
using namespace std;
void main()
{
int age;
Cout<<”please enter the age “<<endl;
Cin>>age;
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 ?
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:
Programming Example: Cable Company Billing | 225For business customers, the following rates
apply:
• Basic service fee: $75.00 for first 10 connections, $5.00 for each additional connection
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
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.
© 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 OBJECTIVES
After finishing the lab ,the student supposed to know the following :
while structure
so far, you could proceed as follows (assume that all variables are properly declared):
cin >> num1 >> num2 >> num3 >> num4 >> num5; //read five 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
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,
53794
Consider the following statements, in which sum and num are variables of type int:
1. sum = 0;
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
Let us repeat statements 2 and 3. After statement 2 (after the programming code reads the
next number):
num = 3
After statement 3:
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:
© 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
© 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
LAB EXERCISES
© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 52
Applied Science Private University – Jordan http://FIT.asu.edu.jo
---------------------------------------
--------------------------------------
--------------------------------------
-------------------------------------- }
© 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
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.
© 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 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
© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 56
Applied Science Private University – Jordan http://FIT.asu.edu.jo
// do-while
do { int sum = 0, number = 1;
body ; do {
} sum += number;
while ( condition ) ; ++number;
} while (number <= 1000);
// 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;
© 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)
__________________________________________________________________________________
© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 58
Applied Science Private University – Jordan http://FIT.asu.edu.jo
__________________________________________________________________________________
Output:
for (i = 0; i < 5; i++) ;
--- --- ----- ----- ----
cout << "*" << endl;
__________________________________________________________________________________
Output:
for (i = 10; i >= 1; i--) --- --- ----- ----- ----
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
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
------------------
------------------
------------------
------------------
------------------
}
2- The following C++ program finds the sum of the first n positive integers.
© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 60
Applied Science Private University – Jordan http://FIT.asu.edu.jo
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.
© 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
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.
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.
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
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.
© 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
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;
}
© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 71
Applied Science Private University – Jordan http://FIT.asu.edu.jo
#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
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
Q2)
© 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
_____________________________________________________________________________________
_____________________________________________________________________________________
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
© 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
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().
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;
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;
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
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;
int main()
{
int m1,m2,m3;
cout<<”enter three marks \n”;
cin>>a>>b>>c;
cout<<"Average is "<<avg(a,b,c);
…
return 0;
}
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.)
Write a complete C++ program that read 10 students score and print their grades.
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.
© 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
Call by reference.
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
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:
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:
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.
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:
© 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
© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 87
Applied Science Private University – Jordan http://FIT.asu.edu.jo
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;
return 0;
}
© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 88
Applied Science Private University – Jordan http://FIT.asu.edu.jo
© Copyright 2013 by Applied Science University – Faculty of IT, All rights reserved Page 89