Hey can any1 figure out wat is wrong in this program...after i compiled it and executed the program ....I inputed the value of n...but after that it does not show the output...Can any1 help me plz..!!

The program which I wrote is below::

#include<iostream.h>


int sumofdigits(int n)


{


int sum=0, x;


while(n>0)


{
x=n%10;


sum+=x;


}


return sum;


}


void main()


{


int n, sum;


cout<<"Enter any number"<<endl;


cin>>n;


sum=sumofdigits(n);


cout<<"Sum of digits ="<<sum;


cout<<endl;


}

Dani AI

Generated

A quick follow-up that complements ’s catch and helps make the program more portable and easier to debug.

Prefer modern, standard C++: use the standard header (<iostream>) and a standard int main() that returns a value. Compiling with warnings enabled (for example -Wall -Wextra on GCC/Clang) often points out non-portable or suspicious code early. See the reference for the main signature () and the standard I/O header (cppreference: iostream).

Handle input and edge cases explicitly. Decide how to treat negative numbers, zero, and very large inputs. For arbitrarily long numbers or to preserve leading zeros, read the value as a string and iterate characters to compute the digit sum; that avoids integer overflow and makes validation (rejecting non-digit characters) straightforward.

Troubleshooting checklist for “no output” or apparent hang:

  • Recompile with full warnings and fix them.
  • Add temporary debug prints or run under a debugger to see where execution stops.
  • Test with simple, known inputs (0, small positives, non-numeric input).
  • Use sanitizers (-fsanitize=address,undefined) if crashes are suspected.
  • Consider output buffering when diagnosing missing output; flushing or printing '\n' helps.

Once the loop progression issue is handled, these changes improve correctness, portability, and maintainability. Thanks to for the spot and to for posting the example.

Recommended Answers

All 2 Replies

You forgot to update the loop counter.

while(n>0)
{
   x=n%10;
   sum+=x;
   n/=10;
}

hey Dave Sinkula thanx a lot...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.