tags:

views:

143

answers:

7

I want to write a program for finding out the sum of first and the last digit of any number entered through keyboard. For example, I entered 52264. Output must be 5+4 = 9.

Yes, this is an assignment.

+2  A: 
int n;
cin >> n;
int num1 = n % 10;
int num2 = n;
while (num2 >= 10)
     num2 /= 10;

cout << num1+num2 << endl;
Mahmoud Younes
+4  A: 

Well, the last digit's easy enough to figure out, right?

int lastDigit = input % 10;

As for the first digit, I'm not sure about the most efficient way to get that. The first thought that immediately springs to my mind is:

int firstDigit = input;
while (firstDigit >= 10)
{
    firstDigit /= 10;
}

So, with 52264 for example:

int lastDigit = 52264 % 10; // 52264 % 10 = 4

int firstDigit = 52264;
firstDigit /= 10; // 5226
firstDigit /= 10; // 522
firstDigit /= 10; // 52
firstDigit /= 10; // 5 -- less than 10
Dan Tao
+1  A: 

Find out total number of digits in the entered number, suppose it's n.

int temp = number;
int n = 0;

while(temp > 0)
{
   temp /= 10;
   n++;
}

Then

sum = number / (int)pow(10, n - 1)  + number % 10;
Hamid Nazari
+1  A: 

This should work. Since the input is an array you just need to to look at the zero element and the last one, then sum them up.

#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 256

int main () {
  char number[MAX_LENGTH];
  int first, last, sum;
  while (scanf("%s", number) == 1 ) {
    first = number[0];
    last = number[strlen(number)-1];
    sum = atoi(&first) + atoi(&last);
    printf("Sum = %d\n", sum);
  }
  return 0;
}

Here's a sample run:

123456
Sum = 7
845731
Sum = 9
35846
Sum = 9
23
Sum = 5
11
Sum = 2
Mahmoud
+1  A: 

A different approach would be to treat the input as a string.

char buf[BUFSIZ];
char *p;
char bufTemp1[2];
char bufTemp2[2];
int sum;

fgets(buf, sizeof(buf), stdin);
if ((p = strchr (buf, '\n')) != NULL)
{
    *p = '\0';
}

bufTemp1[0] = buf[0];
bufTemp1[1] = '\0';

strncpy (bufTemp2, &buf[strlen(buf)-1], 1);
bufTemp2[1] = '\0';

sum = atoi (bufTemp1) + atoi (bufTemp2);
Edward Leno
+1  A: 
#include <iostream>
using namespace std;
int main(){
int sum=0;
int first,last;
int n;
cin>>n;

first=n %10;
 while (n!=0){
 last=n/10;
}
sum=first+last;
cout<<sum<<endl;

}
A: 

A much more efficient way to go about doing this would be to find the number of digits beforehand, like so:

uint32_t digitCount = number == 0 ? 0 : (uint32_t)(log10(abs(number))) + 1;

From there, the process of finding the first and last digits is simplified.