[Solved] Why does while loop create an error in my code?


  1. after applying the proposed corrections to the code,
  2. and applying the axiom: only one statement per line and (at most)
    one variable declaration per statement.
  3. the following proposed code
    performs the desired functionality
    results: cleanly compiles
    properly checks for and handles errors
    the call to printf() format string ends with ‘\n’ so the data is immediately output to the terminal
    displays an appropriate way to extract the digits from a ‘int’ and gather the sum of those digits

and now, the proposed code:

#include <stdio.h>

int main( void ) 
{
    int n;
    int digit;
    int  sum = 0;

    if( scanf("%d", &n) != 1 )
    {
        fprintf( stderr, "scanf for initial value failed" );
        return 1;
    }

    while( n )
    { 
        digit = n % 10;  // extract a digit
        n /= 10;         // reduce the working number
        sum = sum + digit;
    }

    printf("%d\n", sum);   // use '\n' so value immediately output to terminal
    return 0;
} 

3

solved Why does while loop create an error in my code?