If you read the compiler warning carefully, it tells you exactly what is wrong! Don't freak out, read it slowly.
uninitialized local variable 'Z' used
uninitialized local variable 'Y' used
uninitialized local variable 'X' used
What this means is you have not initialized these variables with a value before you decided to use them.
Note N = 10, but what are the values X,Y,Z suppose to have??
Why do you pass in values for x, y ,z to function printnum and then in the loop each is set be 1? What is the point??
It seems the only value you care for is the sum N=10
Also what is with the crazy braces inside the 3rd nested loop??? Seriously understand what braces do =)
Try the code below, when you can give the variable some meaningful names, make code self documenting when you can!
Also what kind of function name is ok? why not give it a better name, like Sum3 or ValidateSum
I changed the loop to go from 0 to sum, since 0+0+sum = sum, got it? If you don't care about zero, start the loop from 1, but then this algo is partially correct.
use pre-increment when you can, like ++x, it's faster since a copy of the return value does not need to take place!
int a = ++x; <== is not the same as ==> int a = x++;
The 2nd requires a copy of x to be made that is then assigned to a, and then x is incremented!
In a function always use const when you don't want the passed in value to be modified.
FYI: Notice how function ok has been simplified, this is a good trick to learn. You actually don't need this function as the check can be done inside the loop.
bool ok( const int a, const int b, const int c, const int sum )
return ( (a + b + c) == sum );
void printnum( const int sum )
for( int x = 0; x <= sum; ++x )
for( int y = 0; y <= sum; ++y )
for( int z = 0; z <= sum; ++z )
if( ok( x, y, z, sum ) ) cout << "(" << x << "," << y << "," << z << ")" << endl;
int main( int argc, char*argv )
printnum( 10 );
Rajinder Yadav <firstname.lastname@example.org>
Creating Amazing Possibilities