user2956514
user2956514

Reputation: 39

Return statement in a digit sum output

So there is a method that I need that would basically ask user for a number input. Then it would check all number from 0 to 1000 and return the ones which have sum of digits equal to number that user gave.

I am not sure that my code is correct and that it works because I have troubles checking it because of the return statement which doesn't work in the way I presume it would.

    public static string stevilo()
    {
        Console.WriteLine("Enter your number! ");
        string vnos = Console.ReadLine();
        int x = Convert.ToInt32(vnos);
        int sum = 0;
        string a= " ";


            foreach (var n in Enumerable.Range(0,1000))
            {
                if (n.ToString().ToCharArray().Sum(c => c - '0') == sum)
                    a = a + n.ToString();   

            }
    return (a);

        }

So if my code looks like this (above), it will always return an empty string, because it's empty in the beginning of the method.

However if I write my code like this (below), I will get a message:

not all code paths return a value

 public static string stevilo()
    {
        Console.WriteLine("Enter your number! ");
        string vnos = Console.ReadLine();
        int x = Convert.ToInt32(vnos);
        int sum = 0;
        string a= " ";


            foreach (var n in Enumerable.Range(0,1000))
            {
                if (n.ToString().ToCharArray().Sum(c => c - '0') == sum)
                    a = a + n.ToString();
                return (a);

            }

        }

Upvotes: 0

Views: 126

Answers (1)

Steve
Steve

Reputation: 216293

The error is in this line

if (n.ToString().ToCharArray().Sum(c => c - '0') == sum)

should be

if (n.ToString().ToCharArray().Sum(c => c - '0') == x)

Of course you need a better formatting of your output. So I suggest to use a StringBuilder to better handle the string concatenations required by your code.

public static string stevilo()
{
    Console.WriteLine("Enter your number! ");
    string vnos = Console.ReadLine();
    int x = Convert.ToInt32(vnos);
    StringBuilder sb = new StringBuilder();
    foreach (var n in Enumerable.Range(0,1000))
    {
        if (n.ToString().ToCharArray().Sum(c => c - '0') == x)
            sb.Append(n.ToString() + ",");   

    }
    if(sb.Length > 0) sb.Length--;
    return sb.ToString();
}

Also, if you want to use LinQ to totally hide the foreach loop, there is this variation

public static string stevilo()
{
    Console.WriteLine("Enter your number! ");
    string vnos = Console.ReadLine();
    int x = Convert.ToInt32(vnos);
    var list = Enumerable.Range(0, 1000)
                         .Where(z => z.ToString()
                         .ToCharArray()
                         .Sum(c => c - '0') == x);
    return string.Join(",", list);
}

Upvotes: 5

Related Questions