| School of Physics |
|
| Physics Home | Study here | Our Teaching | Our Research | Our Centres | News | Work here | EMPS |
Back to top
Exercises 2These form an important part of your learning but are not formally assessed as a part of your course mark. Bring them to a demonstrator next week for feedback. The aim at the moment is for you to be able to use the % operator and integer division, simple if statements and complex arithmetic.One of the exercises has an optional part involving a more advanced use of if statements (one inside another). ExampleHere is a simple example of an if (properly indented of course!):
/*
* Simple if demonstration
*/
#include <stdio.h>
int main() {
int mustbepositive = -2; /* !! */
if ( mustbepositive >= 0 ) {
printf("OK: %d\n", mustbepositive);
return 0;
}
else {
printf("ERROR: it's negative: %d\n", mustbepositive);
return 1;
}
}
Here it is without indentation:
/*
* Simple if demonstration with no indentation
*/
#include <stdio.h>
int main() {
int mustbepositive = -2; /* !! */
if ( mustbepositive >= 0 ) {
printf("OK: %d\n", mustbepositive);
return 0;
}
else {
printf("ERROR: it's negative: %d\n", mustbepositive);
return 1;
}
}
ExercisesMinutes and secondsThe example in the notes of converting a number of seconds to minutes and seconds has one obvious problem: it doesn't test to see if the result is correct. (It's quite possible of course that it was tested when it was written and the test was later removed.) Fix this!
Quadratic equationReview the section on complex numbers.
Optional: people and cars problemWrite a program to solve the "people and cars" problem to produce an output like "4 cars with three people and 2 cars with four people". It's OK to have output like "4 cars with three people and 0 cars with four people" |