Ripiter
Ripiter

Reputation: 13

Is there other way to write this if code?

I Have just started to learn c#. I am most comfortable with if and if else. Right now I am working on a program where it writes an IP address and I need to type the correct subnet, and all that. It takes too long time to make the code with if and else if, so I was wondering if there is a faster way to do it.

Random r = new Random();
            int randomip = r.Next(256);
            int secondip = r.Next(256);
            int subnetip = r.Next(24, 31);
            int numbers = subnetip;

Console.WriteLine("192.168." + randomip + "." + secondip + "/" + subnetip);

            Console.Write("Type the correct netID: ");
            Console.ReadLine();
            Console.Write("Type the correct subnet: ");
            Console.ReadLine();


            if (numbers == 24)
            {
                Console.WriteLine("correct netID is: 192.168." + randomip + 
                "." + secondip / 256);
                Console.WriteLine("correct subnet is: 255.255.255.0");
            } else if (numbers == 25)
            {
                Console.WriteLine("correct netID is: 192.168." + randomip + 
                "." + secondip / 128);
                Console.WriteLine("correct subnet is: 255.255.255.128");
            } else if (numbers == 26)

and so on… with other numbers. Isn’t there a faster and easier way to make it work? It works but if I want to add more numbers there would be a problem

Upvotes: 1

Views: 104

Answers (1)

Chad Hedgcock
Chad Hedgcock

Reputation: 11785

If you think backwards, these are your divisors based on the value of numbers

31 => 2
30 => 4
29 => 8
28 => 16
27 => 32
26 => 64
25 => 128
24 => 256

In other words, they're two to the power of an incrementing number.

31 => 2^1
30 => 2^2
29 => 2^3
28 => 2^4
27 => 2^5
26 => 2^6
25 => 2^7
24 => 2^8

In other words, two to the power of 32 minus numbers

31 => 2^(32-31)
30 => 2^(32-30)
29 => 2^(32-29)
28 => 2^(32-28)
27 => 2^(32-27)
26 => 2^(32-26)
25 => 2^(32-25)
24 => 2^(32-24)

In other words,

var divisor = Math.Pow(2, 32-numbers);
var subnet = 256 - divisor;

Down to 4 lines with no switch or if. Yay!

Console.WriteLine("correct netID is: 192.168." + randomip + "." + secondip / divisor);
Console.WriteLine("correct subnet is: 255.255.255." + subnet);

Upvotes: 11

Related Questions