Professional Documents
Culture Documents
Data Structure
Lab.
Prepared By
Dr. Hanan Ahmed Salman
1026
1027
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Theory:
A computer program is a set of instructions that a programmer writes to
tell a computer how to carry out a certain task. The instructions, however,
must be in a language that the computer understands. Computers only
understand a binary language i.e. that composed of 1’s and 0’s. This is a
low-level language and very hard to program in. So, humans invented
higher level languages such as C++ or Pascal to make the job easier. As
you will see, these languages are nearly like English but you don’t have
the freedom to write what you like – there are still rules you have to
follow.
1
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
ADD X Y Z
This instruction might mean “Add the number in the memory location
called X to the number in the memory location called Y, and place the
result in the memory location called Z.” The above sample instruction is
written in what is called assembly language. Although assembly
2
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
The version of the above instruction that the computer ultimately follows
would then be:
Assembly language instructions and their translation into zeros and ones
differ from machine to machine.
Programs written in the form of zeros and ones are said to be written in
machine language, because that is the version of the program that the
computer (the machine) actually reads and follows.
3
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Editor: accepts the typing of the source code (or header file).
Source file: the file that contains the program you prepared in the editor
after you save it. (.cpp)
Header file: header files such as iostream.h
Pre-processor: performs preliminary operations on files before they are
passed to the compiler.
Compiler: translates the source code to machine language.
Object code: the file containing the translated source code. (.obj)
Linker: links the object file with additional code, such as the library
codes.
Executable code: the file containing the final product. (.exe)
The entire program design process can be divided into two phases, the
problem-solving phase and the implementation phase. The result of the
4
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Program 1:
Probably the best way to start learning a programming language is by
writing a program. Therefore, here is our first program:
#include <iostream.h>
int main ()
{
cout << "Hello World!";
return 0;
}
5
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
The first panel shows the source code for our first program. The second
one shows the result of the program once compiled and executed. The
way to edit and compile a program depends on the compiler you are
using.
This is a comment line. All lines beginning with two slash signs (//)
are considered comments and do not have any effect on the
behavior of the program. The programmer can use them to include
short explanations or observations within the source code itself. In
this case, the line is a brief description of what our program is.
#include <iostream.h>
Lines beginning with a pound sign (#) are directives for the
preprocessor. They are not regular code lines with expressions but
indications for the compiler's preprocessor. In this case, the
directive #include <iostream> tells the preprocessor to include the
iostream standard file. This specific file (iostream) includes the
declarations of the basic standard input-output library in C++, and
it is included because its functionality is going to be used later in
the program.
int main ()
6
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Right after these parentheses we can find the body of the main
function enclosed in braces ({}). What is contained within these
braces is what the function does when it is executed.
cout represents the standard output stream in C++, and the meaning
of the entire statement is to insert a sequence of characters (in this
case the Hello World sequence of characters) into the standard
output stream (which usually is the screen).
7
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Notice that the statement ends with a semicolon character (;). This
character is used to mark the end of the statement and in fact it
must be included at the end of all expression statements in all C++
programs (one of the most common syntax errors is indeed to
forget to include some semicolon after a statement).
return 0;
You may have noticed that not all the lines of this program perform
actions when the code is executed. There were lines containing only
comments (those beginning by //). There were lines with directives for the
compiler's preprocessor (those beginning by #). Then there were lines that
began the declaration of a function (in this case, the main function) and,
finally lines with statements (like the insertion into cout), which were all
included within the block delimited by the braces ({}) of the main
function.
8
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Comments
Comments are parts of the source code disregarded by the compiler. They
simply do nothing. Their purpose is only to allow the programmer to
insert notes or descriptions embedded within the source code. C++
supports two ways to insert comments:
// line comment
/* block comment */
#include <iostream.h>
int main ()
{
cout << "Hello World! "; // prints Hello World!
cout << "I'm a C++ program"; // prints I'm a C++
program
return 0;
}
9
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
compiler will take them as if they were C++ expressions, most likely
causing one or several error messages when you compile it.
Questions:
10
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Theory:
Let us think that we ask you to retain the number 5 in your mental
memory, and then ask you to memorize the number 2 at the same time.
You have just stored two different values in your memory. Now, if we
ask you to add 1 to the first number, you should be retaining the numbers
6 (that is 5+1) and 2 in your memory. Now for example, we could
subtract and obtain 4 as result. The whole process that you have just done
with your mental memory is a simile of what a computer can do with two
variables. The same process can be expressed in C++ with the following
instruction set:
a = 5;
b = 2;
a = a + 1;
result = a - b;
Obviously, this is a very simple example since we have only used two
small integer values, but consider that your computer can store millions
of numbers like these at the same time and conduct sophisticated
mathematical operations with them.
11
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Identifiers
Symbolic names can be used in C++ for various data items used by a
programmer. A symbolic name is generally known as an identifier. The
identifier is a sequence of characters taken from C++ character set. The
rules for the formation of an identifier are:
Another rule that you have to consider when inventing your own
identifiers is that they cannot match any keyword of the C++ language or
your compiler's specific ones since they could be confused with these.
The standard reserved keywords are:
12
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
volatile while
Next, you have a summary of the basic fundamental data types in C++, as
well as the range of values that can be represented with each one:
13
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
signed: -2147483648 to
int Integer. 4bytes 2147483647
unsigned: 0 to 4294967295
signed: -2147483648 to
long int
Long integer. 4bytes 2147483647
(long)
unsigned: 0 to 4294967295
double Double precision floating point number. 8bytes 1.7e +/- 308 (15 digits)
* The values of the columns Size and Range depend on the architecture
of the system where the program is compiled and executed.
Declaration of variables
14
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
int a;
float mynumber;
These are two valid declarations of variables. The first one declares a
variable of type int with the identifier a. The second one declares a
variable of type float with the identifier mynumber. Once declared, the
variables a and mynumber can be used within the rest of their scope in
the program.
If you are going to declare more than one variable of the same type, you
can declare all of them in a single statement by separating their identifiers
with commas. For example:
int a, b, c;
This declares three variables (a, b and c), all of them of type int, and has
exactly the same meaning as:
int a;
int b;
int c;
The integer data types char, short, long and int can be either signed or
unsigned depending on the range of numbers needed to be represented.
Signed types can represent both positive and negative values, whereas
unsigned types can only represent positive values (and zero). This can be
specified by using either the specified signed or the specified unsigned
before the type name. For example:
15
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
int MyAccount;
with exactly the same meaning (with or without the keyword signed)
An exception to this general rule is the char type, which exists by itself
and is considered a different fundamental data type from signed char and
unsigned char, thought to store characters. You should use either signed
or unsigned if you intend to store numerical values in a char-sized
variable.
short and long can be used alone as type of specifies. In this case, they
refer to their respective integer fundamental types: short is equivalent to
short int and long is equivalent to long int. The following two variable
declarations are equivalent:
short Year;
short int Year;
unsigned NextYear;
unsigned int NextYear;
16
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Program 1
#include <iostream.h>
int main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
Initialization of variables
17
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
int a = 0;
For example:
int a (0);
Program 2
// initialization of variables 6
#include <iostream.h>
int main ()
{
int a=5; // initial value = 5
int b(2); // initial value = 2
int result; // initial value undetermined
a = a + 3;
result = a - b;
cout << result;
return 0;
}
18
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Variable Scope
Scope is a region of the program and broadly speaking there are three
places, where variables can be declared:
Local Variables:
Variables that are declared inside a function or block are local variables.
They can be used only by statements that are inside that function or block
of code. Local variables are not known to functions outside their own.
Following is the example using local variables.
Program 3
#include<iostream.h> 30
int main ()
{
// Local variable declaration:
int a, b;
int c;
// actual initialization
a =10;
b =20;
c = a + b;
cout << c;
return0; }
19
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Global Variables:
Global variables are defined outside of all the functions, usually on top of
the program. The global variables will hold their value throughout the
life-time of your program. A global variable can be accessed by any
function. That is, a global variable is available for use throughout your
entire program after its declaration. Following is the example using
global and local variables.
Program 4
#include<iostream.h> 40
// Global variable declaration:
int g=10;
int main ()
// actual initialization
a =10;
b =20;
c = a + b+ g;
cout << c;
return0;
20
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
A program can have same name for local and global variables but value
of local variable inside a function will take preference.
Program 5
#include<iostream.h> 10
// Global variable declaration:
int g=20;
int main ()
cout << g;
return0;
Questions:
1- Write a C++ program that computes the z value from the following
equations:
a- z= a(b*d)-(c*b)+d where a=10, b=20, c=14, and d= 5
C0=5/9(F-32)
21
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Object:
How defining and using stream of characters and constant in the program.
Theory:
Variables that can store non-numerical values that are longer than one
single character are known as strings.
The C++ language library provides support for strings through the
standard string class. This is not a fundamental type, but it
behaves in a similar way as fundamental types do in its most basic
usage.
A first difference with fundamental data types is that in order to
declare and use objects (variables) of this type we need to include
an additional header file in our source code: <string> and have
access to the std namespace (which we already had in all our
previous programs thanks to the using namespace statement).
Program 1
int main ()
{
string mystring = "This is a string";
cout << mystring;
return 0;
22
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Strings can be initialized with any valid string literal just like numerical
type variables can be initialized to any valid numerical literal. Both
initialization formats are valid with strings:
Strings can also perform all the other basic operations that fundamental
data types can, like being declared without an initial value and being
assigned values during execution.
Program 2
int main ()
{
string mystring;
mystring = "This is the initial string
content";
cout << mystring << endl;
mystring = "This is a different
string content";
cout << mystring << endl;
return 0;
}
23
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
212// Legal
215u// Legal
0xFeeL// Legal
078// Illegal: 8 is not an octal digit
032UU// Illegal: cannot repeat a suffix
85// decimal
0213// octal
0x4b// hexadecimal
30// int
30u// unsigned int
30l// long
30ul// unsigned long
Floating-point literals:
24
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
3.14159// Legal
314159E-5L// Legal
510E// Illegal: incomplete exponent
210f// Illegal: no decimal or exponent
.e55 // Illegal: missing integer or fraction
Boolean literals:
There are two Boolean literals and they are part of standard C++
keywords:
You should not consider the value of true equal to 1 and value of false
equal to 0.
Character literals:
Character literals are enclosed in single quotes. If the literal begins with L
(uppercase only), it is a wide character literal (e.g., L'x') and should be
stored in wchar_t type of variable. Otherwise, it is a narrow character
literal (e.g., 'x') and can be stored in a simple variable of char type.
\n Newline
\r carriage return
25
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
\t Tab
\v vertical tab
\b backspace
\a alert (beep)
\\ backslash (\)
String literals:
Here are some examples of string literals. All the three forms are identical
strings.
"hello, dear"
"hello, \
dear"
"hello, ""d""ear"
26
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
You can define your own names for constants that you use very often
without having to resort to memory-consuming variables, simply by using
the #define preprocessor directive. Its format is:
For example:
#define PI 3.14159265
#define NEWLINE '\n'
This defines two new constants: PI and NEWLINE. Once they are
defined, you can use them in the rest of the code as if they were any other
regular constant, for example:
Program 3
#include <iostream.h>
#define PI 3.14159
#define NEWLINE '\n';
int main ()
{
double r=5.0; // radius
double circle;
circle = 2 * PI * r;
cout << circle;
cout << NEWLINE;
return 0; }
27
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
In fact the only thing that the compiler preprocessor does when it
encounters #define directives is to literally replace any occurrence of their
identifier (in the previous example, these were PI and NEWLINE) by the
code to which they have been defined (3.14159265 and '\n' respectively).
The #define directive is not a C++ statement but a directive for the
preprocessor; therefore it assumes the entire line as the directive and does
not require a semicolon (;) at its end. If you append a semicolon character
(;) at the end, it will also be appended in all occurrences within the body
of the program that the preprocessor replaces.
With the const prefix you can declare constants with a specific type in the
same way as you would do with a variable:
In case that no type is explicitly specified (as in the last example) the
compiler assumes that it is of type int.
Program 4
#include<iostream.h>
int main()
28
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
int area;
return 0;
When the above code is compiled and executed, it produces the following
result:
50
Questions:
2- Write a C++ program that computes the average of two marks. For
example, if 75 is the degree of Maths and 89 of Chemistry then the
average is 82.
29
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Theory:
Once we know of the existence of variables and constants, we can begin
to operate with them. For that purpose, C++ integrates operators. Unlike
other languages whose operators are mainly keywords, operators in C++
are mostly made of signs that are not part of the alphabet but are available
in all keyboards. This makes C++ code shorter and more international,
since it relies less on English words, but requires a little of learning effort
in the beginning.
Assignation (=)
a = 5;
This statement assigns the integer value 5 to the variable a. The part at the
left of the assignation operator (=) is known as the lvalue (left value) and
the right one as the rvalue (right value). The lvalue has to be a variable
whereas the rvalue can be either a constant, a variable, the result of an
operation or any combination of these.
The most important rule of assignation is the right-to-left rule: The
assignation operation always takes place from right to left, and never the
other way:
30
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
a = b;
Program 1
#include <iostream.h>
int main ()
{
int a, b;
a = 10;
b = 4;
// a:10, b:4
a = b;
// a:4, b:4
b = 7;
// a:4, b:7
return 0;
}
This code will give us as result that the value contained in a is 4 and the
one contained in b is 7. Notice how a was not affected by the final
31
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
A property that C++ has over other programming languages is that the
assignation operation can be used as the rvalue (or part of an rvalue) for
another assignation. For example:
a = 2 + (b = 5);
is equivalent to:
b = 5;
a = 2 + b;
a = b = c = 5;
Arithmetic operators ( +, -, *, /, % )
+ Addition
- Subtraction
* multiplication
/ division
% modulo
32
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
a = 11 % 3;
the variable a will contain the value 2, since 2 is the remainder from
dividing 11 between 3.
Compound assignation
(+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
Expression is equivalent to
a -= 5; a = a - 5;
a /= b; a = a / b;
Program 2
// compund assignation 5
#include <iostream.h>
int main ()
33
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
{
int a, b=3;
a = b;
a+=2; // equivalent to a=a+2
cout << a;
return 0;
}
C++ provides two special operators '++' and '--' for incrementing and
decrementing the value of a variable by 1. The increment/decrement
operator can be used with any type of variable but it cannot be used with
any constant. Increment and decrement operators each have two forms,
pre and post.
Program 3
// compund assignation 11
10
#include <iostream.h>
int main ()
{
int x,y;
int i=10,j=10;
x = ++i; //add one to i, store the result back in
34
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
x
y= j++; //store the value of j to y then add one
to j
cout<<x;
cout<<y;
}
Questions:
a- z=x++*y.
b- z=2*++x*y.
c- y %=x.
a- x+y2+t/z
b- a3-b2/ c2+25
___________________________________________________________
For the next experiments you shall need to know the following
operators:
35
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
== Equal to
!= Not equal to
(7 == 5) // evaluates to false.
(5 > 4) // evaluates to true.
(3 != 2) // evaluates to true.
(6 >= 6) // evaluates to true.
(5 < 5) // evaluates to false.
Of course, instead of using only numeric constants, we can use any valid
expression, including variables. Suppose that a=2, b=3 and c=6,
Be careful!
The operator = (one equal sign) is not the same as the operator == (two
equal signs), the first one is an assignation operator (assigns the value at
its right to the variable at its left) and the other one (==) is the equality
36
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
operator that compares whether both expressions in the two sides of it are
equal to each other. Thus, in the last expression ((b=2) == a), we first
assigned the value 2 to b and then we compared it to a, that also stores the
value 2, so the result of the operation is true.
The logical operators && and || are used when evaluating two
expressions to obtain a single relational result. The operator &&
corresponds with Boolean logical operation AND. This operation results
true if both its two operands are true, and false otherwise. The following
panel shows the result of operator && evaluating the expression a && b:
(&&) Operator
a b a && b
37
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
( || ) Operator
a b a || b
For example:
( ? ) Conditional operator
38
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Example:
// conditional operator 7
#include <iostream.h>
int main ()
{
int a,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
cout << c;
return 0;
}
( , ) Comma operator
The comma operator (,) is used to separate two or more expressions that
are included where only one expression is expected. When the set of
expressions has to be evaluated for a value, only the rightmost expression
is considered.
39
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
a = (b=3, b+2);
Would first assign the value 3 to b, and then assign b+2 to variable a. So,
at the end, variable a would contain the value 5 while variable b would
contain value 3.
| OR Bitwise Inclusive OR
int i;
40
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
float f = 3.14;
i = (int) f;
The previous code converts the float number 3.14 to an integer value (3),
the remainder is lost. Here, the typecasting operator was (int). Another
way to do the same thing in C++ is using the functional notation:
preceding the expression to be converted by the type and enclosing the
expression between parentheses:
i = int ( f );
sizeof() operator
a = sizeof (char);
This will assign the value 1 to a because char is a one-byte long type.
The value returned by sizeof is a constant, so it is always determined
before program execution.
Precedence of operators
a=5+7%2
41
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
a = 5 + (7 % 2) // with a result of 6, or
a = (5 + 7) % 2 // with a result of 0
The correct answer is the first of the two expressions, with a result of 6.
There is an established order with the priority of each operator, and not
only the arithmetic ones (those whose preference come from
mathematics) but for all the operators which can appear in C++. From
greatest to lowest priority, the priority order is as follows:
Left-to-
1 :: scope
right
() [] . -> ++ -- dynamic_cast
Left-to-
2 static_cast reinterpret_cast postfix
right
const_cast typeid
Right-to-
4 (type) type casting
left
Left-to-
5 .* ->* pointer-to-member
right
Left-to-
6 */% multiplicative
right
Left-to-
7 +- additive
right
42
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Left-to-
8 << >> shift
right
Left-to-
9 < > <= >= relational
right
Left-to-
10 == != equality
right
Left-to-
11 & bitwise AND
right
Left-to-
12 ^ bitwise XOR
right
Left-to-
13 | bitwise OR
right
Left-to-
14 && logical AND
right
Left-to-
15 || logical OR
right
Right-to-
16 ?: conditional
left
Left-to-
18 , comma
right
43
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
a = 5 + 7 % 2;
a = 5 + (7 % 2);
Or a = (5 + 7) % 2;
44
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Theory:
Conditional structure:
1. if statement
if (condition) statement
45
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
For example, the following code fragment prints x is 100 only if the value
stored in the x variable is indeed 100:
if (x == 100)
cout << "x is 100";
if (x == 100)
{
cout << "x is ";
cout << x;
}
Program 1
int a = 10;
if( a < 20 )
return 0; }
46
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
2. If else statement
For example:
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
The program prints on the screen x is 100 if indeed x has a value of 100,
but if it has not -and only if not- it prints out x is not 100.
47
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";
Program 2
48
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Program 3
else
return 0; }
49
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
if ( boolean_expression 1)
{
// Executes when the boolean expression 1 is true
if(boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}}
Program 4
Void main()
int number;
cin>> number;
if (number <=0)
if (number >=127)
50
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Questions:
1- Write a C++ program that computes the division for two integer
numbers.
2- Write a C++ program that inputs an integer number and determines
whether the number is even or odd.
3- Write a C++ program that computes the following equation:
Homework:
1- Write a program that reads a number and determines whether the
number is positive, negative, or zero.
2- Write a C++ program that computes the following equation:
51
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Theory:
The syntax of the switch statement is to check several possible constant
values for an expression. Something similar to several if and else if
instructions. Its form is the following:
switch (expression)
{
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;
break;
.
.
.
default:
default group of statements
}
52
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Finally, if the value of expression did not match any of the previously
specified constants (you can include as many case labels as values you
want to check), the program will execute the statements included after the
default: label, if it exists (since it is optional).
53
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
switch (x) {
if (x == 1) {
case 1:
cout << "x is 1";
cout << "x is 1";
}
break;
else if (x == 2) {
case 2:
cout << "x is 2";
cout << "x is 2";
}
break;
else {
default:
cout << "value of x unknown";
cout << "value of x unknown";
}
}
If you need to check ranges or values that are not constants, use a
concatenation of if and else if statements.
Program 1
switch(grade)
54
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
case 'F' : cout << "Better try again" << endl; break;
return 0;
switch (ch1) {
case 'A':
cout << "This A is part of outer switch";
switch(ch2) {
case 'A':
cout << "This A is part of inner switch";
break;
case 'B': // ...
}
break;
case 'B': // ...
55
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Questions:
56
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Theory:
57
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Program 1
while (n>0) {
cout << n << ", ";
--n;
}
58
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
In this case we have included --n; that decreases the value of the variable
that is being evaluated in the condition (n) by one - this will eventually
make the condition (n>0) to become false after a certain number of loop
iterations: to be more specific, when n becomes 0, that is where our
while-loop and our countdown end.
Its functionality is exactly the same as the while loop, except that
condition in the do-while loop is evaluated after the execution of
statement instead of before, granting at least one execution of statement
even if condition is never fulfilled. Flow the following diagram:
59
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
For example, the following example program echoes any number you
enter until you enter 0.
Program 2
The do-while loop is usually used when the condition that has to
determine the end of the loop is determined within the loop statement
itself, like in the previous case, where the user input within the block is
what is used to determine if the loop has to end. In fact if you never enter
the a value 0 in the previous example you can be prompted for more
numbers forever.
Questions:
1- Write a C++ program that computes the sum of ten numbers input
by the user. Use while loop.
2- Write a C++ program that computes the sum of consecutive integer
number 1+2+3+….+ n. Use do/while loop.
60
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Theory:
Its format is: for (initialization; condition; increase) statement; and its
main function is to repeat statement while condition remains true, like the
while loop. But in addition, the for loop provides specific locations to
contain an initialization statement and an increase statement. So this loop
is specially designed to perform a repetitive action with a counter which
is initialized and increased on each iteration.
61
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Program 1
The initialization and increase fields are optional. They can remain
empty, but in all cases the semicolon signs between them must be written.
For example we could write: for (;n<10;) if we wanted to specify no
initialization and no increase; or for (;n<10;n++) if we wanted to include
62
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Optionally, using the comma operator (,) we can specify more than one
expression in any of the fields included in a for loop, like in initialization,
for example:
This loop will execute for 50 times if neither n or i are modified within
the loop:
n starts with a value of 0, and i with 100, the condition is n!=i (that n is
not equal to i). Because n is increased by one and i decreased by one, the
loop's condition will become false after the 50th loop, when both n and i
will be equal to 50.
Using break we can leave a loop even if the condition for its end is not
fulfilled. It can be used to end an infinite loop, or to force it to end before
its natural end. For example, we are going to stop the count down before
its natural end (maybe because of an engine check failure?):
63
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Program 2
int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
return 0;
}
The continue statement causes the program to skip the rest of the loop in
the current iteration as if the end of the statement block had been reached,
causing it to jump to the start of the following iteration.
Program 3
int main ()
{
for (int n=10; n>0; n--) {
if (n==5) continue;
64
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Questions:
1- Write a C++ program that prints the numbers from 1 to 20.
2- Write a C++ program that computes the sum of ten integer
numbers input by the user.
3- Write a C++ program that computes the factorial of an integer
number.
Homework:
65
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Theory:
Declaring Arrays:
66
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
double balance[10];
You can initialize C++ array elements either one by one or using a single
statement as follows:
The number of values between braces { } can not be larger than the
number of elements that we declare for the array between square brackets
[ ]. Following is an example to assign a single element of the array:
If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write:
The above statement assigns element number 5th in the array a value of
50.0. Array with 4th index will be 5th, i.e., last element because all arrays
have 0 as the index of their first element which is also called base index.
Following is the pictorial representation of the same array we discussed
above:
67
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
The above statement will take 10th element from the array and assign the
value to salary variable. Following is an example, which will use all the
above-mentioned three concepts viz. declaration, assignment and
accessing arrays.
Program 1
Write a C++ program that calculates the sum and average of an initialized
integer array.
#include <iostream.h>
void main ()
int sum=0;
sum+=b[i];
<<”Average is “<<sum/5.0;
Program 2
Write a C++ program that inputs ten integer values into an array and finds
the maximum number in the array.
#include <iostream.h>
void main ()
68
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
cin>>c[i];
max=c[0];
if (c[i]>max)
max=c[i];
Questions:
69
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Theory:
String is a character array that is terminated with null. Null is zero and
can be expressed as NUL or ‘\0’. The compiler adds the null to the end of
string automatically.
For example:
or
str
H e l l o t h e r e 0
70
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Program 3
Write a C++ program that reads a string and then computes the number of
capital letters in the string.
#include <iostream.h>
void main ()
char str[30];
int count=0
cin>>str;
if (str[i]>=’A’&&str[i]<=’Z’)
count++;
Questions:
71
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Theory:
C++ allows multidimensional arrays. Here is the general form of a
multidimensional array declaration:
type name[size1][size2]...[sizeN];
int threedim[5][10][4];
Two-Dimensional Arrays:
type arrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName will be a
valid C++ identifier.
72
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
int a[3][4] = {
};
The nested braces, which indicate the intended row, are optional. The
following initialization is equivalent to previous example:
73
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
The above statement will take 4th element from the 3rd row of the array.
You can verify it in the above diagram.
Program 4
#include <iostream>
int main ()
cout << "a[" << i << "][" << j << "]: ";
return 0;
74
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Program 5
Write a C++ program that finds the average of each row of a 3x4 matrix
input by the user.
#include <iostream>
void main ()
int a[3][4];
int sum;
cin>>a[i][j];
sum=0;
sum+=a[i][j];
cout<<sum/4.0<<endl;
75
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Questions:
1- Write a C++ program that adds two initialized 3x4 matrices A and
B and then stores the result in a matrix C.
2- Write a C++ program that exchanges row3 with row1 in 4x4
integer matrix input by the user.
___________________________________________________
Theory:
For example:
To access an individual string, we simply specify only the row index. For
example: cout<< day[1];
76
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Questions:
1- Write a C++ program that inputs a 4x4 integer matrix and finds the
maximum value in the primary diagonal and the minimum value in
the secondary diagonal.
2- Write a C++ program that converts a two dimensional array into
one dimensional array. Then print the 1D.
3- Use array of string to write a C++ program that prints the week
days.
________________________________________________________
Theory:
Using functions we can structure our programs in a more modular way,
accessing all the potential that structured programming can offer to us in
C++. A function is a group of statements that is executed when it is
called from some point of the program. The following is its format:
where:
77
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Program 1
The result is 8
// function example
#include <iostream.h>
78
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
At the point at which the function is called from within main, the control
is lost by main and passed to the function addition. The value of both
arguments passed in the call (5 and 3) are copied to the local variables int
a and int b within the function.
Function addition declares another local variable (int r), and by means of
the expression r=a+b, it assigns to r the result of a plus b. Because the
actual parameters passed for a and b are 5 and 3 respectively, the result is
8.
return (r);
79
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Finalizes function addition, and returns the control back to the function
that called it in the first place (in this case, main). At this moment the
program follows it regular course from the same point at which it was
interrupted by the call to addition. But additionally, because the return
statement in function addition specified a value: the content of variable r
(return (r);), which at that moment had a value of 8. This value becomes
the value of evaluating the function call.
So being the value returned by a function the value given to the function
call itself when it is evaluated, the variable z will be set to the value
returned by addition (5, 3), that is 8. To explain it another way, you can
imagine that the call to a function (addition (5,3)) is literally replaced by
the value it returns (8).
That, as you may already expect, produces the printing of the result on
the screen.
Program 2
int main ()
{
int x, y, z;
z = subtraction (7,2);
cout << "The first result is " << z << '\n';
cout << "The second result is " << subtraction
(7,2) << '\n';
cout<<"enter your fun parameters<< '\n';
cin>>x>>y;
cout << "The third result is " << subtraction (x,y)
<< '\n';
z= 4 + subtraction (x,y);
cout << "The fourth result is " << z << '\n';
return 0;
}
You will see that the declaration begins with a type, that is the type of
the function itself (i.e., the type of the data that will be returned by the
function with the return statement). But what if we want to return no
value? Imagine that we want to make a function just to show a message
81
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Program 3
void printmessage ()
{
cout << "I'm a function!";
}
int main ()
{
printmessage ();
return 0;
}
Function Arguments:
82
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
this case, changes made to the parameter inside the function have no
effect on the argument.
Program 4
#include <iostream.h>
// function declaration
int main ()
int a = 100;
int b = 200;
swap(a, b);
return 0;
83
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Questions:
1- Write a C++ program that finds the max value in an integer array
a[10] using the function maxa().
2- Write a C++ program that computes the factorial of an integer
number using the function factorial().
3- Write a C++ program that computes the power of an integer
number using the function power().
_________________________________________________________
Theory:
84
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Way-1
Formal parameters as a pointer as follows:
Way-2
Formal parameters as a sized array as follows:
Way-3
Formal parameters as an unsized array as follows:
void myFunction(int param[])
{ ...}
Program 1
85
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
#include <iostream.h>
// function declaration:
double getAverage(int arr[], int size);
int main ()
{
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
// pass pointer to the array as an argument.
avg = getAverage( balance, 5 ) ;
// output the returned value
cout << "Average value is: " << avg << endl;
return 0;
}
When the above code is compiled together and executed, it produces the
following result:
As you can see, the length of the array doesn't matter as far as the
function is concerned because C++ performs no bounds checking for the
formal parameters.
Return array from functions
86
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Program 2
// main function to call above defined function.
#include<iostream.h>
int main ()
{
// a pointer to an int.
int *p;
p = getRandom();
for ( int i = 0; i < 10; i++ )
{
cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
}
return 0;
}
Program 3
Write a C++ program that reads, sorts and prints an integer array a[10]
using three functions setarray(), sortarray, and putarray().
#include <iostream.h>
87
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
int a[10];
setarray(a);
sortarray(a);
cout<<”Sorted array is “;
putarray(a);
}
void setarray(int b[10])
{ cout<<”Enter ten integer array: “;
for (int i=0;i<10;i++)
cin>>b[i];
}
Theory:
88
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
- When we need the function returns more than one value, we can pass
arguments by reference to the function.
- A reference provides an another name for a variable (It’s actually the
memory address of the variable that is passed).
- An important advantage of passing by refrefence is that the function
can access the actual variables in the calling program. This provides a
mechanism for passing more than one value from the function back to
the calling program.
Program 1
Program 2
#include <iostream.h>
void sqr(int&)
void main()
{ int n;
cin>>n;
sqr(n);
_______________________________________________________
Theory:
Recursive Function
A recursive function is a function that calls itself in order to perform a
task of computation. There are two basic components of a recursive
solution:
- Termination step, stating the solution when the process comes to an
end.
- Inductive step, calling the function itself with a renewed parameter
value.
Program 1
Write a C++ program that computes the factorial of a positive
integer number using the recursive function factorial().
#include<iostream.h>
Long factorial(int);
Void main()
{ int number;
90
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Program 2
Write a C++ program that computes the area of square and the area
of rectangle using the overloaded function area().
#include<iostream.h>
int area(int);
int area( int, int);
void main()
{ int length, width;
cout<<”Enter a length of square: ”;
cin>>length;
cout<<”The area of square is “<<area(length)<<endl;
cout<<”Enter a length and width of rectangle : “;
cin>>length>>width;
cout<<”The area of rectangle is “<<area(length, width)<<endl;
}
int area(int a)
{
return (a*a);
}
int area(int a, int b)
{
return (a*b);
}
91
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Questions:
1- Write a C++ program that computes the power of an entered
integer number using the recursive function power().
2- Write a C++ program that adds two numbers of different numeric
data types(e.g. integer, float, double) using the overloaded function
add().
_________________________________________________________
Structure (Part I)
Object:
Theory:
When dealing with the students in a school, many variables of different
types are needed. For example, structure STUDENT which includes
name, age, and marks.
Program 1
#include <iostream.h>
struct STUDENT
{
char name[80];
int, age;
float marks;
};
int main()
{ // declare two variables of the new type
STUDENT s1, s3;
92
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Arrays of Structure
Program 2
Write a C++ program that inputs and prints the personal details (e.g.
name, age, weight, phone_no) for 10 users using the structure Person.
#include<iostream.h>
struct Person
{ char name[10];
int age;
float weight;
char phone_no[20];
};
void main()
{ const int size=10;
Person p[size];//Define array of structure variables
for (int i=0; i<size; i++)
{ cout<<”Person “<<i+1<<endl;
cout<<”Enter name: “; cin>>p[i].name;
cout<<”Enter age: “; cin>> p[i].age;
cout<<”Enter weight: “; cin>>p[i].weight;
cout<<”Enter phone_number: “; cin>>p[i].phone_no;
cout<<endl;
}
for (int i=0; i<size; i++)
{ cout<<”Person “<<i+1<<endl;
cout<<”Name: “; <<p[i].name<<endl;
cout<<”Age: “; <<p[i].age<<endl;
cout<<”Weight: “<<p[i].weight<<endl;
cout<<”Phone_number: “; <<p[i].phone_no<<endl;
93
} }
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Questions:
1- Write a C++ program that inputs and prints the name and date of
birth using the structure Birth.
2- Write a C++ program that inputs and prints hours, minutes and
seconds using the structure Time.
_________________________________________________________
Theory:
Passing Structure to Functions
Write a C++ program that computes the area of rectangle using the
function area() and the structure Rectangle.
#include <iostream.h>
struct Rectangle
{ int length;
int width;
};
int area (Rectangle);
void main ()
{ Rectangle rect;
cout<<”Enter the length and width of rectangle: “;
cin>>rect.length>>rect.width;
94
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
#include <iostream.h>
struct Date
{ int day;
int month;
int year;
};
void getdate(Date&);
void putdate(Date&);
void main ()
{ Date d;
getdate(d);
putdate(d);
}
void getdate(Date& dd)
{ cout<<”Enter your date of birth in day, month, year: “;
cin>>dd.day>>dd.month>>dd.year;
}
void putdate(Date& dd)
{ cout<<”You were born in
“<<dd.day<<”/”<<dd.month<<”/”<<dd.year;
}
Question:
95
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Write a C++ program that inputs a time in hours, minutes and seconds,
and then converts and prints the overall time in seconds, then in minutes
and then in hours using the functions seconds(), minutes(), hours() and
the structure Time.
________________________________________________________
Theory:
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and
var-name is the name of the pointer variable. The asterisk you used to
declare a pointer is the same asterisk that you use for multiplication.
However, in this statement the asterisk is being used to designate a
variable as a pointer. Following are the valid pointer declaration:
96
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
There are few important operations, which we will do with the pointers
very frequently.
(c) finally access the value at the address available in the pointer
variable.
This is done by using unary operator * that returns the value of the
variable located at the address specified by its operand. Following
example makes use of these operations:
Program 1
#include <iostream.h>
int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;
// access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl;
return 0;
}
Program 2
97
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
#include <iostream.h>
int main ()
{
int *ptr = NULL;
cout << "The value of ptr is " << ptr ;
return 0;
}
When the above code is compiled and executed, it produces the following
result:
The value of ptr is 0
ptr++
98
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
The ptr will point to the location 1004 because each time ptr is
incremented, it will point to the next integer.
Program 3
#include <iostream.h>
const int MAX = 3;
int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have array address in pointer.
ptr = var;
for (int i = 0; i < MAX; i++)
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl; // point to the next location
ptr++;
}
return 0; }
Decrementing a Pointer:
Program 4
#include <iostream.h>
const int MAX = 3;
int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have address of the last element in pointer.
ptr = &var[MAX-1];
99
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
___________________________________________________
Experiment No. (20)
Pointer (Part II)
Object:
Learning how to define and use pointers and array in C++ programming
language.
Theory:
C++ Pointers vs Arrays
Pointers and arrays are strongly related. In fact, pointers and arrays are
interchangeable in many cases. For example, a pointer that points to the
beginning of an array can access that array by using either pointer
arithmetic or array-style indexing. Consider the following program.
Program 1
#include <iostream.h>
void main()
{ int a[5]={31, 54, 77, 52, 93};
for (int i=0; i<5; i++)
cout<<a[i]<<endl;
100
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
cout<<endl;
// Or use pointer
for (int i=0; i<5; i++)
cout<<*(a+i)<<endl; }
Program 2
#include <iostream.h>
void main()
{ int a[5]={31, 54, 77, 52, 93};
int *ptr;
ptr=a;
for (int i=0; i<5; i++)
cout<<*(ptr++)]<<endl;
}
Question:
Write a C++ program that uses pointer to read an integer of ten marks
a[10] and compute the average using pointer and print the result.
_________________________________________________________
Theory:
Pointer to Function
The call by pointer method of passing arguments to a function copies the
address of an argument into the formal parameter. Inside the function, the
101
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
address is used to access the actual argument used in the call. This means
that changes made to the parameter affect the passed argument.
Program 1
#include <iostream.h>
// 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.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
102
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Question:
Write a C++ program that finds the maximum value in an entered integer
a[10] using the function max(int*, int).
________________________________________________________
Learning how to define and use pointers and Structure and string in C++
programming language.
Theory:
Program
include <iostream.h>
struct Rectangle
{ float length;
Float width;
};
void main()
{ Rectangle *rect;
float a;
cout<<”Enter the length and width of rectangle: “;
cin>> rect->length*rect->width;
a=rect->length*rect->width;
cout<<”The area of rectangle is “<<a;
}
103
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Program 1
#include <iostream.h>
void main()
{
char str1[]=”Defined as an array”;
char* str2=”Define as a pointer”;
cout<<str1<<endl;
cout<<str2<<endl;
// str1++; // cannot do this because str1 is a constant
str
Program 2
#include <iostream.h>
void dispstr(char*);
void main()
{
char str1[]=”Idle people have the least leisure.”;
dispstr(str);
}
void disptr (chr* ps)
{ while (*ps)
cout<<*ps++;
cout << endl;
}
104
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Theory:
105
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Program 2
#include <fstream.h>
#include <iostream.h>
void main()
{
char ch;
int j;
double d;
char str1[10];
char str2[10];
fstream myfile; //creat a file object
myfile.open(“fdata.txt”, ios::in); //open file for reading
myfile >>ch>>j>>d >>str1>>str2; //read data from file
cout<<ch<<endl<<j<<endl<<d<<endl<<str1<<str2<<endl;
myfile.close(); //close file
}
Program 3
#include <fstream.h>
#include <iostream.h>
void main()
{
char ch=’y’;
int j=88;
double d=7.02;
char str1[] = “Mohammad”;
char str2[] =”Ali”;
106
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
fstream myfile;
myfile.open(“fdata.txt”, ios::app); //open file for adding data
myfile <<endl<<ch<<j<<’ ‘<<d <<str1<<’ ‘<< str2;
myfile.close(); //close file
cout<<”File is written\n”;
}
End-of-file eof()
Program 4
#include <fstream.h>
#include <iostream.h>
void main()
{
char ch;
int j;
double d;
char str1[10];
char str2[10];
fstream myfile;
myfile.open(“fdata.txt”, ios::in);
while(!myfile.eof())
{
myfile >>ch>>j>>d >>str1>>str2; //read data from file
cout<<ch<<endl<<j<<endl<<d<<endl<<str1<<str2<<endl;
}
myfile.close(); //close file
}
107
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Theory:
#include <fstream.h>
#include <iostream.h>
#define max 5 // size of the stack
int top, a[max];
void push(void)
{
int x;
if (top==max-1) // condition for checking if Stack is Full
{
cout<<”stack is overflow\n”;
return;
}
108
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
cout<<”Enter a No.\n”;
cin>>”%d”,&x;
a[++top]=x; //increment the top and inserting element
cout<<”%d succ.pushed\n”,x;
return;
}
void pop(void)
{
int y;
if (top==-1)// Condition for checking if Stack is Empty
{
cout<<”stack is underflow\n”;
return;
}
y=a[top];
a[top--]=0;
//insert 0 at place of removing element and decrement the top
cout<<”%d succ.poped\n”,y;
return;
}
void display(void)
{ int i;
If (top==-1)
{
cout<<”stack is empty\n”;
return;
}
cout<<”elements of Stack are :\n”;
for (i=0;i<=top;i+=)
{
cout<<”%d\n”, a[i];
}
return;
}
void main (void)
{
int c, top=-1;
do
{
cout<<”1:Push\n2:Pop\n3:Display\n4:Exit\nChoice: “;
109
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
cin>>”%d”,&c;
switch (c)
{
case1: push(); break;
case2: pop(); break;
case3: display(); break;
case4: cout<<”program ends\n”; break;
default: cout<<”wrong choic\n”; break;
}
}while(c!=4);
}
Questions:
110
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
Theory:
A queue is a linear list in which data can only be inserted at one end,
called the rear, and deleted from the other end, called the front. These
restrictions ensure that the data is processed through the queue in the
order in which it is received. In other words, a queue is a first in, first out
(FIFO) structure.
Program
include <fstream.h>
#include <iostream.h>
#define MAX 50
int queue_array[MAX];
int rear=-1;
int front=-1;
void main()
{ int choice;
while (1)
{
cout<<”1. Insert element to queue\n”;
cout<<”2. Delete element from queue\n”;
cout<<”3. Display elements of queue\n”;
cout<<”4. Quit\n”;
cout<<”Enter your choice: “;
cin>>”%d”, &choice;
switch (choice)
{
case 1: insert(); break;
case 2: delete(); break;
111
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
insert()
{ int add_item;
if (rear==MAX-1)
cout<<”Queue Overflow \n”;
else
{ if (front==-1)/*if queue is initially empty */
front=0;
cout<<”insert the element in queue: “;
cin>>”%d”, &add_item;
rear=rear+1;
Queue_array[rear]=add_item;
}
} /*End of insert()*/
delete()
{
if (front==-1|| front>rear)
{ cout<<”Queue is Underflow\n”;
return;
}
else
{
cout<<”Element deleted from queue is : %\n”, queue_array[front];
front=front+1;
}
}/*End of delete()*/
display()
{ int i;
if (front==-1)
cout<<”Queue is empty\n”;
else
{
cout<<”Queue is :\n”;
for(i=front; i<= rear; i++)
112
Al-Mustansiriyah University First Class
Faculty of Engineering
Computer Engineering Department Data Structure Lab.
cout<<”%d”, queue_array[i];
cout<<”\n”;
}
}/*End of display*/
113