Programming Primer 1
comments | Posted in ai | tutorial on Tuesday, September 25 2007 17:35:00 GMT

Write a simple test summary tool in C.

Accept an input of test scores and output the highest testscore, lowest testscore and the average testscore.

Solution

/ dgurba 09/25/2007 score.c -- a simple test score tool. /

include <stdio.h>

include <stdlib.h>

define PREAMBLE "Test Tool\n\n"

define PROMPT "Enter score: "

define POSTAMBLE "\nTest Tool\n\nHigh Score: %g\nLow Score: %g\nAvg Score: %g\n"

define SCORE_FORMAT "%e"

int main(int argc, const char* argv[]) {

float score, low_score, high_score, avg_score, cumulative_score;
int iterations;

iterations = 0;
score = 0.0;
low_score = 0.0;
high_score = 0.0;
avg_score = 0.0;
cumulative_score = 0.0;

printf(PREAMBLE);
do {
    printf(PROMPT);
    scanf(SCORE_FORMAT, &score);
    if (score != -1) {
            if (iterations > 0) {
                if (score < low_score) { low_score = score; }
                if (score > high_score) { high_score = score; }
            } else {
                low_score = score;
                high_score = score;
            }
            cumulative_score += score;
            iterations++;
    }
} while (score != -1);

if (iterations > 0) { avg_score = cumulative_score / iterations; }
printf(POSTAMBLE, high_score, low_score, avg_score);
exit(0);

}

Interesting Notes

Though this is a simple example of basic programming structures and logic. Many students get hung up on how to do the Online Search used throughout the program. The term online search comes of Artificial Intelligence terminology. An Online Search is a dynamic search, real-time search while the user waits, for an answer.

Many students think they will store all the inputs in an array or list and then use If/Else logic to find the solution, or sort the array and find the requested values. Any of these methods are valid, but a simple program such as this is a good example of figuring out the best answer in real-time, at any iteration in the loop you have computed the correct value for low_score and high_score.

An Offline Search would be gathering all the values and then inspecting them for the lowest, highest and average. An Offline Search is a search performed not from real time data, but from a store of data and rules.

Always compile with at least the following options [-Wall is important for strict debugging in advanced C usage]: $ gcc score.c -Wall -o score

blog comments powered by Disqus