// A series of demos on looping in C

// Marc Chee (cs1511@cse.unsw.edu.au), February 2021
// 

#include <stdio.h>

int main(void) {
    // *****************************************************
    // This first loop is a basic loop with a counter

    // an integer outside the loop
    int counter = 0;

    while (counter < 10) { // this code has run counter number of times
        printf("The first loop has completed %d times.\n", counter);
        counter = counter + 1;
    }
    // When counter hits 10 and the loop's test fails
    // the program will exit the loop

    // *****************************************************
    // This second loop shows the risk of asking the wrong
    // question in the loop!
    // This program will never end if this loop runs!
    //while (1 < 2) {
        // Never going to give you up
        // Never going to let you down . . .
    //}

    // *****************************************************
    // This loop will end only when a certain condition is
    // met. When it detects that the input number is odd
    
    // an integer outside the loop
    int end_loop = 0;

    // The loop will exit if it reads an odd number
    while (end_loop == 0) {
        int input_number;
        printf("Please type in a number: ");
        scanf("%d", &input_number);
        if (input_number % 2 == 0) {
            printf("Number is even.\n");
        } else {
            printf("Number is odd.\n");
            end_loop = 1;
        }
    }

    // *****************************************************
    // A loop within a loop. These should draw a grid of
    // stars
    
    int y = 0;
    // loop through and print multiple rows
    while (y < 10) { // we have printed y rows
        // print a single row
        int x = 0;
        while (x < 10) { // we have printed x stars in this row
            printf("*");
            x = x + 1;
        }
        // the row is finished, start the next line
        printf("\n");
        y = y + 1;
    }

    return 0;
}

Resource created Wednesday 27 January 2021, 01:16:16 PM, last modified Monday 22 February 2021, 04:07:20 PM.

file: loopDemo.c


Back to top

COMP1511 21T1 (Programming Fundamentals) is powered by WebCMS3
CRICOS Provider No. 00098G