powers of two, recursion.

Reply

Join Date: Oct 2004
Posts: 16
Reputation: Alfy is an unknown quantity at this point 
Solved Threads: 0
Alfy Alfy is offline Offline
Newbie Poster

powers of two, recursion.

 
0
  #1
Nov 4th, 2004
  1. int ans, guess, random, type, counter, num, i;
  2. char option[20], numb[10], input[5];
  3.  
  4.  
  5. int power(int num)
  6. {
  7. ans=2;
  8. if(num==0)
  9. {
  10. return(1);
  11. }
  12. if(num<0)
  13. {
  14. printf("incorrect input, please input a positive integer:");
  15. return(0);
  16. }
  17.  
  18. else
  19. for(i=1; i!=num; i++)
  20. {
  21. return(ans=ans*2);
  22. }
  23. return(0);
  24. }
  25.  
  26. int main()
  27. {
  28. /*before this there is all the switch case stuff*/
  29. case 1 :
  30. /*powers of 2 calculator*/
  31. printf("please enter a positive integer:\n");
  32. fgets(numb, sizeof(numb), stdin);
  33. sscanf(numb, "%d",&num);
  34. printf("the answer is:%d\n",power(num));
  35. break;
  36.  
  37. ok so the origional was:
  38. case 1 :
  39. /*powers of 2 calculator*/
  40. printf("please enter a positive integer:\n");
  41. fgets(numb, sizeof(numb), stdin);
  42. sscanf(numb, "%d", &num);
  43. ans=2;
  44. if(num<0)
  45. printf("incorrect input, please input a positive integer:");
  46. if(num==0)
  47. printf("the answer is 1\n");
  48. for(i=1; i!=num; i++)
  49. ans=ans*2;
  50. printf("The answer is %d\n", ans);
  51. break;

and i had to take that and turn it into a recursive function. IDK what recursion is other than "it calls itself" or something... anyway im lost on this.
please help!
Last edited by alc6379; Nov 4th, 2004 at 11:57 pm.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 10
Reputation: kunal_ktr is an unknown quantity at this point 
Solved Threads: 0
kunal_ktr kunal_ktr is offline Offline
Newbie Poster

Re: powers of two, recursion.

 
0
  #2
Nov 6th, 2004
here is the recursive code for calculating power of 2;
int power(int num)
{
if(num==0)
return 1;
if(num==1)
return 2;
return 2*power(num-1);
}

well after including this function in ur prog, u dont need to check whether the input value is 0 or 1. but check for -ve entry..

here is ur modified switch statements ...
case 1 :
/*powers of 2 calculator*/
printf("please enter a positive integer:\n");
fgets(numb, sizeof(numb), stdin);
sscanf(numb, "%d", &num);
//ans=2;
if(num<0)
printf("incorrect input, please input a positive integer:");
else{
ans=power(num);
printf("The answer is %d\n", ans);}
break;
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the C Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC