Anda di halaman 1dari 16

1.

Arrays

a) Arrays: Data structures containing data items of the same type. Contains static data (size of array is fixed from
declaration all the way to implementation).

b) One Dimensional Array: Arrays having only one index or subscript. (Eg. Array[12])

c) Declaring a one dimensional array of size 10, and assign multiples of 2 using loops

#include <stdio.h>
void main(void){
int nums[10]; // array declaration, with 10 elements
int i; // counter variable used for loop
// assign multiples of 2 to array
for (i=0; i<10; i++){
nums[i] = (i+1) * 2; // add one to i, otherwise 0 will be the first element and 0 is not a multiple of 2
}
// print all elements in array
for (i=0; i<10; i++){
printf("nums[%d] : %d \n", i, nums[i]);
}
// wait till user press return key before closing window
getchar();
}

d) Printing 5 Element Integer Array

#include <stdio.h>
void main(void){
// 5 elements integer array initialized with values
int nums[5] = {11, 22, 33, 44, 55};
// counter variable used for loop
int i;
// print all elements in array
for (i=0; i<5; i++){
printf("nums[%d] : %d \n", i, nums[i]);
}
// wait till user press return key before closing window
getchar();
}

e) Calculate sum of all elements in an array with the following elements

#include <stdio.h>
void main(void){
// 5 elements integer array initialized with values
int nums[10] = {12, 21, 13, 31, 14, 41, 15, 51, 16, 61};
// counter variable used for loop
int i;
// variable to store sum, initialized to zero
int sum=0;
// Calculate sum of all elements
for (i=0; i<10; i++){
sum = sum + nums[i];
}
// print out sum
printf("Sum of all elements in nums[] = %d", sum);
// wait till user press return key before closing window
getchar();
}

www.oumstudents.tk
f) Find the total mark, average mark, and the maximum mark of the following

#include <stdio.h>
void main(void){
// array with all the marks
int marks[5] = {10, 2, 33, 14, 17};

// counter variable used for loop


int i;

// variable to store sum & average, initialized to zero


int sum=0;
float avg=0;

// variable to store maximum marks,


// initialized to first element in array
int max=marks[0];

// traverse through array to find sum, and max


for (i=0; i<5; i++){
sum = sum + marks[i];
if (marks[i] > max)
max = marks[i];
}
//calculate average
avg = sum/5.0;

// print out sum, avg, and max


printf("Sum of all marks = %d\n", sum);
printf("Avg of all marks = %0.2f\n", avg);
printf("Maximum marks = %d\n", max);

// wait till user press return key before closing window


getchar();
}

g) TUTORIAL1: Write a C program to store the below marks in an integer array. And perform the following tasks.

i. Use a loop to display all the elements in the array.


ii. Use another loop to display all the elements in reverse order.
iii. Calculate and display the sum of all marks.
iv. Calculate and display the average of all the marks.
v. Use a function called “getMaxMarks” to find out and display the maximum mark.
vi. Use a function called “getMinSubject” to find out and display which subject got the minimum mark. (Hint:
use two arrays, one to store the Subject, and the second to store the marks).

#include <stdio.h>
// initialize function prototypes
int getMaxMarks(int[], int);
int getMinSubject(int[], int);

void main(void){
// array with all the marks
int marks[9] = {12, 21, 33, 10, 55, 34, 11, 9, 3};
int subjects[9] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'};
// variables used in the program
int sum = 0; // to store sum
double avg = 0; // to store average
int minSubjectIndex; // to store min subject's index
char minSubject; // to store min subject
www.oumstudents.tk
int i;
// use loop to display all elements in array
for (i=0; i<9; i++){
printf("marks[%d] = %d\n", i, marks[i]);
}

printf("\n\n");

// use loop to display all elements in reverse order


for (i=8; i>=0; i--){
printf("marks[%d] = %d\n", i, marks[i]);
}

// calculate sum and average


for (i=0; i<9; i++){
sum = sum + marks[i];
}
avg = sum/9.0;

printf("\n\nSum of all marks = %d\n", sum);


printf("Average of all marks = %0.2f\n", avg);

// print the max marks


printf("\n\nMaximum Marks = %d", getMaxMarks(marks, 9));

// print the minimum subject


minSubjectIndex = getMinSubject(marks, 9);
minSubject = subjects[minSubjectIndex];
printf("\nMinimum Subject = %c", minSubject);

// wait till user press return key before closing window


getchar();
}

