+ All Categories
Home > Documents > DS Module Summary

DS Module Summary

Date post: 30-May-2018
Category:
Upload: phaariz
View: 216 times
Download: 0 times
Share this document with a friend

of 16

Transcript
  • 8/14/2019 DS Module Summary

    1/16

    www.oumstudents.tk

    1.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).

    Arrays

    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

    void main(void){

    int nums[10]; // array declaration, with 10 elements

    int i; // counter variable used for loop

    // assign multiples of 2 to arrayfor(i=0; i

  • 8/14/2019 DS Module Summary

    2/16

    www.oumstudents.tk

    f) Find the total mark, average mark, and the maximum mark of the following

    #include

    void main(void){

    // array with all the marksint marks[5]={10,2,33,14,17};

    // counter variable used for loopint i;

    // variable to store sum & average, initialized to zeroint sum=0;

    float avg=0;

    // variable to store maximum marks,

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

    // traverse through array to find sum, and maxfor(i=0; i max)

    max = marks[i];

    }

    //calculate averageavg = sum/5.0;

    // print out sum, avg, and maxprintf("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 windowgetchar();

    }

    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

    // initialize function prototypesint getMaxMarks(int[],int);int getMinSubject(int[],int);

    void main(void){

    // array with all the marksint 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

  • 8/14/2019 DS Module Summary

    3/16

    www.oumstudents.tk

    int i;

    // use loop to display all elements in arrayfor(i=0; i=0; i--){printf("marks[%d] = %d\n", i, marks[i]);

    }

    // calculate sum and averagefor(i=0; i

  • 8/14/2019 DS Module Summary

    4/16

    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

    void main(void){

    // array declarationsint 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 array1for(i=0; i

  • 8/14/2019 DS Module Summary

    5/16

    www.oumstudents.tk

    #include

    void main(void){

    // array to store studentschar 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 laterint 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 & avgint sTotal =0, sAvg =0;

    // to store class total & avgint classTotal=0, classAvg=0;int bestMarks, worstMarks;

    char bestStudent=students[0], worstStudent=students[0];

    int row, col;

    // calculate and assign student totals & avgsfor(row =0; row

  • 8/14/2019 DS Module Summary

    6/16

    www.oumstudents.tk

    // print marks tableprintf("\n\nStudents\tSub1\tSub2\tSub3\tSub4\tSub5\tTotal\tAvg" );printf("\n========\t====\t====\t====\t====\t====\t=====\t===" );for(row =0; row

  • 8/14/2019 DS Module Summary

    7/16

    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

    #include

    // initializing function prototypesint getLength(char[]);int getUCaseCount(char[]);void inverseCase(char[]);

    void main(void){

    // create the stringchar 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 caseinverseCase(name);

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

    // get length of stringint getLength(char str[]){

    int i=0;while(str[i]!='\0'){

    i++;}

    return i;

    }

    // get number of upper case characters in stringint getUCaseCount(char str[]){

    int i=0, count=0;while(str[i]!='\0'){

    if(isupper(str[i])){count++;

    }i++;

    }

    return count;}

    // reverse case of the stringvoid inverseCase(char str[]){

    int i=0;while(str[i]!='\0'){

    if(isupper(str[i]))str[i]= tolower(str[i]);

    elsestr[i]= toupper(str[i]);

    i++;

    }}

  • 8/14/2019 DS Module Summary

    8/16

    www.oumstudents.tk

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

    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

    #include

    // define long date structure// format: dd-mmm-yyyy, ddd

    // e.g.: 12-Mar-2009, Wedstruct long_date {

    int day;char month[4];int year;char wday[4];

    };

    // define user account structurestruct user_account {

    char name[25];char address[25];struct long_date DOB;

    };

    // Function prototypesvoid 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 dateld = inputdate();printdate(ld);

    printf("\n\n");

    // input and display a user accountmyaccount = inputaccount();printaccount(myaccount);

    // wait till user press return key before closing windowgetchar();

    }

    // Functino to print the date in long date format

    // Accepts a copy of a long_date struct as the parametervoid printdate(struct long_date mydate){

    printf("\n%d-%s-%d, %s\n\n",

    mydate.day,mydate.month,mydate.year,mydate.wday);

    }

  • 8/14/2019 DS Module Summary

    9/16

    www.oumstudents.tk

    // Function to print the user account information

    // Accepts a copy of a user_account struct as the parametervoid 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 structstruct 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 structstruct user_account inputaccount(){

    struct user_account myaccount;

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

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

    puts("DOB:-");

    myaccount.DOB = inputdate();

    return myaccount;}

  • 8/14/2019 DS Module Summary

    10/16

    www.oumstudents.tk

    4.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)

    Pointers

    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 locationof 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.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).

    Linked Lists

    b) Linked Lists: Group of data items that is sequential with itsdata items having links between each other. Consist ofsequential 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 listii. Test weather a list is empty or not: Because If the

    list is empty, deletion cannot be performed

    ii. Test weather a linked list is empty or notiii. Traverse list iii. Traverse linked listiv. Insert new item to list iv. Insert new item to linked listv. 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

    #include

    // type defining and creating the linked list structuretypedefstruct linkedList {

    int data;

    struct linkedList *next;} NODE;

  • 8/14/2019 DS Module Summary

    11/16

    www.oumstudents.tk

    // globally initialising the linked list SlistNODE *Slist;

    // initialising function prototypesvoid viewLinkLst(NODE *);NODE *addSort(NODE *,NODE *);

    // START FUNCTION: MAINvoid 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 headerprintf("\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 listSlist=addSort(Slist,&P);printf("\n\n\n\tSLIST AFTER NODE P(%d) INSERTION\n\n\t", P.data);viewLinkLst(Slist);

    getch();}

    // START FUNCTION: VIEWLINKLISTvoid viewLinkLst(NODE *list){

    // Loop till all elements of the list are printedwhile(list!=NULL)

    { printf("%d ",list->data);// print the element

    list = list->next; // goto the next element}

    }

    // START FUNCTION: SORTORDERNODE *addSort(NODE *list, NODE *P){

    // Initialize list and the new NodeNODE *newList=list,*p=NULL;

    // Add the new node to the listwhile(newList!=NULL){

    p =((newList->data)data))?newList:p;newList = newList->next;

    }

    // sort the list so that P goest to the correct placeif(p!=NULL){

    P->next=p->next;p->next=P;

    }else{P->next=list;list=P;

    }

    // return the new added sorted linked listreturn list;

    }

  • 8/14/2019 DS Module Summary

    12/16

    www.oumstudents.tk

    e) Assignment Question 2B: Combining two null terminated linked lists so that the nodes of the new list alternatebetween those of the original two nodes

    // include libraries#include

    #include

    #include

    // type defining and creating the linked list structuretypedefstruct linkedList {

    char data;

    struct linkedList *next;} NODE;

    // globally initializing the link lists list_1 and list_2NODE *list_1,*list_2;

    // initialising function prototypesvoid viewLinkLst(NODE *);int sizeCheck(NODE *);NODE *combine(NODE *,NODE *);

    //main function

    void main(void){

    // setting up list 1NODE list01_2 ={'B',NULL};NODE list01_1 ={'A',&list01_2};list_1=&list01_1;

    // setting up list 2NODE list02_2 ={'2',NULL};NODE list02_1 ={'1',&list02_2};list_2=&list02_1;

    // Display the headerprintf("\n\n\t-----------------------------------\n" );

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

    // displaying the given two listsprintf("\tList 1:\t");viewLinkLst(list_1);

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

    // displaying the combined listprintf("\n\n\tCombined Alternatively:\n\n\t");viewLinkLst(combine(list_1,list_2));

    getch();

    }

    // function to display the linked listvoid viewLinkLst(NODE *list)

    {while(list!=NULL){

    printf("%c ",list->data);list = list->next;

    }}

    // function to combine the two linked listsNODE *combine(NODE *list_1,NODE *list_2){

    // initializing variableNODE *LIST=list_1,*t;

  • 8/14/2019 DS Module Summary

    13/16

    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.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)

    Stacks

    b) Basic Stack Operations:i. Create Stack

    ii.

    Test empty Stack (for POP)iii. Test Full Stack for PUSH)iv. POP - Remove Element from Stackv. PUSH - Add Element to Stack

    c) Postfix Expression Algorithm:i. Create a Stack

    ii. Repeat Until the End of the Expression1. Read the Next token in the Expression2. If the token is an operand, then

    i. Insert the token into the Stack3. If the token is an Operator, then

    i. Removetwo topmost values from the stackii. Perform operationiii. Insert result into the stack

    7.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).

    Queues

    b) Basic Queue Operations:i. Create Queue

    ii. Test empty Queueiii. Test Full Queueiv. Remove Element from Queuev. Add Element to Queue

  • 8/14/2019 DS Module Summary

    14/16

    www.oumstudents.tk

    8.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)

    Sorting

    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.

    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 tobiggest from left and interchange/ make sub-list if pivot is balancing

    d) Bubble sorting: This sorting performs adjacent element exchanges until all elements are arranged according tothe requirements

    20 11 4 8

    11 20 4 8

    4 11 20 8

    4 8 11 20

    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

    20 11 4 8

    11 20 4 8

    11 4 20 8

    11 4 8 20

    11 4 8 20

    4 11 8 20

    4 8 11 20

    4 8 11 20

    4 8 11 20

    Round 1

    Round 2

    Round 3

  • 8/14/2019 DS Module Summary

    15/16

    www.oumstudents.tk

    9.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.

    Searching

    Say A[1], A[2], ... , A[n] are arrays that consists of n keys Ki; (1

  • 8/14/2019 DS Module Summary

    16/16

    Round 3 The result of the second round has revealed thatthe focus of the search is to the left of the middle key, which is the

    location leading towards the start value. Therefore, we need to

    change the end value of the location to the left of the middle

    value, which is middle value minus one.

    Change end value, End = middle - 1

    = 7 - 1

    = 6

    We find the middle value again.Middle value = (initial + end)/2

    = (5 +6)/2

    = 11/2

    = 5

    Test the middle key with the search key.

    Middle key = k(5) = 25

    In this round we found that the search key value (39) is bigger than

    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.

    Round 4 From the result of round 3, the search locationfocus is now on the right of the middle key, which are the

    locations leading toward the end. Here, we need to change the

    initial value of the location to the left of the middle key value,

    which is the middle minus one.

    Change final value, initial = middle + 1

    = 6 + 1

    = 7

    We calculate for the middle value again.Middle value = (initial + end) / 2

    = (7 + 6)/2

    =13 / 2

    = 6

    Test the middle key with the search key.

    Middle key = k(6) = 39

    Thus, our search is successful.

    10.a) Trees: A structure that consists of nodes that are linked with directed pointers.

    Trees

    b) Binary Tree: A binary tree is a tree in which no node can have more than two subtrees. In other words, a nodecan 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


Recommended