Anda di halaman 1dari 68

Exercises Number 1 Input and Output Statement Direction: Write a source code for the given of the following

program problem on the space provided. Indicate the output. 1. Write a program that subtracts the sum of x and y from z and then increments y.

2. Write a program that will ask the user to input two integers interactively and print the sum, difference, product, quotient, and remainder of the inputted integers.

3. Write a program that will ask the user to input a number in Fahrenheit then convert it into Celsuis.

Exercises Number 2 Conditional Statement Direction: Write a source code for the given of the following program problem on the space provided. Indicate the output. 1. Write a program that reads the users age and then prints You are a child. if the age is less than18, You are an adult. if it is greater than or equal to 18 and less than 65, and You are a senior citizen. if age is greater than or equal to 65.

2. Write a program that will ask the user to input his grade. Display the If the grade of the student ranges from 100 to 90 display EXCELLENT! If the grade is less than 90 but greater than 85 then display GREAT! If the grade is less than 85 but greater than 75 display GOOD! If the grade is 75 display YOU PASSED! Otherwise display Better Luck Next Time!

3. Using switch statement, write a program that will ask the user to input two real numbers. The program should ask again if he wants to add, subtract, multiply or divide the two real numbers then display the output.

Exercises Number 3 Looping Statement Direction: Write a source code for the given of the following program problem on the space provided. Indicate the output. 1. Using the for loop, write a program that will ask the user to input a number then compute and prints the sum of a given number squares. For example the inputted number is 5 then the sum of square of this is 55.

2. Using the while loop, Write a program that reverses the digits of a given positive integer. Display the inputted numbers and its reverse.

3. Write a program that will ask the user to input a number then display the factorial of that number.

Exercises Number 4 Functions Direction: Write a source code for the given of the following program problem on the space provided. Indicate the output. 1. Write a program with function to simulate a table-tennis game for doubles where one team has a 70 percent chance off winning each point.

2. Write a program of the following average() function that returns the average of four numbers: float average(float x1, float x2, float x3, float x4)

Exercises Number 5 Array Direction: Write a source code for the given of the following program problem on the space provided. Indicate the output. 1. A circular list can be implemented using an array. Write a program to simulate the activity of a circular list. The array has 10 integer number. 2.

2. Write a program that will compute student averages and display the individual quiz grades and the average for each student in the class. The program could be used by an instructor to obtain an overview of the class grades. The program will also display the class average for each quiz. Example: Student Name Benito Ronald Rommel Quiz 10 9 10 9.67 Quizzes 10 10 10 8 8 7 9.33 8.33 10 9 10 9.67 Average 10 9 8.75 9.25

Experiment Number 1

STRING
I. Objectives 1. to learn how to create and how does string work and put up with in memory in C++. 2. to be able to understand the function of string as a part of many application. II. Background Information A string is a sequence of characters which is to b e considered as a single data item. The characters of a string are enclosed within double quotations . These strings consist of the following: letters, digits, symbols and control characters. In C++ thrtr is no specific elemental variable type to store strings of characters and in order to fulfill this feature we can use arrays of type char, which are successions of char elements. The data type char is used to store single character, for that reason arrays of them are generally used to make srings of single characters. Example: char A[15]; A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14

Array A can store a string up to 15 characters long. The example above that has the maximum of 15 characters is not required to be used fully. Thus, we represent A storing the strings TIP and EXPERIMENT 6 T E I X P P \0 E R I M E N T 6 \0 -

When you look to our examples, you will notice the null character \0. \0 is the sentinel value to mark the end of the string. The boxes with dash (-) mark specify the intermediate values meaning they are the unused space of an array. When the compiler reads the characters in the string starting at indexed variable A[0], proceed to A[1], then A[2], and so forth. The maximum length that the array can hold is one less than the size of the array because the null character \0 occupies one element of the array.

String Variable Declaration In declaring string variable we follow this format: <char> <space> <name of array><[> <size of the string> <]> <;> or as simple as char name_of_array[size_of_the_string]; Example: char subject_code[10]; In initializing a string variable with preset values, there are two ways. First we can use char subject_code[ ] = CS012L1; or char subject_code[ ] = {C,S,0,1,2,L,1,\0}; The array or string of characters subject_code is declared with a size of eight characters. The seven elements composed of CS012L1 plus a null character \0 which specifies the end of the string on the second case. In the first case when we use double quotation the null character is automatically added. Assigning Values to Strings We can only assign elements of an array and not the entire array, we can use another method: name_of_array[index_of_array] = character_constants_value; ex. subject_code[0] = C; text[4] = ; song[14]= \t ; - stores character C to array subject_code at index 0. - stores blank space to array text at index 4. - stores a horizontal tab to array song at index 14.

In C++, we can store string values in variables and use string values similar to how you use data of other types. There is also class string from the standard library, whose members are declares in the <string>header file. Here are some function in string.h:

a. strcpy(target_string_var,source_string) it copies the string value source_string into the string variable target_string_var. Example: strcpy(source_code, CS012L1); The content of source_code will be CS012L1 b. strcat(target_string_var,source_string) it concatenates the string value source_string onto the end of the string in the string variable target_string_var. Example: char string_var[10] = Data ; strcat(string_var,STRUCTURE); The value of string_var will be Data STRUCTURE. c. strien(source_string) it returns an integer value equal to the length of the source_string. Example: char message[14] = program; int a; a = strlen(message); The value of x will be 7. d. strcmp(string_1, string2) it returns 0 if string_1 and string_2 are the same. Returns a value less than 0 if string_1 is less than string_2. Returns a value greater than 0 if string_1 is greater than string_2. Example: strcmp(data, DATA); It will return a value greater than 0. strcmp(good,good); It will return a zero value which means FALSE. Using getline() to Read Strings Another preferred methos in reading strings, which is the solution to whitespace dilemma is to use the member function of the iostream class called getline(). The geline function is used in conjunction with cin rather than the >> operator. This function will allow cin to read the entire string, including whitespace. The format for this is cin.getline(string_var,size_of_array,delimiting character);

where string_var is the name of the character array, array_size is the size of the array into which the string will be read and the delimiting character terminates the string entry and is not stored as part of the string. Converting Numerical Strings C++ has several standard functions for converting strings to int, long int, and double. The stdlib.h library provides three useful functions for this purpose: a. b. c. III. Exercises PROGRAM A (save as EXP1A) #include <iostream.h> #include <conio.h> main() { char name[30] ; cout << "Please enter your full name:" << endl ; cin >> name ; // cin stops reading in when it sees blank space cout << "Using cin:" << name << endl ; char dummy[30] ; cin.getline(dummy, 30) ; // catches what cin didn't grab it cout << "Please enter your full name:" << endl ; cin.getline(name, 20); // this will read in up to 20 characters // stopping only when you hit the enter button // getline WILL READ THE BLANK SPACES cout << "Using cin.getline:" << name << endl ; cout << "Please enter your full name:" << endl ; cin.getline(name, 20, '.') ; // this will read in up to 20 characters // stopping only when you it reads in a '.' cout << "Using cin.getline, stopping at '.' :" << name << endl ; getch() ; return 0 ; } atol converts a string to an int type. Syntax: atol(string_var); atof converts string to an float type. Syntax: atof(string_var); atoll converts a string to a long int type. Syntax: atoll(string_var);

