Is there a way to make an Int variable equal (==) to all the numbers stored in an Array?

Viewed 125

Okay so I'm new to coding and I just started an account here to get some help. My assignement is to code an application that will print numbers from 0-100 in the console. But not "32, 44 and 77". I know I could make many If statement, but my question is if I can store the three numbers in an Array and then say like:

        int numZero = 0;
        int[] num = { 32, 44, 77 };
        
        while (numZero <= 100)
        {
            Console.WriteLine(numZero);
            numZero++;

         // I know the num needs to have a value assigned. But can I make the "numZero" go through the three numbers in num?
           
            if (numZero == num [])  
            {
                numZero++;
            }

thankful for advice!

1 Answers

You can use a for loop from 0 to 100 and in the loop you test if the index Exists() in the array to not print else to print.

You can also use the Linq extension method Contains() instead of Array.Exists().

Doing that you will have 3 lines of code:

  • for
  • if !contains
  • print (you do nothing if contains).

Thus you can try this:

using System.Linq;

int[] num = { 32, 44, 77 };

for ( int index = 0; index <= 100; index++ )
  if ( !num.Contains(index) )
    Console.WriteLine(index);

You can aslo write:

foreach ( int index in Enumerable.Range(0, 101) )
  if ( !num.Contains(index) )
    Console.WriteLine(index);

Using Enumerable.Range avoids manipulating index and increment, so the code is cleaner and more secure.

Note: if 100 is not included change <= to <, or use Range(0, 100).

Related