Summary: This C program reads a five-digit number and calculates the sum of its individual digits using arithmetic operations. It demonstrates digit extraction using modulo and integer division.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n;
scanf("%d", &n);
int sum = 0;
// Extract each digit and add to sum
sum += n % 10; // last digit
n = n / 10;
sum += n % 10; // 4th digit
n = n / 10;
sum += n % 10; // 3rd digit
n = n / 10;
sum += n % 10; // 2nd digit
n = n / 10;
sum += n % 10; // 1st digit
printf("%d", sum);
return 0;
}
Reading Input:
The program uses scanf()
to read a 5-digit integer from the user.
Digit Extraction:
Each digit is extracted using the modulo operator %
, which returns the last digit. The number is then reduced using integer division by 10.
Step-by-Step Breakdown:
n % 10
: extracts the last digitn / 10
: removes the last digitSummation Logic:
Each extracted digit is added to a running total stored in the sum
variable.
Assumptions:
This program assumes the input is a five-digit number. No input validation is included.