Introduction:The program finds the sum of odd-positioned digits and even-positioned digits of a given number using C#.NET example.
E.g: If you enter number as 9128456, so even place located numbers are 1,8,5 & Odd place located numbers are 9,2,4,6 and expected output should be SumOfEven = 1+8+5=14 SumOfOdd = 9+2+4+6 =21 Program:using System;
namespace DotNetMirror
{
class SumOfOddEvenPositionedDigitsOfNumber
{
static void Main()
{
Console.Write("Enter number to find sum of Even/Odd positioned digits: ");
int number = int.Parse(Console.ReadLine());
int orginalNumber = number;
int sumEvenPositioned = 0; int sumOddPositioned = 0;
int tempNumber = 0;
bool isPointerAtEvenPos = false;
while (number != 0)
{
tempNumber = number % 10; //gives last number
if (isPointerAtEvenPos)
{
sumEvenPositioned = sumEvenPositioned + tempNumber;
isPointerAtEvenPos = false; //set to odd
}
else
{
sumOddPositioned = sumOddPositioned + tempNumber;
isPointerAtEvenPos = true; //set to even
}
number = number / 10; //removes last number
}
Console.WriteLine("Sum of Even positioned numbers in '{0}' is:{1}", orginalNumber, sumEvenPositioned);
Console.WriteLine("Sum of Odd positioned numbers in '{0}' is:{1}", orginalNumber, sumOddPositioned);
Console.ReadKey();
}
}
} Output:
|