-3

This is a simple question don't look for difficulties.

I have such a cycle

int arr[]{ 111, 222, 333 };
    
for (size_t i = 0; i < 3; i++) {
   test = 1000 * test + arr[i];    
}
std::cout << test;

it returns the result 111222333

the question is how to make it output the result 333222111 in short add numbers from the other side

you need to change this line to something else to add values in a different way

test = 1000 * test + arr[i];    

I will update the question a little bit, that would be interesting, what if there is no array and you get the data in this form.

test = 1000 * test + X;

X is an unknown number and not an array

buster
  • 19
  • 2

4 Answers4

3

You could do the loop from the end using reverse iterators:

#include <iostream>
#include <iterator>

int main() {
    int arr[]{ 111, 222, 333 };
    int test = 0;        
    for(auto it = std::rbegin(arr); it != std::rend(arr); ++it) {
        test = 1000 * test + *it;
    }
    std::cout << test;
}

Here's an alternative using std::accumulate and a lambda:

#include <iostream>
#include <iterator>
#include <numeric>

int main() {
    int arr[]{ 111, 222, 333 };
    int test = std::accumulate(std::rbegin(arr), std::rend(arr), 0,
        [](const auto a, const auto b){
            return 1000 * a + b;
        }
    );
    std::cout << test;
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
2

You can use

test = 1000 * test + arr[2 - i];

instead of the line.

To handle input other than arrays, you can use "delta" to keep track the place to insert new values.

int delta = 1;
for (size_t i = 0; i < 3; i++) {
    test += delta * X;
    delta *= 1000;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
1

Assuming you can't reverse the elements in arr, perhaps the simplest way is to write

test = 1000 * test + arr[2 - i];

perhaps not hardcoding the 2. This is considerably simpler than running the loop the other way: size_t is unsigned so getting the stopping conditional correct takes some thought. Personally I use

for (size_t i = 3; i --> 0;) {

for this kind of thing. Note well the slide operator -->. It's not really an operator at all but it consists of the postfix -- followed by the comparison. It's not to everyone's taste and some software houses ban its use.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Iterate the loop from i=2 to 0 i.e for(size_t i = 2; i >= 0; i --)

sumit
  • 31
  • 2