Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why answers won't show

Tags:

c++

I'm learning c++, to be honest, i'm newbie and make basic mistakes. I've started writing code that shows if typed number is divisible by 2, 4, 5, 8, 10 up to 5 times

Problem is that it doesn't show answers...

#include <iostream>
using namespace std;
int main() {
    int num;

    cout << "type in number to check if number is divisible by 2, 4, 5, 8, 10" << endl;
    cin >> num;
    switch (num) {
    case 1:
        if (num / 2 == 0) {
            cout << num << "is divisble by 2" << endl;
        }
    case  2:
        if (num / 4 == 0) {
            cout << num << "is divisible by 4" << endl;
        }
    case  3:
        if (num / 5 == 0) {
            cout << num << "is divisible by 5" << endl;
        }
    case  4:
        if (num / 8 == 0) {
            cout << num << "is divisible by 8" << endl;
        }
    case  5:
        if (num / 10 == 0) {
            cout << num << "is divisible by 10" << endl;
        }
        num++;
        if (num == 5) break;
    }
    return 0;
}
like image 475
C noob Avatar asked Jan 02 '23 00:01

C noob


2 Answers

Your understanding of the switch statement is not right.

switch(num) {

    case 1 :
      // This block will be executed only when num is equal to 1.
      if (num/2 == 0)  {
        cout<<num<<"is divisble by 2"<<endl;}

For your problem, you just need a series of if statements.

cin >>num;

if (num % 2 == 0)  {  // Not  if ( num/2 == 0)
   cout<<num<<"is divisble by 2"<<endl;
}

if (num % 4 == 0){
   cout<<num<<"is divisible by 4"<<endl;
}

if (num % 5 == 0) {
      cout<<num<<"is divisible by 5"<<endl;
}

if (num % 8 == 0){
         cout<<num<<"is divisible by 8"<<endl;
} 

if (num % 10 == 0)
{
   cout<<num<<"is divisible by 10"<<endl;
} 
like image 90
R Sahu Avatar answered Jan 12 '23 00:01

R Sahu


You seem to believe that dividing an integer by another integer returns the remainder. That's not the case. num / 2 with num equal to 6 will return 3 and it will return the same for num equal to 7.

What you want is the modulo operator % which returns the value of the remainder of the division. So, for 6 % 2 you'll get 0 and for 7 % 2 you'll get 1.

See also: https://en.cppreference.com/w/cpp/language/operator_arithmetic

like image 26
Jesper Juhl Avatar answered Jan 12 '23 02:01

Jesper Juhl