Thursday, July 22, 2010

C++: A more realistic set of problems

So far, we've discussed ways in which we can change the flow of execution,
or branch into scenarios based on conditional statements. Also, we've
learned that we can have a part of our program run repeatedly as long as the
condition is right. now, let's put that into practice...

1. You want to buy a friend of yours a gift card on his birthday. The
problem is that he was born on February 29, 1988 - a leap year. To help you
keep track with this problem, you've decided to write a program that checks
whether the year that you've typed is a leap year or not. A leap year is a
year divisible by four unless it is also divisible by 400. For example, the
years 1600, 2000 and 2400, as well as 1996, 2004 and 2012 are leap years.
The years 1500, 1700, 1800, 1900, 2100, etc. are not. Can you come up with a
possible algorithm to solve this dilemma?

2. now, with your algorithm at hand, write a small program to check leap
years: first, try using an if statement, then try writing a program that
keeps asking you to enter a year, output whether it is a leap year or not
until you press 0. Compile after each set and notice the differences (hint:
one is a loop).

3. An elementary school child (perhaps a first grader) asks you if you can
teach her about multiplication table. You asked her how it should be done,
and the child asks you to give her a small toy that will tell her the
multiple of a number from 1 to 10 - for example, a base of three would tell
her numbers from 3 to 30. So you decided to write a small program that you
can put in this toy so that the child can play with it. What will you do to
solve this problem? (hint: we want a for loop to help us out). Write the
English version of your "code", then write your code based on your
algorithms and explain (in comments) as to how this program would run.

The answers and an example program set for each of them will be "offered"
As always, if you have any comments, please let me know...
// JL

No comments:

Post a Comment