user226875
user226875

Reputation: 11

Nested for loop in C not working as expected

for (i = 2; i < input; i++){
    for (d = 2; d < input; d++){
        product = d*i;
        printf("%d\n", product);
        break;
    }
}

This snippet of code is part of my solution to a homework question for my Intro to C class. The actual question is something involving prime numbers, but the solution that I thought of requires the use of for loops nested like this. I can't get them to behave correctly, though. I assume using an array would simplify things, but we haven't taken them up yet and are not allowed to use them in our solution. Anyway:

If, for example, my input is 10, my values of i should be {2,3,4,5,6,7,8,9}. My values for d should also be {2,3,4,5,6,7,8,9}.

What I expect this loop to do is multiply each i by the full loop of d:

2*2
2*3
2*4
.
.
.
2*9
3*2
3*3
.
.
.
.

and onwards. However, it is instead just multiplying i by d = 2, and I get the following:

4
6
8
10
.
.
.
20

What am I doing wrong?

Upvotes: 0

Views: 875

Answers (4)

Alexandru Barbarosie
Alexandru Barbarosie

Reputation: 3002

for (d = 2; d < input; d++){
        product = d*i;
        printf("%d\n", product);
        break;  // because of this line the loop breaks on first iteration.
}

Remove break; from your code and it will work.

Upvotes: 9

cjubb39
cjubb39

Reputation: 464

Remove the break; line. When your code gets here (on the first iteration), the inner loop (d=2...) will be skipped out of.

For statements aren't like switch statements where you need to end with break;. You use a break statement to exit the loop not continue to the next iteration (that's what continue is for).

Upvotes: 2

cut the break;, it's exiting your inner loop

essentially, the break statement turns the following for loop

for (d = 2; d < input; d++){

into an if statement

Upvotes: 2

jh314
jh314

Reputation: 27812

Your break statement makes the inner loop run only once. So you only multiply i by d=2.

You probably want this:

for (i = 2; i < input; i++){
    for (d = 2; d < input; d++){
        product = d*i;
        printf("%d\n", product);
        // break; this statement is causing you to exit loop after 1 iteration
    }
}    

Upvotes: 4

Related Questions