// function to return the maximum marks


int getMaxMarks(int marks[], int length){
// variable to store max marks, start from first element
int max = marks[0];
int i;

for (i=1; i<length; i++){


if (marks[i]>max)
max = marks[i];
}
// return the maximum marks
return max;
}

// function to return the index of the minimum subject


int getMinSubject(int marks[], int length){
// variable to store the minimum marks, start from first element
int min = marks[0];
// variable to store the index of the min marks,
// start from first element // this index will be used to refer to the minimum subject
int minIndex = 0;
int i;

for(i=1; i<length; i++){


if (marks[i]<min){
min = marks[i];
minIndex = i;
}
}
// return the index of the minimum marks
return minIndex;
}

www.oumstudents.tk
h) Write a C program to perform the following array operations using the data below:

• Array 1: {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}
• Array 2: {100, 90, 80, 70, 60, 50, 40, 30, 20, 10}
• Array 3: {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}

i. Create the Array 1, and assign the values while declaring the array.
ii. Create the Array 2 by copying the values in Array 1 in reverse order.
iii. Create the Array 3 by using the values in Array 2. (Hint: divide each array element in Array 2 by 10 before
assigning to Array 3).

#include <stdio.h>

void main(void){

// array declarations
int array1[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int array2[10], array3[10];
int i;

// create array2 in reverse order of array1


for (i=0; i<10; i++){
array2[i] = array1[9-i];
}

// create array3 from array2


for (i=0; i<10; i++){
array3[i] = array2[i]/10;
}

// print array2
for (i=0; i<10; i++){
printf("array2[%d] = %d\n", i, array2[i]);
}

printf("\n\n");

// print array3
for (i=0; i<10; i++){
printf("array3[%d] = %d\n", i, array3[i]);
}

// wait till user press return key before closing window


getchar();
}

i) Two Dimensional Array: Can be regarded as two dimensional matrix that has rows and columns. (Eg. In
Array[x][y], row is x, column is y)

j) Find the Total, Average, Worst, and Best Student from the following marks. Also find the class average using all
the totals.

www.oumstudents.tk
#include <stdio.h>

void main(void){

// array to store students


char students[6] = {'A', 'B', 'C', 'D', 'E', 'F'};

// array to store marks for 5 subjects


// and additional two columns to store total & average
// total and average are entered as 0 when initialized
// because they will be calculated later
int marks[][7] = { {26, 52, 66, 93, 73, 0, 0},
{70, 30, 92, 34, 18, 0, 0},
{62, 61, 64, 82, 11, 0, 0},
{30, 23, 13, 32, 59, 0, 0},
{25, 33, 78, 71, 25, 0, 0},
{32, 73, 25, 49, 19, 0, 0}};

// to store per student total & avg


int sTotal = 0, sAvg = 0;
// to store class total & avg
int classTotal=0, classAvg=0;
int bestMarks, worstMarks;
char bestStudent=students[0], worstStudent=students[0];

int row, col;

// calculate and assign student totals & avgs


for (row = 0; row<6; row++){
// loop until the 5th column
// becuase there are only 5 subjects
for (col = 0; col<5; col++){
sTotal = sTotal + marks[row][col];
}
//calculate student avg
sAvg = sTotal/5;

// assign total & avg


marks[row][5] = sTotal;
marks[row][6] = sAvg;

// add student total to the class total


classTotal = classTotal + sAvg;

// reset student total and avg


sTotal = 0;
sAvg = 0;
}
// calculate class avg
classAvg = classTotal/6;

// assign first student as best and worst


bestMarks=marks[0][5];
worstMarks=marks[0][5];

// find best student


for (row = 0; row<6; row++){
printf("\n%d-%d", marks[row][5], bestMarks);
if (marks[row][5] > bestMarks){
bestMarks = marks[row][5];
bestStudent = students[row];
}

if (marks[row][5] < worstMarks){


worstMarks = marks[row][5];
worstStudent = students[row];
}
}

www.oumstudents.tk
// print marks table
printf("\n\nStudents\tSub1\tSub2\tSub3\tSub4\tSub5\tTotal\tAvg");
printf("\n========\t====\t====\t====\t====\t====\t=====\t===");
for (row = 0; row<6; row++){
printf("\n%c\t", students[row]);
for (col = 0; col<7; col++){
printf("\t%d", marks[row][col]);
}
}
printf("\n\nClass Average = %d", classAvg);
printf("\nBest Student = %c", bestStudent);
printf("\nWorstStudent = %c", worstStudent);

// wait till user press return key before closing window


getchar();
}

