// A demo program using scanf
// This shows a little bit of using libraries and functions
// as well as how the output of a function can be used

// Using scanf, this is a series of different ways we
// can read in multiple inputs and store them in an array

// Marc Chee (cs1511@cse.unsw.edu.au), October 2020

#include <stdio.h>

int main(void) {
    int num_count = 0;
    int numbers[10] = {0};
    // scan in 10 numbers and store them in the array
    // Note that scanf returns the number of inputs read
    // so we're using this as the way to iterate the
    // counter. See if you can find the issues this causes!
    printf("Please enter 10 numbers for the loop.\n");
    while (num_count < 10) {
        num_count += scanf("%d", &numbers[num_count]);
    // Another option for scanning 10 numbers
    // This is a pretty rough way to do this, but it's
    // interesting to note that scanf will ignore gaps
    // like spaces and newline (\n) in console input
    // in between numbers.
    printf("Please enter 10 numbers.\n");
    // If we're looking to only take in values until
    // the input ends, we can check how many values
    // scanf read in as a way to end a loop of scanf
    printf("Please enter up to 10 numbers. Press Ctrl-D if you are finished.\n");
    num_count = 0;
    int keep_looping = 1;
    while (num_count < 10 && keep_looping) {
        // scanf will return the number of values it has
        // read in. We store that in result
        int result = scanf("%d", &numbers[num_count]);
        if (result != 1) {
            // We didn't receive a valid input, so we're ending
            keep_looping = 0;
        // using result to increment num_count
        // this means that num_count will only go up if
        // scanf received a valid input.
        num_count += result;
    // If we want to, we can even put the result of a function
    // into the "question" expression of a loop
    // Every time the while loop starts, the "question" function
    // will run. The result of the function will determine
    // whether the rest of the loop runs
    printf("Please enter up to 10 numbers. Press Ctrl-D if you are finished.\n");
    num_count = 0;
    while (scanf("%d", &numbers[num_count]) == 1) {
    // A loop to print out the contents of the array
    int i = 0;
    while (i < 10) {
        printf("%d, ", numbers[i]);

Resource created Tuesday 01 September 2020, 09:30:27 PM, last modified Monday 05 October 2020, 12:07:52 AM.

file: scanfDemo.c

Back to top

COMP1511 20T3 (Programming Fundamentals) is powered by WebCMS3
CRICOS Provider No. 00098G