Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

CS 2123 Data Structures Summer 2015 - Midterm 2- July 23, 2015 You have 100 min.

ID: 3735240 • Letter: C

Question

CS 2123 Data Structures Summer 2015 - Midterm 2- July 23, 2015 You have 100 min. Good luck You can use the 2-page C reference card posted in the class web page Score: /85 1. (10pt) Review Questions a. (2pt) suppose p and q are defined as integer pointers (i.e, int *p, *q;) . Then what are the purposes of the following statements? Are they equivalent? if (p printf("...aa... are the same") if (*p ) printf (".. .bb.. . are the same" b. (2pt) What is the difference between the typedef's in the left and right columns? RE-WRITE each statement based on the declaration in the right column typedef struct myData i typedef struct myData f int x; int yi ) myDataTl; int x; int y; *myDataT2; myDataT1 *p, q myDataTl r; pmalloc (sizeof (myDataT1));

Explanation / Answer

If you find this helpful, please leave a like. Since there is more than 1 question and since time is limited, I can answer only the first four sub-parts of the question.

1.a)The first statement checks if the addresses the pointers are pointing to are the same. The second statement checks if the values in the addresses to which each pointer is pointing are the same. When we say p, we are referring to the value of the pointer variable, which is an address. When we say *p, we mean the value at p, i.e, the value at the stored address.

1.b) In the first column, we define the datatype myDataT1 as a struct of type myData. In the second we define datatype myDataT2 as a pointer to the struct of type myData. So basically, myDataT1 is the short form of struct myData and myDataT2 is the short form of myData *.

The equivalent code is:

myDataT2 p,q;

myData r;

p=malloc(sizeof(myData));

p->x=5;

r.x=7;

1.c)CODE:

int check_if_unique(int *arr, int n)
{
int flag=1; //First we assume the array is unique.
for(int i=0;i<n-1;i++) //Looping one element through the array.
{
for(int j=i+1;j<n;j++) //Looping another element through the array.
{
if(arr[i]==arr[j]) //If any two elements are the same, flag becomes 0, which means it is not unique.
flag=0;
}
}
if(flag==1)
return 1;
else
return 0;
}

1.d) CODE:

int arr_sum(int arr[], int n)
{
if(n==1) //Base case. To stop recursion.
return arr[0];
return (arr[n-1]+arr_sum(arr,n-1)); //Recursively calling the same function
}