------------------------------------------------------------------------------
MC logo
Looping On Read
[^] CSc 220 Home
------------------------------------------------------------------------------
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Hello, World! (Plain C)] [Average C I/O] [Printf Demo] [Problems With C I/O] [Looping On Read] [Convert To Upper Case] [Indent and Blank Remover] [Reading Lines] [Safer Line Reading] [Printing C++ Strings]
multav2.c
#include <stdio.h>
main()
{
        int cnt = 0,            /* Count of numbers read. */
            tot = 0;            /* Total of numbers read. */

        /* Read until a read fails. */
        int num;
        while(scanf("%d", &num) == 1) {
                tot = tot + num;
                cnt = cnt + 1;
        }

        /* Print the average. */
        if(cnt)
                printf("Average is %g\n", (double)tot / (double)cnt);
        else
                printf("No numbers.\n");
}