How to get fibonacci in c# - c#

Guys I have a question regarding on fibonacci..How do I get the fibonacci series that the number will also end on user input...example if I put 21 the output must be 0 1 1 2 3 5 8 13 21
This is my code
static void Main(string[] args)
{
int input, first = 0, second = 1, third = 0;
Console.Write("Enter a number : ");
n = Convert.ToInt32(Console.ReadLine());
Console.Write("First {0} Fibonacci numbers {1} {2} ", input, first, second);
for (int i = 3; i <= input; i++)
{
third = first + second;
Console.Write("{0} ", third);
first = second;
second = third;
}
}

One of your error is in the looping logic.
If the user inputs 21, you want the fibonacci numbers up to 21. You don't want the first 21 fibonacci numbers.
Rather than
for (int i = 3; i <= input; i++)
{
////
}
Do
while(second <= input)
{
////
}
My answer almost certainly has an off-by-one error, but this should point you in the right direction.
Fibonacci sequences are often used for tech-interview question, because programmers struggle with a temporary variable, especially when under pressure. It's easier without it:
Don't have three variables (first, second and third). Instead, have one variable: an array containing the last two elements of the sequence:
int[] seq = new[] { 0, 1 };
Then, every time you wanted to move to the next number:
while(seq[1] <= input)
{
Console.Write("{0}", seq[1]);
seq = new[] { seq[1], seq[0] + seq[1] };
}

for (int i = 3; i <= input; i++)
means you'll run loop input - 3 + 1 times; if input is 21, you'll run this loop from 3 to 21 including 3, and 21.
Recursive:
static int Fib(int n) {
return (n < 2)? n : Fib(n - 1) + Fib(n - 2);
}
Iterative:
static int Fib(int x) {
if (x == 0) return 0;
int prev = 0;
int next = 1;
for (int i = 1; i < x; i++)
{
int sum = prev + next;
prev = next;
next = sum;
}
return next;
}
Separate your fibonacci logic from application logic.
Running Example:
http://ideone.com/cNLntC
using System;
public class Test
{
static int Fib(int n) {
return (n < 2)? n : Fib(n - 1) + Fib(n - 2);
}
public static void Main()
{
Console.Write(Fib(10));
}
}

