954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Sum of digits

I want to know how to write a program to obtain sum of the first and last digit of a number?

smithag261
Newbie Poster
6 posts since Jul 2004
Reputation Points: 11
Solved Threads: 0
 

Sure... ;)

VB Code:

Function sumFirstLast(number As Integer) As Integer

Dim numberString As String

numberString = Abs(number) & ""

sumFirstLast = Val(Mid(numberString, 1, 1)) + Val(Mid(numberString, Len(numberString), 1))

End Function
Toba
Junior Poster
192 posts since Jun 2004
Reputation Points: 115
Solved Threads: 5
 

or, in C++,

int sumFirstLast( int n )
{
    char s[32];
    return ((n % 10) + (*itoa(n,s,10) - '0')); // itoa converts an int into a string
}
Chainsaw
Posting Pro in Training
436 posts since Jun 2004
Reputation Points: 36
Solved Threads: 11
 

#include
#include
#include

class sod
{
int a,b,c,i,num,num1,sum,n;
public:
void getdata()
{
cout<<"\tProgram for sum of digits\n\n\n";
cout<<"enter a one, two, three, four or five digit number ";
cin>>num;
}
void sumod()
{
sum=0;
n=0;
num1=num;
while(num1>0)
{
b=num1/10;
num1=b;
n++;
}

for(i=0;i

keshalidani
Newbie Poster
2 posts since Nov 2010
Reputation Points: 7
Solved Threads: 0
 

C++ Syntax:
for 4 digit:

#include
#include

class sod
{
int a,b,c,i,n,sum;
public:
void getdata()
{
cout<<"enter a four digit number ";
cin>>n;
}
void sumod()
{
sum=0;
for(i=0;i<4;i++)
{
a=n%10;
b=n/10;
n=b;
sum=sum+a;
}
}
void putdata()
{
cout<<"\nSum of the digits of the above number is = "<

keshalidani
Newbie Poster
2 posts since Nov 2010
Reputation Points: 7
Solved Threads: 0
 

Do you know we have a little button called [CODE] for this?

hiddepolen
Posting Whiz in Training
297 posts since Oct 2010
Reputation Points: 82
Solved Threads: 35
 

Or in Javascript... :P

function sumDigits(val) {
  if (!isNaN(val)) {
    val = parseInt(val, 10) // ensure integer
    if (val>9) {
      var sum = val%10 // last digit number
      while (val>10) {  // searching for the first number
        val = parseInt(val/10, 10)
      }
      alert(sum+val)  // now what left is the last + first digit
    }
    else { alert(val) }
  }
  else { alert(val+" is not a number") }
}
Taywin
Posting Virtuoso
1,727 posts since Apr 2010
Reputation Points: 229
Solved Threads: 239
 

If n is a non-negative integer:

The last digit of n is n%10.

If n < 10, the first digit of n is n.

If n >= 10, the first digit of n is the first digit of n/10.

This is all you need to know in order to solve the problem.

arkoenig
Master Poster
703 posts since Jun 2010
Reputation Points: 359
Solved Threads: 109
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You