C# - Adding indices from an array and filtering for common results

Asked

Viewed 44 times

0

I need to create a for that goes from 10 to 99 and then I need to print inside an if all the values that we summed up resulting in 11 (for example 56 = 5 + 6 = 11)

So far my code is like this

class Program
{
    static void Main(string[] args)
    {
        for(int i = 10; i <= 99; i++)
        {
            int[] array = new int[2];  
            for(int j = 0; j < i.ToString()[j]; j++)
            {
                array[j] = int.Parse()[j];
            }
        }
    }
}

but I’ve been knocking my head for a while and I can’t find the final solution.

2 answers

1


The hardest part is to separate each digit, for example 56 to add up 5 + 6.

One way to do this is to convert to string, ai it is possible to treat each digit separately, to avoid doing mathematical operations, and then convert each digit to a numeric type to be able to add and validate.

Here an example:

for (int i = 10; i <= 99; i++)
{
    int soma = 0;

    // primeiro, vamos transformar o número em string
    string numString = i.ToString();

    // agora, passar por cada "dígito" na string
    foreach (char digitoString in numString)
    {
        // conveter para inteiro e somar
        soma += int.Parse(digitoString.ToString());
        
    }

    // se a soma for 11, fazer alguma coisa
    if (soma == 11)
    {
        Console.WriteLine(i);
    }
}

You can see it working here: https://dotnetfiddle.net/ZdRuhe

  • Thank you very much :D was much clearer to understand.

1

If the numbers are whole and have up to two digits you can extract the drive by calculating the rest of the number division by 10 using the operator % and extract the dozen from that number by just performing the entire division of the number by 10 with the operator /.

using System;

class Program {
    static void Main(string[] args) {
        for(int i = 10; i <= 99; i++) {
          //Se a unidade i%10 mais dezena i/10 for igual a 11...
          if (i%10 + i/10 == 11) Console.WriteLine(i);                 
        }
    }
}

Test the example on Ideone

Another possibility is to convert the characters into one String and use extension method Enumerable.Select() to iterate over their characters by converting them individually into integers and then adding them together with Enumerable.Sum()

using System;
using System.Linq;

class Program {
    static void Main(string[] args) {
        for(int i = 10; i <= 99; i++) {          
          if (i.ToString().Select(c=>c-'0').Sum() == 11) Console.WriteLine(i);                 
        }
    }
}

Test the example on Ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.