You are on page 1of 13

Data Structures

MTS 3021 (Group B)


Individual Assignment
Students Name Matrix No Lecturers Name Due Date : : : : Norasikin Binti Alimom D 20101039025 Encik Md. Zahar Bin Othman 17 October 2011

1) Write a full program for the bubble sort algorithm. User is required to enter specific input numbers and the program will be able to sort the given numbers in ascending order. Write down in a table the time (according to your system clock) that it takes for the program to complete. You may do this by running the program for several values of input. (20 marks) Hints: a) Write full source code b) Use system clock to measure the running time c) Use several input (eg: N = 100 , N = 1000 , N = 10000, N = 100000 etc) d) Have access to a file (to store your running time) #include<iostream> #include<time.h> #include<stdlib.h> #define Array_size 100000000 using namespace std; int main() { int array[Array_size]; int i; time_t begin, end; srand(time(NULL)); for (i=0;i<Array_size;i++) { array[i]=rand(); } begin=clock(); for (i=0;i<Array_size;i++) end=clock(); cout<<"Time elapsed : "<<difftime(end,begin)<<"seconds"<<endl; return 0; } Access file : nano assignment1.cpp Results Input 100 1000 10000 100000 1000000 10000000 Output (T(n)) 0 second 0 second 0 second 0 second 0 second 0 second

2) What is the difference between static and dynamic memory allocations? List advantages and disadvantages for the both type of memory allocations. (5 marks) Static memory allocation refers to the process of allocating memory at compiletime before the associated program is executed, unlike dynamic memory allocation or automatic memory allocation where memory is allocated as required at run-time. An application of this technique involves a program module declaring static data locally, such that these data are inaccessible in other modules unless references to it are passed as parameters or returned. A single copy of static data is retained and accessible through many calls to the function in which it is declared. Static memory allocation therefore has the advantage of modularising data within a program design in the situation where these data must be retained through the runtime of the program. The use of static variables within a class in object oriented programming enables a single copy of such data to be shared between all the objects of that class. Object constants known at compile-time, like string literals, are usually allocated statically. In object-oriented programming, the virtual method tables of classes are usually allocated statically. A statically defined value can also be global in its scope ensuring the same immutable value is used throughout a run for consistency. Static memory allocation may be used to create queues or stack. Dynamic memory allocation (also known as heap-based memory allocation) is the allocation of memory storage for use in a computer program during the run-time of that program. It can be seen also as a way of distributing ownership of limited memory resources among many pieces of data and code. Dynamically allocated memory exists until it is released either explicitly by the programmer, or by the garbage collector. This is in contrast to static memory allocation, which has a fixed duration. It is said that an object so allocated has a dynamic lifetime. Usually, memory is allocated from a large pool of unused memory area called the heap (also called the free store). Since the precise location of the allocation is not known in advance, the memory is accessed indirectly, usually via a pointer reference. The precise algorithm used to organize the memory area and allocate and deallocate chunks is hidden behind an abstract interface and may use any of the methods described below. So that, the difference is dynamic memory allocation is at runtime and static memory allocation is before run time, but the values of variables may be changed at run time. Static memory allocation saves running time, but can't be possible in all cases. Dynamic memory allocation stores it's memory on heap, and the static memory allocation stores it's data in the "data segment" of the memory.

Static memory allocation Advantages


Faster execution than Dynamic.

Dynamic memory allocation


Less Memory space required.

No memory allocation or deallocation actions are performed during Execution.

No need of Dynamically allocated pointers. Memory is allocated during the execution of the program

Disadvantages

Memory is allocated before the execution of the program begins. More memory Space required.

Freeing memory Fragmentation of memory


Slower execution than static.

Pointer is needed to accessing variables. wasting space if we declare more than we need

Memory Bindings are established and destroyed during the Execution.

3) Use structure to wrap student information (such as Matrix Number, name and MTS 3023 mark) and manipulate it by reading information to an array of student structure and print them on to console screen. (10 marks) #include<iostream> using namespace std; struct Student { char name[10]; char id[14]; int grade; }; int main() { cout<<"**STUDENT MTS3023 INFORMATION**\n\n"; Student student1; Student student2; Student student3; Student student4; Student student5; cout<<"student's name :";

cin>>student1.name; cout<<"student matrix no :"; cin>>student1.id; cout<<"student's mark : "; cin>>student1.grade; cout<<" "<<endl; cout<<"student's name :"; cin>>student2.name; cout<<"student matrix no :"; cin>>student2.id; cout<<"student's mark : "; cin>>student2.grade; cout<<" "<<endl; cout<<"student's name :"; cin>>student3.name; cout<<"student matrix no :"; cin>>student3.id; cout<<"student's mark : "; cin>>student3.grade; cout<<" "<<endl; cout<<"student's name :"; cin>>student4.name; cout<<"student matrix no :"; cin>>student4.id; cout<<"student's mark : "; cin>>student4.grade; cout<<" "<<endl; cout<<"student's name :"; cin>>student5.name; cout<<"student matrix no :"; cin>>student5.id; cout<<"student's mark : "; cin>>student5.grade;

