Write a C language function that can reverse a list of integers This is the decl
ID: 3573589 • Letter: W
Question
Write a C language function that can reverse a list of integers This is the declaration for the function. vid reverse_int (int *iLstPtr, int numberOfElernents); If you have a list of integers 34, 24, 75, 84, 11, 23 The function would rearrange the list as follows 23, 11, 84, 75, 24, 34 The list of integers is not fixed, there can be as few as 2 or many millions of integers The function should rearrange the list elements without allocating a new memory, and not using any C library functions. You may use a single temporary variable, although it is not absolutely necessary. You would use the pointers in this program, similar to what we did for strcpyExplanation / Answer
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void reverse_int(int*,int); /* Protype of the Function reverse_int() */
main()
{
int *p,n,i;
clrscr();
printf("How many elements to read:");
//Reading Number of elements
scanf("%d",&n);
//Creating Memory using malloc for Number of elements.
// Memory will be created at runtime.
p=(int*)malloc(n*sizeof(int));
printf(" Enter %d elements: ",n);
//Reading elements
for(i=0;i<n;i++)
{
scanf("%d",p+i);
}
printf(" Given List of Elements are: ");
for(i=0;i<n;i++)
{
printf("%d ",*(p+i));
}
//The following function send address of first memory location and number of elements.
reverse_int(p,n);
printf(" Given List of Elements in Reverse Order are: ");
for(i=0;i<n;i++)
{
printf("%d ",*(p+i));
}
getch();
}
void reverse_int(int *iLstPtr,int numberOfElements)
{
int i,j;
//The following for loop is used to reverse the array elements with using temporary variable and with out creating new memory.
for(i=0,j=numberOfElements-1;i<j;i++,j--)
{
*(iLstPtr+i)=(*(iLstPtr+i))+(*(iLstPtr+j));
*(iLstPtr+j)=(*(iLstPtr+i))-(*(iLstPtr+j));
*(iLstPtr+i)=(*(iLstPtr+i))-(*(iLstPtr+j));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.