Jump to content

Reverse arrays help!

- - - - -

  • Please log in to reply
2 replies to this topic

#1
quabs

quabs

    Newbie

  • Members
  • Pip
  • 1 posts
so my tutor gave me the problem to have the user input certain numbers put that in an array and display the reverse. I can do that except that it displays a bunch of zeros as well. How do i remove these? This is a console application. Thanks a lot,
Quabs
ps- here is my code:

int num;
int ele;
int [] numarray = new int[10];

Console.WriteLine("How many numbers do you want? NO MORE THAN 10 NUMBERS");
num = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("input the numbers here:");
for (int i=0;i<num;i++)
{
Console.WriteLine("Input the number:");
ele = Convert.ToInt32(Console.ReadLine());
numarray[i] = ele;
}
Array.Reverse(numarray);
Console.WriteLine("The reverse order of the numbers are :");


foreach (int n in numarray)
Console.WriteLine(" " + n);

#2
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
The zeroes are the empty spaces of your defined array.

int [] numarray = new int[10];
Lose this, you don't want to define the array before you know how many numbers are going to be inserted.

num = Convert.ToInt32(Console.ReadLine());
int [] numarray = new int[num];
and put it there, with an an argument of 'num' instead of 10. So you are not limited with just 10 numbers.

Actually it would be nicer, if you would just let to insert the numbers as a single String like that: "6 7 10 1 29 19 18", without asking first, how much numbers are going to be inserted.
then split the string....

string s = Console.ReadLine();
string[] numbers = s.[U]Split[/U](' ');
Array.Reverse(numbers);


#3
Tonchi

Tonchi

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 471 posts
  • Location:Varaždin
  • Programming Language:C, C++, C#
i didn't read all but if you want to reverse arrays you should do it throught for loop like this:


...

for(i=0;i<10;i++)

{

  //make input

}


for(i=9; i>=0;i--)

{

  //make output

}






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users