PROGRAM B (save as EXP1B) #include<iostream.h> #include<stdlib.h> #include<string.h> #include<conio.h> main() {clrscr(); char * name1 = "neonprimetime" ; char * name2 = "primetime" ; char * name3 = "neo" ; char * name4 = "neonprimetime" ; cout << "According to ==...." << endl ; if(name1 == name4) cout << "name1 and name2 are equal." << endl ; else cout << "name1 and name2 are not equal." << endl ; cout << "According to strcmp()...." << endl ; if(strcmp(name1, name4) == 0) cout << "name1 and name2 are equal." << endl ; else cout << "name1 and name2 are not equal." << endl ; cout << "According to <..."<< endl ; if(name2 < name3) cout << "name2 is less than name3" << endl ; else cout << "name2 is greater than or equal to name3" << endl ; cout << "According to strcmp()..." << endl ; if(strcmp(name2, name3) < 0) cout << "name2 is less than name3" << endl ; else cout << "name2 is greater than or equal to name3" << endl ; cout << "According to >..."<< endl ; if(name1 > name3) cout << "name1 is less than name3" << endl ; else cout << "name1 is greater than or equal to name3" << endl ; cout << "According to strcmp()..." << endl ; if(strcmp(name1, name3) > 0) cout << "name1 is less than name3" << endl ; else cout << "name1 is greater than or equal to name3" << endl ; getch(); return 0 ; }

10

IV. Assimilation Direction: Express the output on the given box for each pf the programs. Include the line number. Give your observation for each of the problems.

1.

_________________________________________________________________ _________________________________________________________________ _________________________________________________________________ _________________________________________________________________

2.

_________________________________________________________________ _________________________________________________________________ _________________________________________________________________ _________________________________________________________________

11

V. Supplementary Problem 1. Create a program that will copy the content of the first string into the second string and display the result. 2. Create a program that adds the word day to an entered event. 3. Create a program determine the length of an input word and displays the letters successively in sequence. 4. Write a program to convert a document of lowercase or uppercase letters to a sentence case. A sentence case capitalizes the first letter following the closing punctuation and space. All other letters are lowercase.

12

Experiment Number 2

STRUCTURE
I. Objectives 1. to be able to learn how to create very powerful complex data structures by building structures of structures. 2. to be able to learn how to create C++ programs in an organize way. II. Background Information A structure is a collection of members of diverse types of data. A structure member is simply an item of meaningful data. A structure can contain any number of members, with each member having a unique name called member name, Consider a time in a digital clock, such as 10:09:46 It consists of three data items: the hours(10), the minutes(09), and the seconds(46). Each of these data items can be a structure member of different data types. We can make structure of this format like the one below: Time Member Name Hour Minute Seconds Declaring Structures A user-defined data structure must be declared before it can be used. There are two ways the indirect way and the direct way. A. Indirect way struct structure_name {member1_data_type identifier; member2_data_type identifier; : : : : membern_data_typeidentifiern; }; structure_name object_name1, object_name2, object_name3; Member Data Type an integer value an integer value an integer value

13

B. Direct way struct structure_name {member1_data_type identifier; member2_data_type identifier; : : : : membern_data_typeidentifiern; }object_name1, object_name2, object_name3; The structure_name is a name for the model of the structure type(optional), the object_name is valid identifier for structure object instantiation, within curly bracket {} are the structure member or member elements. Example Indirect Way of Declaring Structure struct person{ char name[20]; int age; float height; float weight; }; person p1, p2; Initializing Structure Structure objects can be initialized when they are defined just like any other variable object. To initialize a structure object, heres the general format: structure_name object_name= {member1_value, member2_value, member3_value, .. membern_value}; Example: person p1 = {John Eric, 16, 67, 52}; product orange = {dalandan, 15}; Storing data into structures When accessing a structure, either you will store information or retrieve information from the structure. To access a structure, you can use one of the two ways: (1) by using the ot operator, . or (2) by using the pointer operator, . To assign data to structure, use the format: object_name.member_name=data; Direct Way of Declaring Structure struct product{ char prodname[10]; float price; } orange, apple, mango;

14

To retrieve data from a structure, use format: variable_object_name=object_name.member_name Nested Structure A nested structure is a structure within a structure. In other terms, a nested structure is a member of another structure. Consider this example, a student structure containing members student name, student number, course, and structure contains test results. It makes more sense if a separate structure named Test is made regarding the test scores, average and grade of the student. Heres the required declaration: struct Test{ int Scores[3]; float Average; float Grade; } struct Student{ char Name[20]; int StudNo; char Course; Test TestInfo; }; Next, we will define an object for the Student structure as follows: Student CS1; To access (store/retrieve) data to the nested structure, for example assigning test scores to structure Test, the statement must be: CS1.Testinfo.Score[0]=95; CS1.Testinfo.Score[1]=86; CS1.Testinfo.Score[2]=99; Enumerations (enum) Enumerations serve to create data types to contain something different that is not limited neither to numercal or character constants nor constants true and false. Its form is the following: enum model_name{ value1, value2, value3, .} object_name;

15

For example, we could create new type of variable called colors to store colors with the following declaration: enum colors{black, blue, green, cyan, red, purple, yellow, white}; Notice that we do not include any fundamental data type in the declaration. To say it somehow we have created a new data type without being based on any other existing one: the type colors, whose possible values are the colors that we have enclosed within curly brackets {}. For example, once declared the colors enumeration the following expressions will be valid: colors my colors; mycolor = blue; if (mycolor==green) mycolor==red; In fact our enumerated data type is compiled as an integer and their possible values are any type of integer constant specified. If this one is not specified, the integer value equivalent to the first possible value is 0 and the following ones follow a+1 progression. Thus, in our data type colors that we defined before, black would be equivalent to 0, blue would be equivalent to 1, green to 2 and so on. If we explicitly specify an integer value for some of the possible values of our enumerated type the following values will be the increases of this, for example: enum months {january = 1, February, march, april, may, june, july, august, September, October, November, December}two_thousand_six; In this case, variable two_thousand_six of the enumerated type months can contain any of the 12 possible values that go from january to December and that are equivalent to values between 1 and 12, not between 0 and 11 since we have made anuary to be equal to 1. III. Exercises

16

PROGRAM A (save as EXP2A) #include <iostream.h> #include<conio.h> int x_to_the_n(int x, int n) ; main() {clrscr(); int x = 5 ; int n = 3 ; cout << "if x = "<< x << " and n = " << n << endl ; cout << "x^n = " << x_to_the_n(x, n) << endl ; getch(); return 0 ; } int x_to_the_n(int x, int n) { if(n > 1) { return x * x_to_the_n(x, n-1) ; } else return x ; } PROGRAM B (save as EXP2B) #include <iostream.h> #include <conio.h> class employee { private: char * name ; char male_or_female ; double pay_per_hour; public: employee() ; ~employee() ; double CalculatePay(double hours) ; void DisplayInformation() ; void SetInformation() ; };

17

employee::employee() {name = new char[30] ; male_or_female = '\0' ; pay_per_hour = 0 ;} employee::~employee() {delete name ;} double employee::CalculatePay(double hours) { return (pay_per_hour * hours) ; } void employee::SetInformation() {clrscr(); cout << "Please enter the employee first name..." << endl ; cin >> name ; cout << "Please enter the 'm' for male or 'f' for female..." << endl ; cin >> male_or_female ; cout << "Please enter a the amount of pay " << name << " makes per hour.." << endl; cin >> pay_per_hour ; } void employee::DisplayInformation() { cout << "Employee name is "<< name << " (" << male_or_female << ")" << endl ; if(male_or_female == 'm') cout << "He " ; else cout << "She " ; cout << " makes $" << pay_per_hour << " per hour." << endl ; } main() { employee john ; john.SetInformation() ; john.DisplayInformation() ; int hours ; cout << "Please enter the number of hours worked... " << endl ; cin >> hours ;

18

cout <<employee.name<< " worked on a job for " << hours << " hours." << endl ; cout << "He made $" << john.CalculatePay(hours) << endl ; getch() ; return 0 ; }

IV. Assimilation Direction: Express the output on the given box for each pf the programs. Include the line number. Give your observation for each of the problems.

1.

_____________________________ _____________________________ _____________________________ _____________________________ _____________________________

2.

_____________________________

19

_____________________________ _____________________________ _____________________________ _____________________________

V. Supplementary Problem An institution maintains an inventory consisting of five products of manuals; computer fundamentals and programming, data structure, microprocessor, logic circuit, advance logic circuit. Make a program to keep track of the inventory. The program should allow the user to display the inventory, add items to the inventory and remove items from the inventory. Organize the program around a loop in which the user is asked to make choice from a menu. There are three choices Add Items, Remove Items and Quit. Sample Output Identification Letter A B C D E Choices 1. Add Items 2. Remove Items 3. Quit Choose an operation to perform: Enter the identification number of the product to be added: Number of units to add: Product computer fundamentals and programming data structure microprocessor logic circuit advance logic circuit Quantity 50 60 55 50 60

20

Experiment Number 3

FILE STREAM I/O


I. Objectives 1. to be able to know and understand the importance of I/O files as a mean of storing data. 2. to be able to learn how to create and manipulate your own disk files II. Background Information A file is a collection of data stored together under a common name, usually on the disk, magnetic tape, or CD-ROM. For example, the C++ programs that you store on disk are examples of files. The stored data in a program file are the program code that becomes input data to the C++ compiler. A file is physically stored on an external medium such as disk. Each file has a unique file name referred to as the files external name. The external name is how the file is known by the operating system. A stream is one-way transmission path between a source and a destination. A stream of bytes get sent down this transmission path. There are classification of streams namely: ifstream file stream objects used for input (reading operation) ofstream file stream objects used for output (writing operation) fstream file stream objects used for both input and output For each file your program uses, regardless of the files type (text or binary), a distinct file stream object must be created. If you want your program to read and write to a file, an input and output file stream object are required. Input file stream objects are declared to be of type ifstream, and output file streams are declared to be type of ofstream. For example, examine the ff. declaration statement: ifstream inFile; This statement declares an input file stream named inFile to be an object of the class ifstream. Similarly, examine the next declaration statement: ofstream outFile; This statement declares an output file stream obect named outFile to be an object of the class ofstream. Object names, such as inFile and outFile, can be any programmerselected names that conform to C++s identifier rules.

21

File Stream Methods Each file stream object has access to the methods defined for its respective ifstream or ofstream class. These methods include the ff. a. Opening a File connecting a stream object name to an external file name b. Closing a File determining if a successful connection has been made Creating File Stream To create a named file stream, you must a. define a file stream object for one of the fstream.h file classes. b. Attach the file stream object to a particular disk file to open the file. Opening A File In using the open() method to connect the files external name to its internal object stream name, only one argument is required, which is the external file name. We use this syntax: file_stream_object<.>open(disk_file_name, file_access_mode,file_permission_mode) For example: inFile.open(prices.dat); File Status Methods Prototype fail() eof() Description Returns a Boolean true if the file has not been successfully opened; otherwise, returns a Boolean false value. Returns a Boolean true if a read has been attemped oast the end-of-file; otherwise, returns a Boolean false value. The value becomes true only when the first character after the last valid file character is read. Returns a Boolean true value while the file is available for program use. Returns a Boolean false value if a read has been attempted past the end-of-file. The value becomes false only when the first character after the last valid file character is read. Returns a Boolean true value if a read has been attempted past the end-of-file; otherwise returns false.

good()

bad()

22

Closing A Fle A file is closed using the close() method. This method breaks the connection between the files external name and the file stream object, which can be used for another file. We use the syntax: inFile.close(); This statement closes the inFile streams connection to its current file. As indicted, the close() method takes no argument. Because all computers have a limit on the maximum number of files that can be opened at one time, closing files no longer needed makes good sense. Any open files existing at the end of normal program execution wull be automatically closed by the operating system. Indicator ios::in ios::out ios::app ios::ate ios::binary ios::trunc ios::nocreate ios::noreplace File Position Marker Functions Name seekg(offset, mode) seekp(offset, mode) tellg(void) tellp(void) Description For input files, move to the offset position as indicated by the mode For output files, move to the offset position as indicated by the mode. For input files, return the current value of the file position marker. For output files, return the current value of the file position marker. Description Open a text file in input mode Open a text file in output mode Open a text file in append mode Go to the end of the opened file Open a binary file in input mode Delete file contents if it exists If file does not exists, open fails If file exists, open for output fails

Exit Statement The exit statement is used to end the program immediately. The format is exit(integer_value);

23

III. Exercises PROGRAM A (save as EXP3A) #include <iostream.h> #include <fstream.h> #include<conio.h> int main() { clrscr(); ofstream my_outfile("myfirst.doc", ios::out) ; my_outfile << "Hello World!" << endl ; my_outfile.close() ; ifstream my_infile("myfirst.doc ", ios::in) ; char wordOne[6], wordTwo[7] ; my_infile >> wordOne >> wordTwo ; my_infile.close() ; cout << wordOne << " " << wordTwo << endl ; getch(); return 0 ; } PROGRAM B (save as EXP3B) #include <iostream.h> #include <fstream.h> #include <conio.h> int main(){ ofstream outfile ; outfile.open("mysecond.doc") ; char * sentences[5] = {"neonprimetime is the bomb!", "neonprimetime loves computers", "micky is really cute", "indiana pacers rule", "deion sanders is fast"} ; for(int i = 0 ; i < 5 ; i++) outfile << sentences[i] << endl ; outfile.close() ; ifstream infile ;

24

