0% found this document useful (0 votes)
14 views

C++ and Data Structure Lab Manual

This manual helps to understand C++ programming language and Data Structure

Uploaded by

dbekele2003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

C++ and Data Structure Lab Manual

This manual helps to understand C++ programming language and Data Structure

Uploaded by

dbekele2003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

WOLLO UNIVERSITY

KOMBOLCHA INSTITUTE OF TECHNOLOGY

COLLEGE OF INFORMATICS

DEPARTMENT OF COMPUTER SCIENCE

Data Structure and Algorithm Analysis Lab Manual

By

Daniel Bekele
Data Structure and Algorithm Analysis Lab Manual

Prepared by:-

Daniel Bekele (MSc)

email address: - [email protected]

Wollo University

March, 2015 G.C.


Acknowledgement

I would like to thank my mother Worke Shiferaw, father Bekele Eshete and friends for their
encouragement to write this lab manual.

i
Table of Contents
Chapter One: Introduction to C++ ................................................................................................................ 1

Chapter Two: Array .................................................................................................................................... 18

Chapter Three: Function ............................................................................................................................. 34

Chapter Four: Structure............................................................................................................................... 50

Chapter Five: Algorithm Analysis .............................................................................................................. 58

Chapter Six: Searching and Sorting Algorithm .......................................................................................... 68

Chapter Seven: Linked List ........................................................................................................................ 77

Chapter Eight: Stack and Queue ................................................................................................................. 84

Chapter Nine: Tree...................................................................................................................................... 90

ii
Chapter One: Introduction to C++
Basic Program Construction
Let‘s look at a very simple C++ program. This program is called FIRST, so its source file is
FIRST.CPP. It simply prints a sentence on the screen. Here it is:
#include<iostream>
using namespace std;
int main( )
{
cout << "\nwelcome to Data Structure and Algorithm Analysis lab class";
return 0;
}

Despite its small size, this program demonstrates a great deal about the construction of C++
programs. Let‘s examine it in detail.

Functions
Functions are one of the fundamental building blocks of C++. The FIRST program consists
almost entirely of a single function called main( ). The only parts of this program that are not
part of the function are the first two lines—the ones that start with #include and using.

Function Name
The parentheses following the word main are the distinguishing feature of a function. Without
the parentheses the compiler would think that main refers to a variable or to some other program
element.

Braces and the Function Body


The body of a function is surrounded by braces (sometimes called curly brackets). These braces
play the same role as the BEGIN and END keywords in some other languages: They surround or
delimit a block of program statements. Every function must use this pair of braces around the
function body. In this example there are only two statements in the function body: the line
starting with cout, and the line starting with return. However, a function body can consist of
many statements.

1
Always Start with main( )
When you run a C++ program, the first statement executed will be at the beginning of a function
called main( ). The program may consist of many functions, classes, and other program elements,
but on startup, control always goes to main( ). If there is no function called main( ) in your
program, an error will be reported when you run the program.

Program Statements
The program statement is the fundamental unit of C++ programming. There are two statements
in the FIRST program: the line
cout << "welcome to Data Structure and Algorithm Analysis lab class";
and the return statement
return 0;
The first statement tells the computer to display the quoted phrase. Most statements tell the
computer to do something. In this respect, statements in C++ are similar to statements in other
languages.

A semicolon signals the end of the statement. This is a crucial part of the syntax but easy to
forget. In some languages (like BASIC), the end of a statement is signaled by the end of the line,
but that‘s not true in C++. If you leave out the semicolon, the compiler will often signal an error.

Loops and Decisions


Loops
Loops cause a section of your program to be repeated a certain number of times. The repetition
continues while a condition is true. When the condition becomes false, the loop ends and control
passes to the statements following the loop.

There are three kinds of loops in C++: the for loop, the while loop, and the do loop.

The for Loop


The for loop executes a section of code a fixed number of times.
The for statement controls the loop. It consists of the keyword for, followed by parentheses that
contain three expressions separated by semicolons:

2
These three expressions are the initialization expression, the test expression, and the increment
expression, as shown in Figure 1.1.

FIGURE 1.1 Syntax of the for loop.

Here‘s an example that displays the squares of the numbers from 0 to 14:

#include<iostream>
#include<conio.h>
using namespace std;
int main( )
{
int j; //define a loop variable
for(j=0; j<15; j++) //loop from 0 to 14,
cout << j * j << " "; //displaying the square of j
cout << endl;
getch();
return 0;
}

Here‘s the output:


0 1 4 9 16 25 36 49 64 81 100 121 144 169 196

3
Let‘s see how the three expressions in the for statement control the loop.

The Initialization Expression


The initialization expression is executed only once, when the loop first starts. It gives the loop
variable an initial value. In this example it sets j to 0.

The Test Expression


The test expression usually involves a relational operator. It is evaluated each time through the
loop, just before the body of the loop is executed. It determines whether the loop will be
executed again. If the test expression is true, the loop is executed one more time. If it‘s false, the
loop ends, and control passes to the statements following the loop.

The Increment Expression


The increment expression changes the value of the loop variable, often by incrementing it. It is
always executed at the end of the loop, after the loop body has been executed. Here the
increment operator ++ adds 1 to j each time through the loop. Figure 1.2 shows a flowchart of a
for loop‘s operation.

FIGURE 1.2 Operation of the for loop.

4
Multiple Statements in the Loop Body
Of course you may want to execute more than one statement in the loop body. Multiple
statements are delimited by braces, just as functions are. Note that there is no semicolon
following the final brace of the loop body, although there are semicolons following the
individual statements in the loop body.

The next example uses three statements in the loop body. It prints out the cubes of the numbers
from 1 to 10, using a two-column format.

#include<iostream>
#include<iomanip> //for setw
#include<conio.h> //for getch
using namespace std;
int main( )
{
int numb; //define loop variable
for(numb=1; numb<=10; numb++) //loop from 1 to 10
{
cout << setw(4) << numb; //display 1st column
int cube = numb*numb*numb; //calculate cube
cout << setw(6) << cube << endl; //display 2nd column
}
getch();
return 0;
}

Here‘s the output from the program:

1 1
2 8
3 27
4 64
5 125
6 216
7 343
8 512
9 729
10 1000

5
The while Loop
The while loop looks like a simplified version of the for loop. It contains a test expression but no
initialization or increment expressions. Figure 1.3 shows the syntax of the while loop.

FIGURE 1.3 Syntax of the while loop.

The do Loop
In a while loop, the test expression is evaluated at the beginning of the loop. If the test expression
is false when the loop is entered, the loop body won‘t be executed at all. In some situations this
is what you want. But sometimes you want to guarantee that the loop body is executed at least
once, no matter what the initial state of the test expression. When this is the case you should use
the do loop, which places the test expression at the end of the loop.

#include<iostream>
using namespace std;
int main( )
{
long dividend, divisor;
char ch;

6
do //start of do loop
{ //do some processing
cout << "Enter dividend: "; cin >> dividend;
cout << "Enter divisor: "; cin >> divisor;
cout << "Quotient is " << dividend / divisor;
cout << ", remainder is "<< dividend % divisor;
cout << "\nDo another? (y/n): "; //do it again?
cin >> ch;
}
while( ch != 'n' ); //loop condition
return 0;
}

The do...while repetition statement is similar to the while statement. In the while, the program
tests the loop-continuation condition at the beginning of the loop, before executing the loop's
body. If the condition is false, the body never executes. The do...while statement tests the loop-
continuation condition after executing the loop's body; therefore, the body always executes at
least once.

The syntax of the do loop is shown in Figure 1.4.

FIGURE 1.4 Syntax of the do loop.

7
Question
Write a program that displays multiplication table?
#include<iostream>
#include<iomanip>
#include<conio.h>
using namespace std;
int main(){
int i, j;
cout<<setw(4)<<"X";
for ( i=1;i<=12;i++)
cout<<setw(4)<<i; //display the column number
cout<<endl<<endl;

for (i=1;i<=12;i++){
cout<<setw(4)<<i; //display the row number
for ( j=1;j<=12;j++)
cout<<setw(4)<<i*j; //display the product of row and column
cout<<endl;
}
getch();
return 0;
}

Decisions
Programs also need to make these one-time decisions. In a program a decision causes a onetime
jump to a different part of the program, depending on the value of an expression.

Decisions can be made in C++ in several ways. The most important is with the if...else statement,
which chooses between two alternatives. This statement can be used without the else, as a simple
if statement.

The if Statement
The if single-selection statement performs an indicated action only when the condition is true;
otherwise, the action is skipped. The if...else double-selection statement allows the programmer
to specify an action to perform when the condition is true and a different action when the
condition is false. For example, the pseudocode statement

8
if student's grade is greater than or equal to 50
print "Passed"
else
print "Failed"

prints "Passed" if the student's grade is greater than or equal to 50, but prints "Failed" if it is less
than 50.

The preceding if...else pseudocode statement can be written in C++ as


if ( grade >= 50 )
cout<< "Passed" ;
else
cout<< "Failed" ;

The if statement is the simplest of the decision statements. Our next program provides an
example if statement.

#include<iostream>
#include<conio.h>
using namespace std;
int main( )
{
int x;
cout << "Enter a number: ";
cin >> x;
if( x > 100 )
cout << "That number is greater than 100\n";
getch();
return 0;
}

The if keyword is followed by a test expression in parentheses. The syntax of the if statement is
shown in Figure 1.5. As you can see, the syntax of if is very much like that of while. The
difference is that the statements following the if are executed only once if the test expression is
true; the statements following while are executed repeatedly until the test expression becomes
false. Figure 1.6 shows the operation of the if statement.

9
Here‘s an example of the program‘s output when the number entered by the user is greater than
100:
Enter a number: 2000
That number is greater than 100

If the number entered is not greater than 100, the program will terminate without printing the
second line.

FIGURE 1.5 Syntax of the if statement

FIGURE 1.6 Operation of the if statement

10
Questions
Output
1. What is the output of the following program?
#include<iostream>
#include<conio.h>
using namespace std;
int main(){
char ch1=42, ch2=65, ch3=97;
int x1=ch1, x2=ch2, x3=ch3;
cout<<endl<<x1<<"\t"<<ch1;
cout<<endl<<x2<<"\t"<<ch2;
cout<<endl<<x3<<"\t"<<ch3;
getch();
return 0;
}

2. Write a program that accepts an integer number from the keyboard and displays asterisk in
triangle form. If the user accepts 5 from keyboard, it displays in the following form.

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

#include<iostream>
#include<conio.h>
using namespace std;
int main(){
int num;
cout<<"\nEnter a number \nC:\\>";
cin>>num;
for (int i=1;i<=num;i++){
for (int j=1;j<=i;j++)
cout<<'*';
cout<<endl;
}
getch();
return 0;
}

11
3. Write a program that accepts an integer number from the keyboard and computes n factorial?
#include<iostream>
#include<conio.h>
using namespace std;
int main(){
int num;
cout<<"\nEnter a number \nC:\\>";
cin>>num;
long fact=1;
for (int i=1;i<=num;i++)
fact=fact * i;
cout<<endl<<num<<"!="<<fact;
getch();
return 0;
}

4. Write a program that accepts an integer number from the keyboard and displays the sum of
odd digit of the number.
n Result Reason
1000 1 Only 1 is odd digit in the number
2222 0 There is no odd digit in the number
2357 15 3+5+7=15
133251 13 1+3+3+5+1=13

#include<iostream>
#include<conio.h>
using namespace std;
int main(){
int num;
cout<<"\nEnter a number \nC:\\>";
cin>>num;
int n=num;
int sum=0;
while (n>0){
int temp=n%10;
if (temp%2==1)
sum=sum+temp;
n=n/10;
}

12
cout<<endl<<" The sum of odd digit in "<<num<<" is "<<sum;
getch();
return 0;
}

