gica
gica

Reputation: 31

why is the zero changing in c++

so i'm new to c++. i have to make a program where you enter a number and it displays the largest possible number and the smallest one, with the same digits as the entered number. But when the entered number has 0 it changes to 4310160

sorry for my english;{

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
    int m[10], i, l, x, c, ok, r;

    cout << "x= ";
    cin >> x;

    l = 0;
    while (x > 0) {
        c = x % 10;
        m[l] = c;
        l++;
        x = x / 10;
    }

    do {
        ok = 1;
        for (i = 0; i < l; i++)
            if (m[i] < m[i + 1]) {
                r = m[i];
                m[i] = m[i + 1];
                m[i + 1] = r;
                ok = 0;
            }
        for (i = 0; i < l; i++) {
            cout << m[i] << ", ";
        }
        cout << endl;
    } while (ok != 1);
    cout << "largest= ";
    for (i = 0; i < l; i++) {
        cout << m[i];
    }
    cout << endl;
    do {
        ok = 1;
        for (i = 0; i < l; i++)
            if (m[i] > m[i + 1]) {
                r = m[i];
                m[i] = m[i + 1];
                m[i + 1] = r;
                ok = 0;
            }
    } while (ok != 1);
    if (m[0] == 0) {
        r = m[0];
        m[0] = m[1];
        m[1] = r;
    }
    cout << "smallest= ";
    for (i = 0; i < l; i++) {
        cout << m[i];
    }

    return 0;
}

Upvotes: 3

Views: 120

Answers (2)

Manuel
Manuel

Reputation: 2554

The int m[10] array in main is stored in the stack and its elements initialized to indeterminate values as explained in array_initialization and initialization.

So if x == 0 , the program should print nothing as l will be 0 and it won't enter in any loop.

If you see 4310160 because you are debugging, it is because m[10] elements are initialized to indeterminate values (normally, the value at the stack in that moment.)

You may see here that local, non static data is stored in the stack.

Upvotes: 0

Jarod42
Jarod42

Reputation: 217398

if x == 0, you do

if (m[0] == 0) {
    r = m[0];
    m[0] = m[1];
    m[1] = r;
}

With uninitialized m, leading to undefined behavior.

Upvotes: 3

Related Questions