Dsa lab manual version 2
-
Upload
dwight-sabio -
Category
Software
-
view
67 -
download
5
Transcript of Dsa lab manual version 2
1
2
T A B L E O F C O N T E N T S
1 If Else, Do While, and For Statements…………………..………….5
2 Searching Algorithm……………………………………………………….19
3 Sorting Algorithm………………………………………………….………31
4 Five Sorting Algorithms………………………………………………….38
5 Stacks and Queues………………………………………………….……..45
6 Graphs……………………………………………………………………………89
7 Trees………………………………………………………………………….….108
8 Heaps……………………………………………………………………………..114
9 Collision Resolution Technique……………………………………….124
3
INTEGRATED DEVELOPMENT ENVIRONMENT
How to download Code blocks 1. Type in the web address area the URL: http://www.codeblocks.org/
2. Click on Download 3. Download the binary release 4. The user has a variety of choices to install Code Blocks. It depends on the
workstation’s operating system. 5. If the user is using Windows OS, download codeblocks-10.05mingw-setup.exe.
Download it from BerliOS or Sourceforge.net. Note: The version might be different when you download it
6. The binary file is approximately 71MB. 7. After downloading, click the codeblocks-10.05mingw-setup and install it. 8. After installing, the user should try to output Hello World to test if the IDE is working
properly.
4
INTEGRATED DEVELOPMENT ENVIRONMENT
How to download Dev C++
1. Type in the web address area the URL: http://www.bloodshed.net/devcpp.html
2. Click on Download 3. Find Dev-C++ and click on it. 4. The current beta version is Dev-C++ 5. Note: The version might be different
when you download it. 5. Find Go to Download Page and click.
6. Download Dev-C++ 5.0 beta 9.2 (4.9.9.2) (9.0 MB) with
Mingw/GCC 3.4.2 from SourceForge.
7. The binary file is approximately 9MB. 8. After downloading, click the devcpp-4.9.9.2 and install it. 9. After installing, the user should try to output Hello World to test if the IDE is
working properly.
5
1 If Else, Do While,
and For Statements
6
P R E - L A B O R A T O R Y 1
Name: __________ _________________ Time: 1 hour Objective
1. To learn how to get the operational count using C++. Read and Discover Type, build and run the following code. Answer the questions that follow. Part 1 //=========================================================================
// Name : prelab1_a.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : operation count using for loop
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 unsigned long m;
5
6 void swordfish();
7
8 int main()
9 {
10 swordfish();
11 cout<<"\nOperation count is: "<<m<< endl;
12 }
13
14 void swordfish()
15 {
16 int n = 10; m++;//1 count for n
17
18 for(int k=0; k < n+1; k++)
19 {
20 cout << k << endl; m++;//1 count for k
21 cout << n-k << endl; m++;//1 count for n-k
22
23 }
24 }
1. What is the operation count of the program?
7
O P E R A T I O N C O U N T
//=========================================================================
// Name : prelab1_b.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : operation count using while loop
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 unsigned long m;
5
6 void melon();
7
8 int main()
9 {
10 melon();
11 cout<<"Operation count is: "<<m<< endl;
12 }
13
14 void melon()
15 {
16 int i= 1; m++;// 1 count for i
17 int k = 0; m++;// 1 count for k
18
19 while (i <= 7)
20 {
21 k = k + 1; m+=2;// 2 counts for k
22 i = i + 1; m+=2;// 2 counts for i
23
24 cout << k << endl;
25 cout << i << endl;
26 }
27 }
2. What is the operation count of the program?
/=========================================================================
// Name : prelab1_c.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : operation count using do-while
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 unsigned long m;
5
6 void melon();
8
P R E - L A B O R A T O R Y 1
7 int main()
8 {
9 melon();
10 cout<<"\nOperation count is: "<<m<< endl;
11 }
12
13 void melon()
14 {
15 int x = 5;
16 m++;//1 count for x
17
18 do
19 {
20 cout << x << endl;
21 x=x+1;
22 m+=2;//2 counts for x=x+1
23
24 } while(x<25);
25 m++; //1 count for compare
26 }
3. What is the operation count of the program?
//=========================================================================
// Name : prelab1_d.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : operation count using if-else
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 unsigned long m;
5
6 void swordfish();
7
8 int main()
9 {
10 swordfish();
11 cout<<"\nOperation count is: "<<m<< endl;
12 }
13
14 void swordfish()
15 {
16 int age = 24; m++;//1 count for age
17
18 m++;//1 count for compare
19 if(age > 60)
20 {
21 cout << "wow, you are old" << endl;
22 }
9
O P E R A T I O N C O U N T
23 else
24 {
25 cout << "you are young." << endl;
26 cout << "you have to get a job." << endl;
27 m+=2;// 2 counts for S2
28 }
29 }
4. What is the operation count of the program?
Part 2 5. Calculate the operation count below using the formula. Give the time complexity?
{
int x, y;
if (x%2 == 1)
y = 10;
else
y = x * 10;
}
6. Calculate the operation count below using the formula. Give the time complexity?
k = 500;
for (i = 0; i < k; i++)
{
x += 1;
n = 200;
}
10
P R E - L A B O R A T O R Y 1
7. Calculate the operation count below using the formula. Give the time complexity?
i = 1;
while (i <= 7)
{
k = k + 1;
i = i + 1;
}
11
L A B O R A T O R Y 1
Objective
1. This activity allows the students to understand the operation count using counter-controlled loop, post-test loop and pre-test loop.
Read and Discover Type, build and run the following code. Copy the screen output of the program to the corresponding space provided. Answer the questions that follow. //=========================================================================
// Name : lab1_a.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : counter-controlled loop example
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5
6 int counter, num;
7
8 cout <<"Enter num: ";
9 cin >> num;
10
11 for (counter = num; counter >= 1; counter--)
12 cout << counter;
13
14 return 0;
15 }
1. What are the screen output and the calculated operation count of the program if the user inputs num = 10?
2. Write down the codes using while loop replacing line no. 11 and 12 that will produce the same output. What is the calculated operation count?
12
O P E R A T I O N C O U N T
//========================================================================
// Name : lab1_b.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : counter-controlled loop example
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5
6 int counter;
7
8 for (counter = 2; counter <= 40; counter+=2)
9 cout << counter;
10
11 return 0;
12 }
3. What are the screen output and the calculated operation count of the program?
4. Modify the code by changing line no. 8 to: For(counter = 1; counter <=200; counter*=2)
Write down the screen output of your modified program. What is the calculated operation count?
//========================================================================
// Name : lab1_c.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : counter-controlled loop example
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5
6 char ch;
7 for (ch = 'A'; ch <='S'; ch++)
13
L A B O R A T O R Y 1
8 cout << ch;
9
10 return 0; }
5. What are the screen output and the calculated operation count of the program? //========================================================================
// Name : lab1_d.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : post-test loop example
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5
6 int counter, num;
7
8 cout <<"Input: ";
9 cin >> num;
10
11 counter = 0;
12 do
13 {
14 cout << counter;
15 counter++;
16 }
17 while(counter < num);
18
19 return 0;
20 }
6. What are the screen output and the calculated operation count of the program if the user inputs num = 5?
14
O P E R A T I O N C O U N T
7. What are the screen output and the calculated operation count of the program if
the user inputs num = 0? //========================================================================
// Name : lab1_e.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : post-test loop example
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5
6 int sum, num;
7
8 sum = 0;
9
10 do
11 {
12 cout<< "Input: ";
13 cin >> num;
14
15 sum = sum + num;
16 }
17 while (num > 0);
18 cout<< "Output " << sum;
19
20 return 0;
21 }
8. What is the screen output of the program if the user inputs 10, 15, 17, 25 and -1?
Give the calculated operation count.
15
L A B O R A T O R Y 1
9. The program is supposed to continually ask the user of an integer input until the
user enters a negative answer, and then display the sum of all the positive input. Was it able to accomplish this?
10. Fix the code so that it will display the proper output. Write the new do-while statement here. Input the values again in question 8 and give the calculated operation count.
//========================================================================
// Name : lab1_f.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : post-test loop example
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5
6 char sex;
7
8 do
9 {
10 cout<< "Enter Sex (M/F): ";
11 cin >> sex;
12
13 if ( sex != 'M' && sex != 'F')
14 cout<< "Invalid Input! Try Again \n" ;
15
16 }
17 while (sex != 'M' && sex != 'F');
18 cout << "Input Accepted";
19
20 return 0;
21 }
16
O P E R A T I O N C O U N T
11. What are the screen outputs of the program if the user inputs ‘B’, ‘G’, and ‘F’?
Give the calculated operation count?
12. The program is supposed to continually ask for input while the user’s input is invalid (neither M nor F). Was it able to accomplish its intended task?
13. Modify the code so that it not case sensitive and it would accept input in small caps (‘f’ and ‘m’). Write the new logical expression/condition for the if-statement and do-while statement.
//========================================================================
// Name : lab1_g.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : pre-test loop example
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5
6 int x;
7
8 cout << "Input x: ";
9 cin >> x;
10
11 if (x > 0)
12 cout << "positive\n";
13 else
14 cout << "negative\n";
15
16 return 0;
17 }
17
L A B O R A T O R Y 1
14. What are the screen output and the calculated operation count after executing
the program above by entering 10 as input?
15. What are the screen output and the calculated operation count after executing the program above by entering -5 as input?
16. What are the screen output and the calculated operation count after executing the program above by entering 0 as input?
Modify the code by modifying/adding the code in line nos. 14 and 16. Copy the screen output of the program to the corresponding space provided, and answer the questions that follow. 1 #include <iostream>
2 using namespace std;
3
4 int main() {
5
6 int x;
7
8 cout << "Input x: ";
9 cin >> x;
10
11 if (x > 0)
12 cout << "positive\n";
13 else
14 { cout << "negative\n";
15 cout << “it’s less than zero”; }
16 return 0;
17 }
18
O P E R A T I O N C O U N T
17. What are the screen output and the calculated operation count after executing
the program above and entering 10 as input?
18. What are the screen output and the calculated operation count after executing the program above and entering -5 as input?
19
2 Searching
Algorithms
20
P R E - L A B O R A T O R Y 2
Name: __________ _________________ Time: 1 hour Objective
1. To know the source codes of the searching algorithms. Read and Discover Fill in the blanks of the searching algorithms. //=========================================================================
// Name : prelab2_a.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : Linear Search in c++
// Date :
//=========================================================================
int LinearSearch(int A[], int n, int x)
{
int i;
int index;
int found;
_______ = -1;
found = _______
i = _______
while (_______< n && _______)
{
if _______== x)
{
_______= i;
found = _______
}
_______
}
_______
}
O: ______________
Ω: ______________
21
S E A R C H I N G A L G O R I T H M S //=========================================================================
// Name : prelab2_b.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : Linear Search in c++
// Date :
//=========================================================================
int LinearSearch(int A[], int n, int x)
{
int _______
_______ (i = 0; _______; _______)
{
_______ (_______ == x)
return _______;
}
_______
}
O: ______________
Ω: ______________
//=========================================================================
// Name : prelab2_c.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : Binary Search in c++
// Date :
//=========================================================================
int BinarySearch(int A[], int low, int high, int x)
{
_______ mid;
int _______
found = _______
_______ (_______<= _______)
{
mid = (_______)/_______
if (_______== x)
_______= TRUE;
_______ if (_______)
high = mid-1;
_______
_______ = _______;
}
if (_______)
22
P R E - L A B O R A T O R Y 2
return _______
else
_______ }
O: ______________
Ω: ______________
//=========================================================================
// Name : prelab2_d.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : Binary Search in c++
// Date :
//=========================================================================
int RecursiveBinarySearch(int A[], int low, int high,
int x)
{
int _______;
if (______________)
return -1;
_______= (low + _______)_______ 2;
if (______________)
return mid;
_______if (______________)
_______ _______ (A, _______, mid-1, _______);
_______
return RecursiveBinarySearch(______________);
}
O: ______________
Ω: ______________
23
S E A R C H I N G A L G O R I T H M S
Objective
1. To learn about two searching algorithms and their behaviors. 2. To be able to implement the two searching algorithms- Linear Search &
Binary Search. 3. To explore C++ programming involving arrays and get to see array’s
properties and way of manipulating data. Read and Discover Type, build and run the following code. Copy the screen output of the program to the corresponding space provided. Answer the questions that follow. //=========================================================================
// Name : lab2_a.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : linear search in c++
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int LinearSearch(int [], int, int);
5
6 int main()
7 {
8 const int NUMEL = 15;
9 int nums[NUMEL] = {7,92,24,12,132,78,23,69,71,256,62,32,512,89,8};
10 int item, location;
11
12 cout << "Enter the item you are searching for: ";
13 cin >> item;
14
15 location = LinearSearch(nums, NUMEL, item);
16
17 if (location > -1)
18 cout << "The item was found at index location " << location<<
19 endl;
20 else
21 cout << "The item was not found in the list\n";
22
23 return 0;
24 }
25
26 int LinearSearch(int list[], int size, int key)
27 {
28 int i;
29
30 for (i = 0; i < size; i++)
31
32 {
33 if (list[i] == key)
34 return i;
35 }
36
37 return -1;
38 }
24
L A B O R A T O R Y 2
1. What is the screen output if the user inputs a number = 8?
2. What is the screen output if the user inputs a number = 512?
3. What is the screen output if the user inputs a number = 20?
//=========================================================================
// Name : lab2_b.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : linear search in c++
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int LinearSearch(const int *Array, const int Size, const int ValToSearch)
5 {
6 bool NotFound = true;
7 int i = 0;
8
9 while(i < Size && NotFound)
10 {
11 if(ValToSearch != Array[i])
12 i++;
13 else
14 NotFound = false;
15 }
16 if( NotFound == false )
17 return i;
18 else
19 return -1;
20 }
21
22 int main()
23 {
24 int Number[] = { 92,12,71,32,7,80,121,412,590,1032,78,212,9};
25 int Quantity = sizeof(Number) / sizeof(int);
26 int NumberToSearch = 0;
27
28 cout << "Enter the number to search: "; cin >> NumberToSearch;
25
S E A R C H I N G A L G O R I T H M S
29 int i = LinearSearch(Number, Quantity, NumberToSearch);
30
31 if(i == -1)
32 cout << NumberToSearch << " was not found in the array\n\n";
33 else
34 {
35 cout << NumberToSearch << " is at the " << i;
36
37 if( i == 0 )
38 cout<< "th index of the array\n\n";
39 else if( i == 1 )
40 cout<< "st index of the array\n\n";
41 else if( i == 2 )
42 cout<< "nd index of the array\n\n";
43 else if( i == 3 )
44 cout<< "rd index of the array\n\n";
45 else
46 cout<< "th index of the array\n\n";
47 }
48
49 return 0;
50 }
4. What is the screen output if the user inputs a number = 71?
5. What is the screen output if the user inputs a number = 30?
6. What is the screen output if the user inputs a number = 9?
//=========================================================================
// Name : lab2_c.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : linear search in c++
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int main()
5 {
26
L A B O R A T O R Y 2
6 const int N = 20;
7 int search, array[N];
8
9 for(int i=0; i<N; i++)
10 {
11 array[i]=rand()%100;
12 cout << array[i] << " ";
13 }
14
15 cout << "\n\nWrite a number to search for: ";
16 cin >> search;
17
18 while(search!=-1)
19 {
20 int i=0;
21 while(array[i]!=search || i==N)
22 i++;
23
24 if(array[i] == search)
25 cout << "It is on the index " << i << endl;
26 else
27 cout << "I cannot find it" << endl;
28 cout << "Write another number: ";
29 cin >> search;
30 cout << endl << endl;
31 }
32 cout << "Thanks to use the program" << endl;
33 return 0;
34 }
7. What is the screen output if the user inputs a number = 27?
8. What is the screen output if the user inputs a number = 5?
9. What is the screen output if the user inputs a number = 42?
27
S E A R C H I N G A L G O R I T H M S
10. Is there something wrong with the code? If there is something wrong, explain
why.
11. Input a number 23. Modify the code so that the output will ask you to Write another number. Note: Write only the added code and its line number below.
//=========================================================================
// Name : lab2_d.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : binary search in c++
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int BinarySearch(int [], int, int);
5
6 int main()
7 {
8 const int NUMEL = 15;
9 int nums[NUMEL] = {3,7,11,17,20,28,30,35,39,40,45,48,60,85,100};
10 int item, location;
11
12 cout << "Enter the item you are searching for: ";
13 cin >> item;
14 location = BinarySearch(nums, NUMEL, item);
15
16 if (location > -1)
17 cout << "The item was found at index location " << location <<
18 endl;
19 else
20 cout << "The item was not found in the array list\n";
21
22 return 0;
23 }
24
25 int BinarySearch(int list[], int size, int key)
26
27 {
28 int left, right, midpt;
29
30 left = 0;
28
L A B O R A T O R Y 2
31 right = size - 1;
32
33 while (left <= right)
34 {
35 midpt = (int) ((left + right) / 2);
36
37 if (key == list[midpt])
38 {
39 return midpt;
40 }
41
42 else if (key > list[midpt])
43 left = midpt + 1;
44
45 else
46 right = midpt - 1;
47 }
48 return -1;
49 }
12. What is the screen output if the user inputs a number = 63?
13. What is the screen output if the user inputs a number = 11?
14. What is the screen output if the user inputs a number = 39?
//=========================================================================
// Name : lab2_e.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : binary search in c++
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int main()
29
S E A R C H I N G A L G O R I T H M S
5 {
6 const int N = 25;
7 int low, high, current,search, array[N];
8 srand(time(0));
9
10 for(int i=0; i<N; i++)
11 {
12 array[i]=rand()%300;
13 }
14 for(int i=0; i<N-1; i++)
15 for(int j=i+1; j<N; j++)
16 if(array[i]>array[j])
17
18 {
19 int tmp= array[i];
20 array[i]= array[j];
21 array[j] = tmp;
22 }
23
24 cout << endl << endl;
25 for(int i=0; i<N; i++)
26 cout << array[i] << " ";
27
28 cout << endl;
29 cout << "Give a number to search for: ";
30 cin >> search;
31
32 while(search!=-1)
33 {
34 low = 0;
35 high = N-1;
36 while(low<=high)
37 {
38 current=(low+high)/2;
39 if(search > array[current])
40 low = current+1;
41 else if(search < array[current])
42 high = current-1;
43 else
44 break;
45
46 }
47
48 if(array[current]==search)
49 cout << "I found it at index " << current << endl;
50 else
51 cout << "I cannot find it" << endl;
52
53 cout<<"Enter a value to search: ";
54 cin>>search;
55 }
56
57 return 0;
58 }
30
L A B O R A T O R Y 2
15. What is the screen output if the user inputs a number = 114?
16. What is the screen output if the user inputs a number = 29?
17. What is the screen output if the user inputs a number = 199?
18. Insert the following code in line 46. Do not delete the close bracket. cout << low << “ “ << high << “ “ << current << endl; After compile and run, insert a numbers that are in the lists. Discuss and give strong answers on what happen on the output.
19. Explain the purpose of line 34 in the code.
20. What is the fastest searching algorithm? Explain why.
31
3 Sorting
Algorithms
32
P R E - L A B O R A T O R Y 3
Name: __________ _________________ Time: 1 hour Objective
1. To know the source codes of the sorting algorithms. Read and Discover Fill in the blanks for the five sorting algorithms. //=========================================================================
// Name : prelab3_a.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : bubble sort in c++
// Date :
//=========================================================================
void BubbleSort(int A[], int n)
{
int i, j;
for (_______; i > 0; _______)
{
_______ (j = 0; _______; j++)
{
_______ (___________)
{
Swap(_______,_______);
}
}
}
}
O: ______________
Ω: ______________
33
S O R T I N G A L G O R I T H M S //=========================================================================
// Name : prelab3_b.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : selection sort in c++
// Date :
//=========================================================================
void SelectionSort(int A[], int n)
{
_______i, j, min;
for ( _______; _______; i++)
{
_______= i;
for (_______; j < n; _______)
{
_______ (_______ < A_______)
min = _______
}
_______ ( _______, &A[i]);
}
_______
O: ______________
Ω: ______________
//=========================================================================
// Name : prelab3_c.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : Insertion sort in c++
// Date :
//=========================================================================
void InsertionSort(int A[], int n)
{
int i, j, B;
for (_____________________ )
{
_______ _______ i;
B = _______
_______ (_____________________ )
{
A[j] = _______
34
P R E - L A B O R A T O R Y 3
_______
}
A[j] = _______
}
}
O: ______________
Ω: ______________
//=========================================================================
// Name : prelab3_d.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : quick sort in c++
// Date :
//=========================================================================
void quickSort(int arr[], int left, int right)
{
int i = left, j = right;
int tmp;
_______ pivot = arr[______________];
_______ (_______)
{
while (_______ < _______)
_______
while (_______ > pivot)
j--;
if (_______)
{
tmp = _______
_______ = arr[j];
_______ = tmp;
i++;
_______
}
};
35
S O R T I N G A L G O R I T H M S
_______ (left < j)
_______ (_____________________);
if (_______)
quickSort(arr, _______, right);
} O: ______________
Ω: ______________ //=========================================================================
// Name : prelab3_e.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : Shell sortin c++
// Date :
//=========================================================================
void ShellSort(apvector <int> &num)
{
int i, temp, flag = 1, numLength = num.length( );
int d = _______;
_______ (______________ )
{
_______= 0;
d = ______________
_______ (i = 0; ______________; _______)
{
if (_____________________ )
{
temp = _______
_______ = num[i];
num[i] = _______;
____________________
}
}
}
return;
}
O: ______________
Ω: ______________
36
L A B O R A T O R Y 3
Objective 1. To learn about five sorting algorithms and their behaviors. 2. To be able to implement the following sorting algorithms- Bubble Sort,
Insertion Sort, Selection Sort, Shell Sort and Quick Sort. 3. To explore C++ programming involving arrays and get to see array’s
properties and way of manipulating data. Read and Discover Type, build and run the following code. Copy the screen output of the program to the corresponding space provided. Answer the questions that follow. //=========================================================================
// Name : lab3_a.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : bubble sort in c++
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int main()
5 {
6 int num[7];
7 int i,j;
8
9 for(i=0; i<=6; i++)
10 {
11 cout << "Please enter number: ";
12 cin >> num[i];
13 }
14
15 for(i=0; i<=5; i++)
16 {
17 for (j=i+1; j<=6; j++)
18 {
19 int temp;
20 if(num[i] > num[j])
21 {
22 temp = num[i];
23 num[i] = num[j];
24 num[j] = temp;
25 }
26 }
27 }
28 for(i=0; i<=6;i++)
29 {
30 cout<< endl << num[i] << endl;
31 }
32 return 0;
33 }
37
S O R T I N G A L G O R I T H M S
1. What is the screen output if the user inputs the ff. numbers: 29, 82, 12, 9, 49, 100, 3. Is it in ascending or descending order?
2. Change the code so that it is in the descending order. Jot down the code and its line number below.
3. Change the code so that it possible to order by ascending and descending characters. Jot down the new code with its line number.
4. What is the screen output if the user input these letters: R, u, i, o, e, W, A for ascending order and o, u, p, w, c, z, b for descending order?
38
L A B O R A T O R Y 3
//=========================================================================
// Name : lab3_b.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : insertion sort in c++
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int main()
5 {
6 int i, key;
7 int num[5] = {4321,189,78,90921,784};
8 cout<<endl<<"Unsorted array\t";
9 for(i=0;i<5;i++)
10 cout<<num[i]<<"\t";
11
12 for(int j=1;j<5;j++)
13 {
14 i=j-1;
15 key=num[j];
16 while(i>=0 && num[i]>key)
17 {
18 num[i+1]=num[i];
19 i--;
20 }
21 num[i+1]=key;
22 }
23
24 cout<<endl<<"Sorted Array\t";
25 for(i=0;i<5;i++)
26 cout<<num[i]<<"\t";
27 cout<<endl;
28
29 return 0;
30 }
5. What is the output of the program?
6. Change the program so that the output is in descending order. Write the added code and its line number.
39
S O R T I N G A L G O R I T H M S
7. Modify the elements by encoding the following numbers in the array: 32, 99, 9,
82, 294, 902, 7391, 9092, 562, and 9019. Write the added code and its line number.
8. Make the output return back in the ascending order. Write the code and its line number.
//=========================================================================
// Name : lab3_c.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : selection sort in c++
// Date :
//=========================================================================
1 #include <iostream>
2 #define ARRAY_SIZE 10
3 using namespace std;
4
5 void init(int);
6 void selection_sort(int[]);
7
8 int main()
9 {
10 init(ARRAY_SIZE);
11 return (EXIT_SUCCESS);
12 }
13
14 void init(int counts)
15 {
16 int numbers[counts];
17 cout << "Before sorting: " << endl;
18 for (int i = 0; i < counts; i++)
19 {
20 numbers[i] = rand();
21 cout << numbers[i] << endl;
22 }
23 selection_sort(numbers);
24 }
25
26 void selection_sort(int numbers[])
27 {
28 int minimum = 0;
29 int current = 0;
30 for (current = 0; current < ARRAY_SIZE - 1; current++)
31 {
32 minimum = current;
40
L A B O R A T O R Y 3
33 for (int i = current + 1; i < ARRAY_SIZE; i++)
34 {
35 if (numbers[i] < numbers[minimum])
36 {
37 minimum = i;
38 }
39 }
40 int temp = numbers[minimum];
41 numbers[minimum] = numbers[current];
42 numbers[current] = temp;
43 }
44 cout << "After sorting: " << endl;
45 for (int i = 0; i < ARRAY_SIZE; i++)
46 {
47 cout << numbers[i] << endl;
48 }
49 system("PAUSE");
50 }
9. What is the output of the program?
10. Change the program so that the output is in descending order. Write the added code and its line number.
11. Modify the code by changing the array size by 100 and change the output in a horizontal direction with comma in the middle.
41
S O R T I N G A L G O R I T H M S
//=========================================================================
// Name : lab3_d.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : shell sort in c++
// Date :
//=========================================================================
1 #include<iostream>
2 using namespace std;
3
4 int main()
5 {
6 int array[10];
7 int length = 10;
8 int i, d;
9 int tmp;
10
11 for (i = 0; i < length; i++)
12 {
13 cout << "Enter a number: ";
14 cin >> array[i];
15 }
16
17 d = length;
18 do {
19 d = (d + 1)/2;
20 for (i =0; i < (length - d); i++)
21 {
22 if (array[i + d] > array[i])
23 {
24 tmp = array[i+d];
25 array[i + d] = array[i];
26 array[i] = tmp;
27 }
28 }
29 } while(d > 1);
30
31 for (i = 0; i < 10; i++)
32 {
33 cout << array[i] << endl;
34 }
35
36 return 0;
37 }
12. What is the screen output if the user inputs the ff. numbers: 73, 21, 92, 80, 213,
9, 12, 73, 502, and 32? Is it in ascending or descending order?
42
L A B O R A T O R Y 3
13. Change the array size into 5 and input the ff. numbers: 82, 10, 3, 78, and 45.
What is the screen output and write the code and its line number below.
14. Change the code so that it is in the descending order. Jot down the code and its
line number below.
//=========================================================================
// Name : lab3_e.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : quick sort in c++
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 const int INPUT_SIZE = 10;
5
6 void print(int *input)
7 {
8 for ( int i = 0; i < INPUT_SIZE; i++ )
9 cout << input[i] << " ";
10 cout << endl;
11 }
12
13 int partition(int* input, int p, int r)
14 {
15 int pivot = input[r];
16
17 while ( p < r )
18 {
19 while ( input[p] < pivot )
20 p++;
21
22 while ( input[r] > pivot )
23 r--;
24
25 if ( input[p] == input[r] )
26 p++;
27 else if ( p < r )
28 {
29 int tmp = input[p];
43
S O R T I N G A L G O R I T H M S
30 input[p] = input[r];
31 input[r] = tmp;
32 }
33 }
34
35 return r;
36 }
37
38 void quicksort(int* input, int p, int r)
39 {
40 if ( p < r )
41 {
42 int j = partition(input, p, r);
43 quicksort(input, p, j-1);
44 quicksort(input, j+1, r);
45 }
46 }
47
48 int main()
49 {
50 int input[INPUT_SIZE] = {500, 700, 800, 100, 300, 200, 900, 400,
51 1000, 600};
52 cout << "Input: ";
53 print(input);
54 quicksort(input, 0, 9);
55 cout << "Output: ";
56 print(input);
57 return 0;
58 }
15. What is the screen output of the quick sort algorithm? Is it in ascending or
descending order?
16. Modify the code so that it is in descending order. What is the screen output and write the code and its line number below.
44
L A B O R A T O R Y 3
17. Modify the array size into 5. Input the ff. values-32, 92, 27, 150, and 10. Display
in ascending order. What is the screen output and write the code and its line number below.
18. Modify the array size into 7. Input the ff. values-25, 16, 70, 2, 101, 206, 6. Display in descending order. What is the screen output and write the code and its line number below.
45
4 Five Sorting
Algorithms
46
P R E - L A B O R A T O R Y 4
Name: __________ _________________ Time: 1 hour Objective
1. To know how to generate basic random numbers. Read and Discover Type, build and run the following code. Answer the questions that follow. //=========================================================================
// Name : prelab4_a.cpp
// Author : @DwightSabio
// Version : 1.0
// Copyright : ©Dwight Sabio
// Description : using rand() function
//=========================================================================
1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5
6 int main()
7 {
8
9 for (int d = 1; d < 25; d++){
10 cout << rand() << endl;
11 }
12
13 }
1. What is the output of the program? Repeat it two more times.
//=========================================================================
// Name : prelab4_b.cpp
// Author : Group 1
// Version : 1.0
// Copyright : ©Dwight Sabio
// Description : using modulo operator
//=========================================================================
1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5
47
F I V E S O R T I N G A L G O R I T H M S
6 int main()
7 {
8
9 for (int d = 1; d < 25; d++){
10 cout << (rand()%6) + 1 << endl;
11 }
12
13 }
2. What is the output of the program? Repeat it two more times.
//=========================================================================
// Name : prelab4_c.cpp
// Author : Group 1
// Version : 1.0
// Copyright : ©Dwight Sabio
// Description : using srand function
//=========================================================================
1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5
6 int main()
7 {
8 srand(41);
9
10 for (int d = 1; d < 25; d++){
11 cout << (rand()%6) + 1 << endl;
12 }
13
14 }
48
P R E - L A B O R A T O R Y 4
3. What is the output of the program? Repeat it two more times.
4. Change the value of srand(2). What is the output of the program? Repeat it two more times.
5. Change the value again of srand(128). What is the output of the program? Repeat it two more times.
49
F I V E S O R T I N G A L G O R I T H M S
//=========================================================================
// Name : prelab4_d.cpp
// Author : Group 1
// Version : 1.0
// Copyright : ©Dwight Sabio
// Description : random generator using time(0)
//=========================================================================
1 #include <iostream>
2 #include <cstdlib>
3 #include <ctime>
4
5 using namespace std;
6
7 int main()
8 {
9 srand(time(0));
10
11 for (int d = 1; d < 25; d++){
12 cout << (rand()%6) + 1 << endl;
13 }
14
15 }
6. What is the output of the program? Repeat it two more times.
50
L A B O R A T O R Y 4
Objective 1. To be able to implement the five sorting algorithms- Bubble Sort, Insertion
Sort, Selection Sort, Shell Sort and Quick Sort. 2. To understand the operational count and the processing time for each sorting
algorithms. 3. To explore C++ programming involving arrays and get to see array’s
properties and way of manipulating data. Read and Discover Type, build and run the following code. Copy the screen output of the program to the corresponding space provided. Answer the questions that follow. //=========================================================================
// Name : lab4_a.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : five sorting algo in c++
// Date :
//=========================================================================
1 #include <cstdlib>
2 #include <iostream>
3 #include <ctime>
4 using namespace std;
5
6 unsigned long q;
7 void bubbleSort(int data[], int n)
8 {
9 bool swapped=true;
10 long int tmp=0;
11 while (swapped)
12 {
13 swapped=false;
14 for (int i=0;i<n;i++)
15 {
16 if (data[i]>data[i+1])
17 {
18 tmp=data[i];
19 data[i]=data[i+1];
20 data[i+1]=tmp;
21 swapped=true;
22 q=q+2;
23 }
24 }
25 }
26 }
27
28 void selectionSort(int data[], int n)
29 {
30 int i, j, minIndex, tmp;
31 for(i=0; i < n-1; i++)
32 {
33 minIndex=i;
34 q+=2;
35 for(j=i+1;j<n;j++)
36 {
37 if(data[j]<data[minIndex])
38 minIndex=j;
39 }
51
F I V E S O R T I N G A L G O R I T H M S
40 q+=2;
41 if(minIndex!=1)
42 {
43 tmp = data[i];
44 data[i] = data[minIndex];
45 data[minIndex] = tmp;
46 q+=2;
47 }
48 }
49 }
50
51 void insert(int data[], int n)
52 {
53 long int i, j, tmp;
54 for (i=1;i<=n;i++)
55 {
56 j=i-1;
57 while (j>0 && data[j-1]>data[j])
58 {
59 tmp=data[j];
60 data[j]=data[j-1];
61 data[j-1]=tmp;
62 j--;
63 q+=2;
64 }
65 }
66 }
67
68 void quick(int data[], int left, int right)
69 {
70 int i = left;
71 int j = right;
72 int tmp;
73 int pivot = data[(left + right)/2];
74 q++;
75 while (i<=j)
76 {
77 while (data[i]<pivot)i++;
78 q++;
79 while (data[j]>pivot)j--;
80 q++;
81 if (i<=j)
82 {
83 tmp = data[i];
84 data[i] = data[j];
85 data[j] = tmp;
86 i++;
87 j--;
88 q++;
89 }
90 q++;
91 };
92
93 if (left < j)
94 quick(data , left , j );
95 if (i < right)
96 quick(data , i , right);
97 }
98
99 void shellSort(int data[], int n)
52
L A B O R A T O R Y 4
100 {
101 int i;
102 int width=n;
103 int pole=1;
104 while(pole || (width>1))
105 {
106 pole=0;
107 width=(width+1)/2;
108 for(i=0;i<(n-width);i++)
109 {
110 if(data[i+width]<data[i])
111 {
112 int temp = data[i+width];
113 data[i+width] = data[i];
114 data[i] = temp;
115 pole=0;
116 q++;
117 }
118 q++;
119 }
120 q++;
121 }
122 }
123
124 int main(int argc, char *argv[])
125 {
126 int n;
127 int o;
128 cout<<"Choose the number of the program you want to use.\n";
129 cout<<"[1]Bubble Sort.\n";
130 cout<<"[2]Selection Sort.\n";
131 cout<<"[3]Insertion Sort.\n";
132 cout<<"[4]Quick Sort.\n";
133 cout<<"[5]Shell Sort.\n";
134 cout<<"[6]Exit\n";
135 cout<<"Type your choice here: ";
136 cin>>o;
137 cout<<"Enter number of items to be sorted: ";
138 cin>>n;
139
140 int data[n];
141 cout<<endl;
142 srand(time(NULL));
143
144 switch (o)
145 {
146 case 1:
147 cout<<"Unsorted Arrays: \n";
148 for (int x=0;x<n;x++)
149 {
150 data[x]=rand();
151 cout<<data[x]<<"\t";
152 }
153 cout<<endl;
154 {
155 q=0;
156 clock_t t1, t2;
157 double time1= 0;
158 t1 = clock();
159 bubbleSort(data,n);
53
F I V E S O R T I N G A L G O R I T H M S
160 t2 = clock();
161 time1 = difftime(t2,t1);
162 cout<<"Bubble Sorting:\n";
163 for (int y=0; y<n; y++)
164 {
165 cout<<data[y]<<"\t";
166 }
167 cout<<endl;
168 cout<<"Operation count is: "<<q<<endl;
169 cout<<"Algorithm Runtime is: "<<time1<<" milliseconds.";
170 cout<<endl<<endl<<endl;
171 }
172 break;
173
174 case 2:
175 cout<<"Unsorted Arrays: \n";
176 for (int x=0;x<n;x++)
177 {
178 data[x]=rand();
179 cout<<data[x]<<"\t";
180 }
181 cout<<endl;
182 {
183 clock_t t3, t4;
184 double time2 = 0;
185 q=0;
186 t3 = clock();
187 selectionSort(data,n);
188 t4 = clock();
189 time2 = difftime(t4,t3);
190 cout<<"Selection Sort:\n";
191 for (int y=0;y<=(n-1);y++)
192 {
193 cout<<data[y]<<"\t";
194 }
195 cout<<endl;
196 cout<<"Operation count is: "<<q<<endl;
197 cout<<"Algorithm runtime is: "<<time2<<" milliseconds";
198 cout<<endl<<endl<<endl;
199 }
200 break;
201
202 case 3:
203 cout<<"Unsorted Arrays: \n";
204 for (int x=0;x<n;x++)
205 {
206 data[x]=rand();
207 cout<<data[x]<<"\t";
208 }
209 cout<<endl;
210 {
211 clock_t t6, t5;
212 double time3 = 0;
213 q=0;
214 t5 = clock();
215 insert(data,n);
216 t6 = clock();
217 time3 = difftime(t6,t5);
218 cout<<"Insertion Sort:\n";
219 for (long int y=0;y<n;y++)
54
L A B O R A T O R Y 4
220 {
221 cout<<data[y]<<"\t";
222 }
223 cout<<endl;
224 cout<<"Operation count is: "<<q<<endl;
225 cout<<"Algorithm Runtime is: "<<time3<<" milliseconds.";
226 cout<<endl<<endl<<endl;
227 }
228 break;
229
230 case 4:
231 cout<<"Unsorted Arrays: \n";
232 for (int x=0;x<n;x++)
233 {
234 data[x]=rand();
235 cout<<data[x]<<"\t";
236 }
237 cout<<endl;
238 clock_t t7, t8;
239 double time4;
240 q=0;
241 t7=clock();
242 quick(data,0,(n-1));
243 t8=clock();
244 time4 = difftime(t8,t7);
245 cout<<"Quick Sort: \n";
246 for(int i=0;i<n;i++)
247 cout<<data[i]<<"\t";
248 cout<<endl;
249 cout<<"The Operation count is "<<q<<endl;
250 cout<<"The Runtime is "<<time4<<" milliseconds.";
251 cout<<endl<<endl<<endl;
252 break;
253
254 case 5:
255 cout<<"Unsorted Arrays: \n";
256 for (int x=0;x<n;x++)
257 {
258 data[x]=rand();
259 cout<<data[x]<<"\t";
260 }
261 cout<<endl;
262 clock_t t9, t10;
263 double time5;
264 q=0;
265 t9=clock();
266 shellSort(data,n);
267 t10=clock();
268 cout<<"Shell sort:\n";
269 for (int y=0;y<n;y++)
270 {
271 cout<<data[y]<<"\t";
272 }
273 cout<<endl;
274 cout<<"Operation Count is "<<q<<endl;
275 time5 = difftime(t10,t9);
276 cout<<"Runtime is "<<time5<<" milliseconds.\n";
277 break;
278
279 case 6:
55
F I V E S O R T I N G A L G O R I T H M S
280 {
281 cout<<"Thank you for using the Program.\n";
282 break;
283 }
284 default:
285 cout<<"Invalid choice.";
286 break;
287
288 }
289 cout<<endl;
290 return 0;
291 }
56
L A B O R A T O R Y 4 Table 1 in Ascending Order
n Bubble Sort Selection Sort Insertion Sort Quick Sort Shell Sort
Count Processing Time Count
Processing Time Count
Processing Time Count
Processing Time Count
Processing Time
32
64
128
256
512
1024
2048
4096
8192
16384
32768
65536
57
F I V E S O R T I N G A L G O R I T H M S
Draw line graphs with x coordinates representing the values of n and y axis coordinates representing the processing time for each sorting algorithm. Graphs should be overlaid. Provide a concise discussion about the resulting graphs.
1. What observations can be made from it? Correlate the count and processing time for each sorting algorithm.
2. Do any of the algorithms run consistently the quickest? Slowest?
58
5 Stacks
And
Queues
59
P R E - L A B O R A T O R Y 5
Name: __________ _________________ Time: 1 hour Objective
1. To explore stacks and queues. Read and Discover Type, build and run the following code. Answer the questions that follow.
//=========================================================================
// Name : prelab5_a.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : stack in c++
// Date :
//=========================================================================
1 #include<iostream.h>
2 #include<stdlib.h>
3 #define max 5
4
5 class stack
6 {
7 int e[max];
8 int top, i;
9
10 public:
11 stack()
12 {
13 top=0;
14 }
15 void push(int n);
16 int pop();
17 void show();
18
19 };
20
21 void stack::push(int n)
22 {
23 if(top==max)
24 {
25 cout<<"Stack overflow..."<<endl;
26 exit(0);
27 }
28
29 else
30 e[top++]=n;
31
32 }
33
34 int stack::pop()
35 {
36 if(top==0)
37 {
38 cout<<"Stack underflow..."<<endl;
39 exit(0);
40 }
41
42 else
43 return e[--top];
44 }
45
60
S T A C K S & Q U E U E S 46 void stack :: show()
47 {
48 for(i=0; i<top; i++)
49 cout<<" "<<e[i];
50 }
51
52 int main()
53 {
54 stack s;
55 int n,choice;
56 do
57 {
58 cout<<endl;
59 cout<<"Enter choice:"<<endl;
60 cout<<"1. Push"<<endl;
61 cout<<"2. Pop"<<endl;
62 cout<<"3. Exit"<<endl;
63 cin>>choice;
64
65 switch(choice)
66 {
67 case 1:
68 {
69 cout<<"Enter number:"<<endl;
70 cin>>n;
71 s.push(n);
72 s.show();
73 }
74 break;
75
76 case 2:
77 {
78 s.pop();
79 s.show();
80 }
81 break;
82
83 case 3:
84 cout<<"The program is now exited."<<endl;
85 break;
86
87 default:
88 cout<<"Your choice is out of range."<<endl;
89 cout<<"Please try it again."<<endl;
90 }
91 }
92 while(choice!=3);
93
94 return 0;
95 }
1. Choose option 1 to push these numbers in the stack (23, 78, 920, 390, 3082). What is the output? Draw the stack.
61
P R E - L A B O R A T O R Y 5
2. Choose option 1 to push these numbers in the stack again (23, 78, 920, 390, 3082, 76). What is the output?
3. Enter these numbers in the stack (23, 78, 920, 390, 3082). Choose option two to pop all the numbers. After pop for 5 times what is the result? Draw the stack.
4. Pop for the 6th time and what is the result?
5. Name the operations that exist in the program.
6. Stacks implement what abstract data type and data structure?
62
S T A C K S & Q U E U E S
//=========================================================================
// Name : prelab5_b.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : stacks in c++
// Date :
//=========================================================================
1 #include<iostream.h>
2 #define MAX 7
3
4 class queue
5 {
6 int a[MAX];
7 int front, rear;
8 public:
9 queue()
10 {
11 front=0;
12 rear=0;
13 }
14
15 void enqueue(int n);
16 void dequeue();
17 void display();
18 };
19
20 Void queue::enqueue(int n)
21 {
22 if(rear==MAX)
23 cout<<"Queue overflow.."<<endl;
24 else
25 {
26 a[rear]=n;
27 rear++;
28 }
29 }
30
31 void queue::dequeue()
32 {
33 if(front==rear)
34 cout<<"Queue underflow. Enqueue first."<<endl;
35 else
36 {
37 cout<<"Removed "<<a[front]<<endl;
38 front++;
39 }
40 }
41
42 void queue::display()
43 {
44 cout<<"The Queue contains:"<<endl;
45 for(int i=front; i<rear; i++)
46 cout<<" "<<a[i];
47 cout<<endl;
48 }
49
50 int main()
51 {
52 queue s;
53 int n,choice;
54 do
63
P R E - L A B O R A T O R Y 5
55 {
56 cout<<"Enter choice:"<<endl;
57 cout<<"1. Enqueue"<<endl;
58 cout<<"2. Dequeue"<<endl;
59 cout<<"3. Exit"<<endl;
60 cin>>choice;
61
62 switch(choice)
63 {
64 case 1:
65 cout<<"Enter number:"<<endl;
66 cin>>n;
67 s.enqueue(n);
68 s.display();
69 break;
70
71 case 2:
72 s.dequeue();
73 s.display();
74 break;
75
76 case 3:
77 cout<<"The program is now exited."<<endl;
78 break;
79
80 default:
81 cout<<"Your choice is out of range."<<endl;
82 cout<<"Please try it again."<<endl;
83 break;
84 }
85 }
86
87 while(choice!=3);
88
89 return 0;
90 }
7. Choose option 1 to enqueue these numbers in the queue (77, 32, 103, 8, 1028, 90, 2703). What is the output? Draw the queue.
8. Choose option two to dequeue the numbers. Dequeue 3 times. What is the
result? Draw the queue.
64
S T A C K S & Q U E U E S
9. Dequeue again for 5 times. What is the result?
10. Name the operations that exist in the program.
11. Queues implement what abstract data type and data structure?
65
L A B O R A T O R Y 5
Objective
1. To explore the application of stacks and queues. Read and Discover Type, build and run the following code. Copy the screen output of the program to the corresponding space provided. Answer the questions that follow. //=========================================================================
// Name : lab5_a.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : infix to postfix in c++
// Date :
//=========================================================================
1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 bool error(string );
6 void check();
7 void topostfix(string );
8 void push(string );
9 void pop(string );
10
11 int priority=0;
12
13 string postfix, stack, stack1;
14
15 int main()
16 {
17 string expression;
18
19 cout << "Enter in your expression to be converted from infix to
20 postfix\nEnter in zero to end the loop\n";
21 cin >> expression;
22
23 if (error(expression))
24 {
25 cout << "Program will not execute expression is incorrect\n";
26 }
27 else
28 {
29 topostfix(expression);
30 cout << "Here is your postfix expression " << postfix << endl;
31 }
32
33 return 0;
34 }
35
36 void topostfix(string expression)
37 {
38 string here, number, hold, again=expression;
39 cout << "\nSTART\n";
40
41 for (int a=0; a < expression.length(); a++)
42 {
43 number = here = expression[a];
44 cout << "The expression " << here << endl;
45 cout << "The postfix " << postfix << endl;
66
S T A C K S & Q U E U E S
46
47 if ( expression[a] == '+' || expression[a] == '-')
48 {
49 if (priority <= 2 )
50 {
51 pop(here); push(here);
52 }
53 else push(here);
54 }
55 else if ( expression[a] == '*' || expression[a] == '/' ||
56 expression[a] == '%' )
57 {
58 if (priority == 1 )
59 {
60 here=stack[0]; stack[0]=expression[a]; postfix =
61 postfix + here;
62 }
63 else push(here);
64 }
65
66 else if ( expression[a] == '(' ) push(here);
67 else if ( expression[a] == ')' ) pop(here);
68 else if ( isdigit(again[a]) )
69 {
70 if ( isdigit(again[a+1]) )
71 {
72 int b=a+1;
73 while ( isdigit(again[b]) )
74 {
75 hold=again[b];
76 number = number + hold;
77 ++b;
78 }
79
80 postfix = postfix + ' ' + number;
81 a=b-1;
82
83 }
84
85 else
86 {
87 postfix = postfix + ' ' + number;
88 }
89 }
90
91 cout << "\nPOSTFIX "<< postfix << endl;
92 }
93
94 postfix = postfix + ' ' + stack;
95 }
96
97 void check ()
98 {
99 cout << "This is the first element " << stack[0] << endl;
100 switch (stack[0])
101 {
102 case '*':
103 case '/':
104 case '%':
105 priority=1; break;
106 case '+':
67
L A B O R A T O R Y 5
107 case '-':
108 priority=2; break;
109 };
110 }
111
112 void push(string oper)
113 {
114 string empty;
115 cout << "\nPUSH\n";
116
117 if ( oper == "(" )
118 {
119 stack1=stack;
120 stack=empty;
121 }
122
123 else
124 {
125 stack = oper + ' ' + stack;
126 }
127
128 check();
129 }
130
131 void pop(string oper)
132 {
133 int end=0;
134 string empty;
135
136 if (stack.empty() ) cout <<"\nDirectory is Empty\n";
137 else
138 {
139 if ( ")" == oper )
140 {
141 postfix = postfix + ' ' + stack;
142 stack=stack1;
143 }
144
145 else
146 {
147 postfix = postfix + ' ' + stack;
148 stack = empty; priority=0;
149 }
150
151 cout << "\nPOP\n";
152 check();
153
154 }
155 }
156
157 bool error(string expression)
158 {
159 int count=0, count1=0, len=expression.length(), a=0, b=0;
160
161 while (a <= len)
162 {
163 if ( expression[a] == '(' )
164 {
165 ++count;
166 }
167 ++a;
68
S T A C K S & Q U E U E S
168 }
169
170 while (b <= len)
171 {
172 if ( expression[b] == ')' )
173 {
174 ++count1;
175 }
176 ++b;
177 }
178
179 if (count == count1)
180 return false;
181 else return true;
182 }
Infix Postfix
1. 3+4*5/6
2. (300+23)*(43-21)/(84+7)
3. 10*(50+7)-15/3
4. (15+3-7)*4-(8+10)
//=========================================================================
// Name : lab5_b.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : postfix to infix in c++
// Date :
//=========================================================================
1 #include <iostream>
2 #include <string>
3 #include <stdlib.h>
4 #include <conio.h>
5
6 using namespace std;
7
8 int top=-1;
9
10 char Stack[25][100]={NULL};
11
12 void push(const char *);
13 const char* pop( );
14
15 void postfix_to_infix(const char*);
16
17 int main( )
18 {
19 char Postfix_expression[100]={NULL};
20 cout<<"\n Enter the Postfix Expression : ";
21 cin.getline(Postfix_expression,80);
22
23 postfix_to_infix(Postfix_expression);
24
69
L A B O R A T O R Y 5
25 getch( );
26 return 0;
27 }
28
29 void push(const char* Symbol)
30 {
31 if (top==24)
32 {
33 cout<<"Error : Stack is full."<<endl;
34 }
35 else
36 {
37 top++;
38 strcpy(Stack[top],Symbol);
39 }
40 }
41
42 const char* pop( )
43 {
44 char Symbol[100]={NULL};
45 if(top==-1)
46 cout<<"Error : Stack is empty."<<endl;
47 else
48 {
49 strcpy(Symbol,Stack[top]);
50 strset(Stack[top],NULL);
51 top--;
52 }
53
54 return Symbol;
55 }
56
57 void postfix_to_infix(const char* Postfix)
58 {
59 char Infix_expression[100]={NULL};
60 char Postfix_expression[100]={NULL};
61
62 strcpy(Postfix_expression,Postfix);
63 strcat(Postfix_expression,"=");
64
65 int count=0;
66 char Symbol_scanned[5]={NULL};
67
68 do
69 {
70 Symbol_scanned[0]=Postfix_expression[count];
71
72 if(Symbol_scanned[0]=='/' || Symbol_scanned[0]=='*' ||
73 Symbol_scanned[0]=='-' || Symbol_scanned[0]=='+' ||
74 Symbol_scanned[0]=='^' )
75
76 {
77 char Value_1[100]={NULL};
78 char Value_2[100]={NULL};
79 char Result[100]={NULL};
80
81 strcpy(Value_1,pop( ));
82 strcpy(Value_2,pop( ));
83
84 if(Infix_expression[(count+1)]!='=')
85 strcpy(Result,"(");
70
S T A C K S & Q U E U E S
86
87 strcat(Result,Value_2);
88 strcat(Result,Symbol_scanned);
89 strcat(Result,Value_1);
90
91 if(Infix_expression[(count+1)]!='=')
92 strcat(Result,")");
93
94 push(Result);
95 }
96
97 else
98 push(Symbol_scanned);
99
100 count++;
101 }
102
103 while(Postfix_expression[count]!='=');
104 strset(Infix_expression,NULL);
105 strcpy(Infix_expression,pop( ));
106
107 cout<<"\n\n\t Infix Expression is : "<<Infix_expression;
108 }
Postfix Infix
5. 37+2/
6. 37+24+/
7. 375/-4+37+/
8. 157+*943-*/
//=========================================================================
// Name : lab5_c.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : postfix to prefix in c++
// Date :
//=========================================================================
1 #include <iostream>
2 #include <string>
3 #include <stdlib.h>
4 #include <conio.h>
5
6 using namespace std;
7
8 #define MAX 50
9
10 struct postfix
11 {
12 char stack[MAX][MAX], target[MAX];
13 char temp1[2], temp2[2];
14 char str1[MAX], str2[MAX], str3[MAX];
15 int i, top;
16 };
71
L A B O R A T O R Y 5
17
18 void initpostfix (struct postfix*);
19 void setexpr (struct postfix*, char*);
20 void push (struct postfix*, char*);
21 void pop (struct postfix*, char*);
22 void convert (struct postfix*);
23 void show (struct postfix );
24
25 int main( )
26 {
27 struct postfix q;
28 char expr[MAX];
29
30 initpostfix (&q);
31
32 cout << "\nEnter an expression in postfix form: ";
33 gets (expr);
34
35 setexpr (&q, expr);
36 convert (&q);
37
38 cout << "\nThe Prefix expression is: ";
39 show (q);
40
41 getch();
42
43 return 0;
44 }
45
46 void initpostfix (struct postfix *p)
47 {
48 p -> i = 0;
49 p -> top = -1;
50 strcpy ( p -> target, "" );
51 }
52
53 void setexpr (struct postfix *p, char *c)
54 {
55 strcpy ( p -> target, c );
56 }
57
58 void push (struct postfix *p, char *str)
59 {
60 if (p -> top == MAX - 1)
61 cout <<"\nStack is full.";
62 else
63 {
64 p -> top++;
65 strcpy (p -> stack[p -> top], str);
66 }
67 }
68
69 void pop (struct postfix *p, char *a)
70 {
71 if ( p -> top == -1 )
72 cout <<"\nStack is empty.";
73 else
74 {
75 strcpy (a, p -> stack[p -> top]);
76 p -> top--;
77 }
72
S T A C K S & Q U E U E S
78 }
79
80 void convert (struct postfix *p)
81 {
82 while (p -> target[p -> i] != '\0')
83 {
84 if (p -> target[p -> i] == ' ')
85 p -> i++;
86 if(p -> target[p -> i] == '%' || p -> target[p -> i] == '*' ||
87 p -> target[p -> i] == '-' || p -> target[p -> i]
88 == '+' ||
89 p -> target[p -> i] == '/' || p -> target[p -> i]
90 == '$')
91 {
92 pop (p, p -> str2);
93 pop (p, p -> str3);
94 p -> temp1[0] = p -> target[ p -> i];
95 p -> temp1[1] = '\0';
96 strcpy (p -> str1, p -> temp1);
97 strcat (p -> str1, p -> str3);
98 strcat (p -> str1, p -> str2);
99 push (p, p -> str1);
100 }
101 else
102 {
103 p -> temp1[0] = p -> target[p -> i];
104 p -> temp1[1] = '\0';
105 strcpy ( p -> temp2, p -> temp1 );
106 push ( p, p -> temp2 );
107 }
108 p -> i++;
109 }
110 }
111
112 void show (struct postfix p)
113 {
114 char *temp = p.stack[0];
115 while (*temp)
116 {
117 cout << *temp;
118 temp++ ;
119 }
120 }
Postfix Prefix
9. 37+2/
10. 37+24+/
11. 375/-4+37+/
12. 157+*943-*/
73
L A B O R A T O R Y 5
/=========================================================================
// Name : lab5_d.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : infix to prefix in c++
// Date :
//=========================================================================
1 #include <iostream>
2 #include <string>
3
4 using namespace std;
5
6 #define MAX 50
7
8 struct infix
9 {
10 char target[MAX];
11 char stack[MAX];
12 char *s, *t;
13 int top, l;
14 } ;
15
16 void initinfix ( struct infix * );
17 void setexpr ( struct infix *, char * );
18 void push ( struct infix *, char );
19 char pop ( struct infix * );
20 void convert ( struct infix * );
21 int priority ( char c );
22 void show ( struct infix );
23
24 int main( )
25 {
26 struct infix q;
27 char expr[MAX];
28
29 initinfix ( &q );
30
31 cout << "\nEnter an expression in infix form: ";
32 gets ( expr );
33
34 setexpr ( &q, expr );
35 convert ( &q );
36
37 cout << "The Prefix expression is: ";
38 show ( q );
39
40 return 0;
41 }
42
43 void initinfix ( struct infix *pq )
44 {
45 pq -> top = -1 ;
46 strcpy ( pq -> target, "" );
47 strcpy ( pq -> stack, "" );
48 pq -> l = 0 ;
49 }
50
51 void setexpr ( struct infix *pq, char *str )
52 {
53 pq -> s = str;
54 strrev ( pq -> s );
74
S T A C K S & Q U E U E S
55 pq -> l = strlen ( pq -> s );
56 *( pq -> target + pq -> l ) = '\0';
57 pq -> t = pq -> target + ( pq -> l - 1 );
58 }
59
60 void push ( struct infix *pq, char c )
61 {
62 if ( pq -> top == MAX - 1 )
63 printf ( "\nStack is full.\n" );
64 else
65 {
66 pq -> top++;
67 pq -> stack[pq -> top] = c;
68 }
69 }
70
71 char pop ( struct infix *pq )
72 {
73 if ( pq -> top == -1 )
74 {
75 printf ( "Stack is empty\n" );
76 return -1;
77 }
78 else
79 {
80 char item = pq -> stack[pq -> top];
81 pq -> top--;
82 return item ;
83 }
84 }
85
86 void convert ( struct infix *pq )
87 {
88 char opr;
89
90 while ( *( pq -> s ) )
91 {
92 if ( *( pq -> s ) == ' ' || *( pq -> s ) == '\t' )
93 {
94 pq -> s++;
95 continue;
96 }
97
98 if ( isdigit ( *( pq -> s ) ) || isalpha ( *( pq -> s ) ) )
99 {
100 while ( isdigit ( *( pq -> s ) ) || isalpha ( *( pq -> s )
101 ) )
102 {
103 *( pq -> t ) = *( pq -> s );
104 pq -> s++;
105 pq -> t--;
106 }
107 }
108
109 if ( *( pq -> s ) == ')' )
110 {
111 push ( pq, *( pq -> s ) );
112 pq -> s++ ;
113 }
114
75
L A B O R A T O R Y 5
115 if ( *( pq -> s ) == '*' || *( pq -> s ) == '+' || *( pq -> s
116 ) == '/' ||
117 *( pq -> s ) == '%' || *( pq -> s ) == '-' || *( pq -> s
118 ) == '$' )
119 {
120 if ( pq -> top != -1 )
121 {
122 opr = pop ( pq );
123
124 while ( priority ( opr ) > priority ( *( pq -> s ) ) )
125 {
126 *( pq -> t ) = opr;
127 pq -> t-- ;
128 opr = pop ( pq );
129 }
130 push ( pq, opr ) ;
131 push ( pq, *( pq -> s ) );
132 }
133 else
134 push ( pq, *( pq -> s ) );
135 pq -> s++ ;
136 }
137
138 if ( *( pq -> s ) == '(' )
139 {
140 opr = pop ( pq );
141 while ( opr != ')' )
142 {
143 *( pq -> t ) = opr;
144 pq -> t-- ;
145 opr = pop ( pq );
146 }
147 pq -> s++;
148 }
149 }
150
151 while ( pq -> top != -1 )
152 {
153 opr = pop ( pq );
154 *( pq -> t ) = opr;
155 pq -> t-- ;
156 }
157 pq -> t++ ;
158 }
159
160 int priority ( char c )
161 {
162 if ( c == '$' )
163 return 3;
164 if ( c == '*' || c == '/' || c == '%' )
165 return 2;
166 else
167 {
168 if ( c == '+' || c == '-' )
169 return 1;
170 else return 0;
171 }
172 }
173
174 void show ( struct infix pq )
175 {
76
S T A C K S & Q U E U E S
176 while ( *( pq.t ) )
177 {
178 printf ( " %c", *( pq.t ) );
179 pq.t++;
180 }
181 }
Infix Prefix
13. 10/5-7+14*20-10*7
14. 10*(5+7)*14
15. 10+5*7
16. 10*(5+7)/(14*(20-3))
77
P O S T- L A B O R A T O R Y 5
Objectives 1. To explore Classes and Objects 2. To explore Functions 3. To explore Unary Scope Resolution Operation 4. To explore Arrow Member Selection Operator 5. To explore Pointers
Read and Discover Type and execute the following code. Copy the screen output of the program to the corresponding space provided, and answer the questions that follow.
Part 1 //=========================================================================
// Name : postlab6_a.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : classes and objects
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 class Greetings{
5 public:
6 void coolsaying(){
7 cout<<"It's more fun in the Philippines!" << endl;
8 }
9 void coolsaying2()
10 {
11 cout<<"Hello planet!" << endl;
12 }
13 void say(){
14 cout<<"Goodbye World!" << endl;
15 }
16 };
17
18 int main()
19 {
20 Greetings howdy;
21 howdy.coolsaying();
22 howdy.coolsaying2();
23 howdy.say();
24 }
1. What is the output of the program?
78
S T A C K S & Q U E U E S //=========================================================================
// Name : postlab6_b.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : Functions Part 1
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 void Display();//function prototyping
5
6 int main()
7 {
8 Display();
9 }
10
11 void Display(){
12 cout <<"It's more fun in the Philippines" << endl;
13 }
2. What is the output of the program?
//=========================================================================
// Name : postlab6_c.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : functions part 2
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 void Display(){
5 cout <<"It's more fun in the Philippines" << endl;
6 }
7
8 int main()
9 {
10 Display();
11 }
3. What is the output of the program?
79
P O S T- L A B O R A T O R Y 5
//=========================================================================
// Name : postlab6_d.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : functions part 3
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 void Display(int x){
5 cout <<"My fav's number is " << x << endl;
6 }
7
8 int main()
9 {
10 Display(24);
11
12 }
4. What is the output of the program?
//=========================================================================
// Name : postlab6_e.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : functions part 4
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 void Display(int x);
5
6 int main()
7 {
8 Display(674);
9
10 }
11
12 void Display(int x){
13 cout <<"My fav's number is " << x << endl;
14
15 }
80
S T A C K S & Q U E U E S
5. What is the output of the program? //=========================================================================
// Name : postlab6_f.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : functions part 5(multiple parameters)
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int addNumbers(int a, int b, int c);
5
6 int main()
7 {
8 cout << "The answer is " << addNumbers(10,20,15) << endl;
9
10 }
11
12 int addNumbers(int a, int b, int c){
13 int answer = (a + b) / c ;
14 return answer;
15
16 }
6. What is the output of the program? //=========================================================================
// Name : postlab6_g.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : functions part 6
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int addNumbers(int a, int b, int c, int d);
5
6 int main()
7 {
8 cout << "The answer is " << addNumbers(10,20,15,5) << endl;
9
81
P O S T- L A B O R A T O R Y 5
10 }
11
12 int addNumbers(int a, int b, int c, int d){
13 int answer = (a + b) - (c + d) ;
14 return answer;
15
16 }
7. What is the output of the program?
//=========================================================================
// Name : postlab6_h.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : unary scope resolution operator Part 1
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int tuna = 100;// global variable tuna
5
6 int main()
7 {
8
9 int tuna = 53;// local variable tuna
10 cout << tuna << endl;
11
12 }
8. What is the output of the program?
82
S T A C K S & Q U E U E S //=========================================================================
// Name : postlab6_i.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : unary scope resolution operator Part 2
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int tuna = 100;
5
6 int main()
7 {
8
9 double tuna = 53.4342;
10 cout << ::tuna << endl;
11
12 }
9. What is the output of the program?
10. What is the difference between the output of scope part 1 and scope part 2? //=========================================================================
// Name : postlab6_j.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : pointers part 1
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int main()
5 {
6 int arowana = 5;
7 cout << &arowana << endl;
8 }
83
P O S T- L A B O R A T O R Y 5
11. What is the output of the program?
//=========================================================================
// Name : postlab6_k.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : pointers part 2
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int main()
5 {
6 int arowana = 5;
7 cout << &arowana << endl;//print the memory address of the variable
8
9 int *salmon;
10 salmon = &arowana;
11 cout << salmon << endl;
12
13 }
12. What is the output of the program?
//=========================================================================
// Name : postlab6_l.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : pointers part 3
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int main()
5 {
6 int kingfisher[5];
7 int *basePointer0 = &kingfisher[0];//memory address
8 int *basePointer1 = &kingfisher[1];
9 int *basePointer2 = &kingfisher[2];
10
11 cout << "basePointer0 is at " << basePointer0 << endl;
12 cout << "basePointer1 is at " << basePointer1 << endl;
84
S T A C K S & Q U E U E S
13 cout << "basePointer2 is at " << basePointer2 << endl;
14
15 basePointer0 += 2;
16
17 cout << "basePointer0 is now at " << basePointer0 << endl;
18 }
13. What is the output of the program?
//=========================================================================
// Name : postlab6_m.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : pointers part 4
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int main()
5 {
6 int kingfisher[5];
7 int *basePointer0 = &kingfisher[0];//memory address
8 int *basePointer1 = &kingfisher[1];
9 int *basePointer2 = &kingfisher[2];
10
11 cout << "basePointer0 is at " << basePointer0 << endl;
12 cout << "basePointer1 is at " << basePointer1 << endl;
13 cout << "basePointer2 is at " << basePointer2 << endl;
14
15 basePointer0 ++;
16
17 cout << "basePointer0 is now at " << basePointer0 << endl;
18 }
14. What is the output of the program?
85
P O S T- L A B O R A T O R Y 5
15. What observation can you make between the result of Pointer Part 3 and Part 4?
//=========================================================================
// Name : postlab6_n.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : pointers part 5
// Date :
//=========================================================================
1 #include <iostream>
2 using namespace std;
3
4 int main()
5 {
6 int kingfisher = 100;
7 int *basePointer0 = &kingfisher;//memory address
8
9 cout << "basePointer0 is at " << basePointer0 << endl;
10 cout << "kingfisher is at " << &kingfisher << endl;
11 cout << "the value of kingfisher is " << *basePointer0 << endl;
12
13 }
16. What is the output of the program?
86
S T A C K S & Q U E U E S
Part 2
Arrow Member Selection Operator
1. Go to File -> New -> Class…
Figure 1
2. In Figure 2, type the name of the class. The class name is kingfisher. 3. Unchecked the Has destructor and Virtual destructor. 4. Under the File Policy, checked the Header and implementation file shall be in the
same folder. 5. Click Create.
Figure 2
6. In Figure 3, after the user clicked Create, click Yes to Add to project.
87
P O S T- L A B O R A T O R Y 5
7. Click OK once the Multiple Selection window box appears.
Figure 3
Figure 4
8. In Figure 4, you have 3 window tabs. Namely, main.cpp, kingfisher.h and
kingfisher.cpp. 9. Type all the codes below for the three window tabs.
In main.cpp write this code //main.cpp 1 #include <iostream>
2 #include "kingfisher.h"
3 using namespace std;
4
88
S T A C K S & Q U E U E S
5 int main()
6 {
7 kingfisher kingObject;
8 kingfisher *kingPointer = &kingObject;
9
10 kingObject.display();//accessing with an object
11 kingPointer->display();//accessing with a pointer
12 }
In kingfisher.h write this code //kingfisher.h 1 #ifndef KINGFISHER_H
2 #define KINGFISHER_H
3
4 class kingfisher
5 {
6 public:
7 kingfisher();
8 void display();
9 protected:
10 private:
11 };
12
13 #endif // KINGFISHER_H
In kingfisher.cpp write this code //kingfisher.cpp 1 #include "kingfisher.h"
2 #include <iostream>
3 using namespace std;
4
5 kingfisher::kingfisher()
6 {
7
8 }
9
10 void kingfisher::display(){
11 cout << "It's more fun in the Philippines. " << endl;
12
13 }
17. What is the output of the program?
89
6 Graphs
90
L A B O R A T O R Y 6
Objective
1. To be able to implement BFS and DFS. 2. To explore minimum spanning trees particularly Prim and Kruskal’s Algorithm.
Read and Discover Type, build and run the following code. Copy the screen output of the program to the corresponding space provided. Answer the questions that follow. //=========================================================================
// Name : lab6_a.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : depth-first search in c++
// Date :
//=========================================================================
1 #include<iostream.h>
2
3 int visit[100];
4 class graph
5 {
6 private:
7 int n;
8 graph*next;
9
10 public:
11 graph* read_graph(graph*);
12
13 void dfs(int);
14 void dfs();
15 void ftraverse(graph*);
16 }
17 *g[100];
18
19 graph* graph::read_graph(graph*head)
20 {
21 int x;
22 graph*last;
23 head=last=NULL;
24
25 cout<<"Enter adjacent node ,-1 to stop:\n";
26 cin>>x;
27 while(x!=-1)
28 {
29 graph*NEW;
30 NEW=new graph;
31 NEW->n=x;
32 NEW->next=NULL;
33
34 if(head==NULL)
35 head=NEW;
36 else
37 last->next=NEW;
38 last=NEW;
39
40 cout<<"Enter adjacent node ,-1 to stop:\n";
41 cin>>x;
91
G R A P H S
42 }
43
44 return head;
45 }
46
47 void graph::ftraverse(graph*h)
48 {
49 while(h!=NULL)
50 {
51 cout<<h->n<<"->";
52 h=h->next;
53 }
54
55 cout<<"NULL"<<endl;
56 }
57
58 void graph::dfs(int x)
59 {
60 cout<<"node "<<x<<" is visited\n";
61 visit[x]=1;
62
63 graph *p;
64 p=g[x];
65 while(p!=NULL)
66 {
67 int x1=p->n;
68 if(visit[x1]==0)
69 {
70 cout<<"from node "<<x<<' ';
71 dfs(x1);
72 }
73
74 p=p->next;
75 }
76 }
77
78 void graph::dfs()
79 {
80 int i;
81 cout<<"**********************************************************\n";
82 cout<<"This program is to implement dfs for an unweighted graph \n";
83 cout<<"**********************************************************\n";
84 cout<<"Enter the no of nodes ::";
85 cin>>n;
86
87 for(i=1;i<=n;i++)
88 g[i]=NULL;
89
90 for(i=1;i<=n;i++)
91 {
92 cout<<"\nEnter the adjacent nodes to node no. "<<i<<endl;
93 cout<<"***************************************\n";
94 g[i]=read_graph(g[i]);
95 }
96
97 cout<<"\n\nThe entered graph is ::\n";
98 for(i=1;i<=n;i++)
99 {
100 cout<<" < "<<i<<" > ::";
101 ftraverse(g[i]);
102 }
92
L A B O R A T O R Y 6
103
104 for(i=1;i<=n;i++)
105 visit[i]=0;
106
107 cout<<"\nEnter the start vertex ::";
108 int start;
109 cin>>start;
110
111
112 cout<<"\nThe dfs for the above graph is ::\n";
113 dfs(start);
114
115 }
116
117 int main()
118 {
119 graph obj;
120 obj.dfs();
121 return 0;
121 }
Given the graphs on the next page:
Run the program and perform DFS on each of the graphs. Show the output by generating their traversals.
Run the program and perform BFS on each of the graphs. Show the output by generating their traversals.
Note: For graph G1, start on node 1 For graph G2, G4 & G5 start on node 2 For graph G3, start on node 8
G1 G2
93
G R A P H S
G3
G4 G5
1. For G1, write the output below.
94
L A B O R A T O R Y 6
2. For G2, write the output below.
3. For G3, write the output below.
4. For G4, write the output below.
95
G R A P H S
5. For G5, write the output below.
//=========================================================================
// Name : lab6_b.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : breadth-first search in c++
// Date :
//=========================================================================
1 #include<iostream.h>
2
3 class Queue
4 {
5 private:
6 int data;
7 Queue*next;
8
9 public:
10 void Enque(int);
11 int Deque();
12 } *head,*tail;
13
14 void Queue::Enque(int data)
15 {
16 Queue *temp;
17 temp=new Queue;
18 temp->data=data;
19 temp->next=NULL;
20 if(head==NULL)
21 head=temp;
22 else
23 tail->next=temp;
24 tail=temp;
25 }
26
27 int Queue::Deque()
28 {
29 Queue* temp;
30 temp=head;
31 head=head->next;
32 return temp->data;
33 }
34
35 int visit[100];
36
96
L A B O R A T O R Y 6
37 class graph
38 {
39 private:
40 int a;
41 graph*next;
42 public:
43 void bfs();
44 graph* create(graph*);
45 void ftraverse(graph*);
46 };
47
48 graph* graph::create(graph*head)
49 {
50 int a;
51 graph*last;
52 head=last=NULL;
53 graph*temp;
54 cout<<"Enter adjacent node, -1 to stop:\n";
55 cin>>a;
56 while(a!=-1)
57 {
58 temp=new graph;
59 temp->a=a;
60 temp->next=NULL;
61 if(head==NULL)
62 head=temp;
63 else
64 last->next=temp;
65 last=temp;
66
67 cout<<"Enter adjacent node, -1 to stop:\n";
68 cin>>a;
69 }
70
71 return head;
72 }
73
74 void graph::ftraverse(graph*h)
75 {
76 while(h!=NULL)
77 {
78 cout<<h->a<<"->";
79 h=h->next;
80 }
81 cout<<"NULL\n";
82 }
83
84 void graph::bfs()
85 {
86 cout<<"**********************************************************\n";
87 cout<<"This program is to implement bfs for an unweighted graph \n";
88 cout<<"**********************************************************\n";
89
90 graph *ptr[100];
91 int i, n;
92
93 cout<<"Enter the no. of nodes in the graph:";
94 cin>>n;
95
96 for(int i=1;i<=n;i++)
97 {
97
G R A P H S
98 cout<<"\nEnter the adjacent nodes to node no. "<<i<<endl;
99 cout<<"***************************************\n";
100 ptr[i]=create(ptr[i]);
101 }
102
103 cout<<"\n\nThe Entered Graph is ::\n";
104 for(i=1;i<=n;i++)
105 {
106 cout<<"< "<<i<<" > ::";
107 ftraverse(ptr[i]);
108 }
109
110 int x;
111 cout<<"\nEnter the start node <1,"<<n<<">:";
112 cin>>x;
113 cout<<"\n\nThe Breadth first search traversal is:\n";
114 Queue object;
115
116 for(i=1;i<=n;i++)
117 {
118 visit[i]=0;
119 }
120
121 object.Enque(x);
122
123 int p;
124 while(head!=NULL&&tail!=NULL)
125 {
126 p=object.Deque();
127 int x=p;
128
129 while(ptr[p]!=NULL)
130 {
131 if(visit[ptr[p]->a]!=1)
132 {
133 cout<<"node "<<ptr[p]->a<<" is visited\n";
134 visit[ptr[p]->a]=1;
135 }
136
137 object.Enque(ptr[p]->a);
138 ptr[p]=ptr[p]->next;
139 }
140 }
141
142 cout<<endl;
143 }
144
145 int main()
146 {
147 graph obj;
148 obj.bfs();
149 return 0;
150 }
98
L A B O R A T O R Y 6
6. For G1, write the output below.
7. For G2, write the output below.
8. For G3, write the output below.
99
G R A P H S
9. For G4, write the output below.
10. For G5, write the output below.
//=========================================================================
// Name : lab6_c.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : Prim’s Algorithm in c++
// Date :
//=========================================================================
1 #include<iostream.h>
2
3 class prims
4 {
5 private:
6 int n;
7 int graph_edge[250][4];
8 int g;
9 int tree_edge[250][4];
10 int t;
11 int s;
12 int i;
13 int T1[50],t1;
14 int T2[50],t2;
15
16 public:
17 void input();
18 int findset(int);
19 void algorithm();
100
L A B O R A T O R Y 6
20 void output();
21 };
22
23 void prims::input()
24 {
25 cout<<"*************************************************\n";
26 cout<<"This program implements prims algorithm\n";
27 cout<<"*************************************************\n";
28 cout<<"Enter the no. of nodes in the undirected weighted graph ::";
29 cin>>n;
30 g=0;
31
32 cout<<"Enter the weights for the following edges ::\n";
33 for(int i=1;i<=n;i++)
34 {
35 for(int j=i+1;j<=n;j++)
36 {
37 cout<<" < "<<i<<" , "<<j<<" > ::";
38 int w;
39 cin>>w;
40 if(w!=0)
41 {
42 g++;
43
44 graph_edge[g][1]=i;
45 graph_edge[g][2]=j;
46 graph_edge[g][3]=w;
47 }
48 }
49 }
50
51 cout<<"\n\nThe edges in the given graph are::\n";
52 for(i=1;i<=g;i++)
53 cout<<" < "<<graph_edge[i][1] <<" , "<<graph_edge[i][2] <<" >
54 ::"<<graph_edge[i][3]<<endl;
55 }
56
57 int prims::findset(int x)
58 {
59 for(int i=1;i<=t1;i++)
60 if(x==T1[i])
61 return 1;
62
63 for(i=1;i<=t2;i++)
64 if(x==T2[i])
65 return 2;
66 return -1;
67 }
68
69 void prims::algorithm()
70 {
71 t=0;
72 t1=1;
73 T1[1]=1;
74 t2=n-1;
75 int i;
76 for(i=1;i<=n-1;i++)
77 T2[i]=i+1;
78 cout<<"\n*****The algorithm starts*****\n\n";
79 while(g!=0 && t!=n-1)
80 {
101
G R A P H S
81 int min=9999;
82 int p;
83 int u,v,w;
84 for(i=1;i<=g;i++)
85 {
86 bool flag1=false,flag2=false;
87 if(findset(graph_edge[i][1])!=findset(graph_edge[i][2]))
88 {
89 if(min>graph_edge[i][3])
90 {
91 min=graph_edge[i][3];
92 u=graph_edge[i][1];
93 v=graph_edge[i][2];
94 w=graph_edge[i][3];
95 p=i;
96 }
97 }
98 }
99
100 cout<<"The edge included in the tree is ::";
101 cout<<" < "<<u<<" , "<<v<<" > "<<endl;
102
103 for(int l=p;l<g;l++)
104 {
105 graph_edge[l][1]=graph_edge[l+1][1];
106 graph_edge[l][2]=graph_edge[l+1][2];
107 graph_edge[l][3]=graph_edge[l+1][3];
108 }
109 g--;
110
111 t++;
112 tree_edge[t][1]=u;
113 tree_edge[t][2]=v;
114 tree_edge[t][3]=w;
115
116 t1++;
117
118 int m;
119 if(findset(v)==2)
120 {
121 T1[t1]=v;
122 m=v;
123 }
124 else if(findset(u)==2)
125 {
126 T1[t1]=u;
127 m=u;
128 }
129
130 int x;
131 for(x=1;T2[x]!=m;x++);
132 for(;x<t2;x++)
133 T2[x]=T2[x+1];
134 t2--;
135
136 int k;
137 cout<<"NOW\nT1 :: ";
138 for(k=1;k<=t1;k++)
139 cout<<T1[k]<<' ';
140 cout<<endl;
141
102
L A B O R A T O R Y 6
142 cout<<"T2 :: ";
143 for(k=1;k<=t2;k++)
144 cout<<T2[k]<<' ';
145 cout<<endl;
146
147 cout<<"The graph edges are ::\n";
148 for(i=1;i<=g;i++)
149 cout<<" < "<<graph_edge[i][1] <<" , "<<graph_edge[i][2]
150 <<" > ::"<<graph_edge[i][3]<<endl;
151 cout<<endl<<endl;
152
153 }
154 }
155
156 int main()
157 {
158 prims obj;
159 obj.input();
160 obj.algorithm();
161 return 0;
162 }
Given the graphs below:
Run the program and construct the minimum cost spanning tree by using Prim’s algorithm with starting node a(for G6), node A(for G7), and node E(for G8). Include the total cost of the resulting MST.
Run the program and construct the minimum cost spanning tree by using Kruskal’s algorithm. Include the total cost of the resulting MST.
Note: Lowest data value first.
G6
G7
103
G R A P H S
G8
11. For G6, write the output below.
12. For G7, write the output below.
104
L A B O R A T O R Y 6
13. For G8, write the output below.
//=========================================================================
// Name : lab6_d.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : Kruskal’s Algorithm in c++
// Date :
//=========================================================================
1 #include<iostream.h>
2
3 class kruskal
4 {
5 private:
6 int n;
7 int noe;
8 int graph_edge[100][4];
9 int tree[10][10];
10 int sets[100][10];
11 int top[100];
12
13 public:
14 void read_graph();
15 void initialize_span_t();
16 void sort_edges();
17 void algorithm();
18 int find_node(int );
19 void print_min_span_t();
20 };
21
22 void kruskal::read_graph()
23 {
24 cout<<"*************************************************\n" <<"This
25 program implements kruskal algorithm\n"
26 <<"*************************************************\n";
27 cout<<"Enter the no. of nodes in the undirected weighted graph ::";
28 cin>>n;
29
30 noe=0;
31
32 cout<<"Enter the weights for the following edges ::\n";
105
G R A P H S
33 for(int i=1;i<=n;i++)
34 {
35 for(int j=i+1;j<=n;j++)
36 {
37 cout<<" < "<<i<<" , "<<j<<" > ::";
38 int w;
39 cin>>w;
40 if(w!=0)
41 {
42 noe++;
43
44 graph_edge[noe][1]=i;
45 graph_edge[noe][2]=j;
46 graph_edge[noe][3]=w;
47 }
48 }
49 }
50
51 cout<<"\n\nThe edges in the given graph are::\n";
52 for( int i=1;i<=noe;i++)
53 cout<<" < "<<graph_edge[i][1] <<" , "<<graph_edge[i][2]<<" >
54 ::"<<graph_edge[i][3]<<endl;
55 }
56
57 void kruskal::sort_edges()
58 {
59 for(int i=1;i<=noe-1;i++)
60 {
61 for(int j=1;j<=noe-i;j++)
62 {
63 if(graph_edge[j][3]>graph_edge[j+1][3])
64 {
65 int t=graph_edge[j][1];
66 graph_edge[j][1]=graph_edge[j+1][1];
67 graph_edge[j+1][1]=t;
68 t=graph_edge[j][2];
69 graph_edge[j][2]=graph_edge[j+1][2];
70 graph_edge[j+1][2]=t;
71 t=graph_edge[j][3];
72 graph_edge[j][3]=graph_edge[j+1][3];
73 graph_edge[j+1][3]=t;
74 }
75 }
76 }
77
78 cout<<"\n\nAfter sorting the edges in the given graph are::\n";
79 for( int i=1;i<=noe;i++)
80 cout<<" < "<<graph_edge[i][1]<<" , "<<graph_edge[i][2]<<" >
81 ::"<<graph_edge[i][3]<<endl;
82 }
83
84 void kruskal::algorithm()
85 {
86 for(int i=1;i<=n;i++)
87 {
88 sets[i][1]=i;
89 top[i]=1;
90 }
91
92 cout<<"\nThe algorithm starts ::\n\n";
93
106
L A B O R A T O R Y 6
94 for( int i=1;i<=noe;i++)
95 {
96 int p1=find_node(graph_edge[i][1]);
97 int p2=find_node(graph_edge[i][2]);
98 if(p1!=p2)
99 {
100 cout<<"The edge included in the tree is ::"<<" <
101 "<<graph_edge[i][1]<<" , "<<graph_edge[i][2]<<" > "<<endl<<endl;
102 tree[graph_edge[i][1]][graph_edge[i][2]]=graph_edge[i][3];
103 tree[graph_edge[i][2]][graph_edge[i][1]]=graph_edge[i][3];
104
105 for(int j=1;j<=top[p2];j++)
106 {
107 top[p1]++;
108 sets[p1][top[p1]]=sets[p2][j];
109 }
110
111 top[p2]=0;
112 }
113 else
114 {
115 cout<<"Inclusion of the edge "<<" < <<graph_edge[i][1]<<"
116 , "<<graph_edge[i][2]<<" > "<<"forms a cycle so it is removed\n\n";
117 }
118 }
119 }
120
121 int kruskal::find_node(int n)
122 {
123 for(int i=1;i<=noe;i++)
124 {
125 for(int j=1;j<=top[i];j++)
126 {
127 if(n==sets[i][j])
128 return i;
129 }
130 }
131 return -1;
132 }
133
134 int main()
135 {
136 kruskal obj;
137 obj.read_graph();
138 obj.sort_edges();
139 obj.algorithm();
140 return 0;
141 }
107
G R A P H S
14. For G6, write the output below.
15. For G7, write the output below.
16. For G8, write the output below.
108
7 Trees
109
L A B O R A T O R Y 7
Objective
1. Traversing a binary tree using In order, Pre order and Post order in C++. 2. To know the different operations of tree walk.
Read and Discover Type, build and run the following code. Copy the screen output of the program to the corresponding space provided. Answer the questions that follow. //=========================================================================
// Name : lab7_a.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : trees using c++
// Date :
//=========================================================================
1 #include<iostream.h>
2
3 struct btree
4 {
5 struct btree *left;
6 struct btree *right;
7 int no;
8 };
9
10 void postorder(struct btree *trav);
11 void inorder(struct btree *trav);
12 void preorder(struct btree *trav);
13
14 struct btree * create(struct btree *trav);
15
16 main()
17 {
18 struct btree *root=NULL;
19 char c;
20 while(1)
21 {
22 root=create(root);
23 cout<<"Do you want to continue : ";
24 cin>>c;
25 if(c=='n' ||c=='N')
26 break;
27 }
28
29 cout<<endl<<"Inoder tree walk is : ";inorder(root);
30 cout<<endl<<"Preorder tree walk is : ";preorder(root);
31 cout<<endl<<"Postorder tree walk is : ";postorder(root);
32 }
33
34 struct btree * create(struct btree *trav)
35 {
36 if(trav==NULL)
37 {
38 trav=new btree;
39 trav->right=NULL;
40 trav->left=NULL;
41 cout<<"Enter the no : ";
42 cin>>trav->no;
110
T R E E S
43 return(trav);
44 }
45
46 char choice;
47 cout<<"Enter the left or right child : ";
48 cin>>choice;
49
50 if(choice == 'r' || choice == 'R')
51 {
52 trav->right=create(trav->right);
53 }
54
55 if(choice=='l' || choice=='L')
56 {
57 trav->left=create(trav->left);
58 }
59
60 return(trav);
61 }
62
63 void inorder(struct btree *trav)
64 {
65 if(trav==NULL)
66 return ;
67 inorder(trav->left);
68 cout<<" "<<trav->no;
69 inorder(trav->right);
70 }
71
72 void preorder(struct btree *trav)
73 {
74 if(trav==NULL)
75 return;
76 cout<<" "<<trav->no;
77 preorder(trav->left);
78 preorder(trav->right);
79 }
80
81 void postorder(struct btree *trav)
82 {
83 if(trav==NULL)
84 return;
85 postorder(trav->left);
86 postorder(trav->right);
87 cout<<" "<<trav->no;
88 }
111
L A B O R A T O R Y 7
1. What is the In Order tree walk?
2. What is the Pre Order tree walk?
3. What is the Post Order tree walk?
52
8 53
15
25
75 59
40
18
62
45
49
112
T R E E S
4. What is the In Order tree walk?
5. What is the Pre Order tree walk?
6. What is the Post Order tree walk?
87
0 82
2265
59 83
20
13
75
113
L A B O R A T O R Y 7
7. What is the In Order tree walk?
8. What is the Pre Order tree walk?
9. What is the Post Order tree walk?
50
36 25
3
5
53 59
8222
56
77
61
21
70
15
95
12 0
114
8 Heaps
115
L A B O R A T O R Y 8
Objective
1. To build a maximum heap from an unordered input array. 2. To know the two operations of the heap-insert and delete.
Read and Discover Type, build and run the following code. Copy the screen output of the program to the corresponding space provided. Answer the questions that follow. //=========================================================================
// Name : lab8_a.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : Binary Heap in c++
// Date :
//=========================================================================
1 #include <iostream>
2 #include <ctime>
3 #include <conio.h>
4 #include <iomanip>
5 using namespace std;
6
7 struct HeapNode
8 {
9 int value;
10 HeapNode * left;
11 HeapNode * right;
12 HeapNode(int a_value):value(a_value),left(0),right(0){}
13 void add(HeapNode * child)
14 {
15 if(child->value > value)
16 {
17 int temp = value;
18 value = child->value;
19 child->value = temp;
20 }
21
22 if(left == 0)
23 left = child;
24 else if(right == 0)
25 right = child;
26 else if(right->size() > left->size())
27 right->add(child);
28 else
29 left->add(child);
30 }
31
32 int size()
33 {
34 int total = 1;
35 if(left) total += left->size();
36 if(right)total += right->size();
37 return total;
38 }
39
40 HeapNode * removeTopNode()
41 {
42 HeapNode * toReturn = 0;
116
H E A P S
43 int temp = value;
44
45 if(left != 0 && (right == 0 || left->value >= right->value))
46 {
47 value = left->value;
48 left->value = temp;
49
50 toReturn = left->removeTopNode();
51
52 if(toReturn == left)
53 left = 0;
54 }
55
56 else if(right != 0 && (left == 0 || right->value >= left-
57 >value))
58 {
59 value = right->value;
60 right->value = temp;
61 toReturn = right->removeTopNode();
62 if(toReturn == right)
63 right = 0;
64 }
65
66 if(toReturn == 0)
67 toReturn = this;
68 return toReturn;
69 }
70
71 void printDepthFirst()
72 {
73 cout << value << " ";
74 if(left)left->printDepthFirst();
75 if(right)right->printDepthFirst();
76 }
77
78 int getDepth()
79 {
80 int d = 1;
81 int leftDepth = 0, rightDepth = 0;
82 if(left)leftDepth = left->getDepth();
83 if(right)rightDepth = right->getDepth();
84 d += (leftDepth > rightDepth)?leftDepth:rightDepth;
85 return d;
86 }
87
88 void release()
89 {
90 if(left)
91 {
92 left->release();
93 delete left;
94 left = 0;
95 }
96
97 if(right)
98 {
99 right->release();
100 delete right;
101 right = 0;
102 }
103 } };
117
L A B O R A T O R Y 8
104 class MaxHeap_UsingBinaryTreeNodes
105 {
106 HeapNode * root;
107 public:
108 MaxHeap_UsingBinaryTreeNodes():root(0){}
109 ~MaxHeap_UsingBinaryTreeNodes()
110 {
111 if(root)
112 root->release();
113 delete root;
114 }
115
116 void add(int a_value)
117 {
118 HeapNode * newNode = new HeapNode(a_value);
119 if(root == 0)
120 root = newNode;
121 else
122 root->add(newNode);
123 }
124
125 int removeTopNode()
126 {
127 int value = 0;
128 HeapNode * n = root->removeTopNode();
129 if(n == root)
130 root = 0;
131 value = n->value;
132 delete n;
133 return value;
134 }
135
136 int size()
137 {
138 if(root == 0)
139 return 0;
140 return root->size();
141 }
142
143 void printDepthFirst()
144 {
145 if(root != 0)
146 root->printDepthFirst();
147 }
148
149 void printTree()
150 {
151 if(root == 0)
152 return;
153
154 int depth = root->getDepth();
155 int maxElements = 1;
156 int inRow = 1;
157 for(int i = 0; i < depth; ++i)
158 {
159 maxElements += inRow;
160 inRow *= 2;
161 }
162
118
H E A P S
163 int * pyramidBuffer = new int[maxElements];
164 int defaultValue = 0xb44df00d;
165 for(int i = 0; i < maxElements; ++i)
166 {
167 pyramidBuffer[i] = defaultValue;
168 }
169
170 inRow = 1;
171 int index = 0;
172 bool couldHaveAValue;
173 int value;
174 HeapNode * cursor;
175
176 for(int d = 0; d < depth; ++d)
177 {
178 for(int col = 0; col < inRow; ++col)
179 {
180 cursor = root;
181 couldHaveAValue = true;
182 for(int binaryDigit = 0; couldHaveAValue &&
183 binaryDigit < d; binaryDigit++)
184 {
185 if( ((col >> (d-binaryDigit-1)) & 1) == 0)
186 cursor = cursor->left;
187 else
188 cursor = cursor->right;
189 couldHaveAValue = cursor != 0;
190 }
191
192 value = (couldHaveAValue)?cursor-
193 >value:defaultValue;
194 pyramidBuffer[index++] = value;
195 }
196
197 if(d+1 < depth)
198 inRow *= 2;
199 }
200
201 int NUMCHARS = 2;
202 int maxWidth = (NUMCHARS+1)*inRow;
203 inRow = 1;
204 int leadSpace;
205 int betweenValues;
206 index = 0;
207
208 for(int d = 0; d < depth; ++d)
209 {
210 betweenValues = (maxWidth/inRow)-NUMCHARS;
211 leadSpace = (betweenValues)/2;
212 for(int i = 0; i < leadSpace; ++i)
213 putchar(' ');
214 for(int n = 0; n < inRow; ++n)
215 {
216 if(pyramidBuffer[index] != defaultValue)
217 cout<< setw(2) << pyramidBuffer[index];
218 else
219 cout<<"..";
220 index++;
221 if(n+1 < inRow)
222 {
223 for(int i = 0; i < betweenValues; ++i)
119
L A B O R A T O R Y 8
224 putchar(' ');
225 }
226 }
227 putchar('\n');
228 inRow *= 2;
229 }
230 delete [] pyramidBuffer;
231 }
232
233 int getDepth()
234 {
235 if(root == 0)return 0;
236 return root->getDepth();
237 }
238 };
239
240 class MaxHeap_UsingArray
241 {
242 int * m_data;
243 int m_allocated;
244 int m_size;
245 int m_depth;
246 void allocateSize(int a_depth)
247 {
248 int perRow = 1;
249 int total = 0;
250 for(int i = 0; i < a_depth; ++i)
251 {
252 total += perRow;
253 perRow *= 2;
254 }
255 int * newData = new int[total];
256 if(m_data)
257 {
258 int min = (total<m_allocated)?total:m_allocated;
259 for(int i = 0; i < min; ++i)
260 newData[i] = m_data[i];
261 delete [] m_data;
262 }
263 m_data = newData;
264 m_allocated = total;
265 m_depth = a_depth;
266 }
267 inline int parentOf(int a_index)
268 {
269 return (a_index - 1) / 2;
270 }
271 inline int leftChild(int a_index)
272 {
273 return (a_index * 2) + 1;
274 }
275 void bubbleUp(int a_index)
276 {
277 int cursor = a_index;
278 int parent = parentOf(a_index), value = m_data[a_index];
279 while (cursor > 0 && value > m_data[parent])
280 {
281 m_data[cursor] = m_data[parent];
282 cursor = parent;
283 parent = parentOf(cursor);
284 }
120
H E A P S
285 m_data[cursor] = value;
286 }
287 void bubbleDown(int a_index)
288 {
289 int cursor = a_index, child = leftChild(a_index);
290 int value = m_data[a_index];
291 while (child < m_size)
292 {
293 if (child < (m_size - 1) && m_data[child] <
294 m_data[child+1])
295 ++child;
296 if(value < m_data[child])
297 {
298 m_data[cursor] = m_data[child];
299 cursor = child;
300 child = leftChild(cursor);
301 }
302 else break;
303 }
304 m_data[cursor] = value;
305 }
306 public:
307 MaxHeap_UsingArray():m_data(0),m_allocated(0),m_size(0),m_depth(0){}
308 void add(int a_value)
309 {
310 if(m_size >= m_allocated)
311 allocateSize(m_depth+1);
312 m_data[m_size] = a_value;
313 bubbleUp(m_size++);
314 }
315 int removeTopNode()
316 {
317 int value = m_data[0];
318 m_data[0] = m_data[--m_size];
319 bubbleDown(0);
320 return value;
321 }
322 int getDepth()
323 {
324 return m_depth;
325 }
326 int size()
327 {
328 return m_size;
329 }
330 void printTree()
331 {
332 int inRow = 1;
333 for(int d = 0; d < m_depth; ++d)
334 {
335 if(d+1 < m_depth)
336 inRow *= 2;
337 }
338 int NUMCHARS = 2;
339 int maxWidth = (NUMCHARS+1)*inRow;
340 int leadSpace;
341 int betweenValues;
342 int index = 0;
343 inRow = 1;
344
345 for(int d = 0; d < m_depth; ++d)
121
L A B O R A T O R Y 8
346 {
347 betweenValues = (maxWidth/inRow)-NUMCHARS;
348 leadSpace = (betweenValues)/2;
349 for(int i = 0; i < leadSpace; ++i)
350 putchar(' ');
351 for(int n = 0; n < inRow; ++n)
352 {
353 if(index < m_size)
354 cout<< setw(2) << m_data[index];
355 else
356 cout<< "..";
357 index++;
358
359 if(n+1 < inRow)
360 {
361 for(int i = 0; i < betweenValues; ++i)
362 putchar(' ');
363 }
364 }
365 putchar('\n');
366 inRow *= 2;
367 }
368 }
369 };
370
371 int main()
372 {
373 srand(time(0));
374 int num;
375 int numRandomValues = 31;
376
377 MaxHeap_UsingArray heap;
378
379 for(int i = 0; i < numRandomValues; ++i)
380 {
381 num = rand() % 100;
382 if(heap.size() > 0)
383 {
384 cout<<"----------\n";
385 heap.printTree();
386 }
387
388 cout<<"adding \n" << num, i+1, numRandomValues;
389
390
391 _getch();
392 heap.add(num);
393 }
394
395 cout<<"--- DONE ADDING ---";
396 while(heap.size() > 0)
397 {
398 cout<<"-----------\n";
399 heap.printTree();
400 num = heap.removeTopNode();
401
402 cout<< "removing" << left << "\n" << num, heap.size()+1;
403 _getch();
404 }
405 cout << "done!" << endl;
406 }
122
H E A P S
1. Write the output of the complete binary maximum heap.
2. Run the program again and write the output of the complete binary maximum heap.
123
L A B O R A T O R Y 8
3. Modify the source code to change the number of nodes into 15. Write the output of the complete maximum binary heap.
124
9 Collision
Resolution
Technique
125
L A B O R A T O R Y 9
Objective
1. To explore collision resolution particulary chaining. Read and Discover Type, build and run the following code. Copy the screen output of the program to the corresponding space provided. Answer the questions that follow. //=========================================================================
// Name : lab9_a.cpp
// Author : @DwightSabio
// Version : 1.0
// Description : Hashing in c++
// Date :
//=========================================================================
1 # include <iostream.h>
2 # include <fstream.h>
3 # include <string.h>
4 # include <stdio.h>
5 # include <conio.h>
6
7 class Node
8 {
9 public:
10 int data;
11 Node* Next;
12 };
13
14 # define MAX_ENTRIES 11
15
16 Node* HashTable[MAX_ENTRIES]={NULL};
17 Node* Top[MAX_ENTRIES]={NULL};
18
19 const int generate_hash_key(const int data)
20 {
21 return (data%MAX_ENTRIES);
22 }
23
24
25 void insert_data( )
26 {
27 int data;
28
29 cout<<"\n\n\n\t ********* New Element ********* "<<endl<<endl;
30 cout<<"\t Enter a value : ";
31 cin>>data;
32
33 int index=generate_hash_key(data);
34
35 Node* Entry=new Node;
36
37 if(!Entry)
38 {
39 cout<<"\n\n\n\t Fatal Error : Unable to allcate memory to
40 stroe new element."<<endl;
41 cout<<"\n\n\t\t Pres any key to return to Menu. ";
42
43 getch( );
44 return;
45 }
126
C H A I N I N G
46 if(HashTable[index]==NULL)
47 {
48 Entry->data=data;
49 Entry->Next=NULL;
50 HashTable[index]=Entry;
51 Top[index]=Entry;
52 }
53
54 else
55 {
56 Entry->data=data;
57 Entry->Next=NULL;
58 Top[index]->Next=Entry;
59 Top[index]=Entry;
60 }
61
62 cout<<"\n\n\t\t Pres any key to return to Menu. ";
63
64 getch( );
65 }
66
67
68 void print_data( )
69 {
70 cout<<"\n\n\t ***** HashTable & Data *****\n"<<endl;
71
72 Node* Print;
73
74 for(int index=0;index<MAX_ENTRIES;index++)
75 {
76 if(index<10)
77 cout<<"\t HashTable[0"<<index<<"] : ";
78
79 else
80 cout<<"\t HashTable["<<index<<"] : ";
81
82 Print=HashTable[index];
83
84 if(Print!=NULL)
85 {
86 while(Print!=NULL)
87 {
88 cout<<Print->data;
89 Print=Print->Next;
90
91 if(Print!=NULL)
92 cout<<" , ";
93 }
94
95 cout<<endl;
96 }
97
98 else
99 cout<<"-"<<endl;
100 }
101
102 cout<<"\n\n\t\t Pres any key to return to Menu. ";
103
104 getch( );
105 }
127
L A B O R A T O R Y 9
106 void search_data( )
107 {
108 int data;
109
110 cout<<"\n\n\n\t ***** Search an Element *****\n"<<endl;
111 cout<<"\t Enter a value : ";
112 cin>>data;
113
114 int flag=0;
115 int index=generate_hash_key(data);
116
117 Node* Print=HashTable[index];
118
119 if(Print!=NULL)
120 {
121 while(Print!=NULL)
122 {
123 if(Print->data==data)
124 flag++;
125
126 Print=Print->Next;
127 }
128
129 if(flag)
130 cout<<"\n\n\t *** The Search Element is found
131 "<<flag<<" times.";
132 }
133
134 if(!flag)
135 cout<<"\n\n\t *** The Search Element is not found."<<endl;
136 cout<<"\n\n\n\t\t Pres any key to return to Menu. ";
137
138 getch( );
139 }
140
141 void show_working( )
142 {
143 char Key=NULL;
144
145 do
146 {
147
148 cout<<"\n\n\t********** Implementation of Hashing
149 **********"<<endl;
150 cout<<"\tSelect one of the listed operation :"<<endl;
151 cout<<"\t - Press I or i to Insert an Element"<<endl;
152 cout<<"\t - Press P or p to Print the HashTable & Data"<<endl;
153 cout<<"\t - Press S or s' to Search an Element"<<endl;
154 cout<<"\t - Press E or e to Exit"<<endl<<endl;
155 Input:
156 cout<<"\t Enter your Choice : ";
157
158 Key=getche( );
159
160 if(int(Key)==27 || Key=='e' || Key=='E')
161 break;
162
163 else if(Key=='i' || Key=='I')
164 insert_data( );
165
166 else if(Key=='p' || Key=='P')
128
C H A I N I N G
167 print_data( );
168
169 else if(Key=='s' || Key=='S')
170 search_data( );
171
172 else
173 goto Input;
174 }
175 while(1);
176 }
177
178 int main( )
179 {
180 show_working( );
181
182 return 0;
183 }
1. Given a hash table with bucket size 11, store the keys 11, 35, 99, 32, 10, 33, 76, and 98. Print the hash table and copy the data.
129
L A B O R A T O R Y 9
2. Given a hash table with bucket size 24, store the keys 89, 12, 290, 23, 201, 8712, 9203, 76283, 201, 290, 12, 8723, 9923, 998, 203, 782, 902, 9782, 1423, 12, 4293, 239, 9782. 3890, 12, and 203. Print the hash table and copy the data.
3. Search the elements 12, 201 and 8723. How many times the elements have been found?
130
C H A I N I N G
4. Given the file size of 40, give the hashed addresses of the following key values 59112, 71828, 90921, 9038, 49472, 23928, 78293, 32381, 92831, 78293.
131
M I D T E R M P R O J E C T Five Sorting Algorithms Part 1. The objectives of this particular case study are:
1. To learn the different sorting algorithms and their behaviors. 2. To be able to implement five sorting algorithms, namely: bubble sort, selection sort,
insertion sort, quick sort, and shell in C++ programming language. 3. To observe the relative performance of these different sorting algorithms. 4. To explore programming involving the use of arrays and get to see array’s properties and
way of manipulating data. 5. To strengthen the discipline of self-study, conducting research and working in a group or
with a peer. Requirements: Write a C++ program that will do the following in sequence:
1. Ask the user to input a positive integer value that we will denote as n. Here n represents the size of the problem space, specifically, the number of elements to be sorted.
2. Create arrays for 5 lists of n integers. 3. For one array, its initial values are to be generated randomly (use the random
function/method of your chosen library). 4. Copy the contents of the first array to the other four arrays. After these step, all arrays
should contain the same sequence of integer values. 5. Introduce a count variable into each of your sorting algorithms to keep track of the number
of operations. You should able to discern well as to where should it best placed to count the “important” operations.
6. Sort the first array using bubble sort. Obtain the amount of time it took for bubble sort to rearrange the array as well as the count on the number of operations.
7. Sort the second array using selection sort and obtain the time it took to rearrange the array as well as the count on the number of operations.
8. Sort the third array using insertion sort and obtain the time it took to rearrange the array as well as the count on the number of operations.
9. Sort the fourth array using quicksort and obtain the time it took to rearrange the array as well as the count on the number of operations.
10. Sort the fifth array using shell sort and obtain the time it took to rearrange the array as well as the count on the number of operations.
Run the program for different values of n based on the order. Obtain the processing time for each sorting algorithm and count, and fill up the following table. The processing time should be in milliseconds.
132
M I D T E R M P R O J E C T
Sorting in Ascending Order
n bubble sort selection sort insertion sort quick sort shell sort
Count Processing Time Count
Processing Time Count
Processing Time Count
Processing Time Count
Processing Time
32
64
128
: : : : : :
: : : : : :
32768
65536
Sorting in Descending Order
n bubble sort selection sort insertion sort quick sort shell sort
Count Processing Time Count
Processing Time Count
Processing Time Count
Processing Time Count
Processing Time
32
64
128
: : : : : :
: : : : : :
32768
65536
133
M I D T E R M P R O J E C T Note: the next value of n is computed as n = n * 2. For example, after n = 64 the next n is computed as 64 * 2 = 128. Draw line graphs with x coordinates representing the values of n and y axis coordinates representing the processing time for each sorting algorithm. Graphs should be overlaid. Provide a concise discussion about the resulting graphs. Discussion can be (but not limited to):
(a) What observations can be made from it? Correlate the count and processing time for each sorting algorithm.
(b) Does the performance of each sorting algorithm differ or the same regardless of the sorting order?
(c) Does efficiency is seen when arranging the values in ascending order, descending order or both?
(d) Do any of the algorithms run consistently the quickest? Slowest?
Part 2. Using the programs created in Part 1, test each sorting algorithm again, but this time under the following scenarios:
1. Supply randomly generated values for one array where the values must be in descending order. This set of values must be replicated in the other four arrays. Sort the array in ascending order. Obtain the processing time and count for each sorting algorithm under different values of n as done in Part 1, and provide a discussion based on the observation seen. Provide the line graph as well.
2. Perform the process in #1, but this time, the set of randomly generated values must be in ascending order and you are to sort the data in descending order. Obtain the processing time and count for each sorting algorithm under different values of n as done in Part 1, and provide a discussion based on the observation seen. Provide the line graph as well.
Part 3 Provide an overall conclusion based on the experiments did in Part 1 and Part 2. You should able to consolidate your analysis from both parts, do comparison and contrast as necessary. Provide in your discussion the identified program/time complexity of these algorithms as the value of n → General Requirements:
1. You are to submit all the works did in this project in both printed document and electronic form on or before the specified due date. Submission of the printed document should be in A4 bond paper with short, white sliding folder. Submission of both versions must be done on the same day. In the event that one of the requirements is submitted at the latter date, that date will be considered as the pair’s submission.
2. Late project will be penalized at the rate of 10% per day. That is a project is marked out of 90% for 1 day late, 80% for 2 days late, etc. For example: A project due on Friday but handed in on the next Monday morning is marked out of 70%.
3. This project is mandatory for all the students in the lecture and laboratory class. 4. For the electronic version of your assignment: use the concatenated last names as filename
and .cpp as the extension. For example if your last names are CRUZ and SANTOS, the file name should be cruz_santos.cpp (for C++ program). PDF version on the tables and other needed documents. Email the electronic version to ____________________________
134
M I D T E R M P R O J E C T
with subject heading as: MidtermProject-<Lastname of Person 1 (ID#)>-<Lastname of Person 2 (ID#)>. For example: MidtermProject-Cruz(100893454)-Santos (100452323).
5. The printed document should contain the following:
An introduction of the midterm project
A presentation, discussion and illustrations of Part 1, Part 2 and Part 3. 6. The printed document should be written in single-spaced, font name: Arial, font size: 11 with
one- inch margin on each side. 7. Cover page with title, names of members are included. Timeline (using MS Visio/ MS Project)
should be at the last page. Everyone in the group should have equal division of work. Check the running source code not included the operational count on ______________ during class time. Check the running source code including the operational count on ______________ during class time. Submission Date: ____________________________ . Printed document must be forwarded during the class time. Electronic version must be received on or before ______________ ______________ Design Day: (Project Defense) on ____________________________.
135
F I N A L P R O J E C T Evaluation of Expression – Trees Programming Description The objective of the case study is to understand the Object Oriented side of C++ and the concepts of trees and how to apply such in a simple application – that is to perform evaluation on a simple arithmetic expression. You will work in a group (maximum of 3 members) and each member is expected to give his/her contribution. Specifications Input & Output: The software should provide an interface that will accept from the user an arithmetic expression (parentheses are accepted and can be in different levels) and show the process of converting infix expression into its postfix and prefix notation. Moreover, the software should give the result in the case that the given arithmetic expression is consists of numbers. You are required in your implementation to use trees (if necessary). General Requirements:
1. You are to submit all the works did in this project in both printed document and electronic form on or before the specified due date. Submission of the printed document should be in A4 bond paper with short, white sliding folder. Submission of both versions must be done on the same day. In the event that one of the requirements is submitted at the latter date, that date will be considered as the group’s submission.
2. This project is mandatory for all the students in the lecture and laboratory class. 3. For the electronic version of your assignment: use the concatenated last names as filename
and .cpp as the extension. For example if your last names are CRUZ and SANTOS, the file name should be cruz_santos.cpp (for C++ program). PDF version on the tables and other needed documents. Email the electronic version to ____________________________ with subject heading as: FinalProject-<Lastname of Person 1 (ID#)>-<Lastname of Person 2 (ID#)>#)>-<Lastname of Person 3 (ID#)>. For example: FinalProject-Cruz(100893454)-Santos(100452323)-deLeon(1173951002).
4. The printed document should contain the following:
An introduction of the final project
A presentation and discussion of the algorithms implemented, illustrations of how such transformation and evaluation are done.
The source code 5. The printed document should be written in single-spaced, font name: Arial, font size: 11 with
one-inch margin on each side. 6. Cover page with title, names of members are included. Timeline (using MS Visio/ MS Project)
should be at the last page. Everyone in the group should have equal division of work.
Oral Presentation, Software Demonstration and Q&A Each member should be present and be prepared to answer any question about the case study. The oral presentation (including the software demonstration) will be scheduled. Submission Date: ____________________________ . Printed document must be forwarded during the class time. Electronic version must be received on or before ______________ ______________ Design Day: (Project Defense) on ____________________________.