infile.open("data.dat") ; char * sentence = new char[30] ; cout << "sentences..." << endl ; cout << "--------" << endl ; for(int j = 1 ; j <= 5 ; j++){ infile.getline(sentence, 30, '\n'); cout << j << ".) " << sentence << endl ; } infile.close() ; getch() ; return 0 ; } IV. Assimilation Direction: Express the output on the given box for each pf the programs. Include the line number. Give your observation for each of the problems. 1. _____________________________ _____________________________ _____________________________ _____________________________ _____________________________

2.

_____________________________ _____________________________ _____________________________ _____________________________ _____________________________

25

V. Supplementary Problem

1. Write a program that accepts a word or group of words for a dictionary and searches the file for the corresponding definition of that word or group of words. The eof function returns one(1) if the file pointer is at the end of the file, and zero (0) if there is still more data to be read from the file. Use this statement: result=eof(FileInput); 2. Write a program that will create a file that contains the set of entries of grades of 3 students display its content.

26

Experiment Number 4

Stacks
I. Objectives 1. to be able to understand conceptually the role played by a stack in processing function calls. 2. to be able to implement stack operations in C++ programming. II. Background Information A stack is called a "last in, first out" (LIFO) data structure since the last item pushed onto a stack will be the first one popped off. It can also be called a "first in, last out" (FILO) data structure since the first item pushed onto it will be the last one popped off. Because of these features, a stack is the ideal data structure to use in reversing a sequence of items. Intuitively, a stack is like a pile of plates where we can only remove a plate from the top and can only add a new plate on the top. In computer science we commonly place numbers on a stack, or perhaps place records on the stack. Operations on Stack EMPTY ( ) The empty() function returns true if the stack has no elements, false otherwise. Example: 1 2 TOP 3 4 POP ( ) The function pop() removes the top element of the stack and discards it. Example: 1 TOP 2 R O R O N EMPTY(X) = FALSE

27

3 4 PUSH ( ) The function push() adds value to the top of the current stack. Example: 1 2 TOP 3 4 R O N

SIZE( ) The size() function returns the number of elements in the current stack. Example: The size of the stack X is 3 1 2 TOP 3 4 TOP( ) The function top() returns a reference to the top element of the stack. Example: TOP(X) = N 1 2 TOP 3 R O N R O N

28

NULL( ) The function null() empty the stack. Example: TOP 1 2 3 4 ARRAY IMPLEMENTATION: A stack can also be implemented using an array-based approach. The main idea is that Top holds the index of the top of stack item, which is stored in the Info array. To push a new item onto a stack, Top is simply incremented and the new item placed into the array at that index. To pop an item from the stack, the item at index Top is sent back and Top itself is decremented. Since a value of zero in Top indicates a stack with one item (at index 0), a value of -1 in Top indicates an empty stack. III. Exercises #include<iostream.h> #include<conio.h> struct node { int num; node *next; }; class number { public: number(); ~number(); int add(int num, int success); int remove(int num, int success);

29

void print(); int search(int num, int success); private: node *head; node *cur; node *pre; }; //constructor number::number() { head=NULL; cur=NULL; pre=NULL; } //destructor number::~number() { node *ptr; while(head!=NULL) { ptr=head->next; delete head; head=ptr; } } void main() { char answer; int num; int success=0; number link; cout << "STACKS" << endl; cout << "\n \n"; for(int i=5; i>3; i++) //loop is for keep the program run untill set it false { cout << "Enter 'A' for add a number" << endl; //main menus cout << "Enter 'R' for remove a number" << endl; cout << "Enter 'P' for print all the number" << endl; cout << "Enter 'S' for search fo a number" << endl; cout << "Enter 'Q' for quit the program" << endl; //delete all the numbers

30

cout << "\n\n"; cout << "Enter your choice of A, R, P, S, or Q: "; cin >> answer; //if choice was A or a, asked the user to enter a number then call the add //function, the function will returen success or fail if((answer=='A')||(answer=='a')) { cout << "Enter a number: "; cin >> num; success=link.add(num, success); if(success==1) cout << "Add success" << endl; else cout << "Add fail" << endl; } else if((answer=='R')||(answer=='r')) { success=link.remove(num, success); if(success==1) cout << "Remove success" << endl; else cout << "Remove fail" << endl; } else if((answer=='P')||(answer=='p')) link.print(); else if((answer=='S')||(answer=='s')) { cout << "Enter a number: "; cin >> num; success=link.search(num, success); if(success==1) cout << "Search success" << endl; else cout << "Search fail" << endl; } //if the user enter a Q or q, set the for loop at the beginning to false and

31

//quit the program. else if((answer=='Q')||(answer=='q')) i=0; //if any other input other then A R, P, S, or Q then print out an error message else cout << "Error, you choice must be A, R, P, S, or Q"; i--; //the integer i will never get any larger. } //for loop }// main //this is the link list add function by stack. If the it was empty, make a new cell //copy the number to the new cell, else current equal to head, head equal to new cell //copy the number to the head-> new cell. and new cell ->next equal to current. this //will connect the list together. int number::add(int num, int success) { if(head==NULL) { head=new node; head->num=num; head->next=NULL; success=1; } else { cur=head; head=NULL; head=new node; head->num=num; head->next=cur; success=1; } return success; } //****remove at the head, this is stack, add at the head remove at the head. int number::remove(int num, int success) { node *temp; //make a temp pointer if(head!=NULL) //if the list is not empty

32

{ temp=head->next; //temp equal to head ->next delete head; //delete head, remove the first data of the list head=temp; //now the second data of the list become the first data of the list return success=1; //return success } else return success=0; return success; } //this function will print from the beginning of the list to the end of the list void number::print() { //if the list was empty print out an error message if(head==NULL) { cout << "There isn't any number" << endl; return; } //else while not the end of the list, print out the number and go to the next one else { cur=head; while(cur!=NULL) { cout << "number: " << cur->num << endl; cur=cur->next; } } } //the search function was search from the beginning of the head to the end of the //head. int number::search(int num, int success) { if(head==NULL) { success=0; return 0; } //if there isn't any data return 0 //if the list empty return fail

33

if(head->num == num) //if delete the first node { cout << num << " was found" << endl; success=1; return 1; } else //else delete any node other than the first node { cur=head; cur=cur->next; while(cur!=NULL) { //search all the to the end of the list

if(cur->num ==num) { cout << num << " was found" << endl; success=1; return 1; } pre=cur; cur=cur->next; success=0; }// while } //esle return success; } IV. Assimilation Direction: Express the output on the given box for each pf the programs. Include the line number. Give your observation for each of the problems.

_______________________________________________________________________ _______________________________________________________________________

34

_______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ ______ V. Supplementary Problem 1. Write a program for the following student data: Student ID Name made up of first name, middle ame, last name Gender Date of birth made up of day, month and year An array of ten grades

2. Given the following structure: struct account { char acc_no[7]; char acc_type; char name[20]; float balance; }; Create an array of accounts, assign data for the members of this structure and display the information with suitable headings.

35

Experiment Number 5

