Welcome to ARC Forums

Join our group of tech enthusiasts and Android developers

C++ Program to find the sum of digits of an integer number

Discussion in 'Programming' started by Arjun Chandran, Feb 15, 2017.

Tags:
  1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  1. Arjun Chandran

    Arjun Chandran Super Samurai
    Staff Member

    350
    131
    1,900
    Ratings:
    +131 / 0 / -0
    I'm having a lab practical and has C++ programs. For the question 'Program to find the sum of digits of an integer number' here is the given code on our record book:
    Code:
    #include <iostream>
    using namespace std;
    int main()
    {
     int n,rem,s=0;
     cout<<"Enter the digits :";
     cin>>n;
     while(n>0)
    {
    rem=n%10;
    s=s+rem;
    n=n/10;
    }
     cout<<"Sum of digits = "<<s<</n;
     return 0;
    }
    But this doesn't seem to work and is giving the following errors

    g++ -Wall -c "untitled.cpp" (in directory: C:\Users\Arjun\Desktop)
    untitled.cpp: In function 'int main()':
    untitled.cpp:14:31: error: expected primary-expression before '/' token
    Compilation failed.

    Please give the correct code for this program.
     
  2. Aromal

    Aromal HummingBird

    23
    10
    100
    Ratings:
    +10 / 0 / -0
    Try this code:
    Code:
    #include <iostream>
    using namespace std;
    int main()
    {
     int n,rem,s=0;
     cout<<"Enter the digits :";
     cin>>n;
     while(n>0)
    {
    rem=n%10;
    s=s+rem;
    n=n/10;
    }
     cout<<"Sum of digits = "<<s<<endl;
     return 0;
    }
    Your code didn't work because there was no ending line that is "endl" at line cout<<"Sum of digits = "<<s<<endl;
     
    • Agree Agree x 1
    • Love Love x 1
  3. Arjun Chandran

    Arjun Chandran Super Samurai
    Staff Member

    350
    131
    1,900
    Ratings:
    +131 / 0 / -0
    Thanks, it worked! :)
     
    • Like Like x 1

Share This Page