5. Write a program that accepts an integer number from the keyboard and prints out the powers
of 2 up to including 2 ^ n, one per line, in exactly in the following format.
2^0=1
2^1=2
2^2=4
2^3=8
2 ^ 4 = 16

#include<iostream>
#include<conio.h>
using namespace std;
int main(){
int num;
cout<<"\nEnter a number \nC:\\>";
cin>>num;
for (int i=0;i<=num;i++){
long x=1;
for (int j=1;j<=i;j++)
x=x*2;
cout<<endl<<"2^"<<i<<"="<<x;
}
getch();
return 0;
}

Exercises
1. Write a program that takes one real value as input and computes the first integer n such that 2n
is greater than or equal to the input value. The program should output both n and 2n.

2. Write a program that accepts an integer number from the keyboard and displays the result of
the following expression
0! + 1! + 2! + 3! + … + (n-1)! + n!

13
3. Write a program that displays ASCII numbers from 1 up to 127 and their respective characters
.
.
.

35 #
.
.
.
65 A
.
.
.

97 a
.
.
.

4. Write a program that displays the following triangle of characters on the screen
A
AB
ABC
ABCD
.
.
.
ABCDEFGHIJKLMNOPQRSTUVWX
ABCDEFGHIJKLMNOPQRSTUVWXY
ABCDEFGHIJKLMNOPQRSTUVWXYZ
5. Write a program that accepts an integer number from the keyboard and displays the sum of
digits of the number. For example, if the number is 3425, then the output is 14 because 3 + 4 + 2
+ 5 = 14

6. Write a program that accepts an integer number from the keyboard and displays the sum of
prime digits of the number. For example, if the number is 34259, then the output is 10 because
3 + 2 + 5 = 10

7. Write a program that accepts a positive integer number N and displays the sum of all integers
that are multiple of 3 and less than or equal to N. For example, if N=20 our program must
display 63 which is 3+6+9+12+15+18.
If N=3 or 4 or 5, our program must display 3
If N=1 or 2, our program must display 0

14
8. Many people in Ethiopia live in the rural areas within huts. They can construct a hut with
simple rules, if they know the height of a wall. They can easily construct it with the following
procedure: the height of a wall, height of a roof and width of a wall has the same length and the
distance from the edge of a roof to the wall is equal to (height of a wall -1) / 2

Write a program that accepts height of a hut and displays a hut with the above procedure. If you
enter height of a hut an even number the following message ―Please enter an odd number for
height of a hut‖ displays until you enter an odd number
Hint
Enter height of a hut: 4
Please enter an odd number for height of a hut: 10
Please enter an odd number for height of a hut: 8
Please enter an odd number for height of a hut: 5


A
*
***
*****
*******
*********
*****
*****
*****
*****
*****

Note: The height of a hut should be greater than or equal to three

9. A digital river is a sequence of numbers where the number following n is n plus the sum of
its digits. For example, 12345 is followed by 12360, since 1+2+3+4+5=15. If the first number of
a digital river K we will call it river K.

For example, river 480 is the sequence beginning {480, 492, 507, 519 …} and river 483 is the
sequence beginning {483, 498, 519 …}

15
Normal streams and rivers can meet and the same is true for digital rivers. This happens when
two digital rivers share some of the same values. For example: river 480 meets river 483 at 519,
meets river 507at 507 and never meets river 481.

Every digital river will eventually meet river1, river3 or river9. Write a program which inputs a
single integer n( 1<= n<=16384 ) and outputs the value where river n first meets one of these
three rivers.

Sample run
River: 86
First meet river 1 at 101

10. Ancient Egyptians constructed a pyramid with the following rule. They put a brick. In order
to increase the height of the pyramid they put two bricks at left and right boundary of beneath it
and in order to stand it properly, the middle brick(s) weight of the pyramid must be equal to the
sum of two consecutive bricks weight of the pyramid above it. Write a program that displays a
twenty height of pyramid.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1

Assume takes the third row (1 2 1) the next row is

1 + 2 + 1

1 3 3 1

16
11. Ethiopia has its own character (fidel) and calendar system and make it differs to rest of the
world. The calendar of Ethiopia contains thirteen months and each month holds thirty days
except pagumie. Write a program that accepts day of the year starts from the keyboard and
displays calendar of each month.

Sample
Please enter the day of the year starts
Wednesday

The output is

September
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

October
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30

It also displays to the rest of months including pagumie.

17
Chapter Two: Array
In everyday life we commonly group similar objects into units. We buy peas by the can and eggs
by the carton. In computer languages we also need to group together data items of the same type.
The most basic mechanism that accomplishes this in C++ is the array. Arrays can hold a few
data items or tens of thousands. The data items grouped in an array can be simple types such as
int or float, or they can be user-defined types such as structures and objects

Arrays are grouping a number of items into a larger unit. An array groups items of the same type.
More importantly, the items in an array are accessed by an index number. Using an index
number to specify an item allows easy access to a large number of items.

Array Fundamentals
A simple example program will serve to introduce arrays. This program creates an array of four
integers representing the ages of four people. It then asks the user to enter four values, which it
places in the array. Finally, it displays all four values.

#include<iostream>
#include<conio.h>
using namespace std;
int main( )
{
int age[4],j; //array ‗age‘ of 4 ints
for(j=0; j<4; j++) //get 4 ages
{
cout << "Enter an age: ";
cin >> age[j]; //access array element
}
for(j=0; j<4; j++) //display 4 ages
cout << "You entered " << age[j] << endl;
getch();
return 0;
}

Here‘s a sample interaction with the program:


Enter an age: 44
Enter an age: 16
Enter an age: 23
Enter an age: 68
18
You entered 44
You entered 16
You entered 23
You entered 68

The first for loop gets the ages from the user and places them in the array, while the second reads
them from the array and displays them.

An array is a group of variables (called elements or components) containing values that all have
the same type. Recall that types are divided into two categories primitive types and reference
types. The elements of an array can be either primitive types or reference types. To refer to a
particular element in an array, we specify the name of the reference to the array and the position
number of the element in the array. The position number of the element is called the element's
index or subscript.

Defining Arrays
An array must be defined before it can be used to store information. An array definition specifies
a variable type and a name. But it includes another feature: a size. The size specifies how many
data items the array will contain. It immediately follows the name, and is surrounded by square
brackets. Figure 2.1 shows the syntax of an array definition.

FIGURE 2.1 Syntax of array definition.

Array Elements
The items in an array are called elements. As we noted, all the elements in an array are of the
same type; only the values vary. Figure 2.2 shows the elements of the array age.

19
FIGURE 2.2 Array elements.

Accessing Array Elements


In the above example we access each array element twice. The first time, we insert a value into
the array, with the line
cin >> age[j];
The second time, we read it out with the line
cout << "\nYou entered " << age[j];
In both cases the expression for the array element is
age[j]
This consists of the name of the array, followed by brackets delimiting a variable j. Which of the
four array elements is specified by this expression depends on the value of j; age[0] refers to the
first element, age[1] to the second, age[2] to the third, and age[3] to the fourth. The variable (or
constant) in the brackets is called the array index.

Since j is the loop variable in both for loops, it starts at 0 and is incremented until it reaches 3,
thereby accessing each of the array elements in turn.

20
Initializing Arrays
You can give values to each array element when the array is first defined. Here‘s an example that
sets 12 array elements in the array days_per_month to the number of days in each month.

#include<iostream>
#include<conio.h>
using namespace std;
int main( )
{
int month, day, total_days;
int days_per_month[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
cout << "\nEnter month (1 to 12): "; //get date
cin >> month;
cout << "Enter day (1 to 31): ";
cin >> day;
total_days = day; //separate days
for(int j=0; j<month-1; j++) //add days each month
total_days += days_per_month[j];
cout << "Total days from start of year is: " << total_days<< endl;
getch();
return 0;
}

The program calculates the number of days from the beginning of the year to a date specified by
the user. (Beware: It doesn‘t work for leap years.) Here‘s some sample interaction:
Enter month (1 to 12): 3
Enter day (1 to 31): 11
Total days from start of year is: 70

Once it gets the month and day values, the program first assigns the day value to the total_days
variable. Then it cycles through a loop, where it adds values from the days_per_month array to
total_days. The number of such values to add is one less than the number of months. For
instance, if the user enters month 5, the values of the first four array elements (31, 28, 31, and
30) are added to the total.The values to which days_per_month is initialized are surrounded by
braces and separated by commas. They are connected to the array expression by an equal sign.
Figure 2.3 shows the syntax.

21
FIGURE 2.3 Syntax of array initialization.

Actually, we don‘t need to use the array size when we initialize all the array elements, since the
compiler can figure it out by counting the initializing variables. Thus we can write
int days_per_month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

What happens if you do use an explicit array size, but it doesn‘t agree with the number of
initializers? If there are too few initializers, the missing elements will be set to 0. If there are too
many, an error is signaled.

Multidimensional Arrays
So far we‘ve looked at arrays of one dimension: A single variable specifies each array element.
But arrays can have higher dimensions.

Defining Multidimensional Arrays


The array is defined with two size specifiers, each enclosed in brackets:
double sales[DISTRICTS][MONTHS];
You can think about sales as a two-dimensional array, laid out like a checkerboard. Another way
to think about it is that sales is an array of arrays. It is an array of DISTRICTS elements, each of
which is an array of MONTHS elements. Figure 2.4 shows how this looks.

Of course there can be arrays of more than two dimensions. A three-dimensional array is an
array of arrays of arrays. It is accessed with three indexes:
elem = dimen3[x][y][z];
This is entirely analogous to one- and two-dimensional arrays.

22
FIGURE 2.4 Two-dimensional array.

Accessing Multidimensional Array Elements


Array elements in two-dimensional arrays require two indexes:
sales[d][m]
Notice that each index has its own set of brackets. Commas are not used. Don‘t write sales[d,m];
this works in some languages, but not in C++.

Strings
Strings are arrays of type char.

Here‘s an example that defines a single string variable. It asks the user to enter a string, and
places this string in the string variable. Then it displays the string

23
#include<iostream>
#include<conio.h>
using namespace std;
int main( )
{
const int MAX = 80; //max characters in string
char str[MAX]; //string variable str
cout << "Enter a string: ";
cin >> str; //put string in str
//display string from str
cout << "You entered: " << str << endl;
getch();
return 0;
}

The definition of the string variable str looks like (and is) the definition of an array of type char:
char str[MAX];
We use the extraction operator >> to read a string from the keyboard and place it in the string
variable str. This operator knows how to deal with strings; it understands that they are arrays of
characters.

Questions
1. Write a program that displays the size of the array?
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int a[]={1,2,3,4,5,6};
int size;
size=sizeof a/sizeof(int); //total size of array/size of array data type
cout<<size;
getch();
return 0;
}

2. Write a program that accepts an integer number(s) from the key board and displays the sum of
the number(s) in the following format?

24
The number of integer(s) that The number(s) that you Output
you want to accept (size) accept
1 20 20=20
2 10 34 10+34=44
3 2 3 4 2+3+4=9
5 2 3 4 5 7 2+3+4+5+7=21
6 1 1 1 2 2 2 1+1+1+2+2+2=9

#include<iostream>
#include<conio.h>
using namespace std;
int main(){
int number[50],num,i,sum=0;
cout<<"\nHow many number do you want to accept \nC:\\>";
cin>>num;
for (i=0;i<num;i++){
cout<<"\nEnter a number \nC:\\>";
cin>>number[i];
}
cout<<endl;
for (i=0;i<num;i++){
if (i+1==num)
cout<<number[i]<<"=";
else
cout<<number[i]<<"+";
sum=sum+number[i];
}
cout<<sum;
getch();
return 0;
}

