Easy Tutorial
❮ C Type Casting C Nested If ❯

C Exercise Example 13 - Narcissistic Numbers

C Language Classic 100 Examples

Topic: Print all "narcissistic numbers," which are numbers that are equal to the sum of their own digits each raised to the power of the number of digits. For example, 153 is a narcissistic number because 153 = 1^3 + 5^3 + 3^3.

Program Analysis: Use a for loop to control numbers from 100 to 999, and decompose each number into units, tens, and hundreds.

Example

//  Created by www.tutorialpro.org on 15/11/9.
//  Copyright © 2015 tutorialpro.org. All rights reserved.
//

#include<stdio.h>

int main()
{
    int i, x, y, z;
    for(i = 100; i < 1000; i++)
    {
        x = i % 10;
        y = i / 10 % 10;
        z = i / 100 % 10;

        if(i == (x*x*x + y*y*y + z*z*z))
        printf("%d\n", i);

    }
    return 0;
}

The above example outputs:

153
370
371
407

C Language Classic 100 Examples

❮ C Type Casting C Nested If ❯