Queue
I. Objectives 1. to implement queue operations in C++ programming. 2. to apply queue to real-world situations using C++ programming II. Background Information A queue is an ordered group of elements in which new elements are added at one end (the "rear") and are removed from the other end (the "front"). This is called a First In First Out structure. Once the elements are in the queue we cannot directly manipulate their values, in order to change the value of an element we need to take it off the queue, change its value, and then return it to the queue. Each queue has the following two specifications: MAX_ITEMS = Maximum number of items that might be on the queue ItemType = Data type of the items on the queue OPERATIONS OF QUEUE 1. ENQUEUE Syntax: Enqueue(ItemType newItem) Function: Adds newItem to the rear of the queue Preconditions: Queue has been initialized and is not full Postconditions: newItem is at rear of queue

36

IMPLEMENTATION OF ENQUEUE To add a new item to a queue: q1.Enqueue(newItem);

q1 is the name of the queue we are adding a new item to

newItem is the item being added and it must be of the same data type as the one declared when the queue was initially created. 2. DEQUEUE Syntax: Dequeue(ItemType& item) Function: Removes front item from queue and returns it to item Preconditions: Queue has been initialized and is not empty Postconditions: Front element has been removed from queue and stored in item

37

IMPLEMENTATION OF DEQUEUE To delete an item from a queue: q1.Dequeue(item);

q1 is the name of the queue we are adding a new item to

item is of the same data type as the one declared when the queue was initialized.

3. IsFULL Syntax: Boolean IsFull Function: Determines whether the queue is full Preconditions: Queue has been initialized Postconditions: Function value = (queue is full)

38

IMPLEMENTATION OF IsFULL To check if a queue is full: q1.IsFull();

q1 is the name of the queue that we are looking at

the function returns a boolian that is TRUE when the queue is full and FALSE when it is not. 4. IsEMPTY Syntax: Boolean IsEmpty Function: Determines whether the queue is empty Preconditions: Queue has been initialized Postconditions: Function value = (queue is empty)

39

IMPLEMENTATION OF IsEMPTY To check if a queue is empty: q1.IsEmpty();

q1 is the name of the queue that we are looking at

the function returns a boolian that is TRUE when the queue is empty and FALSE when it is not 5. MakeEMPTY Syntax: MakeEmpty Function: Initializes the queue to an empty state Preconditions: None Postconditions: Queue is empty

40

IMPLEMENTATION OF MakeEMPTY To make a queue empty: q1.MakeEmpty(); q1 is the name of the queue that we want to make empty III. Excersise #include<iostream.h> #include<conio.h> #include<stdio.h> typedef struct {int month; int day; int year; } date; typedef struct {char name[25]; char street[20]; char city[15]; int acct_no; char acct_type; float old_bal; float new_bal; float payment; date lastpaymt; } record;

41

main() //The main program { clrscr(); int i, n; record customer[100]; record readinput(int i); void writeoutput(record customer); cout<<"\t\tCUSTOMER BILLING STATEMENT\n\n"; cout<<"How many customers? "; cin>>n; for(i = 0; i<n; ++i) { customer[i] = readinput(i); if (customer[i].payment >0) customer[i].acct_type = (customer[i].payment < 0.1*customer[i].old_bal)? '0 ': 'C'; else customer[i].acct_type = (customer[i].old_bal > 0)? 'D ': 'C'; customer[i].new_bal = customer[i].old_bal - customer[i].payment; } for (i=0; i<n; ++i) writeoutput(customer[i]); return 0; } record readinput(int i) //Read input data for a customer { record customer; cout<<"\nCustomer no. "<<i+1; cout<<"\n Name: "; gets(customer.name); if (i >= 1) gets(customer.name); cout<<" Street: "; gets(customer.street); cout<<" City:"; gets(customer.city); cout<<"\n Account no.: "; cin>>customer.acct_no; cout<<" Previous balance: "; cin>>customer.old_bal; cout<<" Current payment: "; cin>>customer.payment; cout<<" Payment date (mm/dd/yyyy): "; cin>>customer.lastpaymt.month>>customer.lastpaymt.day>>customer.lastpaymt.year; return(customer); } void writeoutput(record customer) //Write out current information for a customer

42

{cout<<"\nName: "<<customer.name; cout<<"\t\t\t\t\tAccount no.: "<<customer.acct_no; cout<<"\n"<<" Street: "<<customer.street; cout<<"\n City: "<<customer.city; cout<<"\n\n Old balance: "<<customer.old_bal; cout<<"\n Current payment: "<<customer.payment; cout<<"\n New balance: "<<customer.new_bal; cout<<"\nAccount Statuus"; switch (customer.acct_type) { case 'C': cout<<"CURRENT\n\n"; break; case 'O': cout<<"OVERDUE\n\n"; break; case 'D': cout<<"DELINQUENT\n\n"; break; default : cout<<"ERROR\n\n"; } getch(); return; }

43

IV. Assimilation Direction: Express the output on the given box for each pf the programs. Include the line number. Give your observation for each of the problems.

_______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ __________ _______________________________________________________________________ _ _______________________________________________________________________ _

44

V. Supplementary Problem 1. Write a program using a structure comprising club members names, are codes and telephone numbers. Input values for these members and display them by area code. 2. Initialize the structure that has the members names and birthdays. Given a data, display the names of people who were born on this date.

45

Experiment Number 6

Pointers
I. Objectives 1. to implement queue operations in C++ programming. 2. to apply queue to real-world situations using C++ programming II. Background Information A pointer is simply variables that are used to store memory addresses. Pointers are a very powerful feature of the C++ language that has many uses in advanced programming. Farther ahead, we will see how this type of variable is used and declared. Memory Address 2000 2001 2002 2003 2004 2005 2006 Declaring variables of pointer types Due to the ability of a pointer to directly refer to the value that it points to, it becomes necessary to specify in its declaration which data type a pointer is going point to. It is not the same thing to point to a char than to point to an int or a float. The declaration of pointers follows this format: type * name; where type is the data type of the value that the pointer is intended to point to. This type is not the type of the pointer itself! but the type of the data the pointer points to. For example: int * number; char * character; float * greatnumber; Variable in memory 2005

46

These are three declarations of pointers. Each one is intended to point to a different data type, but in fact all of them are pointers and all of them will occupy the same amount of space in memory (the size in memory of a pointer depends on the platform where the code is going to run). Nevertheless, the data to which they point to do not occupy the same amount of space nor are of the same type: the first one points to an int, the second one to a char and the last one to a float. Therefore, although these three example variables are all of them pointers which occupy the same size in memory, they are said have different types: int*, char* and float* respectively, depending on the type they point to. Pointer initialization When declaring pointers we may want to explicitly specify which variable we want them to point to: int number; int *tommy = &number; The behavior of this code is equivalent to: int number; int *tommy = &number; When a pointer initialization takes place we are always assigning the reference value to where the pointer points (tommy), never the value being pointed (*tommy). You must consider that at the moment of declaring a pointer, the asterisk (*) indicates only that it is a pointer, it is not the reference operator (although both use the same sign: *). Remember, they are two different functions of one sign. Thus, we must take care not to confuse the previous code with: int number; int *tommy; *tommy = &number;