3. Write a program that accepts string from the keyboard and displays in the reverse order?

String, that you accept is Output


COC COC
book koob
abc cba
red der
WU UW

25
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int main(){
char str[50];
int i,size;
cout<<"\nEnter the string \nC:\\>";
cin>>str;
size=strlen(str);
cout<<endl;
for (i=size-1;i>=0;i--)
cout<<str[i];
getch();
return 0;
}

4. Consider the following 5 x 5 matrix


10 12 14 16 18
11 20 12 24 26
13 15 30 12 18
17 19 21 20 18
11 13 15 17 10

Write a program that sums diagonal of the matrix. The output is 90 because
10+20+30+20+10=90

#include<iostream>
#include<iomanip>
#include<conio.h>
using namespace std;
int main(){
int num[5][5]={{10,12,14,16,18},{11,20,12,24,26},{13,15,30,12,18},
{17,19,21,20,18},{11,13,15,17,10}};

int i,j,sum=0;
for(i=0;i<5;i++)
for(j=0;j<5;j++)
if(i==j)
sum=sum+num[i][j];

26
for(i=0; i<5;i++){
for(j=0;j<5;j++)
cout<<setw(4)<<num[i][j];
cout<<endl;
}

cout<<endl<<"The sum of diagonal of the matrix is "<<endl;


for(i=0; i<5;i++)
for(j=0;j<5;j++){
if(i==j){
if(i+1==5 && j+1==5)
cout<<num[i][j]<<"=";
else
cout<<num[i][j]<<"+";
}
}
cout<<sum;
getch();
return 0;
}

5. Write a program that accepts string from the keyboard and displays in the first line only the
first character, in the second line the first two characters and so on until the last line the whole
string? Assume the string you are accepted is banana and it displays in the following form?

b
ba
ban
bana
banan
banana

#include<iostream>
#include<string.h>
#include<conio.h>
using namespace std;
int main(){
char str[50];
int i,j,size;

27
cout<<"\nEnter the string\nC:\\>";
cin>>str;
size=strlen(str);

for(i=0;i<size;i++){
for(j=0;j<=i;j++)
cout<<str[j];
cout<<endl;
}
getch();
return 0;
}

6. Write a program that allows the user to input a number of integers, and displays the maximum
number and the minimum number from them?

#include<iostream>
#include<conio.h>
using namespace std;
int main(){
int number[50];
int i,num,min,max;
cout<<"\nHow many number do you want to accept\nC:\\>";
cin>>num;
for(i=0; i<num;i++){
cout<<"\nEnter a number\nC:\\>";
cin>>number[i];
}
min=number[0];
max=number[0];

for(i=1;i<num;i++){
if(number[i]<min)
min=number[i];
if(number[i]>max)
max=number[i];
}
cout<<endl;
for(i=0;i<num;i++)
cout<<number[i]<<"\t";
cout<<endl;

28
cout<<"\n The maximum number is "<<max;
cout<<"\n The maximum number is "<<min;
getch();
return 0;
}

Exercises
1. Write a program that accepts sequence of characters (string) from the keyboard and displays
the frequency distribution of character in the given string. For example, if the string is banana,
then the output looks like
Character Frequency
b 1
a 3
n 2

2. Some computer programs try to prevent easily guessable passwords being used, by rejecting
those that do not meet some simple rules. One simple rule is to reject passwords which contain
any sequence of letters immediately followed by the same sequence. For example
APPLE Rejected (P is repeated)
CUCUMBER Rejected (CU is repeated)
ONION Accepted (ON is not immediately repeated)
APRICOT Accepted
Write a program that inputs a password (between 1 and 10 upper case letters) and then prints
Rejected if the password is rejected, or Accepted otherwise.

3. Consider the following 5 x 5 matrix

10 12 14 16 18
11 20 12 24 26
13 15 30 12 18
17 19 21 20 18
11 13 15 17 10
A.) Write a program that sums elements above the diagonal of the matrix. The output is 170
because 12+14+16+18+12+24+26+12+18+18=170

29
B.) Write a program that sums elements below the diagonal of the matrix. The output is 152
because 11+13+15+17+19+21+11+13+15+17=152

C.) Write a program that sums rows and columns of the matrix. The output is
10 12 14 16 18 70
11 20 12 24 26 93
13 15 30 12 18 88
17 19 21 20 18 95
11 13 15 17 10 66
62 79 92 89 90

D.) Write a program that checks whether element of the matrix is prime or not. If the element
of the matrix is prime it displays P otherwise it displays N. The output is
N N N N N
P N N N N
P N N N N
P P N N N
P P N P N

E.) Write a program that sums even element of the matrix

F.) Write a program that sums odd elements of the matrix

G.) Write a program that swaps elements which is found below the diagonal of the matrix
with upper once. The output is
10 11 13 17 11
12 20 15 19 13
14 12 30 21 15
16 24 12 20 17
18 26 18 18 10

4. Write a program that accepts word from keyboard and checks whether the word palindrome or
not. A palindrome is a word or phrase that reads the same backward as forward

Word Result
COC Palindrome
1221 Palindrome
12341 Not Palindrome
apple Not palindrome
noon Palindrome

30
5. Write a program that shifts the array element‘s value one position to the left for an array of
integers, A. During shifting, A[i] is assigned the original value of the ith+1 element except for the
(N-1)th element, the new value becomes the original value of index 0
Array Shift Array
{2} {2}
{1,2} {2,1}
{1,3,4,5,6,7} {3,4,5,6,7,1}
{12,3,56,23,11,45} {3,56,23,11,45,12}

6. Write a program that computes mean, standard deviation and variance of n numbers. The
mean is defined as the value found by adding together all numbers and dividing the sum by total
number. The standard deviation is defined to be the square root of the average of those number
values (xi - a) 2, where a is the mean or average of those numbers. The variance defined as the
extent to which something varies or differs from something else and mathematically equal to the
square of standard deviation.

Mean
a = x1 + x2 + x3 + . . . + xn
n
Standard Deviation
𝑛 2
𝑖=1(𝑥 𝑖 −𝑎)
s=
𝑛

Variance
𝑛 2
𝑖=1 (𝑥 𝑖 −𝑎)
v=
𝑛

Your program should accept input in the following format

How many numbers do you want to accept?


C:\> 5
Enter the number
C:\> 2
Enter the number
C:\> 3
Enter the number
C:\> 2

31
Enter the number
C:\> 4
Enter the number
C:\> 5

The output is
Mean = 3.2
Standard Deviation = 1.16619
Variance = 1.36

7. (Dice Rolling) Write a program to simulate the rolling of two dice. The program should
generate a random number once to roll the first die and again to roll the second die. The sum of
the two values should then be calculated. Each die can show an integer value from 1 to 6, so the
sum of the values will vary from 2 to 12, with 7 being the most frequent sum and 2 and 12 being
the least frequent sums. Figure 2.5 shows the 36 possible combinations of the two dice. Your
program should roll the dice 36,000 times. Use a one-dimensional array to tally the number of
times each possible sum appears. Display the results in tabular format. Determine whether the
totals are reasonable (e.g., there are six ways to roll a 7, so approximately one-sixth of the rolls
should be 7).

Figure 2.5 The 36 possible sums of two dice.

8. (Duplicate Elimination) Use a one-dimensional array to solve the following problem: Write a
program that inputs five numbers, each of which is between 10 and 100, inclusive. As each
number is read, display it only if it is not a duplicate of a number already read. Provide for the

32
"worst case," in which all five numbers are different. Use the smallest possible array to solve this
problem. Display the complete set of unique values input after the user inputs each new value.

33
Chapter Three: Function
Function
A function groups a number of program statements into a unit and gives it a name. This unit can
then be invoked from other parts of the program.

The most important reason to use functions is to aid in the conceptual organization of a program.
Dividing a program into functions is one of the major principles of structured programming.

Another reason to use functions is to reduce program size. Any sequence of instructions that
appears in a program more than once is a candidate for being made into a function. The
function‘s code is stored in only one place in memory, even though the function is executed
many times in the course of the program. Figure 3.1 shows how a function is invoked from
different sections of a program.

FIGURE 3.1 Flow of control to a function.

Simple Functions
This example demonstrates a simple function whose purpose is to print a line of 45 asterisks. The
program generates a table, and lines of asterisks are used to make the table more readable.

34
#include<iostream>
#include<conio.h>
using namespace std;
void starline( ); //function declaration
int main( )
{
starline( ); //call to function
cout << "Data type Range" << endl;
starline( ); //call to function
cout << "char -128 to 127" << endl
<< "short -32,768 to 32,767" << endl
<< "int System dependent" << endl
<< "long -2,147,483,648 to 2,147,483,647" << endl;
starline( );
getch(); //call to function
return 0;
}

// starline( )
// function definition
void starline( ) //function declarator
{
for(int j=0; j<45; j++) //function body
cout << '*';
cout << endl;
}

The output from the program looks like this:

*********************************************
Data type Range
*********************************************
char -128 to 127
short -32,768 to 32,767
int System dependent
long -2,147,483,648 to 2,147,483,647
*********************************************

The program consists of two functions: main( ) and starline( ). You‘ve already seen many
programs that use main( ) alone. What other components are necessary to add a function to the
program? There are three: the function declaration, the calls to the function, and the function
definition.

35
The Function Declaration
Just as you can‘t use a variable without first telling the compiler what it is, you also can‘t use a
function without telling the compiler about it. There are two ways to do this. The approach we
show here is to declare the function before it is called. (The other approach is to define it before
it‘s called.) In the above program, the function starline( ) is declared in the line
void starline( );
The declaration tells the compiler that at some later point we plan to present a function called
starline. The keyword void specifies that the function has no return value, and the empty
parentheses indicate that it takes no arguments.

Notice that the function declaration is terminated with a semicolon. It is a complete statement in
itself.

Function declarations are also called prototypes, since they provide a model or blueprint for the
function. They tell the compiler, ―a function that looks like this is coming up later in the
program, so it‘s all right if you see references to it before you see the function itself.‖ The
information in the declaration (the return type and the number and types of any arguments) is
also sometimes referred to as the function signature.

Calling the Function


The function is called (or invoked, or executed) three times from main(). Each of the three calls
looks like this:
starline( );
This is all we need to call the function: the function name, followed by parentheses. The syntax
of the call is very similar to that of the declaration, except that the return type is not used. The
call is terminated by a semicolon. Executing the call statement causes the function to execute;
that is, control is transferred to the function, the statements in the function definition are
executed, and then control returns to the statement following the function call.

The Function Definition


Finally we come to the function itself, which is referred to as the function definition. The
definition contains the actual code for the function. Here‘s the definition for starline( ):

36
void starline( ) //declarator
{
for(int j=0; j<45; j++) //function body
cout << '*';
cout << endl;
}

The definition consists of a line called the declarator, followed by the function body. The
function body is composed of the statements that make up the function, delimited by braces.

The declarator must agree with the declaration: It must use the same function name, have the
same argument types in the same order (if there are arguments), and have the same return type.

Notice that the declarator is not terminated by a semicolon. Figure 3.2 shows the syntax of the
function declaration, function call, and function definition.

FIGURE 3.2 Function syntax.

37
When the function is called, control is transferred to the first statement in the function body. The
other statements in the function body are then executed, and when the closing brace is
encountered, control returns to the calling program.

Recursion
The existence of functions makes possible a programming technique called recursion. Recursion
involves a function calling itself. This sounds rather improbable, and indeed a function calling
itself is often a bug. However, when used correctly this technique can be surprisingly powerful.

