Continuing For Loop in C

Recently I’ve been concentrating on learning C instead of C# for a number of reasons. First, C is the grandpa of many other languages like C#, Java, Python and PHP. Second, despite of its age, C is still one of the most important languages today. It’s a general purpose language with which you can target almost any platform from Windows to Linux and it’s more suitable for programming low-level applications for devices like networking equipment and robots. One very good, IT-related example is OMI providers, which are written in C to make switches, routers and other less-powerful devices manageable for IT pros. You can read about this in Don Jones’ article here. Third, this is the language we are learning at school form the 2nd semester on, C# having only been an introduction to programming.

At school we are using Visual Studio to code in C, but Microsoft’s IDE has really been designed for C++, C# and alike. My favorite IDE for programming in C is the open-source and cross-platform CodeBlocks. By saving my projects in Dropbox, I can easily work on my Windows and Linux machines, which is absolutely awesome. There are many C tutorials on the internet, but the ones I most like are the videos made by Bucky Roberts on If you’re a beginner like me, I suggest you start there.

In any programming language, loops are essential parts of even simple command line applications. The app I wrote calculates the average of an arbitrary number of test scores. Based on the average, it also determines a grade from 5 to 1. These are simple tasks, but you can learn very useful things by programming them. First, the app asks the user for the number of tests taken. Then, with the help of a for loop, it asks for each individual score to calculate the average and the final grade.

Calculating avrage and final grade

This is all great, but good programming also involves error handling. In my app I only handled the most obvious errors that could occur. First, you need at least two scores to calculate an average. This is easily handled by an if else statement. Second, any score has to be 0 or greater. Why would anyone want to type in a number less than 0 doesn’t matter. Calculating with negative numbers makes no sense in this program, so you have to handle it. To do this, you have to write your for loop in a way, that it asks for the score again and again, until a correct number is supplied. Also, the loop cannot be exited until the score for each test is collected. For example, if you have 5 tests, the for loop will run five times to ask you for the individual scores. If you supply a negative number at the 3rd round, the program has to keep asking for the 3rd score until you type in a 0 or greater number and the loop has to continue from there. It must not exit prematurely (you can use the break statement to exit a loop earlier). This can be done by using the continue statement, like this:

for (i = 0; i < [number of tests]; i++) // the loop runs as many times as many tests were taken
    printf("Score %d: ", i+1); // each run asks for the individual score, i+1 is neededd beacause the loop starts with 0
    scanf("%f", &score);       // reads the score
    if (score >= 0)            // if the score is 0 or greater, it's added to the sum
        sumOfScores += score;  // sumOfScores = sumOfScores + score
    else                       // else the loop continues, i.e runs again
        printf("Score cannot be less than 0!\n");
        i--;                   // i-- makes sure that the score of the same test will be asked again
        continue;              // as if the round with the incorrect score never happened

That’s how it looks in action:

For loop continues when supplied negative number

When calculating the average, you have to be careful with the data types, lest you may get incorrect results. In this case, you calculate the average by dividing the sum of scores by the number of tests. The average and the sum of scores should be floats, but the number of tests has to be an integer, obviously. C doesn’t like mixing different data types in calculations, so you have to make the number of tests a float just for that one line of code with type casting:

average = sumOfScores / (float)tests;
// by type casting you can make tests, which is an integer, a float just for this calculation

The rest should be quite straightforward, so let’s see the complete code:

#include <stdio.h>
#include <stdlib.h>

int main()
    int tests;         // number of tests taken
    float score;       // score of each test
    float sumOfScores; // sum of the scores
    float average;     // sumOfScores / tests
    int grade;         // 1-5
    int i;             // index for the loop

    printf("Number of tests: "); // asking for the number of tests taken
    scanf("%d", &tests);         // reading the answer
    printf("\n");                // printing a new line to make things look better

    if (tests >= 2) {                  // you need at least 2 tests to calculate an average
        for (i = 0; i < tests; i++) {  // asking for the score of each individual test until the number of tests is reached
            printf("Score %d: ", i+1); // i+1 because the loop starts form 0
            scanf("%f", &score);       // reading the score
            if (score >= 0)            // each score has to be 0 or greater
                sumOfScores += score;  // each score is added to the sum of the previous scores, same as sumOfScores = sumOfScores + score
            else {                     // if score is less than 0
                printf("Score cannot be less than 0!\n");
                i--;                   // this round must not count, since the score is incorrect
                continue;              // continue the loop without exiting, you can exit with break;

        average = sumOfScores / (float)tests; // calculating average
                                              //(float) makes tests, which is an integer, a float just for this calculation
        if (average >= 90)                    // calculating final grade
            grade = 1;                        // you don't need {} if you have only one line of code after if, else if and else
        else if (average >= 80)
            grade = 2;
        else if (average >= 70)
            grade = 3;
        else if (average >= 60)
            grade = 4;
            grade = 5;

        printf("\nAverage:\t%.2f\nGrade:\t\t%d\n", average, grade); // printing results

        printf("You need at least 2 tests to calculate the average!\n"); // if someone defined only one test for instance

    return 0;

This small app is far from being perfect, but it’s a good excercise. For example, if you type in letters or anything nonsense instead of numbers, the program just goes on and calculates an incorrect result of course. This kind of error is easy to handle with try catch statements in C#, but in C you have to code your own functions for that.


I enjoy microcontroller programming (AVR), programming in C/C#, playing with electronics, the Raspberry Pi and Arduino. My other passion is for IT - virtualization, PowerShell, servers and so on.

Tagged with: , ,
Posted in Programming

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Enter your email address to follow this blog and receive notifications of new posts by email.

Join 167 other followers

%d bloggers like this: