Hello dada51,
I have always believed that if you do not understand what is wrong with your program then you will not understand how to fix it.
The code that you started with is fine if you are writing the code for the compiler. This may take a few milliseconds of the compile time. It is also possible to write
1 2
|
#include <iostream>
using to the closing } of "main all on 1 line. // Great for the compiler, but almost impossible to read or work on.
|
When you write your source code you are writing it for someone to read, be it your-self or someone else, so make it easy to read. As an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter a number that is less or equal to 10: ";
if (n <= 10)
{
cin >> n;
for (int i = 1; i <= 10; ++i)
{
cout << n << " * " << i << " = " << n * i << endl;
}
return 0;
}
else cout << "Invalid number. Try again" << endl;
}
|
How you use the {}s is up to you, but be consistent in their use.
Adding the blank lines also can make problems show up easier.
Looking at your code:
Line 7. A better name than "n" would be helpful. I eventually changed "n" to "baseNum" which helps in the rest of the program to see what you are using. It is also a good policy to initialize your variables when you define them. If for no other reason than to know that they do not contain a garbage value.
On my computer an uninitialized "int" generally has the value of (-858993460) and an uninitialized "double" has the value of (-9.2559631349317831e+64). Neither is something that you would want.
This leads to a problem with line 11. To look at it another way:
if (-858993460 <= 10)
. This would make your if statement always true.
Line 13 is entering a value for "baseNum", ("n"), but after you have checked if the value if OK. Kind of backwards. What you have would allow "baseNum" to hold a value of 100 or any number > 10.
Line 20 should be after line 22. If you are inside the if statement the else will be bypassed and if you bypass the if statement when the else is finished you are at the end of the program. So putting the "return 0" inside the if statement has no benefit because either way when either if or else is done you are at the end of "main" and the program is over.
I hope that you understand better what is wrong and that the changes offered make more sense now.
Andy