that is incorrect, and anyway would not have much sense in this case if you think about it. As in the case of arrays, the compiler allows the special case that we want to initialize the content at which the pointer points with constants at the same moment the pointer is char * terry = hello; In this case, memory space is reserved to contain "hello" and then a pointer to the first character of this memory block is assigned to terry. If we imagine that "hello" is

47

stored at the memory locations that start at addresses 1702, we can represent the previous declaration as:

It is important to indicate that terry contains the value 1702, and not 'h' nor "hello", although 1702 indeed is the address of both of these. The pointer terry points to a sequence of characters and can be read as if it was an Array(remember that an array is just like a constant pointer). For example, we can access the fifth element of the array with any of these two expressions: *(terry+4) terry[4] Both expressions have the value of o (the fifth element of the array). Pointer arithmetic To conduct arithmetical operations on pointers is a little different than to conduct them on regular integer data types. To begin with, only addition and subtraction operations are allowed to be conducted with them, the others make no sense in the world of pointers. But both addition and subtraction have a different behavior with pointers according to the size of the data type to which they point. When we saw the different fundamental data types, we saw that some occupy more or less space than others in the memory. For example, in the case of integer numbers, char takes 1 byte, short takes 2 bytes and long takes 4. Suppose that we have three pointers: char *mychar; short *myshort; long *mylong; and that we know that they point to the memory locations 1000, 2000, 3000 respectively. So we write; mychar++; myshort++;

48

mylong++; mychar, as you may expect, would contain the value 1001. Nevertheless, myshort would contain the value 2002, and mylong would contain 3004. The reason is that when adding one to a pointer we are making it to point to the following element of the same type with which it has been defined, and therefore the size of the bytes of the type pointed as added to the pointer.

Pointers to pointers C++ allows the use of pointers that point to pointers, that these, in its turn, point to data (or even to other pointers). In order to do that, we only need to add an asterisk (*) for each level of reference in their declarations: char a; char *b; char **c; a = z; b = &a; c = &b; This, supposing the randomly chosen memory locations for each variable of 7230, 8092 and 10502, could be represented as:

The value of each variable is written inside each cell; under the cells are their respective addresses in memory.

49

The new thing in this example is variable c, which can be used in three different levels of indirection, each one of them would correspond to a different value:

c has type char** and a value of 8092 *c has type char* and a value of 7230 **c has type char and a value of 'z'

void pointers The void type of pointer is a special type of pointer. In C++, void represents the absence of type, so void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereference properties). This allows void pointers to point to any data type, from an integer value or a float to a string of characters. But in exchange they have a great limitation: the data pointed by them cannot be directly dereferenced (which is logical, since we have no type to dereference to), and for that reason we will always have to change the type of the void pointer to some other pointer type that points to a concrete data type before dereferencing it. This is done by performing type-castings. Null pointer A null pointer is a regular pointer of any pointer type which has a special value that indicates that it is not pointing to any valid reference or memory address. This value is the result of type-casting the integer value zero to any pointer type. Do not confuse null pointers with void pointers. A null pointer is a value that any pointer may take to represent that it is pointing to "nowhere", while a void pointer is a special type of pointer that can point to somewhere without a specific type. One refers to the value stored in the pointer itself and the other to the type of data it points to. Pointers to functions C++ allows operations with pointers to functions. The typical use of this is for passing a function as an argument to another function, since these cannot be passed dereferenced. In order to declare a pointer to a function we have to declare it like the prototype of the function except that the name of the function is enclosed between parentheses () and an asterisk (*) is inserted before the name. III. Excersise Exercise A (save as EXP6A) // my first pointer #include<iostream.h> #include<conio.h> main () { 50

clrscr(); int firstvalue, secondvalue; int * mypointer; mypointer = &firstvalue; *mypointer = 10; mypointer = &secondvalue; *mypointer = 20; cout << "firstvalue is " << firstvalue << endl; cout << "secondvalue is " <<secondvalue << endl; getch(); return 0; } Exercise B (save as EXP6B) #include<iostream.h> #include<conio.h> main () { int numbers[5]; int * p; p = numbers; *p = 10; p++; *p = 20; p = &numbers[2]; *p = 30; p = numbers + 3; *p = 40; p = numbers; *(p+4) = 50; for (int n=0; n<5; n++) cout << numbers[n] << ", "; getch(); return 0; } Exercise C (save EXP6C) #include<iostream.h> #include<conio.h> void increase (void* data, int size) { switch (size) { case sizeof(char) : (*((char*)data))++; break; case sizeof(int) : (*((int*)data))++; break; } } main ()

51

{ clrscr(); char a = 'x'; int b = 1602; increase (&a,sizeof(a)); increase (&b,sizeof(b)); cout << a << ", " << b << endl; getch(); return 0; } IV. Assimilation Direction: Express the output on the given box for each pf the programs. Include the line number. Give your observation for each of the problems. 1. _____________________________ _____________________________ _____________________________ _____________________________ _____________________________

2.

_____________________________ _____________________________ _____________________________ _____________________________ _____________________________

3.

_____________________________ _____________________________ _____________________________ _____________________________ _____________________________

52

V. Supplementary Problem 1. Write a program using pointer notation to calculate the average and the standard deviation of a given set of numbers. 2. Write a program that will generate a table of compound interest factors, F/P, where F/P = (1 + i/100)n In this formula, F represents the future value of a given sum of money, P represents its present value, i represents the annual interest rate, expressed as a percentage and n represents the number of years.. Let each row in the table correspond to a different value of n, with n ranging from 1 to 30. Let each column represent different interest rate. Include the following interest rates: 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5, 10, 11, 12 and 15 percent.

53

Experiment Number 7

Linked List
I. Objectives 1. to be able to create, insert delete and edit the content of a linked list. 2. to be able to understand the different applications of linked list. II. Background Information A linked list is simply a chain of structures which contain a pointer to the next element. That is about the simplest explanation I can provide. It is one of the simpler of the advanced data structures, and is frequently one of the first things a student learns in a second year university level data structures course. Here is a diagram to illustrate what I mean:

This definition applies only to Singly Linked Lists - Doubly Linked Lists, Skip Lists and Circle Lists are different. Some common examples of a linked list: The AmigaDOS Viewport structure always points to the next viewport. You can have multiple viewports in the same list Hash tables use linked lists for collission resolution Any "File Requester" dialog uses a linked list Binary Trees Stacks and Queues can be implemented with a doubly linked list Relational Databases (EG Microsoft Access)

Defining the data structure for a linked list The key part of a linked list is a structure, which holds the data for each node (the name, address, age or whatever for the items in the list), and, most importantly, a pointer to the next node. Here I have given the structure of a typical node: struct node { char name[20]; // Name of up to 20 letters int age; // D.O.B. would be better

54

float height; node *nxt; };

// In metres // Pointer to next node

