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

In this C Programming example, we will write a C Program to print sum of first and last digit of number.

Example of the Program Output:
Input: 1234
Output: 5

Before writing this C program, let’s 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 is to find the last digit of the number. To find the last digit of a 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 the first digit we divide the given number by 10 till the number is greater than 0.
  • Now in the last step, we finally calculate the sum of the 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 to print sum of first and last digit of number

After going through the algorithm, write the C program to get input from the user and get the sum of first digit and last digit of the 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 the sum of first digit and last digit of the inputted number, let’s check the output. As We have inputted the value of 123456. It is applicable to any digit length of numbers. Let’s have a look at the output.

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

Leave a Reply

Your email address will not be published. Required fields are marked *