Home > OS >  For loops counting past the limit C
For loops counting past the limit C

Time:11-11

I have a really strange problem with for loop. I have to make a program that given the sum of three dice it has to find all possible combinations of those three dice that yield that sum. The problem is that for loops are counting past the limit that they have and I don't have any idea why.

for (k1 = 1; k1 <= 6; k1  ) //k1 - die 1
{
    for (k2 = 1; k2 <= 6; k2  ) //k2 - die 2
    {
        for (k3 = 1; k3 <= 6; k3  ) //k3 - die 3
        {
            if (k1 k2 k3 == z) //z - sum
                cout<<k1<<"-"<<k2<<"-"<<k3<<endl;
        }

        if (k1 k2 k3 == z)
            cout<<k1<<"-"<<k2<<"-"<<k3<<endl;
    }

    if (k1 k2 k3 == z)
        cout<<k1<<"-"<<k2<<"-"<<k3<<endl;
}

If I input 16 for the sum, these are the results that I get:

2-7-7
3-6-7
4-5-7
4-6-6
5-4-7
5-5-6
5-6-5
6-3-7
6-4-6
6-5-5
6-6-4

These are valid results for the sum of 16 but I shouldn't have number 7 on dice and the dice shouldn't be able to get to 7 because of how for is made.

I am using c 17 in Eclipse with Eclipse CDT.

CodePudding user response:

Why not just check inside the loops?

for (k1 = 1; k1 <= 6; k1  ) //k1 - die 1
{
    for (k2 = 1; k2 <= 6; k2  ) //k2 - die 2
    {
        for (k3 = 1; k3 <= 6; k3  ) //k3 - die 3
        {
            if (k1 k2 k3 == z) //z - sum
                cout<<k1<<"-"<<k2<<"-"<<k3<<endl;
        }
    }
}

CodePudding user response:

This is happening because you have k2,k3 variables which are allocated higher.

As for loop works until it will end loop when k3=7. So, k3 will save it and after loop when you're getting it, you got 7.

You could use one of proposed approaches by Seth Faulfner or Yksisarvinen. If you want to save values for future using, use Seth Faulfner's code. If it is not necessary use Yksisarvinen's code.

CodePudding user response:

The problem is that the variable k3 is not iterating outside the last for loop. That is where the issue is happening. For your desired result, checking the sum and printing if it's true; should only be done once inside the last for loop.

A sample code would be like :-

#include <iostream>
using namespace std;

int main()

{
    
int num,i,j,k;

cout<<"enter a number"<<endl;

cin>> num;

cout<<"dice combinations are "<<endl;

for(i=1;i<=6;i  )
{
    for(j=1;j<=6;j  )
    {
        for(k=1;k<=6;k  )
        {
            if(i j k == num)
            {
                cout<<i<<"-"<<j<<"-"<<k<<endl;
            }
        }
    }
}

}
  •  Tags:  
  • c
  • Related