Here is a sample C# program to find the given number is Happy or Sad.
What is Happy or Sad Numbers?
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are Sad numbers.
Example:
7 is a happy number: 7->49->97->130->10->1.
22 is NOT a happy number: 22->8->64->52->29->85->89->145->42->20->4->16->37->58->89
Code:
What is Happy or Sad Numbers?
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are Sad numbers.
Example:
7 is a happy number: 7->49->97->130->10->1.
22 is NOT a happy number: 22->8->64->52->29->85->89->145->42->20->4->16->37->58->89
Code:
using System;
using System.Collections.Generic;
namespace HappyNumbers
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine();
Console.WriteLine("Enter a Number : ");
string num = Console.ReadLine();
Console.WriteLine();
HappyOrSad hs = new HappyOrSad();
if (hs.IsEqulOne(num))
{
Console.WriteLine();
Console.WriteLine("Happy :) ");
Console.WriteLine();
Console.WriteLine("----------------------");
}
else
{
Console.WriteLine();
Console.WriteLine("Sad :( ");
Console.WriteLine();
Console.WriteLine("----------------------");
}
}
}
}
class HappyOrSad
{
public bool IsEqulOne(string numbr)
{
bool isOne = false;
List<int> al = new List<int>();
while (isOne == false)
{
int val = 0;
char[] numArr = numbr.ToCharArray();
foreach (char n in numArr)
{
int nVal = Int32.Parse(n.ToString());
val += (nVal * nVal);
}
if (val == 1)
{
al.Add(val);
isOne = true;
break;
}
else
{
if (al != null)
{
if (al.Contains(val))
{
al.Add(val);
break;
}
else
{
al.Add(val);
}
}
}
numbr = val.ToString();
}
foreach (var item in al)
{
Console.Write(item + " -> ");
}
return isOne;
}
}
}