Friday, July 31, 2009

I am doing a test run for a C++ program. Can someone figure this out?

Suppose you deposit $1 into an acount this month, $2 into the account the second month, $4 the third month and so on, doubling your deposit each month. Write a program that displays the first month that your deposit exceeds %26amp;1,000,000.

I am doing a test run for a C++ program. Can someone figure this out?
This sounds like an excellent application for a "while" loop. The while loop checks a condition, and as long as that condition is true, it will execute a chunk of code.





So, let's have a variable, let's call it deposit. Since we're expecting a rather large number, let's make it a long integer.





long int deposit = 1;





Let's also have an integer to keep track of how many months it takes to reach our goal.





int month = 1;





Now let's make a loop.





while (deposit %26lt;= 1000000)


{


deposit += deposit; //double deposit's current value


month++; //Add another month


}


cout %26lt;%26lt; "In month number " %26lt;%26lt; month %26lt;%26lt; "we deposited in excess of one million dollars!" %26lt;%26lt; endl;





That code should do it for you.
Reply:Nothing like using the ellegance of recursion to impress your pears:





int deposit = 1;


int month = getMonth(1,1);








int getMonth(int month,int deposit){


if (deposit %26lt;= 1000000){


deposit += deposit;


month++;


return getMonth(month,deposit);


}


return month;


}





a bit less maintainable though....


No comments:

Post a Comment