Change calculator - c#

i have a tusk where i have been asked to write a program that calculate change to be given to a customer after a cash transaction, and determines the number of bank notes and coins in each denomination.
the user has to put in the cost of goods and the amount received from the customer.
I must have a class with a method that accepts decimal arguments, Cost and Chashreceived, plus integer arguments for: Hunderds, Fifties, Twenties, Tens, Fives, Twos, Ones, 50c, 10c, 5c, 2c and 1c.
i substract Cost from and the Cashreceived and calculate the exact number of notes and coins required to be returned as change.
I have tried it but it become problematic when i have to put in the coins.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChangeCalculator
{
class Program
{
static void Main(string[] args)
{
clsCash Money = new clsCash();
clsCash Paid = new clsCash();
Console.WriteLine("What is the cost of the goods?");
Money.Cost = Convert.ToDecimal(Console.ReadLine());
Console.WriteLine("How much was recived?");
Paid.CashRecieved = Convert.ToDecimal(Console.ReadLine());
Money.GetChange(Money.Cost, Paid.CashRecieved);
Console.Read();
}
}
class clsCash
{
private decimal cost;
private decimal cashRecieved;
public decimal Cost
{
get
{
return cost;
}
set
{
cost = value;
}
}
public decimal CashRecieved
{
get
{
return cashRecieved;
}
set
{
cashRecieved = value;
}
}
public void GetChange(decimal Cost, decimal CashRecieved)
{
decimal change = CashRecieved - Cost;
int hundreds = 0;
int fifty = 0;
int twenty = 0;
int ten = 0;
int five = 0;
int two = 0;
int one = 0;
int centsfifty = 0;
int centsten = 0;
int centsfive = 0;
int centstwo = 0;
int centsone = 0;
do
{
if (change >= 100)
{
hundreds = (int)change / 100;
change = (int)change % 100;
} //while (change > 0);
else if (change >= 50)
{
fifty = (int)change / 50;
change = change % 50;
}
else if (change >= 20)
{
twenty = (int)change / 20;
change = change % 20;
}
else if (change >= 10)
{
ten = (int)change / 10;
change = change % 10;
}
else if (change >= 5)
{
five = (int)change / 5;
change = change % 5;
}
else if (change >= 2)
{
two = (int)change / 2;
change = change % 2;
}
else if (change >= 1)
{
one = (int)change / 1;
change = change % 1;
}
else if (change > 1)
{
decimal fhu = change / 0.5m;
centsfifty = (int)fhu;
change = change % 0.5m;
Console.WriteLine("YOUR CHANGE IS:");
}
} while (change >= 0);
Console.WriteLine("YOUR CHANGE IS:");
Console.WriteLine("---------------");
Console.WriteLine("HUNDREDS RANDS \t: {0}", hundreds);
Console.WriteLine("FIFTY RANDS \t: {0}", fifty);
Console.WriteLine("TWENTY RANDS \t: {0}", twenty);
Console.WriteLine("TEN RANDS \t: {0}", ten);
Console.WriteLine("FIVE RANDS \t: {0}", five);
Console.WriteLine("TWO RANDS \t: {0}", two);
Console.WriteLine("ONE RANDS \t: {0}", one);
Console.WriteLine("50 CENTS \t: {0}", centsfifty);
}
}
}

There is a pattern you can use to get the amounts like this,
Here is a small example to get you started, you could probably wrap it up in a function or something, but it gives you an idea on where to start.
// number to find values from
int change = 254;
int _hundreds = 100;
int _fifty = 50;
int _twenty = 20;
int _ten = 10;
int _five = 5;
int _two = 2;
int _one = 1;
int hundreds = (int)(change / _hundreds);
int fifty = (int)((change % _hundreds) / _fifty);
int twenty = (int)(((change % _hundreds) % _fifty) / _twenty);
int ten = (int)((((change % _hundreds) % _fifty) % _twenty) / _ten);
int five = (int)(((((change % _hundreds) % _fifty) % _twenty) % _ten) / _five);
int two = (int)((((((change % _hundreds) % _fifty) % _twenty) % _ten) % _five) / _two);
int one = (int)(((((((change % _hundreds) % _fifty) % _twenty) % _ten) % _five) % _two) / _one);
Returns
hundreds = 2
fifty = 1
twenty = 0
ten = 0
five = 0
two = 2
one = 0;

