By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
462,868 Members | 694 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 462,868 IT Pros & Developers. It's quick & easy.

how do I print a reverse order of these numbers in this while loop

P: 1
Hello how do I print a reverse order of these numbers in this while loop. I'm using array.

Expand|Select|Wrap|Line Numbers
  1.   Sub Main()
  2.         Dim data() = {30, 32, 81, 43, 58, 85, 23, 19}
  3.         Dim i = 0
  4.  
  5.         While (i > 8)
  6.  
  7.             Console.WriteLine(data(i))
  8.             i = i + 1
  9.  
  10.         End While
  11.     End Sub
Oct 29 '19 #1
Share this Question
Share on Google+
3 Replies

gits
Expert Mod 5K+
P: 5,390
well - if you have to use the while loop then 1st you would need to make sure it runs at all - the condition in line 5 is never met - so fix the comparison. now - i is counting up and so you just would need to access the elements from the end in that kind of loop - which basically means that you could use something like (Pseudocode here):

Expand|Select|Wrap|Line Numbers
  1. indexOfElementInTheLoop = (data.Length - 1) - i
a much cleaner way here would probably be a For-loop though - where you count down from the array's length-1 to 0 and you may use the counter directly to access the elements.
Oct 30 '19 #2

cactusdata
Expert 100+
P: 122
Use a For-Next loop:

Expand|Select|Wrap|Line Numbers
  1. Sub Main()
  2.  
  3.     Dim data() As Integer = {30, 32, 81, 43, 58, 85, 23, 19}
  4.     Dim index As Integer
  5.  
  6.     For index = data.Length - 1 To 0 Step -1    
  7.         Console.WriteLine(data(index).ToString())
  8.     Next
  9.  
  10. End Sub
Oct 30 '19 #3

P: 47
Try This Code

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. int main() {
  3.     int n, rev = 0, remainder;
  4.     printf("Enter an integer: ");
  5.     scanf("%d", &n);
  6.     while (n != 0) {
  7.         remainder = n % 10;
  8.         rev = rev * 10 + remainder;
  9.         n /= 10;
  10.     }
  11.     printf("Reversed number = %d", rev);
  12.     return 0;
  13. }
Output

Expand|Select|Wrap|Line Numbers
  1. Enter an integer: 1234
  2. Reversed number = 4321
Apr 10 '20 #4

Post your reply

Sign in to post your reply or Sign up for a free account.