UMBC CS 201, Fall 98
UMBC CMSC 201 & 201H Fall '98 CSEE | 201 | 201 F'98 | lectures | news | help

Sum of Digits

The Task

Read in a number from the keyboard and
add up the digits it contains.

The Program

/* File: digitsum.c ---------------- This program counts the number of digits in a positive integer. The program depends on the fact that the last digit of a integer n is given by n % 10 and the number consisting of all but the last digit is given by the expression n / 10. */ #include <stdio.h> main() { int n, dsum; /* Print messages to and get input from user */ printf("Sum the digits in an integer.\n"); printf("Enter a positive integer: "); scanf("%d", &n); /* Initialize dsum to 0 */ dsum = 0; /* This loop repeatedly strips the last digit off of n and adds it to dsum until there are no more digits */ while (n > 0) { dsum += n % 10; /*Add last digit to dsum */ n /= 10; /*Strip away last digit */ } /* Print the sum of the digits */ printf("The sum of the digits is %d\n", dsum); }

The Sample Run

lassie% a.out Sum the digits in an integer. Enter a positive integer: 342 The sum of the digits is 9 lassie% a.out Sum the digits in an integer. Enter a positive integer: -12 The sum of the digits is 0 lassie%


A More Robust Digitsum

The Task

Read in a number from the keyboard, making sure that it is a positive integer, and add up the digits it contains.

The Program

/* Program: robust.c Query the user for a positive integer. */ #include <stdio.h> main() { /* Declare variables */ int n, dsum; /* Print purpose of program */ printf("Sum the digits in an integer.\n"); /* Get input from the user */ printf("Enter a positive integer: "); scanf("%d", &n); /* Error checking of user input : This loop assures that a positive integer was input by printing an error message and asking for new input. */ while (n <= 0) { printf("Positive integers only, please.\n"); printf("Enter a positive integer: "); scanf("%d", &n); } /* Initialize dsum to 0 */ dsum = 0; /* This loop adds the last digit to dsum and then strips away the last digit until no digits remain */ while (n > 0) { dsum += n % 10; n /= 10; } /* Print the sum of the digits */ printf("The sum of the digits is %d\n", dsum); }

The Sample Run

lassie% a.out Sum the digits in an integer. Enter a positive integer: -12 Positive integers only, please. Enter a positive integer: 42 The sum of the digits is 6 lassie% a.out Sum the digits in an integer. Enter a positive integer: -32 Positive integers only, please. Enter a positive integer: -0 Positive integers only, please. Enter a positive integer: 0 Positive integers only, please. Enter a positive integer: -20 Positive integers only, please. Enter a positive integer: 21 The sum of the digits is 3 lassie%

The Lesson


CSEE | 201 | 201 F'98 | lectures | news | help

Saturday, 12-Sep-1998 16:43:22 EDT