2. Characters and Strings


a) Characters: Can consist of a single letter, digit or even special symbol. (bounded in single quotations ‘ ’ )

b) String: Character arrays that end with a NULL (‘\0’)character. (bounded in double quotations “ ”)

c) File Manipulation Functions for ctype.h library:


i. int isdigit(int c): Returns true if c is a digit, otherwise false (0)
ii. int isalpha(int c): Returns true if c is a letter, otherwise false (0)
iii. int islower(int c): Returns true if c is a lowercase letter, otherwise false (0)
iv. int isupper(int c): Returns true if c is a uppercase letter, otherwise false (0)
v. int tolower(int c): Returns c in its lowercase
vi. int toupper(int c): Returns c in uppercase

d) Input and Output Functions for Characters and Strings in stdlib.h library:
i. int getchar(): Inputs the following character from the input device and return the character as a value
ii. int putchar (int c): Prints the character to the output device
iii. char *gets (char str): Inputs the string from the standard input device and stores in str until ‘\n’ or <eof> is
found. NULL character is added to the end of the string.
iv. int puts (char *str): Prints the str string to the output device
v. int fflush (FILE *file): Empties the file buffer. (Eg. We use fflush(stdin); where stdin means the standard
input device, aka. keyboard)

e) File Manipulation Functions for Strings in string.h library:


i. char *strcpy (char s1[], char s2[]): Copies s2 string to s1 string and returns the value of s1
ii. size_t strlen(char s1[]): Returns the number of characters in the string s1
iii. char *strcat (char s1, char s2): Copies the s2 string on the end of s1 string.
iv. int strcmp (char s1, char s2): Compares s1 and s2 lexographically (s1=s2 returns 0, s1<s2 returns less than 0,
s1>s2 returns greater than 0)
v. char *strtok (char *s1, char *s2): generates tokens in s1 string.

f) String Array: Two dimensional character array where each array line is a single string. (Eg. char day[7][10] =
{“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”} )

www.oumstudents.tk
g) Strings Tutorial

• Create a function to display the length of a string


• Create a function to display the number of Upper Case characters in a string
• Create a function to inverse the case of characters

#include <stdio.h>
#include <ctype.h>
// initializing function prototypes
int getLength(char[]);
int getUCaseCount(char[]);
void inverseCase(char[]);

void main(void){
// create the string
char name[] = "Ahmed Ibrahim";

printf("\nLength of String %s is = %d", name, getLength(name));


printf("\nNumber of Upper Case characters in String %s is = %d", name,
getUCaseCount(name));
printf("\nString %s in reverse case is =", name);

// call function to inverse case


inverseCase(name);
printf(" %s\n", name);
}

// get length of string


int getLength(char str[]){
int i=0;
while (str[i] != '\0'){
i++;
}

return i;
}

// get number of upper case characters in string


int getUCaseCount(char str[])
{
int i=0, count=0;
while (str[i] != '\0'){
if (isupper(str[i])){
count++;
}
i++;
}

return count;
}

// reverse case of the string


void inverseCase(char str[]){
int i=0;
while (str[i] != '\0'){
if (isupper(str[i]))
str[i] = tolower(str[i]);
else
str[i] = toupper(str[i]);

i++;
}
}

www.oumstudents.tk
3. Structures
a) Structures: Combination of bits of data from different sources and types.

b) Structure Array: Represents a group of data from the same type of structure. (Eg. struct account customer[10])

c) Structure Tutorial: Create another user account structure to store the following data.

#include <stdio.h>
#include <string.h>

// define long date structure


// format: dd-mmm-yyyy, ddd
// e.g.: 12-Mar-2009, Wed
struct long_date {
int day;
char month[4];
int year;
char wday[4];
};

// define user account structure


struct user_account {
char name[25];
char address[25];
struct long_date DOB;
};

// Function prototypes
void printdate(struct long_date);
void printaccount(struct user_account);
struct long_date inputdate(void);
struct user_account inputaccount(void);

void main(void) {

struct long_date ld;


struct user_account myaccount;

// input and display a long date


ld = inputdate();
printdate(ld);
printf("\n\n");

// input and display a user account


myaccount = inputaccount();
printaccount(myaccount);

// wait till user press return key before closing window


getchar();
}