Our new program uses recursion instead of a loop.


#include<iostream>
#include<conio.h>
using namespace std;
unsigned long factfunc(unsigned long); //declaration
int main( )
{
int n; //number entered by user
unsigned long fact; //factorial
cout << "Enter an integer: ";
cin >> n;
fact = factfunc(n);
cout << "Factorial of " << n << " is " << fact << endl;
getch();
return 0;
}

// factfunc()
// calls itself to calculate factorials
unsigned long factfunc(unsigned long n)
{
if(n > 1)
return n * factfunc(n-1); //self call
else
return 1;
}

Recursive problem-solving approaches have a number of elements in common. When a recursive


function is called to solve a problem, the function actually is capable of solving only the simplest

38
case(s), or base case(s). If the function is called with a base case, the function returns a result. If
the function is called with a more complex problem, the function typically divides the problem
into two conceptual pieces.

Consider the following function


5 𝑛=1
T(n)=
2𝑇 𝑛 − 1 + 2 𝑛 > 1
T(4) = 2T(3) + 2
= 2[ 2T(2) + 2 ]+2
= 4T(2) + 6
= 4[2T(1)+2]+6
= 8T(1)+8+6
= 8*5+14 T(1) = 5
= 54

Implement the above recursive function

#include<iostream>
#include<conio.h>
using namespace std;
int T(int n){
if ( n>1 )
return 2*T(n-1)+2;
else
return 5;
}

int main(){
int num;
cout<<endl<<"Enter a number \nC:\\>";
cin>>num;
// calls itself of T(n)
int x=T(num);
cout<<endl<<x;
getch();
return 0;
}

39
What is the output of the following program?
#include<iostream>
#include<conio.h>
using namespace std;
void T(int n){
if ( n>0 ){
T(n-1);
cout<<endl<<n;
T(n-2);
}
}
int main(){
int num;
cout<<endl<<"Enter a number \nC:\\>";
cin>>num;
T(num);
getch();
return 0;
}

Here’s a sample interaction with the program T(1)


Enter a number cout<<endl<<2;
C:\> 4 T(2)
T(0)
T(3) cout<<endl<<3;
cout<<endl<<3;
T(4) cout<<endl<<4; T(1)
T(1)
T(2) cout<<endl<<4;
cout<<endl<<4;
T(2)
T(2)
A
B C

T(0) cout<<endl<<1; cout<<endl<<1; cout<<endl<<1;


cout<<endl<<1; cout<<endl<<2; cout<<endl<<2; cout<<endl<<2;
T(-1) cout<<endl<<3; cout<<endl<<3; cout<<endl<<3;
cout<<endl<<2; T(1) T(0) cout<<endl<<1;
T(0) cout<<endl<<4; cout<<endl<<1; cout<<endl<<4;
cout<<endl<<3; T(2) T(-1) T(2)
T(1) cout<<endl<<4;
cout<<endl<<4; T(2)
T(2)

D E F G

40
cout<<endl<<1; cout<<endl<<1;
cout<<endl<<1;
cout<<endl<<2; cout<<endl<<2;
cout<<endl<<2;
cout<<endl<<3; cout<<endl<<3;
cout<<endl<<3;
cout<<endl<<1; cout<<endl<<1;
cout<<endl<<1;
cout<<endl<<4; cout<<endl<<4;
cout<<endl<<4;
T(0) cout<<endl<<1;
T(1)
cout<<endl<<1; cout<<endl<<2;
cout<<endl<<2;
T(0) T(-1)
cout<<endl<<2;
T(0)
H J
I

Note: - A, B, C, D, E, F, G, H, I, and J are sequences that show how the recursive


function works

The output of the above program is


1
2
3
1
4
1
2

Exercise
Implement the following recursive function
2 𝑛=1
A.) T(n) =
2𝑇 𝑛 − 1 𝑛>1

3 𝑛=1
B.) T(n) =
𝑇 𝑛 − 1 + 3𝑛 𝑛>1

1 𝑛=1
C.) T(n)=
2𝑇 𝑛 − 1 − 2 𝑛 > 1

3 𝑛=1
D.) T(n)=
4𝑇 𝑛 − 1 + 𝑛 + 20 𝑛 > 1

41
A.) What is the output of the following program?
Output
#include<iostream>
#include<conio.h>
using namespace std;
void T(int n){
if ( n>0 ){
T(n-1);
T(n-2);
cout<<endl<<n;
}
}
int main(){
T(4);
getch();
return 0;
}

Output
B.) What is the output of the following program?

#include<iostream>
#include<conio.h>
using namespace std;
void T(int n){
if ( n>0 ){
cout<<endl<<n;
T(n-1);
T(n-2);
}
}
int main(){
T(4);
getch();
return 0;
}

42
Output
C.) What is the output of the following program?
#include<iostream>
#include<conio.h>
using namespace std;
void T(int n){
if ( n>0 ){
T(n-2);
cout<<endl<<n;
T(n-1);
}
}
int main(){
T(4);
getch();
return 0;
}

Output
D.) What is the output of the following program?
#include<iostream>
#include<conio.h>
using namespace std;
void T(int n){
if ( n>0 ){
T(n-1);
cout<<endl<<n;
T(n-1);
}
}
int main(){
T(4);
getch();
return 0;
}

43
Questions
1. A sequence of numbers is said to be order balanced if the first number in the sequence must be an even
number and the next number in the sequence must be odd number and alternatively until the end of the
sequence. Write a function that returns 1 if the sequence is order balanced otherwise it returns 0.
Sample
Sequence Return
{2,3,6,7} 1
{2,1} 1
{2,3,1,4} 0
{3,3} 0
{} 1
{2,5,2} 1

#include<iostream>
#include<conio.h>
using namespace std;
int isBalanced(int a[], int size){
int x=1;
for(int i=0;i<size;i++){
if(i%2==0){
if(a[i]%2==1)
x=0;
} else{
if(a[i]%2==0)
x=0;
}
}

return x;
}

int main(){
int x1[]={2,3,6,7};
int x2[]={2,1};
int x3[]={2,3,1,4};
int x4[]={3,3};
int x5[]={};
int x6[]={2,5,2};

44
cout<<endl<<(isBalanced(x1,sizeof x1/sizeof(int)));
cout<<endl<<(isBalanced(x2,sizeof x2/sizeof(int)));
cout<<endl<<(isBalanced(x3,sizeof x3/sizeof(int)));
cout<<endl<<(isBalanced(x4,sizeof x4/sizeof(int)));
cout<<endl<<(isBalanced(x5,sizeof x5/sizeof(int)));
cout<<endl<<(isBalanced(x6,sizeof x6/sizeof(int)));

getch();
return 0;
}

2. An integer number is said to be a perfect number if its factors, including 1 (but not the number
itself), sum to the number. For example, 6 is a perfect number, because 6 = 1 + 2 + 3. Write a
function perfect that determines whether parameter number is a perfect number. Use this
function in a program that determines and displays all the perfect numbers between 1 and 1000.
Display the factors of each perfect number to confirm that the number is indeed perfect.

#include<iostream>
#include<conio.h>
using namespace std;
bool perfect(int n){
int sum=0;
for(int i=1;i<n;i++)
if(n%i==0)
sum=sum+i; //the sum of the factors of the number
if(sum==n)
return true; //return true if number is perfect
else
return false; //return false if number is not perfect
}

int main(){

for (int x=1;x<=1000;x++)


if (perfect(x)){
cout<<endl<<x<<" is the perfect number and its factors are ";

45
for(int i=1;i<x;i++)
if(x%i==0)
cout<<i<<" "; //displays the factors of the perfect number
cout<<endl;
}
getch();
return 0;
}

3. A number is said to be normal if the number has not an odd factor other than 1. Write a function that
returns 1 if the number is normal otherwise it returns 0.

Sample
n Return Factor n Reason
2 1 1,2 It has not odd factor other than 1
6 0 1,2,3,6 It has odd factor other than 1
10 0 1,2,5,10 It has odd factor other than 1
16 1 1,2,4,8,16 It has not odd factor other than 1

#include<iostream>
#include<conio.h>
using namespace std;
int normal(int n){
int x=1;
for(int i=2;i<n;i++)
if(n%i==0)
if(i%2==1)
x=0;
return x;
}

int main(){
cout<<normal(2)<<endl;
cout<<normal(6)<<endl;
cout<<normal(10)<<endl;
cout<<normal(16)<<endl;
getch();
return 0;
}

46
Exercises
1. A sequence of numbers is said to cumulative if the next number in the sequence is equal to
the sum of the previous number(s). Write a function that returns 1 if the sequence is cumulative
otherwise it returns 0.
Sample
Sequence Return
{2,2} 1
{2,3} 0
{1,1,2,4,8} 1
{1,1,1,1,1} 0
{0,0,0,0,0} 1
{1} 0
{-3,-3,-6,-12,-24} 1
{1,3,4,8} 0

2. A sequence of numbers is said to be balanced if the number odd numbers in the sequence is
equal to the number of even numbers. Write a function that returns 1 if the sequence is balanced
otherwise it returns 0.
Sample
Sequence Return
{2} 0
{2,1} 1
{2,3,1,4} 1
{3,3} 0
{3,3,4,4} 1

3. A sequence of numbers is said to be sorted if the numbers are arranged either ascending or
descending order. Write a function that returns 1 if the numbers are sorted otherwise it returns 0.
Sample
Sequence Return
{} 1
{4} 1
{1,3,2,4} 0
{4,3,2,1} 1
{4,1} 1
{3} 1

47
4. A sequence of numbers is said to be sum balanced if the sum of odd numbers in the sequence equal to
the sum of even numbers in the sequence. Write a function that returns 1 if the sequence is sum balanced
otherwise it returns 0.
Sample
Sequence Return Reason
{ 2,3,5,6} 1 2+6 = 3+5
{4} 0 4 ≠0
{1,3,2,4} 0 1+3 ≠ 2+4
{1,1,1,1,4} 1 1+1+1+1 = 4

5. A sequence of numbers is said to odd increment if the number is increase by the sum of its odd
factors other than the number itself and one. Write a function that returns 1 if the sequence is odd
increment otherwise it returns 0.
Sample
Sequence Return
{6,9,12,15,23} 1
{2,2,2} 1
{3,4} 0
{18,30,53} 1
{20,25,30,53} 1
{3,4,5,6} 0
{33,47} 1
{4,6,9} 0

6. Write a function that takes two Distance values as arguments and returns the larger one.
Include a main() program that accepts two Distance values from the user, compares them, and
displays the larger.

7. An integer is said to be prime if it is divisible by only 1 and itself. For example, 2, 3, 5 and 7
are prime, but 4, 6, 8 and 9 are not.
A.) Write a function that determines whether a number is prime.
B.) Use this function in main program that determines and displays all the prime numbers
less than 10,000. How many numbers up to 10,000 do you have to test to ensure that you
have found all the primes?

48
8. Write a function called hms_to_secs() that takes three int values—for hours, minutes, and
seconds—as arguments, and returns the equivalent time in seconds (type long). Create a program
that exercises this function by repeatedly obtaining a time value in hours, minutes, and seconds
from the user, calling the function, and displaying the value of seconds it returns.

9. Write a function that takes an integer value and returns the number with its digits reversed. For
example, given the number 7631, the function should return 1367. Incorporate the function into
the main program that reads a value from the user and displays the result.

49
Chapter Four: Structure
Structure
A structure is a collection of simple variables. The variables in a structure can be of different
types: Some can be int, some can be float, and so on. (This is unlike the array in which all the
variables must be the same type.) The data items in a structure are called the members of the
structure.

