Home > Blockchain >  How Can I sum all digits in a number using loop?
How Can I sum all digits in a number using loop?

Time:03-12

when I enter 1 for n and 1111 for lines the sum must be 1 1 1 1=4 but the output is 1.

THIS IS THE QUESTION...

you will get a (n) then (n) lines as an input, In each line there are some numbers (we don’t know how many they are) and you must print (n) lines, In the i-th line print the sum of numbers in the i-th line.

using System;

namespace prom2
{
    class Program
    {
            
        static void Main(string[] args)
        {
            int lines=0, sum = 0;

            Console.Write("Enter a number of lines ");
            int n = int.Parse(Console.ReadLine());

            for (int i = 1; i <= n&n>0&1000>n; i  )
            {
                Console.WriteLine("Enter line "   i   " numbers");
                lines = int.Parse(Console.ReadLine());
                lines = lines / 10;

                sum  = lines % 10;
                             
                Console.WriteLine("sum is "   sum);

            }
        }
    } 
}

CodePudding user response:

Try this:

static void Main(string[] args)
        {
            int input;
            bool times = true;
            List<int> numbers = new List<int>();
            while (times)
            {
                Console.Clear();
                Console.WriteLine("Enter number: ");
                var num = int.TryParse(Console.ReadLine(), out input);//tryparse will output a bool into num and set input to a int
                if (num)
                {
                    numbers.Add(input);//only integers will be added to list
                }
                Console.Clear();
                Console.WriteLine("Another? Y or N");//ask if they want to sum more numbers
                var yesno = Console.ReadLine();//get answer from user
                if (yesno.ToUpper().Trim() != "Y")//if N or anything else
                {
                    //assume no
                    times = false;
                }
                Console.Clear();
            }

            var sum = numbers.Sum();
            Console.WriteLine("Sum : "   sum.ToString());
            Console.ReadLine();//just to pause screen
        }

CodePudding user response:

Because Console.ReadLine returns a string, and it's possible to treat a string as if it's an array of chars (where char represents a single character), you can have a method like this to calculate the sum of all the digits in a single line:

private int SumTheDigits(string line)
{
    var sum = 0;
    foreach (var character in line)
    {
        sum  = int.Parse(character.ToString());
    }

    return sum;
}

Please note this method contains no validation - ideally you should validate that line is purely numeric, otherwise int.Parse will throw an exception, although the same is true of the code you provided too.

If you want to work with multiple lines of console input, just call this method from within another loop which solicits / works through those lines of console input.

Edit

My answer doesn't answer all of your question, it only answers the part which asks how to calculate the sum of the digits in a numeric string, and it does work, to the extent that it correctly does what it says on the tin.

Here's all the code I wrote to validate the answer before posting the original answer (I wrote it as a xUnit unit test rather than a console application, but that doesn't change the fact that the code I shared works):

using System;
using Xunit;

namespace StackOverflow71442136SumDigits
{
    public class UnitTest1
    {
        [Theory]
        [InlineData("1", 1)]
        [InlineData("12", 3)]
        [InlineData("23", 5)]
        [InlineData("1234", 10)]
        [InlineData("123456789", 45)]
        public void Test1(string line, int expectedSum)
        {
            var actualSum = this.SumTheDigits(line);
            Assert.Equal(expectedSum, actualSum);
        }

        private int SumTheDigits(string line)
        {
            var sum = 0;
            foreach (var character in line)
            {
                sum  = int.Parse(character.ToString());
            }

            return sum;
        }
    }
}

You might want to read How do I ask and answer homework questions?

  •  Tags:  
  • c#
  • Related