Search code examples
c++arraysnumbersgenerate

How to generate number with 3 digit from list of number by c++?


I'm a new programmer, and want to generate array of number with 3-digits from number list (2,5,8). I have created a code, but the output is not my expected result. This is my simple code:

int main()
{
    int arr[3]={2,5,8};

    int d=3;
    int times=1;

    for (int a:arr){
        int sum = a;
        for (int i=1; i<d; i++){
            times *= 10;
            sum += a*times;
        }
        cout<<sum<<endl;
        sum=0;
    }

    return 0;
}

My expected the result of 222,555 and 888, but the actual output is 222,55005 and 8800008.


Solution

  • It will help probably. You forget to reset times variable

    int main()
    {
        int arr[3]={2,5,8};
    
        int d=3;
        int times=1;
    
        for (int a:arr){
            int sum = a;
            for (int i=1; i<d; i++){
                times *= 10;
                sum += a*times;
            }
            cout<<sum<<endl;
            times = 1;   //<---added
            sum=0;
        }
        return 0;
    }