Divisibility by 3

I'm trying to write a code for an integer n
a) n is less than 500

b) n is positive

c) n is divisible by 3

but the result for divisibility by 3 is not showing when I run it.
Here is my code.

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char** argv)
{
int n,x,y;
cout <<"input the value of n"<<endl;
cin >>n;
x=500-n;
if(x>0)
cout<<"the value of n is less than 500 "<<endl;
if(n>0)
cout<<"the value of n is positive"<<endl;
y=n%3;
if(y=0)
cout<<"the value of n is divisible by 3"<<endl;
return 0;
}

Am I missing something?
1
2
if(y=0) // y=0 assigns the value 0 to y
    cout<<"the value of n is divisible by 3"<<endl;


should be
1
2
if(y==0) // y==0 tests if y is equal to 0
    cout<<"the value of n is divisible by 3"<<endl;


1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int main()
{
    int n ;
    std::cout << "input the value of n: " ;
    std::cin >> n;

    if( n < 500 ) std::cout << "the value of n is less than 500\n" ;

    if( n > 0 ) std::cout << "the value of n is positive\n" ;

    if( n%3 == 0 ) std::cout << "the value of n is divisible by 3\n" ;
}
Thanks, understood and it worked great.
and I always start with the using namespace std to avoid defining them over again
Last edited on
It's ok as long as you do not write a using namespace directive (at global scope) in a header file or before an #include

Ideally, it is best when the using namespace directive is at function local scope.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main()
{
    using namespace std ; // this won't affect the meaning of the code
                          // in other functions that we may use later

    int n ;
    cout << "input the value of n: " ; // within this function, we can still use
    cin >> n;               // unqualified names for entities from namespace std

    if( n < 500 ) cout << "the value of n is less than 500\n" ;

    if( n > 0 ) cout << "the value of n is positive\n" ;

    if( n%3 == 0 ) cout << "the value of n is divisible by 3\n" ;
}
inefficiently but interestingly if the sum of the digits are divisible by 3, so is the number. Useful for humans, but not really in code.
yeah could work but that will be another code to add individual values in a number
Registered users can post here. Sign in or register to post.