Lecture 5 - Looping
Back to Previous Lecture
Up to Main Page
Forward to Next Lecture
Get Number from User Within a Range
The program
getnum.c
shows you how to get a number from the user within a certain range.
If the user enters an incorrect number,
the program prints an error message and asks for the number again.
Run this program and enter some invalid numbers to see how it works.
Try numbers like: -1, 99, 0, 1, 10, and 7. Which ones were acceptable?
Getting Information From User and Validating Input
The
getinfo.c
program is a further enhancement from the previous lectures.
In this version,
the length of the name fields are checked.
If invalid, the user's response is rejected, and a new value is asked for.
For the purposes of testing, NAMESIZ is set to 10.
In production mode, that would be much larger.
Counter Program
The program
count.c
shows you how a for loop works.
Analyzing a Line from the User
The program
analyze.c
reads a line of text from the user, and then analyzes the string.
The program then prints out how many characters of various types
appeared in the line.
Notice that since the final category is "other",
we have to keep track of whether or not a given character
has been categorized.
Loop Getting Numbers and Squaring Them
The program
squares.c
shows you how to loop getting numbers from a user until the user
indicates they are done.
For each number, the square of that number is displayed.
Using the Case Statement
The program
case.c
shows you how to use the case (or switch) statement.
The program is functionally similar to the
calc.c program from the previous lecture,
but uses the case statement instead of nested if statements.
The program asks the user for two numbers and an operator.
If the user enters a supported operator, the calculation is performed
and the result is displayed.
If the user enters something the program doesn't understand,
an error message is printed.
Math Quiz Program
The program
quiz.c
is a simple math drill program.
It generates a random addition problem and asks the user for the answer.
Small Calculator
The program
calc.c
is small calculator.
This program works similar to hand help calculators you have used.
There is an accumulator, which displays the current
value.
You can enter an operation, possibly followed by some value.
You add, subtract, multiply, and divide the accumulator with
other values you enter.
You can also clear the accumulator, which resets it to zero,
and start another set of calculations.
The program loops asking the user for a command,
which is optionally followed by a value.
For example, if you want to add 123.456 to the calculator,
you would enter:
The program supports some other commands.
For example, the c command will clear the accumulator
and set it to zero.
The q command quits the program.
What would it take to support other functions?
For example, how would you add trig functions like
sin and cos?
Back to Previous Lecture
Up to Main Page
Forward to Next Lecture