-2

program asked is sum of digits :

Input data are in the following format: first line contains N - the number of values to process; and then N lines will follow describing the values for which sum of digits should be calculated by 3 integers A B C; for each case you need to multiply A by B and add C (i.e. A * B + C) - then calculate sum of digits of the result.

Answer should have N results, also separated by spaces

MY CODE IN C++ :

#include <iostream>

using namespace std;

int main ()
{
    int n, a, b, c, t, sum = 0;
    cin >> n;
  
    for (int i = 0; i < n; i++)
    {
        cin >> a >> b >> c;
        t = a * b + c;
    
        while (t % 10 != 0)
        {
            sum = sum + t % 10;
            t = t / 10;
        }

        while (t % 10 == 0)
        {
            sum = sum;
            t = t / 10;
        }
    }
    
    cout << " ";
    cout << sum;
    cout << " ";

    return 0;
}

I'm having hard time correcting my code.

Any help is appreciated.

My assumption is there should be a better way to code this other than using 2 while loops.

PS : I checked other topics just want somebody that could help with my code thank you.

Chris
  • 26,361
  • 5
  • 21
  • 42

2 Answers2

1

You don't need second while loop, and first one should be corrected to while (t != 0). After that your program for computing sum works correctly.

Try it online!

#include <iostream>

using namespace std;

int main ()
{
    int n, a, b, c, t, sum = 0;
    cin >> n;
  
    for (int i = 0; i < n; i++)
    {
        cin >> a >> b >> c;
        t = a * b + c;
    
        while (t != 0)
        {
            sum = sum + t % 10;
            t = t / 10;
        }
    }
    
    cout << " ";
    cout << sum;
    cout << " ";

    return 0;
}

Input:

1
123 456 789

Output:

33

Just noticed that you need N separate outputs instead of single sum (like you did), so then your program becomes like this:

Try it online!

#include <iostream>

using namespace std;

int main ()
{
    int n, a, b, c, t, sum = 0;
    cin >> n;
  
    for (int i = 0; i < n; i++)
    {
        cin >> a >> b >> c;
        t = a * b + c;

        sum = 0;
    
        while (t != 0)
        {
            sum = sum + t % 10;
            t = t / 10;
        }

        cout << sum << " ";
    }
    
    return 0;
}

Input:

2
123 456 789
321 654 987

Output:

33 15 
Arty
  • 14,883
  • 6
  • 36
  • 69
-1
    #include <iostream>
    
    using namespace std;
    
    int main()
    
     {
    
        int num = 0;
    
        cout << "please input any number  3digits = ";
    
        cin >> num;
    
        int sum[] = { 0,0,0 };
    
        sum[0] = num/100;
    
        sum[1] = (num/10)%10;
    
        sum[2] = num%10;
    
        int x = sum[0] + sum[1]  + sum[2] ;
    
        cout << x << endl;
    
        return 0;

}
toyota Supra
  • 3,181
  • 4
  • 15
  • 19