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

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

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
}
#include<iostream.h>
#include<conio.h>
#include<string.h>

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<n;i++)
        {
        a=num%10;
        b=num/10;
        num=b;
        sum=sum+a;
        }

    }
    void putdata()
    {
    cout<<"\nSum of the digits of the above number is = "<<sum;
    }
};

int main()
{
sod s1;
clrscr();
s1.getdata();
s1.sumod();
s1.putdata();
getch();
return 0;
}
commented: bad code, not CODE tags, mix of C and C++. Attempting to help the OP cheat. Terrible post! -3

C++ Syntax:
for 4 digit:

#include<iostream.h>
#include<conio.h>

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 = "<<sum;
    }
};

int main()
{
sod s1;
clrscr();
s1.getdata();
s1.sumod();
s1.putdata();
getch();
return 0;
}

Do you know we have a little button called (CODE) for this?

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") }
}

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.

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.