none
Question with my code C#

    Question

  • I'm a little confused, what im trying to do is take 2 digits in an int add them together and return the sum. When i run the program though it returns the original variable.

        

    namespace practice
    {
        class Program
        {
            static void Main(string[] args)
            {
                int sum = 0;
                int test = 29;
                int[] n = new int[] { test };
                for(int i = 0; i< n.Length; i++)
                {
                    sum += n[i];
                }
                Console.Write(sum);
                Console.ReadLine();

            }
        }

    }


    Friday, April 14, 2017 5:01 PM

All replies

  • That's because your array has only 1 item in it. If you look at the length of n then it is 1. So your for loop executes once and sum = 29.

    To accept 2 digits, using the array you'll need to set the array to be of size 2.  You aren't actually accepting any input from the user so you'll need to assign a value to each of the array elements.

    int[] n = new int[2] { test, test + 1 };
    ...
    
    sum will equal test + (test + 1)

    Alternatively prompt the user and forego the array altogether.

    static void Main ( string[] args )
    {
       int sum = 0;
       do
       {
          //Get input from user
          Console.Write("Enter a value: ");
          
          //Exit loop if user does not enter a value
          var str = Console.ReadLine();
          if (str == "")
              break;
    
          //Convert to int
          int value;
          if (Int32.TryParse(str, out value)
          {
             if (value != 0)
                sum += value;
          };
       } while (true);
    
       Console.Write(sum);
       Console.ReadLine();
    }

    Michael Taylor
    http://www.michaeltaylorp3.net

    • Proposed as answer by Ryan Software Friday, April 14, 2017 5:28 PM
    Friday, April 14, 2017 5:18 PM
    Moderator
  • If you mean the sum of ‘2’ and ‘9’, then try this:

       int test = 29;

       int sum = test / 10 + test % 10;

       Console.WriteLine( sum );

    Friday, April 14, 2017 5:42 PM
  • This will work:

    int sum = 0;
    int test = 42;
    char[] array = test.ToString().ToArray();
    for (int i = 0; i < array.Length; i++)
    {
        sum += int.Parse(array[i].ToString());
    }
    


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Saturday, April 15, 2017 4:55 PM
    Moderator