reversing a for loop

Hey Guys!

I have this for loop with this following data
79927398713
and it isn't working

1
2
3
for (i = size -1 ; i <=0; i = i - 2)
{
}


i have to ignore the last digit(3) and i need to start the for loop counting right to left

Does anyone have an idea why is not working ?
Thanks
Last edited on
Your question is not particularly clear, but to count backwards, use some math:

1
2
3
4
5
for (int i = 1; i < size; i++)
{
  int index = size - 1 - i;
  foo( a[i] );
}

Various ways to iterate a range:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <iterator>

int main()
{
  int xs[] = { 1, 2, 3, 4, 5, 6, 7 };
  
  using std::begin;
  using std::end;
  using std::rbegin;
  using std::rend;
  
  std::cout << "forward:\n";
  for (auto xi = begin(xs); xi != end(xs); xi++)
    std::cout << *xi << " ";
  std::cout << "\n\n";
  
  std::cout << "backward:\n";
  for (auto xi = rbegin(xs); xi != rend(xs); xi++)
    std::cout << *xi << " ";
  std::cout << "\n\n";
  
  std::cout << "forward, skipping last two:\n";
  for (auto xi = begin(xs); xi != std::prev(end(xs),2); xi++)
    std::cout << *xi << " ";
  std::cout << "\n\n";
  
  std::cout << "backward, skipping last two:\n";
  for (auto xi = std::next(rbegin(xs),2); xi != rend(xs); xi++)
    std::cout << *xi << " ";
  std::cout << "\n\n";
}

Good luck!
What i am trying to ask is that i have an array with this data 79927398713, what i need to do is ignore the last digit(3) for future operations, and start looping from right to left
so 1, 7, 8 and so on.
if i do as im trying it doesn't work.
Maybe sth. like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <stdint.h>

typedef uint64_t UInt64;

const UInt64 VALUE = 79927398713;

int main()
{
  UInt64 num = VALUE / 10; // remove last digit
  while (num > 0)
  {
    std::cout << num % 10 << " ";
    num = num / 10;
  }

  return 0;
}


OUTPUT
1 7 8 9 3 7 2 9 9 7 

Your original post was far from clear.

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>
using namespace std;

int main()
{
   string data = "79927398713";
   for ( int i = data.size() - 2; i >= 0; i-- ) cout << data[i] << "  ";
   cout << endl;
}


1  7  8  9  3  7  2  9  9  7  




If you want your data as a (long) int then
1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;

int main()
{
   unsigned long long idata = 79927398713;
   unsigned long long temp = idata;
   while ( ( temp /= 10 ) > 0 ) cout << temp % 10 << "  ";
   cout << endl;
}
Last edited on
Topic archived. No new replies allowed.