-2

//Program to print sum of digits

#include <iostream>
using namespace std;

int main()
{
    int n, m, sum = 0;
    cin >> n;             
   for(int i = 0; i < n; i++)
    {
        m = n % 10;     
        sum += m;      
        n = n / 10;    
    }
    cout << sum;
}

    //Outputs
    
   // Input = 123
   // Output = 5 (should be 6)
    
   // Input = 0235
   // Ouput = 8 (should be 9)

Not printing the right answer when input no. is starting from 1 or 0.

By using While (n>0), it's giving the right output but I can't figure out why?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Please provide a few triples of sample input, expected output and output you get, for both failing cases and successful cases. That will help explaining the mistakes in your program. – Yunnosch May 19 '21 at 06:01
  • 4
    Because your condition checks `i < n`. Suppose the number was 12, when `n` becomes `1`, `i` becomes 1. So the loop terminates before 1 is added to `sum` – kuro May 19 '21 at 06:03
  • Insert an output of the currently used digit, i.e. `m`, within the loop. It will probably have surprisingly helpful insights for you. – Yunnosch May 19 '21 at 06:03
  • Side note: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – Aconcagua May 19 '21 at 06:05
  • Why not simply `while(n)`? At some point, you *will* be dividing the last digit by 10, which results in zero, so the loop *will* break. – Aconcagua May 19 '21 at 06:07
  • You should get used to the habit of *always* checking the stream state after input operations, otherwise invalid input can easily break your (future?) applications. `if(std::cin >> n) { /* your code */ } else { /* error handling, e. g. printing a message to screen */ }` – More advanced error handling is handled [here](https://stackoverflow.com/q/257091/1312382), but you should prefer [this answer](https://stackoverflow.com/a/257182/1312382) over the accepted one. – Aconcagua May 19 '21 at 06:13
  • @kuro Yes, got your point. – Swaraj Sharma May 19 '21 at 06:20
  • @Aconcagua I'll definitely look into those suggestions, and thank you, while(n) it cleared my doubts. – Swaraj Sharma May 19 '21 at 06:23
  • @Yunnosch yes! I wasn't considering that when n becomes 1, i becomes 1 and the loop terminates without adding 1 to sum. Thank you – Swaraj Sharma May 19 '21 at 06:27
  • *'By using While (n>0) [...]'* – because (for *positive* integers; consider [Vlad's answer](https://stackoverflow.com/a/67597980/1312382)!) with every division, `n` gets reduced by one digit: 1977 -> 197 -> 19 -> 1. Then for the last digit, as in range 1-9 and thus smaller than 10, the division will result in 0 – et voilá... – Aconcagua May 19 '21 at 07:07
  • `for(int i = 0; i < n; i++)` -> `for( ; n; )` or similar. That is, stop once the number is "used up". And change the type of `n` to `unsigned`. – Bathsheba May 19 '21 at 07:11
  • @Aconcagua Understood :) – Swaraj Sharma May 19 '21 at 07:46
  • @Bathsheba I didn't know for loop can be used like this, thanks. – Swaraj Sharma May 19 '21 at 07:47

1 Answers1

0

For starters the user can enter a negative number because the type of the variable n is the signed type int.

Thus neither loop either

for(int i = 0; i < n; i++)

or

while (n>0)

will be correct.

A correct loop can look like

while ( n != 0 )

And you need to convert each obtained digit to a non-negative value or you should use an unsigned integer type for the variable n.

As for this loop

for(int i = 0; i < n; i++)

then it entirely does not make a sense.

For example let's assume that n is initially equal to 123,

In this case the in the first iteration of the loop the condition of the loop will look like

0 < 123

In the second iteration of the loop it will look like

1 < 12

And in the third iteration of the loop it will look like

2 < 1

That means that the third iteration of the loop will not be executed.

Thus as soon as the last digit of a number is less than or equal to the current value of the index i the loop stops its iterations and and the digit will not be processed.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Thank you so much, I never really considered negative numbers, btw what about while(n), Is there any loophole in it? And is it necessary that programs that could run with for loop must run with while and do-while and vice-versa? – Swaraj Sharma May 19 '21 at 06:36
  • @SwarajSharma Actually you can use any kind of loop but you need to write the condition of the loop correctly. – Vlad from Moscow May 19 '21 at 06:42