Digit sum in for loop C# - 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;
}

Related

Making a program that sums up only even numbers entered from console

In one of my classes I was given an assignment to write a simple program that combines multiple numbers entered from the console, but only adding up the even ones. I was able to do the summing up part pretty easily but I can't figure out how to check for even numbers! If anyone can figure out how or explain for a beginner how to do it would be greatly appreciated.
Here's the full code so far:
using System;
namespace Test_3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Amount of numbers n = ");
var n = int.Parse(Console.ReadLine());
Console.WriteLine("Enter numbers:");
var sum = 0;
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
}
else
{
}
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
Console.WriteLine("The sum of the numbers is " + sum);
}
}
}
You seem to already know how to get the even numbers but here is how to apply it!
Console.WriteLine("Amount of numbers n = ");
var n = int.Parse(Console.ReadLine());
Console.WriteLine("Enter numbers:");
var sum = 0;
for (int i = 0; i < n; i++)
{
var num = int.Parse(Console.ReadLine()); //first read a number from the console
if (num % 2 == 0) //then check if it is even
{
sum = sum + num; //if it is, then add it to sum
}
}
Console.WriteLine("The sum of the numbers is " + sum);
You seem not to get the idea of an if-clause, let me explain this, using the following pieces of code:
Your code:
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
}
else
{
}
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
This calculates the sum of all numbers (you check whether a number is even or not, but you don't use that information).
My proposal: (you check if a number is even, and you use that information)
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
else
{
}
}
Another one, how to calculate the sum of the odd numbers? (Here you check if a number is even, but you use the case where it is not)
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
}
else
{
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
}
So, you see? You can use if-clauses to filter out what you want to do when a condition is met or when a condition is not met, that's the whole idea behind it.
You need to check whether the variable num is divisible by two instead of the sum. The code you have checks if the sum is even and if so does nothing since you didn't add anything to the if statement. Instead, you should be doing if ( num % 2 == 0) .
You also need to move where num is declared to the top of the for loop and move the part where you add to the sum to the inside of the conditional (The if statement).

how to write a console application that calculates the sum of a given number of integers

Write a console application that calculates the sum of a given number of integers.
The numbers are entered one per line, and the application will read one by one until the user writes the character instead of a number. When the user has typed x, the application knows that all the numbers in the string have been entered and displays their amount.
If the first thing the user enters is the x character, the application will return 0.
Example:
For input:
2
5
-3
1
X
The console will display:
5
and this is my code
string[] answer = new string[10];
int sum = 0
for (int i = 0; i < answer.Length; i++)
{
sum += Int32.Parse(answer[i]);
if (answer[i] == "x")
{
Console.WriteLine(sum);
}
answer[i] = Console.ReadLine();
}
Console.Read();
Can anyone tell me why is not working?
First of all, the working code (I didn't focus on X but on any char that isn't a number):
int n;
int sum = 0;
while (int.TryParse(Console.ReadLine(), out n))
{
sum += n;
}
Console.Write(sum );
Console.ReadKey();
Secondly, your code doesn't work because your array is full of 'null'-s when you try to parse the content of its first cell in 'answer[i]'
Here's a dumb (a bit) fix for your code:
string[] answer = new string[10];
//HERE
for (int i = 0; i < answer.Length; i++)
{
answer[i] = "0";
}
int sum = 0;
for (int i = 0; i < answer.Length; i++)
{
sum += Int32.Parse(answer[i]);
if (answer[i] == "x")
{
Console.WriteLine(sum);
}
answer[i] = Console.ReadLine();
}
Console.Read();
Another problem with your code is you don't stop the iteration once "x" is entered, but continue until the end of the array (until it's been 10 times).
Here's kind of a complete fix for your code:
string[] answer = new string[10];
for (int i = 0; i < answer.Length; i++)
{
answer[i] = "0";
}
int sum = 0;
for (int i = 0; i < answer.Length; i++)
{
answer[i] = Console.ReadLine();
if (answer[i] == "x")
{
break;
}
sum += Int32.Parse(answer[i]);
}
Console.WriteLine(sum);
Console.Read();
Few issues:
I think order of your code instructions is not correct. First time when you parse your array element, its not yet initialized.
int sum = 0 is missing ; at the end.
You should always use TryParse instead of Parse
Try the following code:
string[] answer = new string[10];
int sum = 0, number;
for (int i = 0; i < answer.Length; i++)
{
answer[i] = Console.ReadLine();
if (answer[i] == "x")
{
Console.WriteLine(sum);
break;
}
if(Int32.TryParse(answer[i], out number))
sum += number;
}
I gave you your terminating 'x'
var answer = Console.ReadLine();
var sum = 0;
while (answer != "x")
{
if (Int32.TryParse(answer, out var value))
{
sum += value;
}
answer = Console.ReadLine();
}
Console.WriteLine(sum);
You should check for "x" first since int.Parse("x") throws exception:
Wrong order (current code):
sum += Int32.Parse(answer[i]); // <- this will throw exception on "x" input
if (answer[i] == "x") {
...
}
...
Right order:
if (answer[i] == "x") {
...
}
else
sum += Int32.Parse(answer[i]);
...
in order to check for syntax errors (e.g. when user inputs "bla-bla-bla") I suggest int.TryParse instead of int.Parse and let's get rid of the array why should we collect the items (esp. with unwanted restriction of 10 items)?
// long: we don't want overflow, e.g. 2000000000, 1000000000
long sum = 0;
while (true) {
// Trim() - let's be nice and allow user put leading/trailing spaces
string input = Console.ReadLine().Trim();
if (string.Equals("x", input, StringComparison.OrdinalIgnoreCase))
break;
if (int.TryParse(input, out var item))
sum += item;
else {
//TODO: Incorrect input, neither integer nor "x" (e.g. "abracadabra")
}
}
Console.WriteLine(sum);
Console.Read();

How to get fibonacci in 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;
}
}
}

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