Tuesday, July 28, 2009

C Program Question- Yes this is homework?

Hi all,





Long time I haven't asked a question. Normally I'm the one answering you questions. Well this time I am in need of your programming experts help. I tried figuring it out but I just cant do this one. I had no problems with my other homework questions.


Please Help :) Thanks in advance for all your help.





Write a program to do the following:


● input an integer from 1 to 100.


● input a second integer between 0 and 4.


● shift the first number left by the second number of places. Shift is an arithmetic operator.


● print out “This is the result:” plus the numeric result of the shift operation as an integer.


○ an input function must be called to get an integer from the main program


○ the inpufunction will be given range values by the main program.


○ the input function must make sure the input number is within specified range.


○ If the number is outside the range, an error message must be displayed and a new input prompt given again.

C Program Question- Yes this is homework?
Assuming you meant C not C++, and you wanted to do a bitwise shift, I think this code does what you want. It could be expanded on to do nice things like tell you when you enter an illegal value, rather than just re-prompting you, etc. but you can get the basic idea.





-John





#include %26lt;stdio.h%26gt;





int get_input(int min, int max);





int main (void)


{





int inp, shiftBy, result;





while (1)


{


printf("Enter a number between 1 and a 100 to operate on, or 0 to end.\n");


inp = get_input(0,100);


if (inp == 0) break;





printf("Enter number of places to shift (0-4).\n");


shiftBy = get_input(0,4);





result = inp %26lt;%26lt; shiftBy;





printf("This is the result: %d\n", result);





}


}








int get_input(int min, int max)


{


int inp = min - 1;





while (inp %26lt; min || inp %26gt; max)


{


printf("Number? ");


scanf("%d",%26amp;inp);


}





return inp;


}
Reply:Thanks for the help man :) Report It

Reply:I haven't done any C in a while, but here I go:





%26lt;%26lt; is the bitwise shift left operator





Say you input a 4 (in binary: 0000 0100) into the first parameter.


And your shift parameter is to shift it 2 bit to the left, so your results should be a 16 (in binary: 0001 0000)





Here is the syntax to use the %26lt;%26lt; operator:


Value = firstParameter %26lt;%26lt; shiftParameter; //Value == 16





Each space shifted left is like multiplying the value by a power of 2 and shifting to the right divides the number by a power of 2 (On big endian machines it is the oposite, shifting left is division and shifting right is multiplication. Just ignore this rant if I confused you). The bit shift operators are a good trick for code optimization, but could make your code less readable.





You can do the rest.


No comments:

Post a Comment