Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what is the use of this function

This is my task. I googling for find out reason behind this function but can not find out. My teacher tell me what is the use of this function.

My Question is:

What is the purpose of the following function, assuming that the parameter size represents the size of the array data that’s also passed as a parameter. Further assume that size is at least 2.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is sample code he give me:

#include <stdio.h>

void procArray( int data[], int size ) {
     int temp = data[0];
     int index;
     for( index = 0; index < size - 1; index++ )
     {
         data[index] = data[index + 1];
         data[size-1] = temp;
         
         printf("%d ", + data[index]);
         printf("%d ", + data[size-1]);
     }
}

int main()
{
    int arr[2];
    procArray(arr, 2);

    return 0;
}

Every time i got random number in output like:

32767 -2102338448 

>Solution :

The routine procArray appears to be written with the intent that it “rotate” the array one position “left,” meaning to modify the array such that, upon return from the function:

  • The last element (index [size-1]) contains the value the first element (index [0]) the first element had upon calling the function.
  • Each other element (index [i] for some i other than size-1) contains the value the element to its “right” (index [i+1]) had upon calling the function.

However, if this was the purpose, the function was written incorrectly. The statement data[size-1] = temp; should be after the loop, not inside it.

Further, the main routine fails to demonstrate how the function behaves because it fails to put values into arr.

A corrected function with a useful demonstration is:

#include <stdio.h>
#include <stdlib.h>


void procArray(int data[], size_t size)
{
     int temp = data[0];

     for (size_t i = 0; i < size-1; ++i)
         data[i] = data[i+1];

     data[size-1] = temp;
}


int main(void)
{
    int arr[5] = {10, 11, 12, 13, 14};
    procArray(arr, 5);
    for (int i = 0; i < 5; ++i)
        printf("arr[%d] = %d.\n", i, arr[i]);

    return 0;
}

This program outputs:

arr[0] = 11.
arr[1] = 12.
arr[2] = 13.
arr[3] = 14.
arr[4] = 10.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading