Someone know what is wrong with my program?

closed account (4wRjE3v7)
Hi so I made a program using if statements, but when I put 64 as the input it does include all of the correct input except the last part "Not divisible!" I really don't know how to fix the problem anyone please care to look over my code and help me. I am new to c++.



#include <iostream>
using namespace std;

int main()
{
int num;
cout << "Please enter a number\n";
cin >> num;

if (num % 2 == 0)
{
cout << "Divisible by 2!\n";

}

else if (num % 3 == 0)
{
cout << "Divisible by 3!\n";

}

if (num % 4 == 0)
{
cout << "Divisible by 4!\n";
}
if (num % 5 == 0)
{
cout << "Divisible by 5!\n";
}
if (num % 6 == 0)
{
cout << "Divisible by 6!\n";

}
if (num % 7 == 0)
{
cout << "Divisible by 7!\n";

}
if (num % 8 == 0)
{
cout << "Divisible by 8!\n";
}
if (num % 9 == 0)
{
cout << "Divisible by 9!\n";
}
else
{
cout << "Sorry not divisible by anything!!\n";
}
}
cuz this loop is wrong try 9 and check that out...

the scope of that else starts as below...

1
2
3
4
5
6
7
8
9
10
....
if (num % 9 == 0)
{
cout << "Divisible by 9!\n";
}
else
{
cout << "Sorry not divisible by anything!!\n";
}
....
Last edited on
How about this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main()
{
int num;
cout << "Please enter a number\n";
cin >> num;

for(int Ivalue = 2; Ivalue <= 9 ; ++Ivalue)
{
	if(num % Ivalue == 0)
	{
		cout << "Divisible by " << Ivalue << endl;
	}
}

return 0;
}
Firstly, when posting code, please enclose it in code tags to make it more readable.

The problem isn't really a C++ problem, it's a basic logic problem. You need to think more clearly about the logic of your if and else . For example, you have the following:

1
2
3
4
5
6
7
8
9
if (num % 2 == 0)
{
  cout << "Divisible by 2!\n";
}

else if (num % 3 == 0)
{
  cout << "Divisible by 3!\n";
}

This will only check whether num is divisible by 3 if it fails the test for being divisible by 2.

What will happen if num is 6? The first test will register as true, as 6 is is divisible by 2. It will not perform the second test, so will not report that 6 is divisible by 3 as well.

The specific problem you mentioned is down to your final if and else:
1
2
3
4
5
6
7
8
if (num % 9 == 0)
{
  cout << "Divisible by 9!\n";
}
else
{
  cout << "Sorry not divisible by anything!!\n";
}

It should be clear what's happening here - if num isn't divisible by 9, then it will report "not divisible", regardless of what other numbers it is divisible by.
Last edited on
joneele that was awesome and fast.. i just copied it to codeblocks and it worked fine..
Topic archived. No new replies allowed.