What is wrong with this help?

closed account (4wRjE3v7)
When I type 64 for input I get the correct results expect for the last else, ("Sorry not divisible by anything!") I get it every time! I do not know how to make it work, can anyone please help me I am really struggling and I am a freshmen in college in my first programing class. Thanks I would appreciate it.



#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";
}

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";
}

}
That else statement applies only to the immediately preceding if statement (check for divisibility by 9). All those if statements should be an if-else if chain.
That's because your else only applies to the last if. Looking at it with proper indentation:
1
2
3
4
if (num % 9 == 0)
    cout << "Divisible by 9!\n";
else
    cout << "Sorry not divisible by anything!!\n";

So any number not evenly divisible by 9 will display "Not divisible by anything".

Try putting an else after each if statement:
1
2
3
4
5
6
7
8
9
10
if (num % 2 == 0)
    cout << "Divisible by 2!\n";
else if (num % 3 == 0)
    cout << "Divisible by 3!\n";
else ... etc
...
else if (num % 9 == 0)
    cout << "Divisible by 9!\n";
else
    cout << "Sorry not divisible by anything!!\n";





PLEASE USE CODE TAGS (the <> formatting button) when posting code.

closed account (4wRjE3v7)
Hi I did use the else if statement TRUST ME and it did not work!! I have tried everything! Someone please help me!!
Please post the code (using [code] tags) you tried with the else if statements, as if it did not work there must be some other problem.
closed account (4wRjE3v7)
Maybe I can come up with a statement for example: else if (num % 2,3,4,5,6,7,8,9 !=0) but it did not work either! Can anyone suggest anything?
And I am sorry but I have no clue what you guys all mean when you tell me use code tags!!???
Last edited on
Code tags means wrapping your code in them like so:
[code]
// Your code here
[/code]
becomes
 
// Your code here 


Using ifs and else ifs for the statements should work, so please post what you tried. That way we can show you what you did incorrectly.
closed account (4wRjE3v7)
Is there something wrong with my duplicate posting on here?
You should not post the same question multiple times. Keeping your question to a single thread avoids confusion. If you don't get any responses in a reasonable time, you can bump your thread.
Topic archived. No new replies allowed.