Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple if statements in C++

I'm doing the first project euler problem and I just did this

#include <iostream>
using namespace std;

int main(){

int threes =0;
int fives = 0;
int both = 0;
for (int i = 0; i < 10; i++){
      
       if(i%3==0){
   threes += i;
   }
  
       if(i%5==0){
   fives += i;
   }
   
      if ( i % 5 == 0 && i % 3 == 0){
      both += i;
  }

}

cout << "threes = " << threes << endl;
cout << "fives = " << fives << endl;
cout << "both = " << both << endl;

cout << " threes + fives - both = " << endl;
int result = (threes + fives) - both;
cout << result<< endl;

return 0;
}

My professor recently corrected me for doing this in a different problem saying something about else statements, but I don't understand WHY i have to add else in front of the next if. for what its worth I have another version with else if(i%5){ fives += .... } and they both work and get me the right answer.

My question is whats inherently wrong with this way of thinking, is it stylistic or am I not thinking logically about something?

If it works, why use switch statements ever?

like image 321
Dave2081 Avatar asked Dec 21 '22 13:12

Dave2081


2 Answers

The only thing that I see wrong with your implementation is that in the case where the number is both a multiple of 3 and a multiple of 5 not only is the both variable incremented but the fives and threes variables are also incremented. Based on what the professor described I believe he wants you to use an else-if so that the both variable is the only one that is incremented when you pass in a number that is both a multiple of 3 and a multiple of 5.

The reason you get the correct answer both ways is because you are only going to 10 in the for loop, if you increase it to i <= 15 you will get fives and threes being 1 higher than I think he intended.

For example:

for( int i = 0; i < 10; i++ )
{
   if( ( ( i % 3 ) == 0 ) && ( ( i % 5 ) == 0 ) )
   {
      both++;
   }
   else if( ( i % 3 ) == 0 )
   {
      threes++;
   }
   else if( ( i % 5 ) == 0 )
   {
      fives++;
   }
}
like image 96
Jonathan Rucker Avatar answered Jan 10 '23 15:01

Jonathan Rucker


The else branch in an if-else statement is only executed if the if branch is false. If you just have two if statements in a row, they'll both be executed, which can be a waste. In the below code, the else prevents the second computation from running if the first is satisfied.

if (expensive_computation1()) {
  ...
}
else if (expensive_computation2()) {
  ...
}

Additionally, it's clearer to humans reading the code whether both if statements should be allowed to run or whether only one should.

like image 38
erjiang Avatar answered Jan 10 '23 13:01

erjiang