// Functino to print the date in long date format


// Accepts a copy of a long_date struct as the parameter
void printdate(struct long_date mydate) {
printf("\n%d-%s-%d, %s\n\n",
mydate.day,
mydate.month,
mydate.year,
mydate.wday);
}

www.oumstudents.tk
// Function to print the user account information
// Accepts a copy of a user_account struct as the parameter
void printaccount(struct user_account myaccount) {
printf("Print User Account Details\n");
printf("--------------------------\n");
printf("Name:\t\t%s\nAddress:\t%s\nDOB:\t\t%d-%s-%d, %s\n",
myaccount.name,
myaccount.address,
myaccount.DOB.day,
myaccount.DOB.month,
myaccount.DOB.year,
myaccount.DOB.wday);
}

// Function to input the long date


// Returns a copy of a long_date struct
struct long_date inputdate() {
struct long_date mydate;

printf("Day: ");
scanf("%d", &mydate.day);
fflush(stdin);

printf("Month: ");
gets(mydate.month);
fflush(stdin);

printf("Year: ");
scanf("%d", &mydate.year);
fflush(stdin);

printf("Week Day: ");


gets(mydate.wday);
fflush(stdin);

return mydate;
}

// Function to input the user account details


// Returns a copy of a user_account struct
struct user_account inputaccount() {

struct user_account myaccount;

puts("Name: ");
gets(myaccount.name);

puts("Address: ");
gets(myaccount.address);

puts("DOB:-");
myaccount.DOB = inputdate();

return myaccount;
}

www.oumstudents.tk
4. Pointers
a) Pointer: A variable that contains an address value referring to the memory location of a variable or an array
element. (* (star) is the Reference Operator while & (ampersand) is the Address Operator)

int *p; // pointer to the int variable


int a; // variable declaraton
p=&a; // p points to a
*p=3; // assign 3 to the address that is pointed by p, which is a

b) Array Name: A constant pointer to the first element of an array. (Eg. xarray points to &xarray[0]). It cannot
change its value or point to another location other than the first element of the array.

c) Reference Passing: Method of passing the address to a local pointer variable that points to the actual location
of the data item, where changes can be made to the actual data item.

d) Dynamic Memory related Functions in stdlib.h:


i. viod *malloc (size_t size): Returns the address for the memory that has been reserved, otherwise returns
NULL upon failure.

Eg. Nnode = (NODE *) malloc (sizeof(NODE));

ii. viod free (void *prt): Release the memory that has been reserved by malloc().

5. Linked Lists
a) Lists: Group of data items that is sequentially forming a list, where its data items are not linked to one another
(Implemented using arrays).

b) Linked Lists: Group of data items that is sequential with its


data items having links between each other. Consist of
sequential items known as Nodes. (Nodes have 2 parts;
data element and the link to the next node) (Implemented
using both arrays AND pointers)

c) Basic Operations:

Lists Linked Lists


i. Create empty list i. Create empty linked list
ii. Test weather a list is empty or not: Because If the ii. Test weather a linked list is empty or not
list is empty, deletion cannot be performed
iii. Traverse list iii. Traverse linked list
iv. Insert new item to list iv. Insert new item to linked list
v. Delete an item from the list v. Delete an item from the linked list
vi. Create new nodes (Using malloc() )
vii. Search Linked list linearly

d) Assignment Question 2A: Using linked lists to insert a node into the linked list so that it remains sorted

// include libraries
#include <stdio.h>
#include <conio.h>
// type defining and creating the linked list structure
typedef struct linkedList {
int data;
struct linkedList *next;
} NODE;

www.oumstudents.tk
// globally initialising the linked list Slist
NODE *Slist;
// initialising function prototypes
void viewLinkLst(NODE *);
NODE *addSort(NODE *,NODE *);

// START FUNCTION: MAIN


void main(void)
{
// setting up the given linked list Slist
NODE node4 = {18,NULL};
NODE node3 = {15,&node4};
NODE node2 = {14,&node3};
NODE node1 = {10,&node2};
Slist=&node1;

NODE P = {12,NULL}; //The Node P that is to be inserted into the linked list

// Display the header


printf("\n\n\t-----------------------------------\n");
printf("\t LINKED LIST INSERTION AND SORTING\n");
printf("\t-----------------------------------\n\n\n");

printf("\n\tDISPLAYING THE GIVEN SLIST\n\n\t");


viewLinkLst(Slist); // Displaying the given linked list
Slist=addSort(Slist,&P);
printf("\n\n\n\tSLIST AFTER NODE P(%d) INSERTION\n\n\t", P.data);
viewLinkLst(Slist);
getch();
}

// START FUNCTION: VIEWLINKLIST


void viewLinkLst(NODE *list)
{
// Loop till all elements of the list are printed
while (list!= NULL)
{
printf("%d ",list->data); // print the element
list = list->next; // goto the next element
}
}

// START FUNCTION: SORTORDER


NODE *addSort(NODE *list, NODE *P)
{
// Initialize list and the new Node
NODE *newList=list,*p=NULL;

// Add the new node to the list


while (newList!=NULL)
{
p = ((newList->data)<(P->data))?newList:p;
newList = newList->next;
}

// sort the list so that P goest to the correct place


if (p!=NULL)
{
P->next=p->next;
p->next=P;
} else {
P->next=list;
list=P;
}

// return the new added sorted linked list


return list;
}
www.oumstudents.tk
e) Assignment Question 2B: Combining two null terminated linked lists so that the nodes of the new list alternate
between those of the original two nodes

// include libraries
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

// type defining and creating the linked list structure


typedef struct linkedList {
char data;
struct linkedList *next;
} NODE;

// globally initializing the link lists list_1 and list_2


NODE *list_1,*list_2;

// initialising function prototypes


void viewLinkLst(NODE *);
int sizeCheck(NODE *);
NODE *combine(NODE *,NODE *);

//main function
void main(void)
{
// setting up list 1
NODE list01_2 = {'B',NULL};
NODE list01_1 = {'A',&list01_2};
list_1=&list01_1;
// setting up list 2
NODE list02_2 = {'2',NULL};
NODE list02_1 = {'1',&list02_2};
list_2=&list02_1;

// Display the header


printf("\n\n\t-----------------------------------\n");
printf("\t COMBINING TWO LINKED LISTS\n");
printf("\t-----------------------------------\n\n\n");

// displaying the given two lists


printf("\tList 1:\t");
viewLinkLst(list_1);

printf("\n\n\tList 2:\t");
viewLinkLst(list_2);

// displaying the combined list


printf("\n\n\tCombined Alternatively:\n\n\t");
viewLinkLst(combine(list_1,list_2));

getch();
}

// function to display the linked list


void viewLinkLst(NODE *list)
{
while (list!=NULL)
{
printf("%c ",list->data);
list = list->next;
}
}

// function to combine the two linked lists


NODE *combine(NODE *list_1,NODE *list_2)
{
// initializing variable
NODE *LIST=list_1,*t;
www.oumstudents.tk
while (list_1!=NULL)
{
t=list_2->next;
list_2->next=list_1->next;
list_1->next=list_2;
list_1=list_2->next;
list_2=t;
}

return LIST;
}

6. Stacks
a) Lists: A heap of arranged data items that can be accessed from one end only. (Limited version of an Array, LIFO:
Last-In-First-Out) (Implemented using both arrays AND pointers)

b) Basic Stack Operations:


i. Create Stack
ii. Test empty Stack (for POP)
iii. Test Full Stack for PUSH)
iv. POP - Remove Element from Stack
v. PUSH - Add Element to Stack

c) Postfix Expression Algorithm:


i. Create a Stack
ii. Repeat Until the End of the Expression
1. Read the Next token in the Expression
2. If the token is an operand, then
i. Insert the token into the Stack
3. If the token is an Operator, then
i. Remove two topmost values from the stack
ii. Perform operation
iii. Insert result into the stack

7. Queues
a) Queues: an ordered list where elements can be added at only one point (which is called the back or end) and an
item can only be removed from the other end (which is called the front or head).

b) Basic Queue Operations:


i. Create Queue
ii. Test empty Queue
iii. Test Full Queue
iv. Remove Element from Queue
v. Add Element to Queue

www.oumstudents.tk
8. Sorting

a) Simple selection sorting: Starting from the left, interchange with the smallest digit and do this with each
line.(so that the smallest number will be at the left side after every step)
20 11 4 8
4 11 20 8
4 8 20 11
4 8 11 20

b) Linear Insertion Sorting: there will be a sorted list(starting from the left) and an unsorted list. In every step,
number of digit in sorted list will be incremented with one.
20 11 4 8
11 20 4 8
4 11 20 8
4 8 11 20
Highlighted is the sorted list where whole list is pushed to right as the smallest digit from the unsorted list is
taken to the sorted list.

c) Quick sorting: Compare pivot to smallest from right and interchange, then in the next line compare pivot to
biggest from left and interchange/ make sub-list if pivot is balancing
20 11 4 8 27 25
8 11 4 20 27 25
8 11 4 27 25
4 11 8 25 27
4 8 11
4 8 11 20 25 27

d) Bubble sorting: This sorting performs adjacent element exchanges until all elements are arranged according to
the requirements
Round 1
20 11 4 8
11 20 4 8
11 4 20 8
11 4 8 20

Round 2
11 4 8 20
4 11 8 20
4 8 11 20

Round 3
4 8 11 20
4 8 11 20

www.oumstudents.tk
9. Searching

a) Sequential Search: This technique is applied to records that are arranged using arrays or linked lists. Searching
begins with the first record and this is done sequentially until the data is found.

Say A[1], A[2], ... , A[n] are arrays that consists of n keys Ki; (1 <= i <= n) that are different.

The K key is the argument that is searched (key search). The following algorithm
will find the smallest integer i (array index) where Ki is its key.

For i = 0 until key number n


Start_for
If search_value = K(i)
Return i value
End_for

b) Binary Search: In binary search, what needs to be found is the position for a K search key in a table. The search
key is compared to a key in the middle of the table.

If key value in middle of table =


search key,
Search successful.
If not,
Test whether the value of search key > value of middle key.
If yes,
The search process continues for the element above
the middle key in the table.

If not, the search process continues for the elements below the
middle key in the table.

For example, find search key 39.

Number of data = 10
Initial value = 0 (array index value starts from 0)
Final value = 9

Round 1 We find the middle value first. Round 2 The result of round 1 found that the focus location
Middle value = (initial + final)/2 for the search is on the right of the middle key, which are the
= (0 + 9)/2 locations that goes toward the end. Therefore, we need to
change the initial value to the location to the right of the middle
= 9/2 value, which is the middle value plus 1.
=4
Change initial value, which is initial = middle + 1
Test the middle key with the search key. =4+1
Middle key = k(4) = 20 // 20 < 39 =5
We calculate for the middle value again.
Middle value = (initial + end) / 2
= (5 + 9)/2
=14 / 2
Since the search key value (39) is bigger than the middle key (20), =7
the focus of the search will only be on the right of the middle key, Test middle key with search key:
which is location k(5) until k(9). Middle key = k(7) = 40 //40 < 39

In this round, we found that the value of the search key (39) is
less that the middle key (40), therefore, the focus of the search
will only by to the left of that middle key, which is location k(5)
and k(6). You need to give your full attention to follow this
algorithm. Let us continue to the next round

www.oumstudents.tk
Round 3 The result of the second round has revealed that Round 4 From the result of round 3, the search location
the focus of the search is to the left of the middle key, which is the focus is now on the right of the middle key, which are the
location leading towards the start value. Therefore, we need to locations leading toward the end. Here, we need to change the
change the end value of the location to the left of the middle initial value of the location to the left of the middle key value,
value, which is middle value minus one. which is the middle minus one.

Change end value, End = middle - 1 Change final value, initial = middle + 1
=7-1 =6+1
=6 =7

We find the middle value again. We calculate for the middle value again.
Middle value = (initial + end)/2 Middle value = (initial + end) / 2
= (5 +6)/2 = (7 + 6)/2
= 11/2 =13 / 2
=5 =6

Test the middle key with the search key. Test the middle key with the search key.
Middle key = k(5) = 25 Middle key = k(6) = 39

In this round we found that the search key value (39) is bigger than Thus, our search is successful.
the middle key (25), so the focus of the search is only to the right of
the middle key, which is location k(5). Therefore, our search is
successful.

10. Trees

a) Trees: A structure that consists of nodes that are linked with directed pointers.
b) Binary Tree: A binary tree is a tree in which no node can have more than two subtrees. In other words, a node
can be zero, one or two subtrees.
c) Expression Trees:
Look at the following expression:
A/(B*C)+D
Add parentheses.
((A/(B*C))+D)

i. Infix expression (LNR): ((A / ( B * C ) ) + D )


ii. Postfix expression (LRN): A B C * / D +
iii. Prefix expression (NLR): + / A * B C D

www.oumstudents.tk

Anda mungkin juga menyukai