One way to help simplify your code and improve it's readability is to eliminate the conditionals and
nested arithmetic operations, which almost always make the code harder to understand.
I see int is being cast too many times, this probably means it's best to use int right from the start. Eventhough you declare the cost and cashreceived variables as decimal types they are both being cast to int.
Therefore it would be better to declare both of them as int from the beginning, this will help to ease on the casting.
you may do something like this
hundreds = change / 100;
change %= 100;
fifty = change / 50;
change %= 50;
ten = change / 10;
change %= 10;
five = change / 5;
change %= 5;
two = change / 2;
change %= 2;
one = change;

Instead of
if (change >= 100)
{
hundreds = (int)change / 100;
change = (int)change % 100;
}
Try using
if (change >= 100)
{
decimal rand = change / 100;
hundred= (int)rand;
change = change % 100;
}
if (change >= 50)
{
decimal rand = (int)change / 50;
fifty = (int)rand;
change = change % 50;
}
if (change >= 20)
{
decimal rand = change / 20;
twenty = (int)rand;
change = change % 20;
}
I hope this helps.

Related

Float Evaluation returns integer?

I recently started with the euler Project for practice, I completed 1 and 2, but 3 is just not working. I used the same line of code for every solution to check if the number is decimal or not. This worked fine except this time, but I dont know why. This code
for (float i = 0; i < 1000; i++)
{
float temp = i / 3;
float temp2 = i/ 5;
if ((temp % 1) == 0 || (temp2 % 1) == 0)
{
num += i;
}
}
worked perfectly fine, but this one (which is basically the same)
float input = 600851475143;
for (float i = 0; i < 1000; i++)
{
float temp = input/i;
if ((temp % 1) == 0)
{
Console.Write(temp + ", ");
}
just returns every number. Then I tried this
float temp = 10/9;
Console.WriteLine(temp);
But it just returns 1. So i thought of an overflow or something like that, but my next approach didnt work either:
float temp = 10/9;
bool temp2 = (temp%1) == 0;
Console.WriteLine(temp2);
Return: True
I dont now what to do anymore, does someone know why this happens? Thanks in advance.
float in C# has precision of 6-9 digits according to docs, 600851475143 divided by maximum i in the loop (i.e. 999) will have more than 9 digits in mantissa so float will not be able to cover fractional part, so try switching to double or even decimal:
double input = 600851475143;
for (double i = 0; i < 1000; i++)
{
double temp = input / i;
if ((temp % 1) == 0)
{
Console.Write(temp + ", ");
}
}
Also I would say that you can use long's in this case:
long input = 600851475143;
for (long i = 1; i < 1000; i++)
{
var x = (input % i);
if (x == 0)
{
Console.WriteLine(input / i);
}
}
As for the last snippet - 10 and 9 in 10/9 are int's, so the result of 10/9 is an int and equals to 1, which give you the result you get.

How to loop random number to make result equal user input summary [duplicate]

This question already has answers here:
How to generate random 5 digit number depend on user summary
(2 answers)
Closed 4 years ago.
i have some problem like this.
user(A) enter 500000 to my application and then i want to generate 50 random 5 digit number and when summary 50 random number need to equal 500000, How to do like i tried already but it's not working this is my code
int balane = 500000;
int nums = 50;
int max = balane / nums;
Random rand = new Random();
int newNum = 0;
int[] ar = new int[nums];
for (int i = 0; i < nums - 1; i++)
{
newNum = rand.Next(max);
ar[i] = newNum;
balane -= newNum;
max = balane / (nums - i - 1);
ar[nums - 1] = balane;
}
int check = 0;
foreach (int x in ar)
{
check += x;
}
the result that i tell you not working because in my array list i have value more than 5 digit but the result equal 500000.
How to solve this issue ? Thank you very much.
This works for me
public static void test(int balance = 500000, int nums = 50, int max_digits = 5)
{
int rest = balance;
var max_value = (int)Math.Pow(10, max_digits) - 1;
var rand = new Random();
int[] ar = new int[nums];
for (int i = 0; i < nums - 1; i++)
{
var max = rest / (nums - i);
if (max > max_value) max = max_value;
var newNum = rand.Next(max);
ar[i] = newNum;
rest -= newNum;
}
while (rest > max_value)
{
var all_values_are_max = true;
for (int i = 0; i < nums - 1; i++)
{
if (ar[i] < max_value)
{
var d = (int)((max_value - ar[i]) / 10.0); // 10% increase
ar[i] += d;
rest -= d;
all_values_are_max = false;
}
}
if (all_values_are_max)
throw new Exception("This is not possible at all!");
}
while (rest < 0)
{
for (int i = 0; i < nums - 1; i++)
{
if (ar[i] > 0)
{
var d = (int)(ar[i] / 20.0); // %5 decrease
ar[i] -= d;
rest += d;
}
}
}
ar[nums - 1] = rest;
int check_sum = 0;
foreach (int x in ar)
{
check_sum += x;
if (x > max_value || x < 0)
MessageBox.Show("wrong value");
}
if (check_sum != balance)
MessageBox.Show("Error: sum is " + check_sum);
MessageBox.Show("ok");
}
For example, test(500000,50) works fine all times, but test(500000, 5) throw an exception, because is not possible
Perhaps try this:
var rnd = new Random();
var numbers = Enumerable.Range(0, 50).Select(x => rnd.Next(500_000)).OrderBy(x => x).ToArray();
numbers = numbers.Skip(1).Zip(numbers, (x1, x0) => x1 - x0).ToArray();
numbers = numbers.Append(500_000 - numbers.Sum()).ToArray();
Console.WriteLine(numbers.Count());
Console.WriteLine(numbers.Sum());
This outputs:
50
500000
This works by generating 50 random numbers between 0 and 499,999 inclusively. It then sorts them ascendingly and then gets the difference between each successive pair. This by definition produces a set of 49 values that almost adds up to 500,000. It's then just a matter of adding the one missing number by doing 500_000 - numbers.Sum().

Find subset of numbers that add up to a given number

I have a problem I need to solve using C#. There is an array of decimal numbers (representing quantities of an item received by a warehouse at different times). This array is already sorted in the order in which the quantities were received. I need to be able to find the earliest combination of quantities that sum up to a specified total quantity.
So for example, say I have some quantities that came in chronologically as follows [13, 6, 9, 8, 23, 18, 4] and say my total quantity to match is 23. Then I should be able to get [13, 6, 4] as the matching subset although [6, 9, 8] and [23] are also matching but not the earliest.
What would be the best approach/algorithm for this?
I have so far come up with a rather naive approach using recursion.
public class MatchSubset
{
private decimal[] qty = null;
private decimal matchSum = 0;
public int operations = 0;
public int[] matchedIndices = null;
public int matchCount = 0;
private bool SumUp(int i, int n, decimal sum)
{
operations++;
matchedIndices[matchCount++] = i;
sum += qty[i];
if (sum == matchSum)
return true;
if (i >= n - 1)
{
matchCount--;
return false;
}
if (SumUp(i + 1, n, sum))
return true;
sum -= qty[i];
matchCount--;
return SumUp(i + 1, n, sum);
}
public bool Match(decimal[] qty, decimal matchSum)
{
this.qty = qty;
this.matchSum = matchSum;
matchCount = 0;
matchedIndices = new int[qty.Count()];
return SumUp(0, qty.Count(), 0);
}
}
static void Main(string[] args)
{
var match = new MatchSubset();
int maxQtys = 20;
Random rand = new Random(DateTime.Now.Millisecond);
decimal[] qty = new decimal[maxQtys];
for (int i = 0; i < maxQtys - 2; i++)
qty[i] = rand.Next(1, 500);
qty[maxQtys - 2] = 99910;
qty[maxQtys - 1] = 77910;
DateTime t1 = DateTime.Now;
if (match.Match(qty, 177820))
{
Console.WriteLine(DateTime.Now.Subtract(t1).TotalMilliseconds);
Console.WriteLine("Operations: " + match.operations);
for (int i = 0; i < match.matchCount; i++)
{
Console.WriteLine(match.matchedIndices[i]);
}
}
}
The matching subset can be as short as one element and as long as the original set (containing all elements). But to test the worst case scenario, in my test program I am using an arbitrarily long set of which only the last two match the given number.
I see that with 20 numbers in the set, it calls the recursive function over a million times with a max recursion depth of 20. If I run into a set of 30 or more numbers in production, I am fearing it will consume a very long time.
Is there a way to further optimize this? Also, looking at the downvotes, is this the wrong place for such questions?
I was unable to end up with something revolutionary, so the presented solution is just a different implementation of the same brute force algorithm, with 2 optimizations. The first optimization is using iterative implementation rather than recursive. I don't think it is significant because you are more likely to end up with out of time rather than out of stack space, but still it's a good one in general and not hard to implement. The most significant is the second one. The idea is, during the "forward" step, anytime the current sum becomes greater than the target sum, to be able to skip checking the next items that have greater or equal value to the current item. Usually that's accomplished by first sorting the input set, which is not applicable in your case. However, while thinking how to overcome that limitation, I realized that all I need is to have for each item the index of the first next item which value is less than the item value, so I can just jump to that index until I hit the end.
Now, although in the worst case both implementations perform the same way, i.e. may not end in a reasonable time, in many practical scenarios the optimized variant is able to produce result very quickly while the original still doesn't end in a reasonable time. You can check the difference by playing with maxQtys and maxQty parameters.
Here is the implementation described, with test code:
using System;
using System.Diagnostics;
using System.Linq;
namespace Tests
{
class Program
{
private static void Match(decimal[] inputQty, decimal matchSum, out int[] matchedIndices, out int matchCount, out int operations)
{
matchedIndices = new int[inputQty.Length];
matchCount = 0;
operations = 0;
var nextLessQtyPos = new int[inputQty.Length];
for (int i = inputQty.Length - 1; i >= 0; i--)
{
var currentQty = inputQty[i];
int nextPos = i + 1;
while (nextPos < inputQty.Length)
{
var nextQty = inputQty[nextPos];
int compare = nextQty.CompareTo(currentQty);
if (compare < 0) break;
nextPos = nextLessQtyPos[nextPos];
if (compare == 0) break;
}
nextLessQtyPos[i] = nextPos;
}
decimal currentSum = 0;
for (int nextPos = 0; ;)
{
if (nextPos < inputQty.Length)
{
// Forward
operations++;
var nextSum = currentSum + inputQty[nextPos];
int compare = nextSum.CompareTo(matchSum);
if (compare < 0)
{
matchedIndices[matchCount++] = nextPos;
currentSum = nextSum;
nextPos++;
}
else if (compare > 0)
{
nextPos = nextLessQtyPos[nextPos];
}
else
{
// Found
matchedIndices[matchCount++] = nextPos;
break;
}
}
else
{
// Backward
if (matchCount == 0) break;
var lastPos = matchedIndices[--matchCount];
currentSum -= inputQty[lastPos];
nextPos = lastPos + 1;
}
}
}
public class MatchSubset
{
private decimal[] qty = null;
private decimal matchSum = 0;
public int operations = 0;
public int[] matchedIndices = null;
public int matchCount = 0;
private bool SumUp(int i, int n, decimal sum)
{
operations++;
matchedIndices[matchCount++] = i;
sum += qty[i];
if (sum == matchSum)
return true;
if (i >= n - 1)
{
matchCount--;
return false;
}
if (SumUp(i + 1, n, sum))
return true;
sum -= qty[i];
matchCount--;
return SumUp(i + 1, n, sum);
}
public bool Match(decimal[] qty, decimal matchSum)
{
this.qty = qty;
this.matchSum = matchSum;
matchCount = 0;
matchedIndices = new int[qty.Count()];
return SumUp(0, qty.Count(), 0);
}
}
static void Main(string[] args)
{
int maxQtys = 3000;
decimal matchQty = 177820;
var qty = new decimal[maxQtys];
int maxQty = (int)(0.5m * matchQty);
var random = new Random();
for (int i = 0; i < maxQtys - 2; i++)
qty[i] = random.Next(1, maxQty);
qty[maxQtys - 2] = 99910;
qty[maxQtys - 1] = 77910;
Console.WriteLine("Source: {" + string.Join(", ", qty.Select(v => v.ToString())) + "}");
Console.WriteLine("Target: {" + matchQty + "}");
int[] matchedIndices;
int matchCount;
int operations;
var sw = new Stopwatch();
Console.Write("#1 processing...");
sw.Restart();
Match(qty, matchQty, out matchedIndices, out matchCount, out operations);
sw.Stop();
ShowResult(matchedIndices, matchCount, operations, sw.Elapsed);
Console.Write("#2 processing...");
var match = new MatchSubset();
sw.Restart();
match.Match(qty, matchQty);
sw.Stop();
ShowResult(match.matchedIndices, match.matchCount, match.operations, sw.Elapsed);
Console.Write("Done.");
Console.ReadLine();
}
static void ShowResult(int[] matchedIndices, int matchCount, int operations, TimeSpan time)
{
Console.WriteLine();
Console.WriteLine("Time: " + time);
Console.WriteLine("Operations: " + operations);
if (matchCount == 0)
Console.WriteLine("No Match.");
else
Console.WriteLine("Match: {" + string.Join(", ", Enumerable.Range(0, matchCount).Select(i => matchedIndices[i].ToString())) + "}");
}
}
}

Creating 2 numbers from a one #C

I should create two new numbers from a one, the first group will contain digits which are divisible by 2 and the other group will contain the others.
int checkCount = 94321, num1 = 94321, count2 = 0, countRest = 0;
while (checkCount > 0)
{
if (checkCount % 2 == 0)
count2++;
else
countRest++;
checkCount /= 10;
}
int[] a = new int[count2];
int[] b = new int[countRest];
int k2 = 0, kRest = 0;
for (int j = 0; j < a.Length + b.Length; j++)
{
if (num1 % 2 == 0)
{
a[k2] = num1 % 10;
k2++;
}
else
{
b[kRest] = num1 % 10;
kRest++;
}
num1 /= 10;
}
I created two arrays with the numbers I should use, now how can I build two INT varabile when each one contains all of the numbers together from the array?
Example:
If I have this number - 12345 so
var = 24, other var = 135
If you have another solution without arrays I think it will be better.
Thank you.
Why not just:
int decimalMaskA = 1;
int decimalMaskB = 1;
while (checkCount > 0)
{
if (checkCount % 2 == 0)
{
count2 = count2 + (checkCount % 10)*decimalMaskA;
decimalMaskA *= 10;
}
else
{
countRest = countRest + (checkCount % 10)*decimalMaskB;
decimalMaskB *= 10;
}
checkCount /= 10;
}
count2 and countRest will contain those numbers (135 and 24) instead of counts.
This splits number 12345 to numbers 135 and 24.
int checkCount = 12345;
int even = 0;
int odd = 0;
int reverseEven = 0;
int reverseOdd = 0;
while (checkCount > 0) {
int current = checkCount % 10;
if (current % 2 == 0) {
reverseEven = 10 * reverseEven + current;
} else {
reverseOdd = 10 * reverseOdd + current;
}
checkCount /= 10;
}
while (reverseEven > 0) {
even = 10 * even + reverseEven % 10;
reverseEven /= 10;
}
while (reverseOdd > 0) {
odd = 10 * odd + reverseOdd % 10;
reverseOdd /= 10;
}
Console.WriteLine("even: {0}", even);
Console.WriteLine("odd: {0}", odd);
If I understand what you're looking for this will do the trick:
//Setup a sample array
int[] a = new int[2];
a[0] = 2;
a[1] = 4;
//Convert each item to a string, convert that to a string array, join the strings and turn into an int
int output = int.Parse(String.Join("", a.Select(s => s.ToString()).ToArray()));
This works for me:
int number = 12345;
string result1 = "";
string result2 = "";
string numberString = number.ToString();
for (int i = 0; i < numberString.Length; i++ )
{
if (numberString[i] % 2 == 0)
{
result1 = result1 + numberString[i];
}
else
{
result2 = result2 + numberString[i];
}
}
int evenNumbers = int.Parse(result1);
int oddNumbers = int.Parse(result2);
How can I build two INT varabile
when each one contains all of the
numbers together from the array?
I can't say for sure, but I think you're asking how to assemble a number given each of its digits in decreasing order of significance.
To 'append' a digit to a number, you can multiply the number by 10 and then add the digit to that. To create the 'assembled' number, you can perform this operation for each digit in the array,
int[] digits = ...
int num = digits.Aggregate(0, (numSoFar, digit) => 10 * numSoFar + digit);
As a loop, this would look like:
int num = 0;
foreach(int digit in digits)
{
num = 10 * num + digit;
}
Try this with LINQ,
int num = 92345;
string strNum = Convert.ToString(num);
var divisibleby2 = from c in strNum
where int.Parse(c.ToString()) % 2 == 0
select c.ToString();
var notDivisibleby2 = from c in strNum
where int.Parse(c.ToString()) % 2 != 0
select c.ToString();
int int_divisibleby2num = int.Parse(String.Join("", divisibleby2.ToArray()));
int int_Notdivisibleby2num = int.Parse(String.Join("", notDivisibleby2.ToArray()));
Every programmer should write wacky code at least once a day:
int checkCount = 12345, numEven, numOdd;
Boolean result;
result = int.TryParse(checkCount.ToString().Replace("0", "").Replace("2", "").Replace("4", "").Replace("6", "").Replace("8", ""), out numOdd);
result = int.TryParse(checkCount.ToString().Replace("1", "").Replace("3", "").Replace("5", "").Replace("7", "").Replace("9", ""), out numEven);
Another solution could be...
var num1 = 94321;
var oddFinal = 0;
var evenFinal = 0;
var odd = new List<int>();
var even = new List<int>();
while( num1>0 )
{
if( num1 % 2 == 0 )
odd.Add( num1 % 10 );
else
even.Add( num1 % 10 );
num1 = num1 / 10;
}
for (int i = 0; i < odd.Count; i++)
{
oddFinal += odd[i] * (int) Math.Pow(10,i);
}
for (int i = 0; i < even.Count; i++)
{
evenFinal += even[i] * (int) Math.Pow(10,i);
}

Sum of digits in C#

What's the fastest and easiest to read implementation of calculating the sum of digits?
I.e. Given the number: 17463 = 1 + 7 + 4 + 6 + 3 = 21
You could do it arithmetically, without using a string:
sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
I use
int result = 17463.ToString().Sum(c => c - '0');
It uses only 1 line of code.
For integer numbers, Greg Hewgill has most of the answer, but forgets to account for the n < 0. The sum of the digits of -1234 should still be 10, not -10.
n = Math.Abs(n);
sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
It the number is a floating point number, a different approach should be taken, and chaowman's solution will completely fail when it hits the decimal point.
public static int SumDigits(int value)
{
int sum = 0;
while (value != 0)
{
int rem;
value = Math.DivRem(value, 10, out rem);
sum += rem;
}
return sum;
}
int num = 12346;
int sum = 0;
for (int n = num; n > 0; sum += n % 10, n /= 10) ;
I like the chaowman's response, but would do one change
int result = 17463.ToString().Sum(c => Convert.ToInt32(c));
I'm not even sure the c - '0', syntax would work? (substracting two characters should give a character as a result I think?)
I think it's the most readable version (using of the word sum in combination with the lambda expression showing that you'll do it for every char). But indeed, I don't think it will be the fastest.
I thought I'd just post this for completion's sake:
If you need a recursive sum of digits, e.g: 17463 -> 1 + 7 + 4 + 6 + 3 = 21 -> 2 + 1 = 3
then the best solution would be
int result = input % 9;
return (result == 0 && input > 0) ? 9 : result;
int n = 17463; int sum = 0;
for (int i = n; i > 0; i = i / 10)
{
sum = sum + i % 10;
}
Console.WriteLine(sum);
Console.ReadLine();
I would suggest that the easiest to read implementation would be something like:
public int sum(int number)
{
int ret = 0;
foreach (char c in Math.Abs(number).ToString())
ret += c - '0';
return ret;
}
This works, and is quite easy to read. BTW: Convert.ToInt32('3') gives 51, not 3. Convert.ToInt32('3' - '0') gives 3.
I would assume that the fastest implementation is Greg Hewgill's arithmetric solution.
private static int getDigitSum(int ds)
{
int dssum = 0;
while (ds > 0)
{
dssum += ds % 10;
ds /= 10;
if (dssum > 9)
{
dssum -= 9;
}
}
return dssum;
}
This is to provide the sum of digits between 0-9
public static int SumDigits1(int n)
{
int sum = 0;
int rem;
while (n != 0)
{
n = Math.DivRem(n, 10, out rem);
sum += rem;
}
return sum;
}
public static int SumDigits2(int n)
{
int sum = 0;
int rem;
for (sum = 0; n != 0; sum += rem)
n = Math.DivRem(n, 10, out rem);
return sum;
}
public static int SumDigits3(int n)
{
int sum = 0;
while (n != 0)
{
sum += n % 10;
n /= 10;
}
return sum;
}
Complete code in: https://dotnetfiddle.net/lwKHyA
int j, k = 1234;
for(j=0;j+=k%10,k/=10;);
A while back, I had to find the digit sum of something. I used Muhammad Hasan Khan's code, however it kept returning the right number as a recurring decimal, i.e. when the digit sum was 4, i'd get 4.44444444444444 etc.
Hence I edited it, getting the digit sum correct each time with this code:
double a, n, sumD;
for (n = a; n > 0; sumD += n % 10, n /= 10);
int sumI = (int)Math.Floor(sumD);
where a is the number whose digit sum you want, n is a double used for this process, sumD is the digit sum in double and sumI is the digit sum in integer, so the correct digit sum.
static int SumOfDigits(int num)
{
string stringNum = num.ToString();
int sum = 0;
for (int i = 0; i < stringNum.Length; i++)
{
sum+= int.Parse(Convert.ToString(stringNum[i]));
}
return sum;
}
If one wants to perform specific operations like add odd numbers/even numbers only, add numbers with odd index/even index only, then following code suits best. In this example, I have added odd numbers from the input number.
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Please Input number");
Console.WriteLine(GetSum(Console.ReadLine()));
}
public static int GetSum(string num){
int summ = 0;
for(int i=0; i < num.Length; i++){
int currentNum;
if(int.TryParse(num[i].ToString(),out currentNum)){
if(currentNum % 2 == 1){
summ += currentNum;
}
}
}
return summ;
}
}
The simplest and easiest way would be using loops to find sum of digits.
int sum = 0;
int n = 1234;
while(n > 0)
{
sum += n%10;
n /= 10;
}
#include <stdio.h>
int main (void) {
int sum = 0;
int n;
printf("Enter ir num ");
scanf("%i", &n);
while (n > 0) {
sum += n % 10;
n /= 10;
}
printf("Sum of digits is %i\n", sum);
return 0;
}
Surprised nobody considered the Substring method. Don't know whether its more efficient or not. For anyone who knows how to use this method, its quite intuitive for cases like this.
string number = "17463";
int sum = 0;
String singleDigit = "";
for (int i = 0; i < number.Length; i++)
{
singleDigit = number.Substring(i, 1);
sum = sum + int.Parse(singleDigit);
}
Console.WriteLine(sum);
Console.ReadLine();

Categories