147k views
5 votes
rite a C program that does a large number of references to elements of two- dimensionedarrays, using only subscripting. Write a second program that does the same operations but uses pointersand pointer arithmetic for the storage- mapping function to do the array references. Compare the timeeciency of the two programs. Which of the two prog

User Chantalle
by
4.1k points

1 Answer

4 votes

Answer:

See explaination

Step-by-step explanation:

#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;

}

User Tivie
by
3.0k points