node *start_ptr = NULL; The important part of the structure is the line before the closing curly brackets. This gives a pointer to the next node in the list. This is the only case in C++ where you are allowed to refer to a data type (in this case node) before you have even finished defining it! How to address elements in a linked list It is always a good idea to put your linked list into it's own Class. This makes it much easier to manage as you can write your own methods to manipulate it. A linked list class should contain the following elementary functions:

Add To Head (Var_Type element) Add To Tail (Var_Type element) Var_Type Remove From Head Var_Type Remove From Tail

Other functions such as search, sort, and a remove from within the list are also useful, and implementation of these will be provided in pseudo-code and in C++ in the sample source code. A list item has a pointer to the next element, or to 0 if the current element is the tail (end of the list). This pointer is of the same type as the structure itself. This structure that contains elements and pointers to the next structure is called a Node. A sample call would look like the following: //move to the next element in the list temp = temp->next; //move 2 elements down the list temp = temp->next->next; // and so on //go to the head of the list temp = head; // temp = tail to go to the end These 3 examples show how easy it is to traverse a list. As you move though the list, to access the elements all you need to do is address the appropriate field in the Node structure. value = Node->info; // info is the data contained at this location in the list Adding an element to the head of a linked list

55

Adding an element to the head of a linked list is quite simple. First the procedure must allocate the appropriate resources/memory in such a way that it will point to the head of the list. Then it will make sure that current element (head+1 if you will) is not the last element in the list. If so, it will change the pointers accordingly. // Add an element to the start of the linked list procedure AddToHead(element) head = new Node(element, head) if(not the Tail) tail = head end if end procedure Adding an element to the tail of a linked list Adding an element to the tail of a list is slightly different. The procedure must allocate a node that is pointed to by the last element in the list. Then the procedure must set the current node pointer to the next element, and do the same for the tail pointer (tail+1 if you will). Removing an element from the head of a linked list This one is a little harder to follow. First, it must get the element contained in head. Then it must patch up the linked list accordingly. The bond between head and the next element is broken, so the next element in the list is set to be the head. Removing an element from the head of a linked list Removing an element from the tail of the list is a bit simpler. First, the element must be obtained, and then the memory used by the tail node is released. The tail pointer is set at the preceding element and the procedure makes sure that this is not the last element in the list. Displaying the list of nodes Having added one or more nodes, we need to display the list of nodes on the screen. This is comparatively easy to do. Here is the method: 1. 2. 3. 4. Set a temporary pointer to point to the same thing as the start pointer. If the pointer points to NULL, display the message "End of list" and stop. Otherwise, display the details of the node pointed to by the start pointer. Make the temporary pointer point to the same thing as the nxt pointer of the node it is currently indicating. 5. Jump back to step 2.

56

III. Excersise #include <iostream.h> struct node { char name[20]; // Name of up to 20 letters int age; // D.O.B. would be better float height; // In metres node *nxt;// Pointer to next node }; node *start_ptr = NULL; node *current; int option = 0; // Used to move along the list