Using Binet's Formula:
public static void Main()
{
double root5 = Math.Sqrt(5);
double phi = (1 + root5) / 2;
int input;
Console.Write("Enter a number : ");
input = Convert.ToInt32(Console.ReadLine());
Console.Write("Fibonacci numbers to {0}: ", input);
int n=0;
int Fn;
do
{
Fn = (int)((Math.Pow(phi,n) - Math.Pow(-phi, -n)) / (2 * phi - 1 ));
Console.Write("{0} ", Fn);
++n;
} while(Fn < input);
}
Code Running in IDEOne
Doing it all in a single expression using Enumerables and Lambdas.
static void Main(string[] args)
{
double root5 = Math.Sqrt(5);
double phi = (1 + root5) / 2;
int input;
Console.Write("Enter a number : ");
input = Convert.ToInt32(Console.ReadLine());
Console.Write("Fibonacci numbers to {0}: ", input);
Enumerable.Range(0, 80).All(n => {
int f = (int)((Math.Pow(phi, n) - Math.Pow(-phi, -n)) / (2 * phi - 1));
Console.Write(" " + ((f<input)?f.ToString():""));
return f < input;
});

int first = 0, second = 1, third = 0;
Console.Write("Enter a number : ");
var n = Convert.ToInt32(Console.ReadLine());
Console.Write("First {0} Fibonacci numbers {1} {2} ", n, first, second);
for (int i = 3; i <= n; i++)
{
third = first + second;
Console.Write("{0} ", third);
first = second;
second = third;
}
You only need either n or input

This question is fairly old already, but it may be useful to programmers for interviews, so here goes:
As mentioned by some of the other answers, you have too many variables. Also, you want to separate the business logic from the GUI - which will score you points in your interview.
Refer the following code:
static void Main(string[] args)
{
Console.Write("Enter a maximum number for the Fibonacci sequence: ");
Console.WriteLine(Fibonacci(Convert.ToInt32(Console.ReadLine())));
Console.WriteLine("Press any key to quit.");
Console.ReadKey();
}
static string Fibonacci(int max)
{
int i = 0;
StringBuilder result = new StringBuilder();
for (int j = 1; j <= max; j += i)
{
result.Append(string.Format("{0} {1} ", i, j));
i += j;
}
if (i <= max)
result.Append(i);
return result.ToString();
}
In the Main method, we handle all UI logic and in the Fibonacci method, we handle the generation of the output string to the calling code. The following is the result of the code with a maximum of 21 (or 33):
If we examine the code, you will notice that Maximum is an argument for the Fibonacci method and we declare only 2 variables - i for the first number and j for the second number.
Furthermore, the loop is a normal for loop instead of a while loop, as there are enough other examples of while loops. The reason for this is simple - to show that you can also use external variables with your control variables to control the loop.
From there, it is quite simple. The first number is instantiated as 0 and the second as 1. Inside of the loop, we will add the second number to the first number and the loop will use this number to increment the second number.
Finally, the last number is added to the results, as the loop will exit as soon as the second number is greater than the maximum.
To better visualize this during the interview, draw a table as follows, and populate the values through the different iterations:
If you want to take this further and test yourself a bit, you can use this example and convert it to a recursive method.

Most of the people here have correctly pointed out your mistake within your code. I'll just show the most elegant approach I could come up with:
Console.Write("Enter a number: ");
var input = int.Parse(Console.ReadLine());
Console.Write($"Fibonacci numbers up to {input}: ");
var (first, second) = (0, 1);
while (first <= input)
{
Console.Write($"{first}, ");
(first, second) = (second, first + second);
}

What i did is;
public int Fibonacci(int nth)
{
if (nth < 0) return 0;
if (nth < 2) return nth;
int Next = 0;
int Current = 1;
int Previous = 0;
for (int i = 1; i < nth; i++)
{
Next = Current + Previous;
Previous = Current;
Current = Next;
}
return Next;
}

Fibonacci numbers with caches for better time complexity
Dictionary<int, int> _cacheDict = new Dictionary<int, int>() { { 0, 0 }, { 1, 1 } };
private int Fib(int number)
{
if (_cacheDict.ContainsKey(number))
return _cacheDict[number];
int sum = Fib(number - 1) + Fib(number - 2);
_cacheDict[number] = sum;
return sum;
}

using System;
public class Demo
{
public static void Main(string[] args)
{
int n1 = 0, n2 = 1, n3, i, number;
Console.Write("\n Enter number: ");
number = Convert.ToInt32(Console.ReadLine());
Console.Write("Fibonacci numbers 0 to {0}: ", number);
Console.Write("\n" + n1 + " "+ n2);
for(i = 2; i <= number; ++i )
{
n3 = n1 + n2;
Console.Write(" " + n3);
n1 = n2;
n2 = n3;
}
}
}

Related

Need help creating console app that outputs percent response for a rating on a survey 1-5 (whole number)

Working on an assignment where i need to accomplish the following: On a survey a question asks the surveyed person to rate something from 1-5 (whole number). The end user of your program iinputs the answers for that question on an unknown number of surveys. Write a program that allows this and outputs the percent response for each value (1, 2, 3, 4, and 5).
I did a previous Console app with a loop to collect an average and I am unsure how to collect a percent response on 5 different possible inputs.
Below is my previous code.
namespace WhileLoopsMean
public class MeanProgram
static void Main(string[] args)
{
long test, sum, loop, count;
double avg;
Console.Write("How many tests? ");
count = long.Parse(Console.ReadLine());
sum = 0;
loop = 1;
while (loop <= count)
{
Console.Write("enter score " + loop + " : ");
test = long.Parse(Console.ReadLine());
sum = sum + test;
loop = loop + 1;
}
avg = sum;
avg = avg / count;
Console.WriteLine("\naverage : " + avg);
Console.WriteLine("\n\nenter a score of -100 to end\n");
count = 1;
sum = 0;
Console.Write("enter score " + count + " : ");
test = long.Parse(Console.ReadLine());
sum = sum + test;
while (test != -100)
{
count = count + 1;
Console.Write("enter score " + count + " : ");
test = long.Parse(Console.ReadLine());
if (test != -100)
{
sum = sum + test;
}
else { }
}
count = count - 1;
avg = sum;
avg = avg / count;
Console.WriteLine("\naverage : " + avg);
Console.ReadKey();
class Program {
static void Main(string[] args) {
string input = "";
List<List<int>> answers = new List<List<int>>();
int questionsCount = ReadInt32("The number of questions: ");
for (int i = 0; i < questionsCount; i++) {
answers.Add(new List<int>());
}
while (input == "" || input == "y") {
for (int i = 0; i < answers.Count; i++) {
List<int> a = answers[i];
a.Add(ReadInt32($"Question [{i}]: "));
}
input = Read("Continue (y/n)? ").ToLower();
}
WriteLine("End of input!");
for (int i = 0; i < answers.Count; i++) {
List<int> a = answers[i];
Write($"Average for question[{i}]: {a.Average()}\n");
}
ReadKey();
}
static string Read (string a) {
Write(a);
return ReadLine();
}
static int ReadInt32 (string a = "") {
Write(a);
return ToInt32(ReadLine());
}
}
Try this out. You can customize the questions. And note that to use Write() and WriteLine(), you should add
using static System.Console;
at the top, in the references of the project.

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())) + "}");
}
}
}

Digit sum in for loop C#

