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();
}

Dani AI

Generated

The thread mixes two different tasks: reversing a number’s digits and summing its digits. ’s original loop accumulates digit values (the digit sum), as noticed, while the title asks for digit reversal — called out that mismatch. Several replies show Python/C idioms; for C++ prefer standard headers and int main() rather than old iostream.h/conio.h and void main().

A concise, robust C++ approach is to treat the input as a string (handles very large numbers and preserves any leading zeros when desired), extract digits, compute the sum, and produce both a string-style reversal and a numeric-style reversal (trim leading zeros):

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

int main() {
    std::string s;
    if (!(std::cin >> s)) return 0;
    bool negative = !s.empty() && s[0] == '-';
    std::string digits;
    for (char ch : s) if (std::isdigit(static_cast<unsigned char>(ch))) digits.push_back(ch);

    int sum = 0;
    for (char d : digits) sum += d - '0';

    std::string rev = digits;
    std::reverse(rev.begin(), rev.end());

    std::string rev_trim = rev;
    rev_trim.erase(0, rev_trim.find_first_not_of('0'));
    if (rev_trim.empty()) rev_trim = "0";

    if (negative) std::cout << '-';
    std::cout << rev_trim << "  (reversed as number)\n";
    std::cout << rev << "  (reversed as string, keeps zeros)\n";
    std::cout << "sum=" << sum << '\n';
    return 0;
}

Notes and cautions: the string method accepts arbitrarily long input and is simple to reason about; an arithmetic reversal (multiply-then-add) is slightly faster and uses constant memory but risks overflow for large inputs (see ’s numeric example). What “shorter” means was raised by — brevity in source text often trades readability or safety. Decide whether reversed output should preserve leading zeros or represent a numeric value, and choose the string or numeric method accordingly.

Recommended Answers

All 11 Replies

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: ')))
commented: Why should it be Python in a C++ forum? -3

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:

Moved to C section

And moved again to C++

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;
}
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.