Hello guys.
I've seen another thread with this name but it was in C i'm interested to do it in C#
okay the program
how I can add the digits of a number. Could you give me an idea?

I have source, but i need another source with the same function!

here is my source
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication17
{
    class Program
    {

        static void Main(string[] args) {
            Random r = new Random();

            int[] y = new int[10];
            int[] x = new int[10];

            for (int i = 0; i < y.Length; i++)
            {
                y[i] = r.Next(100);
                Console.WriteLine(y[i]);
            }

            Console.WriteLine();

            for (int i = 0; i < x.Length; i++)
            {
                x[i] = r.Next(100);
                Console.WriteLine(x[i]);
            }

            Console.WriteLine();

            Sum(y);
            Sum(x);

            Console.ReadKey();
        }

        static void Sum(int[] x) {
            int sum = 0;
            for (int i = 0; i < x.Length; i++)
            {
                sum += x[i];
            }
            Console.WriteLine("Sum = " + sum);
        }


    }
}

Recommended Answers

All 4 Replies

Take the value, mod by 10 add to result, divide original result by 10 (ignore decimal place) iterate in loop until original value is 0.

For those of you who are interested in my on going "One Line Challenge", this can be done on a single line.

@Ketsuekiame: does this meet your specs?
Console.WriteLine(Console.ReadLine().ToArray().Sum(s => s - 48));

Yep, although your will also add up standard characters too :P

You could also use '0' instead of 48. Just easier to remember :)

Also, strictly speaking, you could do the conversion in a select (removing the .ToArray()) and then .Sum(s => s)

My version: Console.WriteLine(Console.ReadLine().Select(c => c - '0').Where(c => c < 10 && c >= 0).Sum(c => c));

I did two version of mine because I didn't like the lengthy if statement and calculating the value c - '0' three times. The other version has no select statement but applies the mathematics everywhere that c is used.

!!IMPORTANT NOTE!! This is an incredibly inefficient and/or stupid way to do it :D

!!IMPORTANT NOTE!! This is an incredibly inefficient and/or stupid way to do it :D

Agreed, but it had to be on one line!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.