I wrote I method which is suppose to recieve a nubmer from user and then check number from 0 to 1000. Then it should return all number which have digit sum equal to recieved number. So if I enter 6, it should return numbers like 6, 42, 51, 33, 123 etc. I'd really appreciate help since I've been dwelling on this for a while now.
public static double number() {
Console.WriteLine("Enter your number! ");
string enter = Console.ReadLine();
double x = Convert.ToDouble(enter);
for (int i = 0; i < 1000; i++ ) {
double r;
double sum = 0;
while (i != 0) {
r = i % 10;
i = i / 10;
sum = sum + r;
}
if (sum == x) {
Console.WriteLine(i + " ");
}
}
return(0);
}
I am aware of the fact that there is a problem with "return(0)", but I'm not completely sure what exactly it is that this should be returning.
I'd suggest trying to do something like this:
public static IEnumerable<int> number()
{
Console.WriteLine("Enter your number!");
string enter = Console.ReadLine();
int digitSum = int.Parse(enter);
foreach (var n in Enumerable.Range(0, 1000))
{
if (n.ToString().ToCharArray().Sum(c => c - '0') == digitSum)
{
yield return n;
}
}
}
When I run this and enter 6 then I get this result:
You are almost there: the only remaining problem is that you are modifying your loop counter i inside the nested while loop, which changes the workings of the outer loop.
You can fix this problem by saving a copy of i in another variable, say, in ii, and modifying it inside the while loop instead:
double r;
double sum = 0;
int ii = i;
while (ii != 0) {
r = iCopy % 10;
ii /= 10;
sum = sum + r;
}

issues on using mode in C#

I'm having issues with my Mode and getting it to let me input more then 10 numbers!
Those are the two issues I am having with my code.
public static void Main(string[] args)
{
int[] myNums = new int[10];
int number = 0;
int count = 0;
Console.WriteLine("--Nmber Modifier--\n");
Console.WriteLine("Entering a number that is no between 1 and 10 will end your process");
do// limited to 10 HELP
{
number = Util.PromptForInt("Enter a number between 1 and 10 : ");
if ((number <= 10) && (number >= 1))
{
myNums[count] = number;
}
count++;
}
while ((number <= 10) && (number >= 1));
Array.Sort(myNums);
Console.WriteLine("Average number is : " + MeantAverage(myNums));
Console.WriteLine("Largest Number is : " + LargestNum(myNums));
Console.WriteLine("Smallest Number is : " + SmallestNum(myNums));
Console.WriteLine("Most common number is : " + Mode(myNums));
Console.ReadLine();
}
static double MeantAverage(int[] nums)
{
double dMeanAverage;
double dSum = 0;
var groups = nums.GroupBy(item => item);
foreach (var group in groups)
{
dSum = group.Key + dSum;
}
dMeanAverage = dSum / nums[nums.Length - 1];
return Math.Round(dMeanAverage, 2);
}
static int LargestNum(int[] nums)
{
int highestNum;
highestNum = nums[nums.Length - 1];
return highestNum;
}
static int SmallestNum(int[] nums)
{
int lowest = 0;
for (int b = 0; b < nums.Length; b++)
{
if (nums[b] > lowest)
{
lowest += nums[b];
return lowest;
}
} return lowest;
}
static int Mode(int[] nums)
{
// issues with mode
int modes = 0;
var modeGroup = nums.GroupBy(v => v);
int max = modeGroup.Max(g => g.Count());
modes = modeGroup.First(g => g.Count() == max).Key;
return modes;
}
}
}
You created an array of ten numbers:
int[] myNums = new int[10];
So while your loop doesn't restrict you to 10 numbers because you don't check against count, the system does because as soon as you try to access the 10th element (myNums[10]) you will get an IndexOutOfRangeException.
Since you don't catch it anywhere, its just going to terminate your program.
To solve your problem:
Check against count so you don't input too many numbers!
If you need a variable length collection, use a collection built for that like List<T> instead of an array. Arrays are fixed-length (mostly), and the way around that is a horrible misuse of the array semantic.
Modified code somewhat, intention is the same though.
You forgot to check against count in the while case
You will crash on '0' inputs (no safe guard against empty array)
Changed Mode to merge items and then sort descending
var myNums = new List<int>(10);
for(int i=0; i < 10; ++i)
{
int number = Utils.PromptForInt("Enter a number between 1 and 10 : ");
if(number > 10 || number < 1)
break;
myNums.Add(number);
}
if(myNums.Count < 1)
return; //no item input, do something
myNums.Sort();
Console.WriteLine("Average: {0}", myNums.Sum() / (double)myNums.Count);
Console.WriteLine("Largest: {0}", myNums[myNums.Count - 1]);
Console.WriteLine("Smallest: {0}", myNums[0]);
var result = myNums.GroupBy(n => n)
.Select(c => new { Key = c.Key, total = c.Count() })
.OrderByDescending( a => a.total);
Console.WriteLine("Most common: {0}, used {1} times", result.First().Key, result.First().total);

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