Sunday, July 26, 2009

Intro to c++ class HW?

you are to prompt the user to enter an integer value, and then accept the value from the user. The program should then determine and display an appropriate message as to whether the entered integer's value was EVEN or ODD. HINT: this is a situation where the modulo (remaindering) operation may come in handy; that is, what do you get as a result of taking an integer modulo 2 (divide the number by 2 and take the remainder)?





This is the last part of the HW that I am suppose to do, but I can't seem to figure out the modulo.





Can anybody help me with this?





I think if-else statement is needed for this, since that's what we are currently learning.





Thank you

Intro to c++ class HW?
#include%26lt;iostream.h%26gt;





int num1;








main()


{


cout%26lt;%26lt;"Enter a number:";


cin%26gt;%26gt;num1;





if(num1%2==0)


{


cout%26lt;%26lt;"EVEN";


}


else


{


cout%26lt;%26lt;"ODD";


}


}
Reply:#include%26lt;iostream.h%26gt;





int main()


{


int i;


cout%26lt;%26lt;"Enter an integer : ";


cin%26gt;%26gt;i;


if(i%2==0)


cout%26lt;%26lt;"The integer is even.";


else


cout%26lt;%26lt;"The integer is odd";


return 0;


}
Reply:The modulus operator in c++ is %. So, you can solve the question using a= x%2 and if a=0 then the integer number entered is Even otherwise it is odd.





You can use conditional operator ? and : to check this condition like this :





(a%2==0)?cout%26lt;%26lt;"Even Number ":cout%26lt;%26lt;"Odd Number." ;
Reply:#include %26lt;iostream%26gt;


using namespace std;





int main(){


long number;


while(1){


cout %26lt;%26lt; "\n\nEnter an integer number : ";


cin %26gt;%26gt; number;


(number % 2 == 0) ? cout %26lt;%26lt; "Even Number " : cout %26lt;%26lt; "Odd Number." ;


}


}
Reply:modulo arithmetic is the remainder after a division.


x / y = z + remainder


x % y = remainder





% is the modulo operator in C and C++


No comments:

Post a Comment