A Simple Structure
Let‘s start off with a structure that contains three variables: two integers and a floating-point
number. This structure represents an item in a widget company‘s parts inventory. The structure is
a kind of blueprint specifying what information is necessary for a single part. The company
makes several kinds of widgets, so the widget model number is the first member of the structure.
The number of the part itself is the next member, and the final member is the part‘s cost.

The program defines the structure part, defines a structure variable of that type called part1,
assigns values to its members, and then displays these values.

#include<iostream>
#include<conio.h>
using namespace std;
struct part //declare a structure
{
int modelnumber; //ID number of widget
int partnumber; //ID number of widget part
float cost; //cost of part
};
int main( )
{
part part1; //define a structure variable
part1.modelnumber = 6244; //give values to structure members
part1.partnumber = 373;
part1.cost = 217.55F;
//display structure members
cout << "Model " << part1.modelnumber;
cout << ", part " << part1.partnumber;
cout << ", costs $" << part1.cost << endl;
getch();
return 0;
}
50
The program‘s output looks like this:
Model 6244, part 373, costs $217.55
The above program has three main aspects: defining the structure, defining a structure variable,
and accessing the members of the structure. Let‘s look at each of these.

Defining the Structure


The structure definition tells how the structure is organized: It specifies what members the
structure will have. Here it is:
struct part
{
int modelnumber;
int partnumber;
float cost;
};

Syntax of the Structure Definition


The keyword struct introduces the structure definition. Next comes the structure name or tag,
which is part. The declarations of the structure members—modelnumber, partnumber, and cost—
are enclosed in braces. A semicolon follows the closing brace, terminating the entire structure.
Note that this use of the semicolon for structures is unlike the usage for a block of code. As
we‘ve seen, blocks of code, which are used in loops, decisions, and functions, are also delimited
by braces. However, they don‘t use a semicolon following the final brace. Figure 4.1 shows the
syntax of the structure declaration.

FIGURE 4.1 Syntax of the structure definition

51
Use of the Structure Definition
The structure definition serves only as a blueprint for the creation of variables of type part. It
does not itself create any structure variables; that is, it does not set aside any space in memory or
even name any variables. A structure definition is merely a specification for how structure
variables will look when they are defined.

Defining a Structure Variable


The first statement in main( )
part part1;
defines a variable, called part1, of type structure part. This definition reserves space in memory
for part1. How much space? Enough to hold all the members of part1—namely modelnumber,
partnumber, and cost. In this case there will be 4 bytes for each of the two ints (assuming a 32-bit
system), and 4 bytes for the float. Figure 4.2 shows how part1 looks in memory.

FIGURE 4.2 Structure members in memory.

In some ways we can think of the part structure as the specification for a new data type. This will
become more clear as we go along, but notice that the format for defining a structure variable is
the same as that for defining a basic built-in data type such as int:
part part1;
int var1;

52
Accessing Structure Members
Once a structure variable has been defined, its members can be accessed using something called
the dot operator. Here‘s how the first member is given a value:
part1.modelnumber = 6244;
The structure member is written in three parts: the name of the structure variable (part1); the dot
operator, which consists of a period (.); and the member name (modelnumber). This means ―the
modelnumber member of part1.‖ The real name of the dot operator is member access operator.

Remember that the first component of an expression involving the dot operator is the name of the
specific structure variable (part1 in this case), not the name of the structure definition (part). The
variable name must be used to distinguish one variable from another, such as part1, part2, and so
on, as shown in Figure 4.3.

FIGURE 4.3 The dot operator.

53
Structure members are treated just like other variables. In the statement part1.modelnumber =
6244;, the member is given the value 6244 using a normal assignment operator. The program
also shows members used in cout statements such as
cout << "\nModel " << part1.modelnumber;
These statements output the values of the structure members.

Arrays of Structures
Arrays can contain structures as well as simple data types. Here‘s an example based on the part
structure.

// structure variables as array elements


#include<iostream>
#include<conio.h>
using namespace std;
const int SIZE = 4; //number of parts in array

struct part //specify a structure


{
int modelnumber; //ID number of widget
int partnumber; //ID number of widget part
float cost; //cost of part
};

int main()
{
int n;
part apart[SIZE]; //define array of structures

for(n=0; n<SIZE; n++) //get values for all members


{
cout << endl;
cout << "Enter model number: ";
cin >> apart[n].modelnumber; //get model number
cout << "Enter part number: ";
cin >> apart[n].partnumber; //get part number
cout << "Enter cost: ";
cin >> apart[n].cost; //get cost
}

cout << endl;

54
for(n=0; n<SIZE; n++) //show values for all members
{
cout << "Model " << apart[n].modelnumber;
cout << " Part " << apart[n].partnumber;
cout << " Cost " << apart[n].cost << endl;
}
getch();
return 0;
}

The user types in the model number, part number, and cost of a part. The program records this
data in a structure. However, this structure is only one element in an array of structures. The
program asks for the data for four different parts, and stores it in the four elements of the apart
array. It then displays the information. Here‘s some sample input:

Enter model number: 44


Enter part number: 4954
Enter cost: 133.45

Enter model number: 44


Enter part number: 8431
Enter cost: 97.59

Enter model number: 77


Enter part number: 9343
Enter cost: 109.99

Enter model number: 77


Enter part number: 4297
Enter cost: 3456.55

Model 44 Part 4954 Cost 133.45


Model 44 Part 8431 Cost 97.59
Model 77 Part 9343 Cost 109.99
Model 77 Part 4297 Cost 3456.55

The array of structures is defined in the statement


part apart[SIZE];

This has the same syntax as that of arrays of simple data types. Only the type name, part, shows
that this is an array of a more complex type.

55
Accessing a data item that is a member of a structure that is itself an element of an array involves
a new syntax. For example

apart[n].modelnumber

refers to the modelnumber member of the structure that is element n of the apart array. Figure 4.4
shows how this looks.

Arrays of structures are a useful data type in a variety of situations. We‘ve shown an array of car
parts, but we could also store an array of personnel data (name, age, salary), an array of
geographical data about cities (name, population, elevation), and many other types of data.

FIGURE 4.4 Array of structures.

Exercise
Payroll is the amount of wages and salaries paid to the employees of a company. In many
organizations one of the main problems is how to calculate the payroll system.

56
To calculate Payroll
Income tax must be calculated by using this formula
Salary Income Tax
0 – 150 0
151 - 650 10% - 15.00
651 - 1400 15% - 47.50
1401 - 2350 20% - 117.50
2351 - 3550 25% - 235.00
3551 - 5000 30% - 412.50
Greater than 5000 35% - 662.50

To calculate pension
=salary * 7%
To calculate Total deduction
= income tax + pension
To calculate net pay
= salary – total deduction

Write a program that accepts names and salaries of employees and calculate their income tax,
pension, total deduction and net pay of the employees.
Name Salary Income tax Pension Total deduction Net pay
===========================================================
Alemu 147
Ali 750
Belay 12500
Chala 455
Fayza 4500
Jacob 7475
Mohammed 1691

57
Chapter Five: Algorithm Analysis
Algorithm
An algorithm is a well-defined computational procedure that takes some value or a set of values
as input and produces some value or a set of values as output.

An algorithm can also be defined as follows

 An algorithm is a set of rules for carrying out calculation either by hand or on a machine
 An algorithm is a finite step-by-step procedure to achieve a required result
 An algorithm is a sequence of computational steps that transform the input into the
output

Algorithm:- is a step by step procedure to solve a given problem


 To accept input values. Example cin>>age;
 To change a value held by data. Example age=age+1;
 To reorganize the data structure itself. Example sorting , deleting / adding
 To display the content of the data structure. Example cout<<age;

Properties of Algorithm
1. Finiteness:- should have finite number of step
Example while ( 1 ) { // it is infinite
cout<<20;
}
2. Absence of ambiguity:-should have only one interpretation

yes
2 >1

yes

print 5 print 7

It is ambiguity

58
3. Sequential Start step
.
. preceding steps
.
Stop step

4. Feasibility:- the possibility of each operation to be executed


for(int i=0; i<0; i++) // not feasibility
cout<<i;

5. Every algorithm should have I/O


 Zero or more input
 One or more output

Example
#include <iostream>
using namespace std;
int main( )
{
cout<<"Hello"; //zero input and one output
return 0;
}

Algorithm Analysis Concepts


How do we measure the efficiency of algorithm?
1. Empirical Analysis:- from the total running time of the program
 uses system time
Empirical Analysis cannot be used to determine efficiency of algorithm because the total running
time of the algorithm varies on the following condition
 processor speed of the computer
 the current processor load
 input size
 software environment
 single tasking
 multi tasking
 internal structure

59
2. Theoretical Analysis
 Based on quantity of resource (time resources) using mathematical concepts

We use the theoretical approach to determine the efficiency of algorithm because


 the number of operations will not vary under different conditions
 it helps to determine the complexity of algorithm

How do we estimate the complexity of algorithm?


Two phases:
1. Algorithm Analysis (Theoretical )
Algorithm T(n) measuring the complexity of an algorithm
2. Order of magnitude T(n) O(T(n))
Determine the category of the complexity to which it belongs

Analysis Rules
1. Assume an arbitrary time

2. Execution of one of the following operations takes time one


 assignment statements eg. sum=0;
 single I/O statement eg. cout<<x;
cin>>x;
 single boolean statement eg. x>y
 single arithmetic operation eg. a+b
 function return eg. return sum;

3. Selection statements
Time for conditional evaluation + maximum time of its clause

1 //conditional test
if (a > b)
a=a+b; 2
else
cout<<a; 1

60
T(n) =1+max(2,1)
=1+2
=3

4. Loop statement set up test update

n
i=1(body time) + 1 + n+1 + n
n is the number of iterations

5. Function call
1 + (parameter) + body time

Calculate T(n) for the following fragment code

A.) k=0;
cout<<"Enter the number";
cin>>n;
for(i=0; i<n; i++)
k++;

T(n) = 1+1+1+1+n+1+n+n
= 3n+5

B.) i=0;
while( i < n)
{
x++;
2n
y++;
}

j=1
while(j <=10)
{
x++; 20
j++;
}

T(n) = 1+ n+1+2n+1+11+20
= 3n + 34

61
C.) for ( i=1; i<=n; i++)
for(j=1; j<=n; j++)
k++;

T(n) = 1+n+1+n+n(1+n+1+n+n)
= 2n+2+n(3n+2)
= 2n+2+3n2+ 2n
= 3n2+4n+2

Exercises
Calculate T(n) for the following code
A.) sum=0;
for(i=1; i<5; i++)
sum=sum+i;

B.) if ( a > b)
{
for (i=0; i<=10; i++)
cout<<i;
}
else
cout<<i;

C.) sum=0;
for ( i=1; i<=n; i++)
for (j=1; j<=m; j++)
sum++;

D.) sum=0;
for ( i=1; i<=n; i++)
for (j=1; j<=i; j++)
sum++;

Complexity Analysis
Complexity Analysis is the systematic study of the cost of computation, measured either in time
units or in operations performed, or in the amount of storage space required.

The goal is to have a meaningful measure that permits comparison of algorithms independent of
operating platform.

62
There are two things to consider:
 Time Complexity: Determine the approximate number of operations required to solve a
problem of size n.
 Space Complexity: Determine the approximate memory required to solve a problem of
size n.

Complexity analysis involves two distinct phases:


 Algorithm Analysis: Analysis of the algorithm or data structure to produce a function
T(n) that describes the algorithm in terms of the operations performed in order to measure
the complexity of the algorithm.
 Order of Magnitude Analysis: Analysis of the function T(n) to determine the general
complexity category to which it belongs.