void add_node_at_end() { node *temp, *temp2; // Temporary pointers // Reserve space for new node and fill it with data temp = new node; cout << "Please enter the name of the person: "; cin >> temp->name; cout << "Please enter the age of the person : "; cin >> temp->age; cout << "Please enter the height of the person : "; cin >> temp->height; temp->nxt = NULL; // Set up link to this node if (start_ptr == NULL) { start_ptr = temp; current = start_ptr; } else { temp2 = start_ptr; // We know this is not NULL - list not empty! while (temp2->nxt != NULL) { temp2 = temp2->nxt; // Move to next link in chain } temp2->nxt = temp; } } void display_list() { node *temp;

57

temp = start_ptr; cout << endl; if (temp == NULL) cout << "The list is empty!" << endl; else { while (temp != NULL) { // Display details for what temp points to cout << "Name : " << temp->name << " "; cout << "Age : " << temp->age << " "; cout << "Height : " << temp->height; if (temp == current) cout << " <-- Current node"; cout << endl; temp = temp->nxt; } cout << "End of list!" << endl; } } void delete_start_node() { node *temp; temp = start_ptr; start_ptr = start_ptr->nxt; delete temp; } void delete_end_node() { node *temp1, *temp2; if (start_ptr == NULL) cout << "The list is empty!" << endl; else { temp1 = start_ptr; if (temp1->nxt == NULL) { delete temp1; start_ptr = NULL; } else { while (temp1->nxt != NULL) { temp2 = temp1; temp1 = temp1->nxt; } delete temp1; temp2->nxt = NULL; } } }

58

void move_current_on () { if (current->nxt == NULL) cout << "You are at the end of the list." << endl; else current = current->nxt; } void move_current_back () { if (current == start_ptr) cout << "You are at the start of the list" << endl; else { node *previous; // Declare the pointer previous = start_ptr; while (previous->nxt != current) { previous = previous->nxt; } current = previous; } } void main() { start_ptr = NULL; do { display_list(); cout << endl; cout << "Please select an option : " << endl; cout << "0. Exit the program." << endl; cout << "1. Add a node to the end of the list." << endl; cout << "2. Delete the start node from the list." << endl; cout << "3. Delete the end node from the list." << endl; cout << "4. Move the current pointer on one node." << endl; cout << "5. Move the current pointer back one node." << endl; cout << endl << " >> "; cin >> option; switch (option) { case 1 : add_node_at_end(); break; case 2 : delete_start_node(); break; case 3 : delete_end_node(); break; case 4 : move_current_on(); break; case 5 : move_current_back(); } } while (option != 0); }

59

IV. Assimilation Direction: Express the output on the given box for each of the programs. Include the line number. Give your observation for each of the problems.

_______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________

60

V. Supplementary Problem 1. Write a program that will ask the user to enter a code for a flight number and the list of all the flights available. Then the program will display the fare of that airplane. The output should be like as follows: WELCOME TO COE AIRLINES CHOICES: [A] Enter flight number [B] List all flights [Q] - Quit Enter your choice: A Flight Number: SV718 Fare: $789.00 Enter your choice: A Flight Number: TI567 Fare: $897.00 Enter your choice: L Flight Number: SV718 Fare: $789.00 Flight Number: TI567 Fare: $897.00 Enter your choice: Q Thank you for flying with COE AIRLINES. Good Day!

61

Experiment Number 8

Trees
I. Objectives 1. to be to understand the structure of a tree in programming of C++. 2. to be able to create a program for trees. II. Background Information A tree is a nonlinear data structure. The elements in a tree do not form a sequence of first, second, third and so. Instead, they have a more complex linking. The fact that trees are nonlinear structures makes them useful when we implement collection classes. Usually we call the primary element of a tree a node. Binary Tree A binary tree is made of nodes, where each node contains a "left" pointer, a "right" pointer, and a data element. The "root" pointer points to the topmost node in the tree. The left and right pointers recursively point to smaller "subtrees" on either side. A null pointer represents a binary tree with no elements -- the empty tree. The formal recursive definition is: a binary tree is either empty (represented by a null pointer), or is made of a single node, where the left and right pointers (recursive definition ahead) each point to a binary tree.

A "binary search tree" (BST) or "ordered binary tree" is a type of binary tree where the nodes are arranged in order: for each node, all elements in its left subtree are less-or-equal to the node (<=), and all the elements in its right subtree are greater than the 62

node (>). The tree shown above is a binary search tree -- the "root" node is a 5, and its left subtree nodes (1, 3, 4) are <= 5, and its right subtree nodes (6, 9) are > 5. Recursively, each of the subtrees must also obey the binary search tree constraint: in the (1, 3, 4) subtree, the 3 is the root, the 1 <= 3 and 4 > 3. Watch out for the exact wording in the problems -- a "binary search tree" is different from a "binary tree". The nodes at the bottom edge of the tree have empty subtrees and are called "leaf" nodes (1, 4, 6) while the others are "internal" nodes (3, 5, 9).

Binary Search Tree Niche Basically, binary search trees are fast at insert and lookup. The next section presents the code for these two algorithms. On average, a binary search tree algorithm can locate a node in an N node tree in order lg(N) time (log base 2). Therefore, binary search trees are good for "dictionary" problems where the code inserts and looks up information indexed by some key. The lg(N) behavior is the average case -- it's possible for a particular tree to be much slower depending on its shape. Strategy Some of the problems in this article use plain binary trees, and some use binary search trees. In any case, the problems concentrate on the combination of pointers and recursion. (See the articles linked above for pointer articles that do not emphasize recursion.) For each problem, there are two things to understand...

The node/pointer structure that makes up the tree and the code that manipulates it The algorithm, typically recursive, that iterates over the tree

When thinking about a binary tree problem, it's often a good idea to draw a few little trees to think about the various cases. Insert() Insert() -- given a binary search tree and a number, insert a new node with the given number into the tree in the correct place. The insert() code is similar to lookup(), but with the complication that it modifies the tree structure. As described above, insert() returns the new tree pointer to use to its caller. Calling insert() with the number 5 on this tree... 2 /\ 1 10

63

returns the tree... 2 /\ 1 10 / 5 The solution shown here introduces a newNode() helper function that builds a single node. The base-case/recursion structure is similar to the structure in lookup() -each call checks for the NULL case, looks at the node at hand, and then recurs down the left or right subtree if needed.

The shape of a binary tree depends very much on the order that the nodes are inserted. In particular, if the nodes are inserted in increasing order (1, 2, 3, 4), the tree nodes just grow to the right leading to a linked list shape where all the left pointers are NULL. A similar thing happens if the nodes are inserted in decreasing order (4, 3, 2, 1). The linked list shape defeats the lg(N) performance. We will not address that issue here, instead focusing on pointers and recursion. AVL Tree An AVL tree is a special type of binary tree that is always "partially" balanced. The criteria that is used to determine the "level" of "balanced-ness" is the difference between the heights of subtrees of a root in the tree. The "height" of tree is the "number of levels" in the tree. Or to be more formal, the height of a tree is defined as follows: 1. The height of a tree with no elements is 0 2. The height of a tree with 1 element is 1 3. The height of a tree with > 1 element is equal to 1 + the height of its tallest subtree. An AVL tree is a binary tree in which the difference between the height of the right and left subtrees (or the root node) is never more than one. The idea behind maintaining the "AVL-ness" of an AVL tree is that whenever we insert or delete an item, if we have "violated" the "AVL-ness" of the tree in anyway, we must then restore it by performing a set of manipulations (called "rotations") on the tree. These rotations come in two flavors: single rotations and double rotations (and each flavor has its corresponding "left" and "right" versions). An example of a single rotation is as follows: Suppose I have a tree that looks like this:

64

c / b Now I insert the item "a" and get the resulting binary tree: c / b / a Now, this resulting tree violates the "AVL criteria", the left subtree has a height of 2 but the right subtree has a height of 0 so the difference in the two heights is "2" (which is greater than 1). SO what we do is perform a "single rotation" (or RR for a single right rotation, or LL for a single left rotation) on the tree (by rotating the "c" element down clockwise to the right) to transform it into the following tree: b /\ a c This tree is now balanced. An example of a "double rotation" (or RL for a double right rotation, or LR for a double left rotation) is the following: Suppose I have a tree that looks like this: a \ c Now I insert the item "b" and get the resulting binary tree: a \ c / b This resulting tree also violates the "AVL criteria" so we fix it by first rotating "c" down to the right (so we get "a-b-c"), and then rotating "a" down to the left so that the tree is transformed into this: b /\

65

a c In order to detect when a "violation" of the AVL criteria occurs we need to have each node keep track of the difference in height between its right and left subtrees. We call this "difference" the "balance" factor and define it to be the height of the right subtree minus the height of the left subtree of a tree. So as long as the "balance" factor of each node is never >1 or <-1 we have an AVL tree. As soon as the balance factor of a node becomes 2 (or -2) we need to perform one or more rotations to ensure that the resultant tree satisfies the AVL criteria. III. Excersise PROGRAM A (save as EXP8A) template <class T> class treeNode{ public: treeNode() {LC=0; RC=0;} //constructor -- sets both subtrees to be empty trees T getData() const{return data;} treeNode<T> * getLC() const{return LC;} //return the left subtree treeNode<T> * getRC() const{return RC;} //return the right subtree void setData(T d){data = d;} //set the value of the root element void setLC(treeNode<T> * left) {LC= left;} // set the left subtree void setRC(treeNode<T> * right){RC= right;} // set the right subtree private: T data; treeNode<T> * LC; treeNode<T> * RC; }; #include <fstream.h> #include<conio.h> #include<iostream.h> void inOrder(treeNode<char> * Tree){// print the nodes of Tree in order if (Tree == 0) return; inOrder(Tree->getLC()); cout <<" " << Tree->getData(); inOrder(Tree->getRC()); } void main(){ treeNode<char> * T; T = new treeNode<char>; T->setData('o'); T->setLC(new treeNode<char>);

66

T->setRC(new treeNode<char>); (T->getLC())->setData('l'); (T->getRC())->setData('r'); cout << "\n\tThe tree is: "; inOrder(T); cout<<endl; getch(); } IV. Assimilation Direction: Express the output on the given box for each pf the programs. Include the line number. Give your observation for each of the problems.

_______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ ________

67

CASE STUDY I. Documentation Outline Part I. Title Page Technological Institute of the Philippines College of Engineering Computer Engineering Department Data Structure and Algorithm SUBJECT CODE / SECTION / SCHEDULE CASE STUDY for TITLE OF CASE STUDY Group No.: Names Date Submitted: _________________________ Instructor Attendance Grade

Part II. Evaluation Sheet Technological Institute of the Philippines College of Engineering Computer Engineering Department Data Structure and Algorithm SUBJECT CODE / SECTION / SCHEDULE CASE STUDY for TITLE OF CASE STUDY Group No.: Names Date Submitted: _________________________ 68 Instructor Job Assignment

Anda mungkin juga menyukai