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.
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.
int n;
cin >> n;
int num1 = n % 10;
int num2 = n;
while (num2 >= 10)
num2 /= 10;
cout << num1+num2 << endl;
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
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;
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
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);