Asymptotic Analysis
Asymptotic analysis is concerned with how the running time of an algorithm increases with the
size of the input in the limit, as the size of the input increases without bound.

There are different notations used to describe a running time function. These are:
 Big-Oh Notation (O)
 Big-Omega Notation (Ω)
 Theta Notation (θ)

The Big-Oh Notation


Big-Oh notation is a way of comparing algorithms and is used for computing the complexity of
algorithms; i.e., the amount of time that it takes for computer program to run. It‘s only concerned
with what happens for very a large value of n. Therefore only the largest term in the expression
(function) is needed. For example, if the number of operations in an algorithm is n2 – n, n is
insignificant compared to n2 for large values of n. Hence the n term is ignored. Of course, for
small values of n, it may be important.

However, Big-Oh is mainly concerned with large values of n.

63
Formal Definition: f (n)= O (g (n)) if there exist c, k ε R+ such that for all n≥ k, f (n) ≤ c.g (n).

Big-O expresses an upper bound on the growth rate of a function, for sufficiently large values of n.

Each of the following functions is big-O of its successors:

k
logbn
n
nlogbn
n2
n to higher powers
2n
3n
larger constants to the nth power
n!
nn

Example
f(n) = 3nlogbn + 4 logbn+2 is O(nlogbn)
f(n) = 7n4+3n2+5n+1000 is O(n4)
f(n) = 7n2 + 2n +5n! – 234 is O (n!)
Note:- Constant factors may be ignored

Big-Omega Notation
Just as O-notation provides an asymptotic upper bound on a function, Ω notation provides an
asymptotic lower bound.

Formal Definition: A function f(n) is Ω( g (n)) if there exist constants c and k ε R+ such that
f(n) >=c. g(n) for all n>=k.

f(n)= Ω( g (n)) means that f(n) is greater than or equal to some constant multiple of g(n) for all
values of n greater than or equal to some k.

Theta Notation
A function f (n) belongs to the set of θ(g(n)) if there exist positive constants c1 and c2 such that
it can be sandwiched between c1.g(n) and c2.g(n), for sufficiently large values of n.

64
Formal Definition: A function f (n) is θ (g(n)) if it is both O( g(n) ) and Ω( g(n) ). In other words,
there exist constants c1, c2, and k >0 such that c1.g (n)<=f(n)<=c2. g(n) for all n >= k

If f(n)= θ (g(n)), then g(n) is an asymptotically tight bound for f(n).

Questions
Write a program that displays a total running time for various input sizes for the following
complexity category functions and plot a graph (input size vs. time)
A.) Complexity category function T(n) = n
B.) Complexity category function T(n) = n2

A.) Complexity category function T(n) = n

#include<iostream>
#include<time.h>
#include<conio.h>
using namespace std;
int main(){
clock_t start,end;
int n;
cout<<endl<<"Enter a number\nC:\\>";
cin>>n;

start=clock();
for (int i=1;i<=n;i++){
cout<<"\n welcome to Wollo University";
cout<<"\n welcome to Informatics College";
cout<<"\n welcome to Computer Science Department";
}
end=clock();

cout<<endl<<"The time require to finish the above for loop is = "<<(end-start)/CLK_TCK;


getch();
return 0;
}

Run the above program, takes time for different input sizes, draw graph (input size vs. time) and
compare the graph with the complexity category of the program.

65
Input (n) Time (t)
100
500
1000
2000
3000

Draw the graph (input size vs. time)

Time (t)

Input (n)

B.) Complexity category function T(n) = n2

#include<iostream>
#include<time.h>
#include<conio.h>
using namespace std;
int main(){
clock_t start,end;
int n;
cout<<endl<<"Enter a number\nC:\\>";
cin>>n;

start=clock();
for(int i=1; i<=n;i++)
for (int j=1;j<=n;j++){
cout<<"\n welcome to Wollo University";
cout<<"\n welcome to Informatics College";
cout<<"\n welcome to Computer Science Department";
}
end=clock();

cout<<endl<<"The time require to finish the above for loop is = "<<(end-start)/CLK_TCK;


getch();
return 0;
}

66
Run the above program, takes time for different input sizes, draw graph (input size vs. time) and
compare the graph with the complexity category of the program.

Input (n) Time (t)


50
75
100
150
200

Draw the graph (input size vs. time)

Time (t)

Input (n)

Exercise
Write a program that displays a total running time for various input sizes for the following
complexity category functions and plot a graph (input size vs. time). Write functions in
ascending order of complexity

A.) T(n) = 1 (constant)


B.) T(n) = logn
C.) T(n) = n
D.) T(n) = n
E.) T(n) = nlogn
F.) T(n) = n2
G.) T(n) = n3
H.) T(n) = 2n
I.) T(n) = n!
J.) T(n) = 2(n* n)

67
Chapter Six: Searching and Sorting Algorithm
Searching data involves determining whether a value (referred to as the search key) is present in
the data. Two popular search algorithms are the simple linear search and the faster but more
complex binary search. Sorting places data in order, typically ascending or descending, based on
one or more sort keys. A list of names could be sorted alphabetically, bank accounts could be
sorted by account number, and employee payroll records could be sorted by social security
number, and so on.

Searching
Searching is a process of looking for a specific element in a list of items or determining that the
item is not in the list. There are two simple searching algorithms:
 Sequential Search
 Binary Search

Linear Search
The linear search algorithm searches each element in an array sequentially. If the search key does
not match an element in the array, the algorithm tests each element, and when the end of the
array is reached, informs the user that the search key is not present. If the search key is in the
array, the algorithm tests each element until it finds one that matches the search key and returns
the index of that element.

As an example, consider an array containing the following values


34 56 2 10 77 51 93 30 5 52
and a program that is searching for 51. Using the linear search algorithm, the program first
checks whether 34 matches the search key. It does not, so the algorithm checks whether 56
matches the search key. The program continues moving through the array sequentially, testing 2,
then 10, then 77. When the program tests 51, which matches the search key, the program returns
the index 5, which is the location of 51 in the array. If, after checking every array element, the
program determines that the search key does not match any element in the array, the program
returns a sentinel value (e.g. -1).

A big Oh of a linear search is n which is also known as linear run time

68
Implementation of Linear Search
#include<iostream>
using namespace std;
int data[]={2,14,5,11,7,22,33,9,13,50,41};
int size=sizeof data/sizeof(int); //total size of array/size of array data type
int linearSearch( int searchKey )
{
// loop through array sequentially
for ( int index = 0 ; index < size; index++ )
if ( data[ index ] == searchKey )
return index; // return index of integer
return -1; // integer was not found
} // end

int main(){
char ch='y';
int n;
do{
cout<<"\nEnter the number you want to search\nC:\\>";
cin>>n;
int r=linearSearch(n);
if(r!=-1)
cout<<endl<<n<<" is found in the list at index "<<r;
else
cout<<endl<<n<<" is not found in the list ";
cout<<"\n\n do you want to search another number (y|n)";
cin>>ch;
}while(ch=='y' || ch=='Y');
return 0;
}

Binary Search
The binary search algorithm is more efficient than the linear search algorithm, but it requires
that the array be sorted. The first iteration of this algorithm tests the middle element in the array.
If this matches the search key, the algorithm ends. Assuming the array is sorted in ascending
order, then if the search key is less than the middle element, the search key cannot match any
element in the second half of the array and the algorithm continues with only the first half of the
array (i.e., the first element up to, but not including the middle element). If the search key is

69
greater than the middle element, the search key cannot match any element in the first half of the
array and the algorithm continues with only the second half of the array (i.e., the element after
the middle element through the last element). Each iteration tests the middle value of the
remaining portion of the array. If the search key does not match the element, the algorithm
eliminates half of the remaining elements. The algorithm ends either by finding an element that
matches the search key or reducing the sub-array to zero size.

As an example consider the sorted 15-element array


2 3 5 10 27 30 34 51 56 65 77 81 82 93 99
and a search key of 65. A program implementing the binary search algorithm would first check
whether 51 is the search key (because 51 is the middle element of the array). The search key (65)
is larger than 51, so 51 is discarded along with the first half of the array (all elements smaller
than 51.) Next, the algorithm checks whether 81 (the middle element of the remainder of the
array) matches the search key. The search key (65) is smaller than 81, so 81 is discarded along
with the elements larger than 81. After just two tests, the algorithm has narrowed the number of
values to check to three (56, 65 and 77). The algorithm then checks 65 (which indeed matches
the search key), and returns the index of the array element containing 65. This algorithm required
just three comparisons to determine whether the search key matched an element of the array.
Using a linear search algorithm would have required 10 comparisons. [Note: In this example, we
have chosen to use an array with 15 elements so that there will always be an obvious middle
element in the array. With an even number of elements, the middle of the array lies between two
elements. We implement the algorithm to chose the lower of those two elements.]

A big Oh of a binary search is log n which is also known as logarithmic run time

Implementation of Binary Search


#include<iostream>
using namespace std;
int data[]={2,5,7,9,11,13,14,22,33,41,50};
int size=sizeof data/sizeof(int); //total size of array/size of array data type

int binarySearch( int searchElement )


{
int low = 0 ; // low end of the search area
int high = size-1 ; // high end of the search area

70
int middle = ( low + high + 1 ) / 2 ; // middle element
int location = -1; // return value; -1 if not found

do // loop to search for element


{
// if the element is found at the middle
if ( searchElement == data[ middle ] )
location = middle; // location is the current middle

// middle element is too high


else if ( searchElement < data[ middle ] )
high = middle - 1 ; // eliminate the higher half
else // middle element is too low
low = middle + 1 ; // eliminate the lower half
middle = ( low + high + 1 ) / 2 ; // recalculate the middle
} while ( ( low <= high ) && ( location == -1 ) );

return location; // return location of search key


} // end

int main(){
char ch='y';
int n;
do{
cout<<"\nEnter the number you want to search\nC:\\>";
cin>>n;
int r=binarySearch(n);
if(r!=-1)
cout<<endl<<n<<" is found in the list at index "<<r;
else
cout<<endl<<n<<" is not found in the list ";

cout<<"\n\n do you want to search another number (y|n)";


cin>>ch;

}while(ch=='y' || ch=='Y');
return 0;
}

71
Sorting Algorithms
Sorting is one of the most important operations performed by computers. Sorting is a process of
reordering a list of items in either increasing or decreasing order. The following are simple
sorting algorithms used to sort lists.
 Selection Sort
 Bubble Sort
 Insertion Sort

Selection Sort
Basic Idea:
 Loop through a list of items from i=1 to n-1.
 Select the smallest element in the list of items from i+1 to n
 Swap this value with value at position i.

Algorithm of Selection Sort


void selection_sort(int list[])
{
int i,j, smallest;
for(i=0;i<n-1;i++){
smallest=i;
for(j=i+1;j<n;j++){
if(list[j]<list[smallest])
smallest=j;
}//end of inner loop
temp=list[smallest];
list[smallest]=list[i];
list[i]=temp;
} //end of outer loop
}//end of selection_sort

Analysis
How many comparisons?
(n-1)+(n-2)+…+1= O(n2)
How many swaps?
n=O(n)

72
Write a program that sorts list of data using selection sort algorithm
#include<iostream>
#include<iomanip>
#include<conio.h>
using namespace std;
int data[]={13,11,14,7,2,9,5};
int size=sizeof data/sizeof(int); //total size of array/size of array data type

void selection_sort(int list[])


{
int i,j, smallest;
for(i=0;i<size-1;i++){
smallest=i;
for(j=i+1;j<size;j++){
if(list[j]<list[smallest])
smallest=j;
}//end of inner loop

int temp=list[smallest];
list[smallest]=list[i];
list[i]=temp;
cout <<endl<<"pass "<<i+1<< "=";
for(int k=0;k<size;k++)
cout<<setw(5)<<data[k];

} //end of outer loop


}//end of selection_sort

