ES101 - Lesson 6 : Arrays and Loops Continued

From Embedded Systems Learning Academy
Jump to: navigation, search

do/while Loops

do/while loops provide a way to loop through elements, and is preferred solution if the content of the body is more complex than a for loop. As long as the condition enclosed in the round brackets is a non-zero number, the loop will repeat the code body. Notice from the examples that:

  • do/while loop checks for its loop continuation condition at the end
  • while loop checks for its loop continuation at the beginning
int quit = 0;
/**
 * do/while loop will always enter its code at least once
 * if quit is not 1, loop will repeat
 */
do {
    printf("Enter 1 to quit: ");
    scanf("%i", &quit);
}while(quit != 1);


/**
 * If quit was already 1, loop will never run
 */
while(quit != 1) {
    printf("Enter 1 to quit: ");
    scanf("%i", &quit);
}

In summary, you enclose your code within the body of the loop that you want to run and if the condition inside the round brackets is true, the loop will keep repeating the code body. The conditions can use combinational logic, such as quit != 1 && quit != -1 as well. Furthermore, there are more ways to control the behavior of the loop as discussed in the break and continue section of this laboratory lecture.


break and continue

The break and continue are instructions that can be used inside a loop to control the loop behavior. In simple words, the word break quits the loop immediately, and makes the CPU go to the instruction after the loop. The continue statement makes the CPU restart the loop immediately. These instructions should not be used unless absolutely necessary.

int main(void)
{
    int quit = 0;
    while(1) { // forever loop until broken
        printf("Enter 1 to quit: ");
        scanf("%i", &quit);

        if(1 == quit) {
            break;
            printf("This will not print, break immediately quits the loop.");
        }
    }

    int restart = 0;
    while(1) { // forever loop until broken
        printf("Enter 1 to restart the loop: ");
        scanf("%i", &restart);

        if(1 == restart) {
            continue;
            printf("This will not print, continue immediately restarts the loop.");
        }
        else {
            break;
        }
    }
}



Pre and Post Increment

You have used ++ operator before, which increments the value of a variable by one, but there is a difference between i++ and ++i when it comes to comparing the variable inside an if statement or during the comparison within a loop. i++ is called post-increment, and ++i is called pre-increment, and the difference is when the value is being compared for both.

int main(void)
{
    int i = 0;
    
    // i is compared to zero first, and then incremented to 1
    i = 0;
    if(i++ == 0) {
        printf("This will be printed!\n");
    }

    // i is changed to 1 first, then compared with 0
    i = 0;
    if(++i == 0) {
        printf("This will NOT be printed!\n");
    }
}



Example Program

This example code shows you how to get an input string, and capitalize every single letter of the string, and then print out the string.

#include <ctype.h> // This file needed for tolower() or toupper() functions

int main(void)
{
    char name[32];
    printf("Enter your name: ");
    scanf("%s", &name[0]);

    // Get the number of chars user entered
    int len = strlen(name);

    for(int i=0; i<len; i++) {
        // Call toupper() function to capitalize a char
        // assign the upper-cased version back to name[i]
        name[i] = toupper( name[i] );
    }

    printf("Your name in capital letters: %s\n", name);

    return -1;
}



Assignment

  1. Build and present a menu to a user like the following and enclose it into a loop that ends when the Quit option is chosen.
    1. Enter user name.
    2. Enter exam scores.
    3. Display average exam scores.
    4. Display summary.
    5. Quit
  2. For choice 1, scanf a string, and store it to a username char array.
  3. For choice 2, use a for loop to enter 3 exam scores.
  4. For choice 3, if the user has already entered exam scores, display the average. If the user has not yet entered exam scores, display an error message similar to: "Please use the menu to enter exam scores first"
  5. For choice 4, if the user has not yet entered their name and exam scores, display an error message. Otherwise display the average, the letter grade of the average, and the user's name.
    Example: "Hello Preet, your exam scores were 80, 90, and 100. Your average is 90.0 with letter grade: A"
  6. When the Quit option is chosen, end the primary loop that contains the menu.

Sample Code

#include <ctype.h> // This file needed for tolower() or toupper() functions

int main(void)
{
    int option = 0;
    char name[32] = { 0 };
    // bool is a variable that can either be true or false
    // We set this to false, and later set it to true when user enters their name
    bool name_entered = false;

    do {
        printf("1. Enter name\n");
        printf("2. Display name\n");
        printf("3. Quit\n");
      
        scanf("%i",&option);

        if(1 == option) {
            name_entered = true;
            printf("Enter your name: ");
            scanf("%s", name);
        }
        else if(2 == option) {
            if (name_entered) {
                printf("Your name is: %s\n", name);
            }
            else {
                printf("Please use the menu to enter your name first.\n");


            }
        }
    } while(option != 3);
}