Skip to content
School of Physics
Home Our Teaching Resources C programming ex3.html
Back to top

Week 3 Exercises

These exercises are assessed.

Remember

  • Markers will be extremely strict on layout: indentation of if() and while() and not over-running the line so it won't print properly.
  • Have a clear and specific comment at the top so we know what the program does. Avoid comments that don't tell you anything.
  • Use clear but fairly short variable names.
  • Revise if() and while() from the lecture.
  • Make sure there's a clear and specific test to show that the code works.
  • Remember the megaprinciple!

When it says hand in below, that means the code and a sample of the output.

If you get stuck email your code to me as plain text (copy and paste it into your email).

The if() statement

Revise the two ways we wrote the "positive/negative, odd/even" if code (nested ifs and else ). Chose the method you think is simpler for the next task.

Exercise

Extend your quadratic code, still assuming real coefficients, but handling all of the possible cases: both a and b equals zero (invalid equation), a equals zero with b non-zero (linear equation), and all three possible conditions on the discriminant (postive, zero, negative). Construct a suitable if statement to handle them all, checking that the result is correct in each case.

I strongly recommend you write this a bit at a time. Get one case working, and check it, before starting on the next.

Using the while() loop

Tip

To see what your while() loop is doing (for example, if it's not behaving as you would wish), have a printf() statement inside the loop that prints out the names and values of all the relevant variables.

Exercise

  1. Write a program to calculate the value of n factorial for n >= 0.

    Print out the value for a few values of n small enough for you to check by hand. Hand this in.

  2. A funny thing will happen if you increase your upper limit on your factorial to, say, 20 factorial. You may want to think about why this is.
                                                                                                                                                                                                                                                                       

Validate   Link-check © Copyright & disclaimer Share
Back to top