29.2k views
0 votes
Write a C program that does a large number of references to elements of two-dimensioned arrays, using only subscripting. Write a second program that does the same operations but uses pointers and pointer arithmetic for the storage-mapping function to do the array references. Compare the time efficiency of the two programs. Which of the two programs is likely to be more reliable

User Shaves
by
5.2k points

1 Answer

4 votes

Answer:

#include <stdio.h>

#include <time.h>

int main()

{

clock_t start, end;

double cpu_time_used;

//starting the cpu clock.

start = clock();

for(int i=0; i<10000; i++){

my_func_with_only_subscript();

}

// closing the cpu clock.

end = clock();

// calculating time elapsed in secs.

cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

printf("Time taken with subscript references::%f\\",cpu_time_used);

// starting the cpu clock

start = clock();

for(int i=0; i<10000; i++){

my_func_with_pointers();

}

// closing the cpu clock.

end = clock();

// calculating the time elapsed in array reference through pointers.

cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

printf("Time taken with pointers::%f\\",cpu_time_used);

return 0;

}

// function to reference the 2D array through subscripts.

void my_func_with_only_subscript()

{ //assuming that the usage of

int arr[15][5] = {0}; //square matrice is not mandatory

for(int j=0; j<5 ; j++){

for(int i=0; i<15; i++){

arr[i][j]; //no operation is done, only accessing the element

}

}

return;

}

// function to reference the 2D array through pointers.

void my_func_with_pointers()

{ //assuming that the usage of

int arr[15][5] = {0}; //square matrice is not mandatory

for(int j=0; j<5 ; j++){

for(int i=0; i<15; i++){

*(*(arr+i)+j); //no operation is done, only accessing the element

}

}

return;

}

/******************************************************************************************************************************/

OUTPUT

[Attached in the attachments]

Write a C program that does a large number of references to elements of two-dimensioned-example-1
User Guido Caffa
by
4.6k points