C Exercise 13 - Narcissistic Number
100 Classic C Language Examples
**Problem:** Print all "narcissistic numbers". A narcissistic number is a three-digit number whose sum of the cubes of its digits equals the number itself. For example, 153 is a narcissistic number because 153 = 1^3 + 5^3 + 3^3.
**Analysis:** Use a for loop to iterate over the numbers from 100 to 999, splitting each number into its units, tens, and hundreds digits.
Example
// Created by www.runoob.com on 15/11/9.
// Copyright (c) 2015 Runoob Tutorial. All rights reserved.
//
#include
<
stdio.h
int
main
(
)
{
int
i
,
x
,
y
,
z;
// Iterate over the numbers from 100 to 999
for
(
i
=
100
;
i
<
1000
;
i
++
)
{
// Compute the individual digits
x
=
i
%
10
;
// Units digit
y
=
(
i
/
10
)
%
10
;
// Tens digit
z
=
(
i
/
100
)
%
10
;
// Hundreds digit
// Compute the sum of cubes
int
sum
=
x
x
x
y
y
y
z
z
z
;
// Check whether it is a narcissistic number
if
(
i
==
sum
)
{
printf
(
"
%d
\
n
"
,
i
)
;
}
}
return
0
;
}
The output of the above example is:
153
370
371
407
The following demonstrates how to find and output narcissistic numbers within a specified range in C:
Example
#include
#include
// Function declaration
int
countDigits
(
int
num
)
;
int
isArmstrong
(
int
num
)
;
int
main
(
)
{
int
start
,
end
;
// Input the range
printf
(
"Enter the start of the range: "
)
;
scanf
(
"%d"
,
&
start
)
;
printf
(
"Enter the end of the range: "
)
;
scanf
(
"%d"
,
&
end
)
;
// Output the narcissistic numbers within the range
printf
(
"Armstrong numbers between %d and %d are:\n"
,
start
,
end
)
;
for
(
int
i
=
start
;
i
<=
end
;
i
++
)
{
if
(
isArmstrong
(
i
)
)
{
printf
(
"%d\n"
,
i
)
;
}
}
return
0
;
}
// Count the number of digits
int
countDigits
(
int
num
)
{
int
count
=
0
;
while
(
num
!=
0
)
{
num
/=
10
;
count
++;
}
return
count
;
}
// Check whether a number is a narcissistic number
int
isArmstrong
(
int
num
)
{
int
originalNum
=
num
;
int
digits
=
countDigits
(
num
)
;
int
sum
=
0
;
while
(
num
!=
0
)
{
int
digit
=
num
%
10
;
sum
+=
pow
(
digit
,
digits
)
;
num
/=
10
;
}
return
sum
==
originalNum
;
}