skip to Main Content

This code snippet is supposed to return the reverse of the given integer and in the Sololearn compiler it works but in VSCode and Code::Blocks the output is different.
For 543 it returns -93835951 in VSCode and 694653940 in Code::Blocks.
Does anybody know why?

#include <iostream>

using namespace std;

int main()
{
    int n, sum, a;
    a = 0;
    sum = 0;
    cin >> n;
    while (n>0)
    {
        a = n % 10;
        sum = sum * 10 + a;
        n = n / 10;
    }
    cout << sum;

    return 0;
}

2

Answers


  1. int n,sum,a=0;
    

    the above expression only initializes the last variable ‘a’, leaving ‘n’ and ‘sum’ uninitialized.

    although n is assigned a value in

    cin >> n;
    

    the variable ‘sum’ is likely to have a garbage value. That explains the different results.

    Login or Signup to reply.
  2. Here is the working version with a bit of refactoring but still keeping it very similar to your snippet:

    #include <iostream>
    
    
    int main( )
    {
        std::cout << "Enter a number: ";
        int num { };
        std::cin >> num;
    
        int sum { };
    
        while ( num > 0 )
        {
            const int remainder { num % 10 };
            sum = sum * 10 + remainder;
            num = num / 10;
        }
    
        std::cout << "The reversed number: " << sum << 'n';
    }
    

    A few general things to keep in mind:

    1. Do not use using namespace std;. That’s a bad practice. See Why is "using namespace std;" considered bad practice?.
    2. Do not declare multiple variables in a single statement. That can lead to various issues.
    3. Make sure to initialize your variables before using them if their initial values will be read and used in some operation. If the initial value is not used by anyone, then do not initialize the variable since it would be a waste of computing power.
    4. Try to shrink the scope of variables as much as appropriate to reduce the risk of them being used accidentally by another statement that is not supposed to access those variables. In the above example, I declared remainder inside the scope of the while loop because it was not being used outside the loop.
    5. And last but not least, avoid ambiguous identifiers like int a, int n, etc. These are not meaningful and purposeful names in this context. Use names that MAKE sense.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search