isnt this the shortest method

#include<iostream.h>
#include<conio.h>
void main()
{
 clrscr();
 int a,i=0;
 cout<<"enter a number";
 cin>>a;
 while(a>0)
 {
  int b=a%10;
  a=a/10;
  i=i+b;
 }
cout<<"sum="<<i;
getch();
}

Edited 5 Years Ago by peter_budo: Keep It Clear - Do wrap your programming code blocks within [code] ... [/code] tags

Doesn't look Python code for me!

from sys import stdout
def rev(a):
    while a:
        a, d = divmod(a,10)
        stdout.write(d)

rev(int(raw_input('Give number: ')))

Edited 5 Years Ago by pyTony: n/a

Comments
Why should it be Python in a C++ forum?

i=i+b;
This will give you the sum of the digits. Add some print statements so you know what is going on.

isnt this the shortest method

Not when you post C code in python forum.

>>> raw_input('enter a number: ')[::-1]
enter a number: 1234
'4321'

Not when you post C code in python forum.

>>> raw_input('enter a number: ')[::-1]
enter a number: 1234
'4321'

How true! That accepts anything (in spirit of duck typing), not only number, prints those distracting quotes, however. Hmmm. Lets make it full program:

print(' '.join(((raw_input('Anything ')[::-1]) ,'reversed.')))

:icon_wink:

Edited 5 Years Ago by pyTony: n/a

And now that it's in the C++ forum, I can point out that the title of this thread talks about printing the reverse of a number, but the program computes the sum of its (decimal) digits. Which is right?

And now that it's in the C++ forum, I can point out that the title of this thread talks about printing the reverse of a number, but the program computes the sum of its (decimal) digits. Which is right?

It will be down to whatever that program is doing. I had to reuse title of original thread where this was hijaked. Sorry for misleading info, but OP wasn't helpful with his descriptions, plus it was long time I had to do anything with C or C++ code (hence why it was moved to C and then to C++)

sorry guys fr the mistake but is there any shorter method to print sum of individual decimals(talking of c++)

What exactly does the OP mean by shorter?
Shorter in code ? Or Shorter in execution time ? Or something else?
I dont see why there is a need to change the current program into something shorter.
However, I would sure recommend you to use a newer compiler.

#include <stdio.h>

int main()
{
   int n, reverse = 0;

   printf("Enter a number to reverse\n");
   scanf("%d",&n);

   while (n != 0)
   {
      reverse = reverse * 10;
      reverse = reverse + n%10;
      n = n/10;
   }

   printf("Reverse of entered number is = %d\n", reverse);

   return 0;
}
This article has been dead for over six months. Start a new discussion instead.