write a program that enters an array of characters from the user and reverses the sequence without creating a new array
Swap the ends constantly, using a single variable as a temporary buffer. In pseudo-code:
temp = a[0]
a[0] = a[size - 1]
a[size - 1] = temp
and so on.
Dont bother reversing the array in memory, just iterate over it backwards!
Homework means pseudo-code only from me, which you've made relatively easy by not specifying what language you want anyway :-)
Turn this into your language of choice:
Set i1 to index of first element in array
Set i2 to index of last element in array
while i1 < i2:
Set temporary variable to element number i1
Set element number i1 to element number i2
Set element number i2 to temporary value
Add 1 to i1
Subtract 1 from i2
An ideal thing to do is to actually run that algorithm in your head, using a piece of paper to keep track of variables:
- each the elements in the array.
i1
andi2
.temporary variable
.
I tend to do that for simpler algorithms. Harder ones I insert debug statement into so that the computer can do that grunt work for me. Start with a piece of paper thus:
i1 | i2 | tempvar | el[0] | el[1] | el[2] | el[3] | el[4] | el[5]
---+----+---------+-------+-------+-------+-------+-------+------
H e l l o !
and just run through the steps one by one, checking and/or changing each column as you go. That will result in you understanding how it works far better than just being given some code.