Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get my if loop to stop ignoring the position 1?

Im trying to create an if loop that writes out the numbers at odd (non-even) positions in an array, which it does on every position except 1. I assume this is because the modulus rounds down the 0.5 to 0. I have resorted to just writing it out but am thinking that there must be a better way.

int[] num = new int[10];
Random rand = new Random();
for (int i = 0; i < num.Length; i++)
{
    num[i] = rand.Next(1, 50);
}
for (int i=0; i < num.Length;i++)
{
    Console.Write(" " + num[i] + " ");
}
for (int i = 0; i < num.Length; ++i)
{
    if (i%2 != 0)
    {
        Console.WriteLine(" " + num[i]);
    }
}

I tried having the modulus operation as a seperate double to see if that would make it register the 0.5 but it didn’t make a difference. I also added a specific "OR" variable in the if loop for i = 1 but for some reason that didn’t work either.

This is the result I get from the code above:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem you are facing is that the loop, which shows only the odd numbers, starts at the end of the first line.

If you count the numbers on the first line.. you count 11 (instead of 10).

That’s because the Console.Write stays on the same line for the next write. You need to insert a CR there.

int[] num = new int[10];
Random rand = new Random();
for (int i = 0; i < num.Length; i++)
{
    num[i] = rand.Next(1, 50);
}
for (int i=0; i < num.Length;i++)
{
    Console.Write(" " + num[i] + " ");
}

// insert a linebreak here. So the next output starts
// on a new line.
Console.WriteLine();

for (int i = 0; i < num.Length; ++i)
{
    if (i%2 != 0)
    {
        Console.WriteLine(" " + num[i]);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading