Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reverse while iteration not going backwards

I am trying to make a reverse loop through a list using while.
I am trying the following code:

#include <iostream>
#include <list>


int main(){
    
    std::list <int> l1 = {1,2,3,4};
    
    auto it1 = l1.end();
    int val1;
    int sum1=0, exp1=1;
    
    int i = 0;
    while( it1 != l1.begin() ){
        --it1;
        val1 = *it1;
        
        sum1 +=  val1 * exp1;
        exp1 *= 10;
        i++ ;   
    }
    
    std::cout << sum1 << std::endl;
    
    return 0;
}

It is retuning 1234 while I was expecting the oposite: 4321

Why this? How do I make it work with while loop?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This statement

sum1 +=  val1 * exp1;

produces the result 1234

That is in the first iteration of the while loop you get that sum1 is equal to 4. Then in teh second iteration of the while loop you actually have according to the above statement

sum = 4 + 3 * 10;

that result in 34 and so on.

Instead you need to write

sum = sum * exp1 + val1;.

You could leave the statement

sum1 +=  val1 * exp1;

as is if you would write the while loop like

auto it1 = l1.begin();
//...
while( it1 != l1.end() ){
//...

Anpther approach is to use the range-based for loop

for ( const auto &val1 : l1 )
{
    sum1 +=  val1 * exp1;
    exp1 *= 10;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading