Friday, July 31, 2009

Hey everyone. Can some one help me with C programming?

I'm needing a little help with the switch statement.





I need to write a do while loop in order to find the factorial of a number, the number can only be odd, but if someone were to input a even number it needs to say that the input is invalid and ask again. I can get my program to ask and allow for one more input but another even number after that and it just calculates the factorial of the even number, I know why it does this I just don't know how to make it ask again.





Here is my code:





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


int main()


{


int a, r, f;





a=1;





printf("What is the number?\n");


scanf("%i", %26amp;f);





r=f%2;





switch(r){


case 0:


printf("Invalid number, try again.\n");


scanf("%i", %26amp;f);





default:


do{


a*=f;


f--;


}


while(f%26gt;0);





printf("%i", a);





break;





}


return 0;


}





I know the only reason it does it 1 time is because I don't have a break on case 0. I don't know how to reset the switch statement from the beginning. Such as if I wanted to make a code where you input operators and values to calculate.

Hey everyone. Can some one help me with C programming?
Rather than a switch statement, use a while-loop that will continue asking for an input until the input parameter meets your condition. THEN, after input is validated, calculate the factorial. There is no reason to place the input validation in the same loop as the factorial calculation; that's bad design.
Reply:put a "break;" after scanf("%i",%26amp;f); in the switch statement otherwise for case 0 it will continue into default
Reply:Create a while loop for your input section.





while your input in invalid, ask for input





exit the loop when the user gives you a valid input.


No comments:

Post a Comment