• Zero Spam Tolerance Policy is now in effect. Any accounts posting spam will be permanently banned without warning. Learn more
Welcome to our Community
Wanting to join the rest of our members? Feel free to sign up today.
Sign up

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

pr0ph3t

Expert
⚔️ MOD
Dec 30, 2016
872
22
19,400
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.


 
Last edited:
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;
 
As the above problem is solved, but i still mark some point why it doesn't work.
It is because you have used /n which means new line but it isn't a keyword. /n is used in comments when for new line. Instead you can use endl which is a keyword and it means end of line. Or you can use "/n" which counted as a comment but as the comments has only /n it will print new line.
 
  • Like
Reactions: pr0ph3t
As the above problem is solved, but i still mark some point why it doesn't work.
It is because you have used /n which means new line but it isn't a keyword. /n is used in comments when for new line. Instead you can use endl which is a keyword and it means end of line. Or you can use "/n" which counted as a comment but as the comments has only /n it will print new line.
Abhiram Shibu Abhiram Shibu gave me this code


 

Sponsored