Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C# Program to Check Whether the Entered Number is an Armstrong Number or Not
For an Armstrong number, let us say a number has 3 digits, then the sum of cube of its digits is equal to the number itself.
For example, 153 is equal to −
1³ + 3³ + 5³
To check for it using C#, check the value and find its remainder. Here “val” is the number you want to check for Armstrong −
for (int i = val; i > 0; i = i / 10) {
rem = i % 10;
sum = sum + rem*rem*rem;
}
Now compare the addition with the actual value. If it matches, that would mean the sum of cubes are the same and it is an Armstrong number −
if (sum == val) {
Console.Write("Armstrong Number");
}else {
Console.Write("Not an Armstrong Number");
}
Example
Let us see a complete example to check whether a number is Armstrong or not.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
class ApplicationNew {
static void Main(string[] args) {
int val = 153, sum = 0;
int rem;
// check for armstrong
for (int i = val; i > 0; i = i / 10) {
rem = i % 10;
sum = sum + rem*rem*rem;
}
if (sum == val) {
Console.Write("Armstrong Number");
} else {
Console.Write("Not an Armstrong Number");
}
Console.ReadLine();
}
}
}
Output
Armstrong Number
Advertisements