Pascal: Armstrong numbers

Before going straight to programming we should analyze  some different types of numbers.

The first one which I am introducing to you here is the Armstrong number. An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, we could take 153 = 1^3 + 5^3 +3^3. There some other numbers which are written down at the bottom of post.

So now when we already know what the number consists of, we can make a simple Pascal program which will find this kind of number at given integers interval. Moreover, a good objective for this task is to use a boolean type.

Here is the whole program of this task:

program Armstrog_numbers;
  var a, b,
    WriteLn('Input the beginning and end of interval: ');
    ReadLn(a, b);
    whether := FALSE;
    while whether = TRUE do
        a_copy := a;
        sum := 0;
        while a_copy = 0 do
            digit := (a_copy mod 10);
            sum := sum + digit * digit * digit;
            a_copy := a_copy div 10;
        if sum = a
         then whether := TRUE
         else a := a + 1;
    WriteLn('Result: ', a);

As you can see we take inputed values and start to search the number from a variable which increases if there was not found any Armstrong number.

The second internal while loop works with a copy of increasing variable a. This loop calculates a sum of number digits to the power of 3. Then we try to equal the sum and our number. If they are equal, we call for stop by using whether boolean variable. After the main loop finishes, we output a number.

However, by adding an additional if statement, we can make a string which warns us if there is no such number in the interval. Try to make that by yourself and let me know if you have any problems by writing a comment.

Here are some Armstrong numbers as control data for your program:
370, 371, 407.

Leave a comment

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. Cookies are only used for statistical purposes.