Write a function that reverses the contents of an array of double and test it in
ID: 3937835 • Letter: W
Question
Write a function that reverses the contents of an array of double and test it in a simple program.
GIVEN CODE:
#include <stdio.h>
#include <stdlib.h>
void PrintArray(int *a, int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", *(a+i));
printf(" ");
}
int main()
{
int *pa;
int size;
int i, j;
int temp;
printf("Data size: ");
scanf("%d", &size);
if (size < 1)
return -1;
pa = (int*) malloc( size * sizeof(int));
if (pa == NULL){
printf(" Error ");
return -2;
}
for (i = 0; i < size; i++)
scanf("%d", (pa + i));
printf(" Array: ");
PrintArray(pa, size);
// Reverses the Array Here
reverseArray(pa,size);
void reverseArray(int *a, int size)
{
int j;
printf(" ReverseArray: ");
for (j = size-1; j >=0; j--)
printf("%d ", *(a+j));
}
printf(" New Array ");
PrintArray(pa, size);
free(pa);
return 0;
}
Explanation / Answer
//preprocessor directives
#include<stdio.h>
# include<conio.h>
using namespace std;
//starting execution from here
int main() {
double arr[30], temp;
int i,j,num;
//enter total number of elements
printf(" Enter no of elements : ");
scanf("%d", &num);
//Read elements in an array
for (i = 0; i < num; i++) {
scanf("%lf", &arr[i]);
}
j = i - 1; // j will Point to last Element
i = 0; // i will be pointing to first element
while (i < j) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++; // increment i
j--; // decrement j
}
//reverse array
printf(" Result after reversal : ");
for (i = 0; i < num; i++) {
printf("%lf ", arr[i]);
}
getch();
return (0);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.