Posted in: C Language

C Program to print sum of first and last digit of number.

In this C program we have to print sum of first and last digit of the inputted number by the user.

Example-

INPUT

Input number – 1234

OUTPUT

Output – 5

Table of contents:-

  1. Concept
  2. Algorithm
  3. Program
  4. Output
  5. Resource

Before writing this C program, lets learn about the concept we are gonna use in our program.

1. Concept

First we have to take the input number by the user and store it in some variable say num.

  • Then our next step to find last digit of the number. To find last digit of given number we modulo divide the given number by 10. Which is  lastDigit = num % 10.
  • Now we have to find the first digit of the number. To find first digit we divide the given number by 10 till number is greater than 0.
  • Now in the last step we finally calculate sum of first and last digit i.e sum=firstdigit + lastdigit.

The concepts of C programming you need to learn before writing the program are:-

  1. while loop
  2. Arithmetic Operators

Kindly learn these topics before continuing and writing this C program.

2. Algorithm

Here’s the algorithm of writing C program to print sum of first digit and last digit of the inputted number.

  1. START
  2. Input num
  3. lastDigit = num % 10
  4. firstdigit =num
  5. sum = firstDigit + lastDigit
  6. Write sum
  7. STOP

3. C program

After going through the algorithm, write C program to get input from the user and get the sum of first digit and last digit of inputted number.

#include <stdio.h>
#include <conio.h>

void main()
{
int num, sum=0, firstDigit, lastDigit;

printf("Enter any number to find sum of first and last digit: ");
scanf("%d", &num);

lastDigit = num % 10;

firstDigit = num;

while(num >= 10)
{
num = num / 10;
}
firstDigit = num;

sum = firstDigit + lastDigit;

printf("Sum of first and last digit = %d", sum);

getch();

}

4. Output

After writing the C program to print sum of first digit and last digit of inputted number, let’s check the output. As We have inputted the value of 123456 . It is applicable for any digit length of numbers . Let’s have a look at the output.

C program Sum first last digit number

5. Resources

If you want to try the program on your own then please use the resources and files of this program and learn by practicing.

  1. C program file
  2. Raw code

Comments (2) on "C Program to print sum of first and last digit of number."

  1. A thorough explanation of the C concept, and a must read for all the beginners diving into the world of programming!!!!

Leave a Reply

Your email address will not be published.