Question:
Create the logic for a program that reverse an array of numbers?
Halo
2015-11-01 11:55:19 UTC
I'm having a little trouble with homework. I believe I have a solution to the problem, but I'd like to make sure. Here's the question.

"Create the logic for a program that prompts a user for ten numbers and stores them in an array. Pass the array to a method that reverses the order of the numbers. Display the reversed numbers in the main program."

Here's what I have so far:

Start
Declarations
NUM numbers[10]

for count = 0 to 9 step 1
input numbers[x]
endfor
reverseArray(numbers[x])
for count = 0 to 9 step 1
output nums[x]
endfor
Stop

reverseArray(NUM nums[x])
Declarations
NUM nums[10]
for count = 0 to 9 step 1
if nums[x] > nums[x + 1]
Swap()
endif
nums[x] = nums[x + 1]
endfor
return nums[x]

Any help would be appreciated. This isn't in any specific program, so the syntax doesn't matter too much.
Four answers:
?
2015-11-01 14:11:19 UTC
The problem doesn't say anything about sorting, so why do you ask "if nums[x] > nums[x + 1]" ?



Swap() is not defined anywhere.



"nums[x] = nums[x + 1]" will shift the array forward: {0, 1, 2, 3} becomes {1, 2, 3, 3} and then throws an error when there's nothing to copy to the last position.



To reverse the array you need nums[x] = nums[9-x], except don't write over the numbers you haven't copied yet:

temp = nums[x]

nums[x] = nums[9-x]

nums[9-x] = temp



The array named "numbers" exists in main. "nums" exists within reverseArray. You cannot then output from "nums" in main.

Depending on the programming language, "nums" and "numbers" might refer to the same array, so "numbers" in main is now reversed. In languages where "nums" is a copy and that can return an array, you still need to assign it to a variable in main: reversed[10] = reverseArray(numbers[x]). And in Java you can't do either of these so you have to use pointers.
?
2015-11-01 12:11:57 UTC
I do not believe this is correct.



if nums[x] > nums[x + 1]

Swap()

endif



This would be good logic if your goal was to sort the numbers. But your goal is NOT to sort the numbers. Your goal is to reverse their order.
juliepelletier
2015-11-01 12:47:22 UTC
The shortest approach is to swap the whole array by looping halfway through it.



for (i = 0; i < 5; i++) {

tmp = arr[i];

arr[i] = arr[9 - i];

arr[9 - i] = tmp;

}
?
2015-11-01 14:02:00 UTC
int s,e,t;

e= length_of_array

int j[100];

......

for(s=0;s
t=j[s];

j[s]=j[e];

j[e]=t;

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...