Code_Steel
Code_Steel

Reputation: 435

Why does adding braces to the inner most for loop give such weird results?

This is a slightly modified answer I got to a previous question I asked here. I'm changing it to understand it better, when something weird happened.

For loops in C# are supposed to work this way:

for (initial increment value, end increment value, increment rate)
{
    // for loop body
}

The answer code I got seems to work but doesn't have braces around the inner most for loop. Here's the code:

using System;

class Prime_Screening
{
    static void Main()
    {
        Console.WriteLine("Prime numbers x, where: 0 < x < 100");
        bool prime;

        for (int num = 2; num <= 100; num++)
        {
            prime = true; /


            for (int div = 2; div <= Math.Sqrt(num); div++)
            // Why isn't the contents of this for loop in braces? Attempting it produces a weird output
                if(num % div == 0) 
                    prime = false;
                if (prime) 
                    Console.Write(num.ToString() + ", ");
        }
    } 
}

I added braces to that for loop so that I could keep the code clear, but I got some oddly repeating output:

5, 7, 9. 11, 11, 13, 13, 15, 17, 17, 17, 19, 19, 19, 21, 23, 23, 23, 25, 25, 25, 27, 29, 29, 29, 29, 31... 93, 95, 95, 95, 97, 97, 97, 97, 97, 97, 97, 97, 99,

Why? While we're on the subject, should if statements be in braces too?

Edit: Spelling/Grammar

Upvotes: 3

Views: 96

Answers (4)

Servy
Servy

Reputation: 203836

The for loop does not need to be followed by a statement block (some number of statements wrapped in curly braces), it simply needs to be followed by a single statement. A statement block is simply a way of transforming some number of statements into a single (complex) statement.

The statement that follows your inner for loop is:

if(num % div == 0) 
    prime = false;

If you wrapped that in braces it wouldn't change the code. If you wrapped that and the following statement (the second if block) in braces (as your indentation appears to indicate) then you'll have changed the semantics of the code.

This same behavior applies to if, while, foreach, do, etc. structures as well, although interestingly enough not try/catch/finally blocks

Upvotes: 3

Shaharyar
Shaharyar

Reputation: 12449

We use braces when we have multiple statements to put in a code block. It can be for for loop while loop if else etc.

But we do not use braces when we have only one statement. The very next statement is considered in loop when we are not using braces.

In your situation you have to put both if conditions in the braces otherwise it will consider only first if condition inside the loop.

Upvotes: 0

C Bauer
C Bauer

Reputation: 5103

The reason you get weird results is because an unbraced statement only applies to the next statement.

This is what gets compiled with no brace:

for (int div = 2; div <= Math.Sqrt(num); div++)
{
    // Why isn't the contents of this for loop in braces? Attempting it produces a weird output
    if(num % div == 0) 
        prime = false;
}

if (prime) 
     Console.Write(num.ToString() + ", ");

Upvotes: 3

Tim Schmelter
Tim Schmelter

Reputation: 460168

You don't need to use the braces, but then only the first statement belongs to the loop.

Since here is not an if-else but two ifs only the first belongs to the loop:

for (int div = 2; div <= Math.Sqrt(num); div++)
    if (num % div == 0)
        prime = false;
    if (prime)
        Console.Write(num.ToString() + ", ");

that is the same as:

for (int div = 2; div <= Math.Sqrt(num); div++)
{
    if (num % div == 0)
        prime = false;
}
if (prime)
    Console.Write(num.ToString() + ", ");

as opposed to this code where both belong to the loop:

for (int div = 2; div <= Math.Sqrt(num); div++)
{
    if (num % div == 0)
        prime = false;
    if (prime)
        Console.Write(num.ToString() + ", ");
}

From msdn: for-loop

The body of the loop consists of a statement, an empty statement, or a block of statements, which you create by enclosing zero or more statements in braces.

Upvotes: 4

Related Questions