int main(){
cout<<"\n\t Unsorted data\n\n ";
for(int i=0;i<size;i++)
cout<<data[i]<<" ";
cout<<"\n\n\t Sorted data\n";
selection_sort(data);
getch();
return 0;
}

Questions
A.) Write a program that sorts list of data using Bubble sort algorithm
B.) Write a program that sorts list of data using Insertion sort algorithm

73
Exercise
Searching is a process of looking for a specific element in a list of items or determining that the
item is or is not found in the list. The following puzzle demonstrates how to search a given key
in the matrix. The matrix is 4x4 and fills with characters
Sample
0 1 2 3
0 b l l a
1 f a t l
2 l a t l
3 h a t d
After we get the starting character of the key in the matrix, we can search the key in up, down,
left, right or diagonal of the matrix in any straight direction of the cells.
Key :- bat Key:- hat Key:- all
0 1 2 3 0 1 2 3 0 1 2 3
0 b l l a 0 b l l a 0 b l l a
1 f a t l 1 f a t l 1 f a t l
2 l a t l 2 l a t l 2 l a t l
3 h a t d 3 h a t d 3 h a t d
bat is found in the matrix hat is found in the matrix all is found in the matrix

Key :- dll Key:- fat Key:- ball


0 1 2 3 0 1 2 3 0 1 2 3
0 b l l a 0 b l l a 0 b l l a
1 f a t l 1 f a t l 1 f a t l
2 l a t l 2 l a t l 2 l a t l
3 h a t d 3 h a t d 3 h a t d
dll is found in the matrix fat is found in the matrix ball is not found in the matrix
The following program searches a given word starting from (0, 0) coordinates moves through in
any direction.

#include<iostream>
#include<string.h>
using namespace std;
int search(char puzzle[4][4], char key[4], int, int);
void display(char puzzle[4][4]);
int main( ){
char puzzle[4][4];
char ch='y';

74
for (int i=0;i<4;i++)
for(int j=0;j<4;j++) {
cout<<"\n enter the character for row "<<i+1<<" for column"<<j+1<<"=";
cin>>puzzle[i][j];
}

cout<<endl;
display(puzzle);

do{
char key[4];
cout <<"\n please enter the key you want to search=";
cin>>key;

int x=search(puzzle, key,0,0);


if (x==1)
cout<<"\n"<<key<<" is found in matrix";
else
cout<<"\n"<<key<<" is not found in matrix";

cout<<endl<<"do you want to search another key(y|n)";


cin>>ch;
}while (ch=='Y' || ch=='y');
return 0;
}

void display(char puzzle[4][4]){


for(int i=0;i<4;i++){
for(int j=0;j<4;j++)
cout<<puzzle[i][j]<<" ";
cout <<endl;
}
}

int search(char puzzle[4][4], char key[4], int a, int b){


int exist=0, i;
int length=strlen(key);
int x=1;
for(i=a;i<length;i++)
if(puzzle[0][i]!=key[i])
x=0;
if(x==1)
exist=1;

75
x=1;
for( i=b;i<length;i++)
if(puzzle[i][0]!=key[i])
x=0;
if(x==1)
exist=1;

x=1;
for(i=a;i<length;i++)
if(puzzle[i][i]!=key[i])
x=0;
if(x==1)
exist=1;

return exist;
}

Exercise
Write a program that searches a given word in any direction of the Puzzle?

76
Chapter Seven: Linked List
A linked list is a data structure consisting of a group of nodes which together represent a
sequence. Under the simplest form, each node is composed of a data and a reference (in other
words, a link) to the next node in the sequence

A Linked list
 A linked list is a dynamic data structure that can grow and shrink during program
execution, so you can use as much memory as you need.
 A building block of a linked list is a block of memory that has two items: data stored in
the list, and a pointer to the rest of the list.
 A linked list is a set of building blocks where one blocks points to the next. The start of
the list, called head, is a pointer that points to the first element of the list.
 Finally, there‗s a special linked list: the empty list. This is usually represented by a
special pointer, the null pointer. The end of the list is indicated by the null pointer.

Consider the following data structure of the linked list is


struct character {
char ch;
character *next;
}

A linked list that stores a list of characters: "FIRST ".

head

F I R S T null

The principal benefit of a linked list over a conventional array is that the list elements can easily
be inserted or removed without reallocation or reorganization of the entire structure because the
data items need not be stored contiguously in memory or on disk, while an array has to be
declared in the source code, before compiling and running the program. Linked lists allow
insertion and removal of nodes at any point in the list, and can do so with a constant number of
operations if the link previous to the link being added or removed is maintained during list
traversal.

77
Self-Referential Structures
Structures can hold pointers to instances of themselves.
struct list{
char name[10];
int count;
list *next;
};

Linked lists are the most basic self-referential structures.

Linked lists are a way to store data with structures so that the programmer can automatically
create a new place to store data whenever necessary. Specifically, the programmer writes a struct
definition that contains variables holding information about something, and then has a pointer to
a struct of its type. Each of these individual struct in the list is commonly known as a node.

Think of it like a train. The programmer always stores the first node of the list. This would be the
engine of the train. The pointer is the connector between cars of the train. Every time the train
adds a car, it uses the connectors to add a new car. This is like a programmer using the keyword
new to create a pointer to a new struct.

Each of the nodes in a struct has a pointer. Remember that the pointer only stores the memory
location of something, it is not that thing, so the arrow goes to the next one. At the end, there is
nothing for the pointer to point to, so it does not point to anything, it should be a null pointer or a
dummy node to prevent it from accidentally pointing to a totally arbitrary and random location in
memory.

So far we know what the node struct should look like:

#include<iostream>
#include<conio.h>
using namespace std;

struct node {
int x;
node *next;
};

78
int main()
{
node *root;
root = new node; // Now the root node creates
root->next = NULL; // The root node points to null pointer
root->x = 5; // Assign 5 to x of the root node
cout<<root->x; //Display the value x of root node
getch();
return 0;
}

The following linked list program shows how to create a node, how to links a node to another
node and how to traverse (go through) the linked list

#include<iostream>
#include<conio.h>
using namespace std;
struct node {
int x;
node *next;
};

int main()
{
node *root; // This won't change, or we would lose the list in memory
node *conductor; // This will point to each node as it traverses the list

root = new node; // Sets it to actually point to something


root->next = NULL; // Otherwise it would not work well
root->x = 12;

conductor = root; // The conductor points to the first node


if ( conductor != NULL) {
while ( conductor->next != NULL)
conductor = conductor->next;
}

conductor->next = new node; // Creates a node at the end of the list


conductor = conductor->next; // Points to that node
conductor->next = NULL; // Prevents it from going any further
conductor->x = 42;

79
node *temp=root;
while ( temp!= NULL)
{
cout<<temp->x<<endl; //Display the value x of each node
temp=temp->next;
}
getch();
return 0;
}

That is the basic code for traversing a list. The if statement ensures that there is something to
begin with (a first node). If the if statement is true, then it is good to try and access the node
pointed to by conductor. The while loop will continue as long as there is another pointer in the
next. The conductor simply moves along. It changes what it points to by getting the address of
conductor->next.

We can add a new node at the end of the linked list. Once the while loop finished, the conductor
will point to the last node in the linked list. Therefore, conductor->next is set to null, so it is good
to allocate a new area of memory for it to point to. Then the conductor traverses one more
element and makes sure that it has its pointer to next set to NULL so that the list has an end.
Finally, the new node has its x value set. (It can be set through user input. The new node its x is
assigned the value 42.)

To print a linked list, the traversal function is almost the same.

For example:

node *temp=root;
while ( temp!= NULL)
{
cout<<temp->x<<endl;
temp=temp->next;
}

80
Sample code for linked list that is adding a node to the list and display the list of the nodes

#include<iostream>
#include<iomanip>
using namespace std;
struct person{
char name[10];
int age;
float height;
person *next;
};

person *head=NULL;
void display( );
void add( );
int main( ){
int n=1;
do{
cout<<"\n Enter 1 to add data to the linked list";
cout<<"\n Enter 2 to display the data";
cout<<"\n Enter 3 to exit from the program";
cout<<endl<<"C:\\>";
cin>>n;
if (n==1)
add( );
else if (n==2)
display( );
else if (n==3)
n=0;
else
cout<<"\nplease enter appropriate number";

}while(n!=0);
return 0;
}

void add( ){
person *temp=new person;
person *last;
cout<<"\n Enter the name of the student\n C:\\>";
cin>>temp->name;

81
cout<<"\n Enter the age of the student\n C:\\>";
cin>>temp->age;
cout<<"\n Enter the height of the student\n C:\\>";
cin>>temp->height;
temp->next=NULL;
if (head==NULL)
head=temp;
else{
last=head;
while(last->next!=NULL){
last=last->next;
}
last->next=temp;
}
}

void display( ){
person *temp=head;
cout<<endl<<setw(15)<<"Name"<<setw(10)<<"Age"<<setw(10)<<"Height"<<endl;
for(int i=1;i<=10;i++)
cout<<" ";
for(int i=1;i<=25;i++)
cout<<"=";

while(temp!=NULL){
cout<<endl<<setw(15)<<temp->name<<setw(10)<<temp->age<<setw(10)<<temp->height;
temp=temp->next;
}
cout<<endl;
}

Exercise
Write a menu driven program using single linked list data structure, which keeps track of
students record systems of Wollo University (WU). The system should maintain at least the
following information about students: Id, Name, Age, Year and Semester GPA.

The system should be able to do the following operations.


A.) Inserting students data from the keyboard
B.) Displaying the whole list of students
82
C.) Adding new students data from the keyboard
D.) Deleting a recording using a given Id number
E.) Updating the age and year of existing records (Based on Id , 1st search if found and then
update)
F.) Sorting records by students Id Number
G.) Searching students by Id number
H.) Displays students whose grade is above a given GPA
I.) Saving the records on the hard disk
J.) Reading the records on the hard disk
K.) Add other operations that are appropriate to system

Note:- The system should avoid accepting the same ID number for two different records

83
Chapter Eight: Stack and Queue
Stack
A stack is a container of objects that are inserted and removed according to the last-in-first-out
(LIFO) principle. Inserting an item is known as ―pushing‖ onto the stack. ―Popping‖ off the stack
is synonymous with removing an item.

The operations of insertion and deletion are called PUSH and POP
Push - push (put) item onto stack
Pop - pop (get) item from stack

TOS= Top of the Stack

The Basic Operations:


Algorithm for push operation
Push( )
{
if there is room {
put an item on the top of the stack
else
give an error message
}
}

Algorithm for pop operation


Pop( )
{
if stack not empty {
return the value of the top item
remove the top item from the stack
}

84
else {
give an error message
}
}

Applications of Stacks
 The simplest application of a stack is to reverse a word. You push a given word to stack -
letter by letter - and then pop letters from the stack.
 Another application is an "undo" mechanism in text editors; this operation is
accomplished by keeping all text changes in a stack.
 Evaluation of Algebraic Expressions
 Infix to Postfix (RPN) Conversion
 Function Calls

Implementation of the stack

#include<iostream>
using namespace std;

const int UPPERLIMIT=4;


int stack[UPPERLIMIT];

void push(int);
int pop();
void display();
int top=-1;

int main(){

int exit=0;
int n;

do{
cout<<"\n Enter 1 to add an integer number on the top of the stack";
cout<<"\n Enter 2 to pop an integer number from the top of the stack";
cout<<"\n Enter 3 to display the content of the stack";
cout<<"\n Enter 4 to exit from the program";
cout<<endl<<"C:\\>";
cin>>n;

85
if (n==1) {
int num;
cout<<"\nEnter the number you want to add on the top of the stack\nC:\\>";
cin>>num;
push(num);
}
else if (n==2){
int t=pop();
if(t==-1)
cout<<"\n Stack Underflow";
else
cout<<"\n"<<t<<" is remove from top of the stack";
cout<<endl;
}
else if (n==3){
display();
}
else if (n==4){
exit=1;
}
else
cout<<"\nplease enter appropriate number";
}while(exit==0);
return 0;
}

void push(int item){


if(top < UPPERLIMIT-1){
top = top + 1;
stack[top] = item;
}
else
cout<<"Stack Overflow";
cout<<endl;
}

int pop(){
if(top >= 0){
top = top - 1;
return stack[top+1];
}

86
else
return -1;
}

void display(){
cout<<endl;
int temp=top;
cout<<"\n Content of Stack";
while(temp>=0){
cout<<"\n\t"<<stack[temp];
temp=temp-1;
}
cout<<endl;
}

Queues
A queue is a container of objects (a linear collection) that are inserted and removed according to
the first-in first-out (FIFO) principle. An excellent example of a queue is a line of students in the
food court of the University. In the queue only two operations are allowed enqueue and
dequeue. Enqueue means to insert an item into the back of the queue, dequeue means removing
the front item.

The operations of insertion and deletion are called enqueue and dequeue
 enqueue - inserting data at the rear of the queue
 dequeue – removing data at the front of the queue

Application of Queues
 Print server- maintains a queue of print jobs
 Task scheduler in multiprocessing system- maintains priority queues of processes
 Telephone calls in a busy environment –maintains a queue of telephone calls
 Simulation of waiting line- maintains a queue of person

87
Example

Algorithm for enqueue and dequeue operations


Consider the following structure: int Num[MAX_SIZE];
We need to have two integer variables that tell:
 the index of the front element
 the index of the rear element

We also need an integer variable that tells:


 the total number of data in the queue

int FRONT =-1,REAR =-1;


int QUEUESIZE=0;

To enqueue data to the queue


 check if there is space in the queue
REAR<MAX_SIZE-1 ?
Yes: Increment REAR
Store the data in Num[REAR]
Increment QUEUESIZE
FRONT = = -1?
Yes: - Increment FRONT
No: - Queue Overflow

88
To dequeue data from the queue
 check if there is data in the queue
QUEUESIZE > 0 ?
Yes: Copy the data in Num[FRONT]
Increment FRONT
Decrement QUEUESIZE
No: - Queue Underflow

Exercise
1. Write a program that implements Queue using Array.

89
Chapter Nine: Tree
Tree
A tree is a set of nodes and edges that connect pairs of nodes. It is an abstract model of a
hierarchical structure.

Rooted tree has the following structure:


 One node distinguished as root.
 Every node C except the root is connected from exactly other node P. P is C's parent, and
C is one of P's children.
 There is a unique path from the root to the each node.
 The number of edges in a path is the length of the path.

Binary tree: a tree in which each node has at most two children called left child and right child.

Data Structure of a Binary Tree


struct DataModel
{
Declaration of data fields
DataModel * Left, *Right;
};

Consider the following definition of binary tree.


struct Node
{
int Num;
Node * Left, *Right;
};
Node *RootNodePtr=NULL;

Traversing
A tree traversal is a specific order in which to trace the nodes of a tree.
There are 3 common tree traversals.
 Inorder: left, root, right
 Preorder: root, left, right
 Postorder: left, right, root

90
This order is applied recursively.
So for in-order, we must print each subtree's left branch before we print its root.
Note "pre" and "post" refer to when we visit the root.

Tree Traversal
Example 1

Consider the following binary tree

Inorder: (left, root, right)


3, 5, 6, 7, 10, 12, 13, 15, 16, 18, 20, 23
Preorder: (root, left, right)
15, 5, 3, 12, 10, 6, 7, 13, 16, 20, 18, 23
Postorder: (left, right, root)
3, 7, 6, 10, 13, 12, 5, 18, 23, 20, 16, 15

Example 2
Consider the following Binary tree

3 9

2 4 8 10

A.) What is the order of data using Preorder traversal?

91
Preorder traversal - traversing binary tree in the order of parent (root), left and right.
Parent Left Right

6 3 9

4 10
2 8

Parent Left Right Parent Left Right Parent Left Right


6 3 2 4 9 8 10

Note: - Recursively apply to each sub tree until one node remain
Preorder traversal is 6 3 2 4 9 8 10

B.) What is the order of data using Inorder traversal?


Inorder traversal - traversing binary tree in the order of left, parent (root) and right.
Left Parent Right

3 6 9

10
2 4 8

Left Parent Right Left Parent Right Left Parent Right


2 3 4 6 8 9 10

Note: - Recursively apply to each sub tree until one node remain
Preorder traversal is 2 3 4 6 8 9 10

Exercise
What is the order of data using postorder traversal for the above tree?

Binary search tree (ordered binary tree): a binary tree that may be empty, but if it is
not empty it satisfies the following.
 Every node has a key and no two elements have the same key.
 The keys in the right subtree are larger than the keys in the root.
 The keys in the left subtree are smaller than the keys in the root.
 The left and the right subtrees are also binary search trees.

92
Example

Operations on Binary Search Tree


Consider the following definition of binary search tree.
struct Node
{
int Num;
Node * Left, *Right;
};
Node *RootNodePtr=NULL;

Insertion
When a node is inserted the definition of binary search tree should be preserved. Suppose there is
a binary search tree whose root node is pointed by RootNodePtr and we want to insert a node
(that stores 17) pointed by InsNodePtr.

Case 1: There is no data in the tree (i.e. RootNodePtr is NULL)


The node pointed by InsNodePtr should be made the root node.

93
Case 2: There is data
Search the appropriate position.
Insert the node in that position.

Function call:
if(RootNodePtr = = NULL)
RootNodePtr=InsNodePtr;
else
InsertBST(RootNodePtr, InsNodePtr);

Implementation:
void InsertBST(Node *RNP, Node *INP)
{
//RNP=RootNodePtr and INP=InsNodePtr
int Inserted=0;
while(Inserted = =0)
{
if(RNP->Num > INP->Num)
{
if(RNP->Left = = NULL)
{
RNP->Left = INP;
Inserted=1;
}

94
else
RNP = RNP->Left;
}
else
{
if(RNP->Right = = NULL)
{
RNP->Right = INP;
Inserted=1;
}
else
RNP = RNP->Right;
}
}
}

A recursive version of the function can also be given as follows.

void InsertBST(Node *RNP, Node *INP)


{
if(RNP->Num>INP->Num)
{
if(RNP->Left==NULL)
RNP->Left = INP;
else
InsertBST(RNP->Left, INP);
}
else
{
if(RNP->Right==NULL)
RNP->Right = INP;
else
InsertBST(RNP->Right, INP);
}
}

Traversing
Binary search tree can be traversed in three ways.
A.) Preorder traversal - traversing binary tree in the order of parent (root), left and right.
B.) Inorder traversal - traversing binary tree in the order of left, parent (root) and right.
C.) Postorder traversal - traversing binary tree in the order of left, right and parent (root).

95
Example:

Preorder traversal - 10, 6, 4, 8, 7, 15, 14, 12, 11, 13, 18, 16, 17, 19
Inorder traversal - 4, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19
==> Used to display nodes in ascending order.
Postorder traversal- 4, 7, 8, 6, 11, 13, 12, 14, 17, 16, 19, 18, 15, 10

Function calls:
Preorder(RootNodePtr);
Inorder(RootNodePtr);
Postorder(RootNodePtr);

Implementation:
void Preorder (Node *CurrNodePtr)
{
if(CurrNodePtr ! = NULL)
{
cout<< CurrNodePtr->Num; // or any operation on the node
Preorder(CurrNodePtr->Left);
Preorder(CurrNodePtr->Right);
}
}

96
void Inorder (Node *CurrNodePtr)
{
if(CurrNodePtr ! = NULL)
{
Inorder(CurrNodePtr->Left);
cout<< CurrNodePtr->Num; // or any operation on the node
Inorder(CurrNodePtr->Right);
}
}

void Postorder (Node *CurrNodePtr)


{
if(CurrNodePtr ! = NULL)
{
Postorder(CurrNodePtr->Left);
Postorder(CurrNodePtr->Right);
cout<< CurrNodePtr->Num; // or any operation on the node
}
}

Question
Write a menu driven program using single linked list that inserts integer number in the
appropriate place of Binary Search Tree and displays the number in Preorder traversal,
Inorder traversal and Postorder traversal .

#include<iostream>
using namespace std;

struct Number
{
int num;
Number * Left, *Right;
};

Number *RootNodePtr=NULL;

void InsertBST(Number *RNP, Number *INP);


void Preorder(Number *CurrNodePtr);
void Inorder(Number *CurrNodePtr);
void Postorder(Number *CurrNodePtr);

97
int main( ){
int exit=0;
int n;
do{
cout<<"\n Enter 1 to insert an integer number in the appropriate location";
cout<<"\n Enter 2 to display integer number(s) in Preorder traversal";
cout<<"\n Enter 3 to display integer number(s) in Inorder traversal";
cout<<"\n Enter 4 to display integer number(s) in Postorder traversal";
cout<<"\n Enter 5 to exit from the program";
cout<<endl<<"C:\\>";
cin>>n;

if (n==1) {
Number *InsNodePtr=new Number;
cout<<"\n Enter the number you want to insert\nC:\\>";
cin>>InsNodePtr->num;
InsNodePtr->Left=NULL;
InsNodePtr->Right=NULL;

if(RootNodePtr == NULL)
RootNodePtr=InsNodePtr;
else
InsertBST(RootNodePtr, InsNodePtr);

}
else if (n==2){
Number *temp;
temp= RootNodePtr;
Preorder (temp);
}
else if (n==3){
Number *temp;
temp= RootNodePtr;
Inorder (temp);
}
else if (n==4){
Number *temp;
temp= RootNodePtr;
Postorder (temp);
}

98
else if (n==5){
exit=1;
}
else
cout<<"\nplease enter appropriate number";

}while(exit==0);
return 0;
}

void InsertBST(Number *RNP, Number *INP)


{
//RNP=RootNodePtr and INP=InsNodePtr
int Inserted=0;
while(Inserted ==0)
{
if(RNP->num > INP->num)
{
if(RNP->Left == NULL)
{
RNP->Left = INP;
Inserted=1;
}
else
RNP = RNP->Left;
}
else
{
if(RNP->Right == NULL)
{
RNP->Right = INP;
Inserted=1;
}
else
RNP = RNP->Right;
}
}
}

99
void Preorder (Number *CurrNodePtr)
{
if(CurrNodePtr != NULL)
{
cout<< CurrNodePtr->num<<" "; // or any operation on the node
Preorder(CurrNodePtr->Left);
Preorder(CurrNodePtr->Right);
}
}

void Inorder (Number *CurrNodePtr)


{
if(CurrNodePtr != NULL)
{
Inorder(CurrNodePtr->Left);
cout<< CurrNodePtr->num<<" "; // or any operation on the node
Inorder(CurrNodePtr->Right);
}
}

void Postorder (Number *CurrNodePtr)


{
if(CurrNodePtr != NULL)
{
Postorder(CurrNodePtr->Left);
Postorder(CurrNodePtr->Right);
cout<< CurrNodePtr->num<<" "; // or any operation on the node
}
}

Exercise
Write a program that searches a node and delete a node in a binary search tree?

100

You might also like