How to resolve the algorithm Sum digits of an integer step by step in the Modula-2 programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sum digits of an integer step by step in the Modula-2 programming language

Table of Contents

Problem Statement

Take a   Natural Number   in a given base and return the sum of its digits:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sum digits of an integer step by step in the Modula-2 programming language

Source code in the modula-2 programming language

MODULE SumOFDigits;
FROM STextIO IMPORT
  WriteString, WriteLn;
FROM SWholeIO IMPORT
  WriteInt;
FROM Conversions IMPORT
  StrBaseToLong;

PROCEDURE SumOfDigitBase(N: LONGCARD; Base: CARDINAL): CARDINAL;
VAR
  Tmp, LBase: LONGCARD;
  Digit, Sum : CARDINAL;
BEGIN
  Digit := 0;
  Sum   := 0;
  LBase := Base;
  WHILE N > 0 DO
    Tmp := N / LBase;
    Digit := N - LBase * Tmp;
    N := Tmp;
    INC(Sum, Digit);
  END;
  RETURN Sum;
END SumOfDigitBase;

VAR
  Num: LONGCARD;

BEGIN
  WriteString('   1 sums to '); 
  WriteInt(SumOfDigitBase(1, 10), 1); 
  WriteLn;
  WriteString('1234 sums to '); 
  WriteInt(SumOfDigitBase(1234, 10), 1); 
  WriteLn;
  IF StrBaseToLong('FE', 16, Num) THEN
    WriteString(' $FE sums to '); 
    WriteInt(SumOfDigitBase(Num, 16), 1); 
    WriteLn;
  END;
  IF StrBaseToLong('F0E', 16, Num) THEN
    WriteString('$F0E sums to '); 
    WriteInt(SumOfDigitBase(Num, 16), 1); 
    WriteLn;
  END;
  WriteString('MAX(LONGCARD) (in dec) sums to '); 
  WriteInt(SumOfDigitBase(MAX(LONGCARD), 10), 1); 
  WriteLn;
END SumOFDigits.


  

You may also check:How to resolve the algorithm Remove duplicate elements step by step in the NewLISP programming language
You may also check:How to resolve the algorithm Even or odd step by step in the TI-57 programming language
You may also check:How to resolve the algorithm Loops/Downward for step by step in the Java programming language
You may also check:How to resolve the algorithm Determine sentence type step by step in the Raku programming language
You may also check:How to resolve the algorithm Bulls and cows step by step in the VBScript programming language