Difference between revisions of "ES101 - Lesson 6 : Arrays and Loops Continued"

From Embedded Systems Learning Academy
Jump to: navigation, search
(break and continue)
(do/while Loops)
Line 4: Line 4:
 
<syntaxhighlight lang="c">
 
<syntaxhighlight lang="c">
 
int quit = 0;
 
int quit = 0;
// do/while loop will always enter its code at least once
+
/**
 +
* do/while loop will always enter its code at least once
 +
* if quit is not 1, loop will repeat
 +
*/
 
do {
 
do {
 
     printf("Enter 1 to quit: ");
 
     printf("Enter 1 to quit: ");
 
     scanf("%i", &quit);
 
     scanf("%i", &quit);
 
}while(quit != 1);
 
}while(quit != 1);
// if quit is not 1, loop will repeat
 
  
// If quit was already a 1, loop will never run
+
 
 +
/**
 +
* If quit was already 1, loop will never run
 +
*/
 
while(quit != 1) {
 
while(quit != 1) {
 
     printf("Enter 1 to quit: ");
 
     printf("Enter 1 to quit: ");
Line 21: Line 26:
  
 
<br/>
 
<br/>
 +
 
== break and continue ==
 
== 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.
 
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.

Revision as of 00:26, 15 September 2012

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. There is a do/while loop and a while loop, and the only difference is that the do/while loop guarantees to execute the body of the loop at least once; the while loop is not guaranteed to be executed at least once. As long as the condition enclosed in the round brackets is a non-zero number, the loop will repeat the code body.

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 tolower() function to capitalize a char
        // assign the lower-cased version back to name[i]
        name[i] = tolower( 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. Display the square of all numbers from 1-100
    2. Enter a word
    3. Enter Midterm scores and calculate average.
    4. Quit
  2. For choice 1, use a for loop, and using a single variable, your output should be similar to:
    Square of 1 is 1
    Square of 2 is 4
  3. For choice 2, scanf a string, change the entire string to uppercase letters and print it out. Then,

change the entire string to lowercase letters and print it out.

  1. For choice 3, first, ask how many midterms there are (maximum of 5), and then ask the score for

each midterm, and print out the average score on the screen. If the user enters more than 5, inform the user that it is not a valid entry, and re-prompt the user to enter the number of midterms again.

  1. 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;
    do {
        printf("1. Menu item 1\n");
        printf("2. Menu item 2\n");
        printf("3. Quit\n");

        if(1 == option) {
            // do something here
        }
        else if(2 == option) {
            // do something else here
        }
    } while(option != 3);
}