-2

I wanted to reverse half of the arrays inputs with the other half.

    #include <stdio.h>
    #include <math.h>
    void main() {
       double size = 5;
       int array[5] = {1, 2, 3, 4, 5};
       int half_size = ceil(size / 2);
       for(int i = 0; i < half_size; i++){
           int a;
           int rev = size - (i + 1);
           array[i] = a;
           array[i] = array[rev];
           array[rev] =  a;`enter code here`
           }
       printf("%d", array[5]);
       }

recnac
  • 3,511
  • 6
  • 21
  • 43
  • 4
    `array[5]` is out of bounds. Also I would suggest to think about a way to avoid floating point numbers here. – Eugene Sh. Apr 16 '19 at 20:14
  • 2
    You can't print a whole array like that: you must print each element in a loop. – Weather Vane Apr 16 '19 at 20:16
  • If you want to do exact arithmetic, use int. Double is for inexact arithmetic over a greater range than an int can hold. – stark Apr 16 '19 at 20:38
  • 1
    What is the purpose of the line `array[i] = a;`, followed immediately by another (different) assignment to array[i]? – FredK Apr 16 '19 at 20:59
  • `void main()` is wrong. [What should main() return in C and C++?](https://stackoverflow.com/q/204476/995714), [main() always returns int?](https://stackoverflow.com/q/12570837/995714). And the output isn't returned, it's printed out – phuclv Apr 17 '19 at 02:06

1 Answers1

0

I agree with @Eugene Sh.'s and @FredK's suggestions. The line array[5] in the line printf("%d", array[5]); is out of bound since array only have indexes from 0 to 4. Since I assume you want to print out the last element in the array, you should change it to printf("%d", array[4]);. Another thing is that your assignment expression array[i] = a; is wrong. I assume the expression is part of the swapping process from element in index i with element in index rev. If that was the case then you should change it to a = array[i]; instead. I update you code according to my suggestion and it outputs the correct result. I added the for loop to verify that the array values are reversed for testing purpose. You can delete it after you're done testing.

#include <math.h>
int main() {
    double size = 5;
    int array[5] = {1, 2, 3, 4, 5};
    int half_size = ceil(size / 2);
    for(int i = 0; i < half_size; i++){
        int a;
        int rev = size - (i + 1);
        a = array[i];
        array[i] = array[rev];
        array[rev] =  a;
    }
    for (int i = 0; i < size; ++i) {
        printf("%d ", array[i]);
    }
    printf("\n");
    printf("%d", array[4]);
}
VietHTran
  • 2,167
  • 2
  • 7
  • 16