cout<<" "<<endl; cout<<"\nName:"<<" "<<student1.name<<" "<<student2.name<<" "<<student3.name<<" "<<student4.name<<" "<<student5.name<<endl; cout<<"\nMatric No:"<<" "<<student1.id<<" "<<student2.id<<" "<<student3.id<<" "<<student4.id<<" "<<student5.id<<endl; cout<<"\nMark:"<<" "<<student1.grade<<" "<<student2.grade<<" "<<student3.grade<<" "<<student4.grade<<" "<<student5.grade<<endl; }

4) The common error message which might encounter in your program is memory access violation or segmentation violation. What does it mean? How to avoid it? (5 marks) A segmentation fault (often shortened to segfault), bus error or access violation is generally an attempt to access memory that the CPU cannot physically address. It occurs when the hardware notifies an operating system about a memory access violation. The OS kernel then sends a signal to the process which caused the exception. By default, the process receiving the signal dumps core and terminates. The default signal handler can also be overridden to customize how the signal is handled. A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed (for example, attempting to write to a read-only location, or to overwrite part of the operating system). Segmentation is one approach to memory management and protection in the operating system. It has been superseded by paging for most purposes, but much of the terminology of segmentation is still used, "segmentation fault" being an example. Some operating systems still have segmentation at some logical level although paging is used as the main memory management policy. On Unix-like operating systems, a signal called SIGSEGV is sent to a process that accesses an invalid memory address. On Microsoft Windows, a process that accesses invalid memory receives the STATUS_ACCESS_VIOLATION exception. How to overcome: 1. Indicator variable must be a valid address (ie, appears on the left side of the assignment 1) prior to access (ie, appears on the right side of the assignment). Make sure that you have started all the instructions to point to a valid memory area. Control of the right indicators can be done several ways. The examples listed below. Incorrect use of "&" (address) and "*" (dereferencing) operator. 2. Ensure operators understand how this works. Know when they should be used and when not required. As mentioned above, it is common to forget to use "&" with each variable in the scanf call. Remember, scanf requires the address of the variable is read. In particular, know when "&" and "*" is absolutely necessary and when it is better to avoid using it.attempting to alter memory the program does not own (storage violation). Exceeding the allowable stack size (possibly due to runaway recursion or an infinite loop)

5) For each of the following four program fragments: a. Give an analysis of the running time (Big-Oh) b. Implement the code and give the running time for several values of N c. Compare your analysis with the actual running times (20 marks)

1) Sum = 0; for( i = 0 ; i < 5; i++) Sum++; Answer: T(n)=0(5) 2) Sum = 0; for( i = 0 ; i < 5; i++) for (j = 0 ; j < 5 ; j++) Sum++; Answer: T(n)=0(5)*0(5) =0(25) 3) Sum = 0; for( i = 0 ; i < 5; i++) for (j = 0 ; j < i ; j++) Sum++; Answer: T(n)=0(5)*0(5) =0(25) 4) Sum = 0; for( i = 0 ; i < 5; i++) for (j = 0 ; j < i *i; j++) Sum++; Answer: T(n)=0(5)*0(5*5) =0(100)

6) Implement in two separate files, called fibonacci1.cpp and fibonacci2.cpp, the iterative and the recursive methods for computing Fibonacci numbers. The programs should read from the standard input the value of N, and output the corresponding Fibonacci value. Write down in a table the time (according to your system clock) that it takes for each program to complete, for each of the following N values: 1, 2, 4, 8, 16, 32, 64. (20 marks)

Fibonacci iterative #include <iostream> using namespace std; unsigned long fibonacci(unsigned long); int main () { unsigned long result, number; for(number = 0; number <= 64; number++) { result = fibonacci(number); cout << "Fibonacci(" << number << ") = " << result << endl; } return 0; } //Iterative fibonacci function unsigned long fibonacci(unsigned long n) { static unsigned long int f, f1, f2; if (n == 0) { f1 = 0; f2 = 0; } else if (n == 1 || n == 2) { f1 = 1; f2 = 0; } f = f1 + f2; f2 = f1; f1 = f; return f; }

Fibonacci recursive #include <iostream> #include <iomanip> using namespace std; double fibonacci(unsigned int n); int main() { int n; cout << "Enter a number: "; cin >> n; if (n<0){ cout << "Please Enter a positive integer!" << endl; return 0; } else cout << "The fibonacci number is " << fibonacci(n) << endl; cout << "The fibonacci sequence is as follows:" << endl; //Print Table Heading cout << setw(10) << "n" << setw(10) << " | " << setw(10) << "F(n)" << endl; cout << "-----------------------------------------" << endl; for(int i=0;i<=64;i++) cout << setw(10) << i << setw(10) << " | " << setw(10) << fibonacci(i) << endl; return 0; } //function definition double fibonacci(unsigned int n) { double n_minus_1=0,n_minus_2=1,sum; switch(n) { //if n=0 then F(n)=0 case 0: return 0; case 1: return 1;

default: for(int counter=0;counter<n;counter++) { sum=n_minus_1+n_minus_2; n_minus_2=n_minus_1; n_minus_1=sum ; } } return sum; }

You might also like