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

From Embedded Systems Learning Academy
Jump to: navigation, search
(Assignment)
(Sample Code)
 
(5 intermediate revisions by 2 users not shown)
Line 1: Line 1:
 
== do/while Loops ==
 
== 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.
+
'''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
  
 
<syntaxhighlight lang="c">
 
<syntaxhighlight lang="c">
Line 103: Line 105:
  
 
     for(int i=0; i<len; i++) {
 
     for(int i=0; i<len; i++) {
         // Call tolower() function to capitalize a char
+
         // Call toupper() function to capitalize a char
         // assign the lower-cased version back to name[i]
+
         // assign the upper-cased version back to name[i]
         name[i] = tolower( name[i] );
+
         name[i] = toupper( name[i] );
 
     }
 
     }
  
Line 116: Line 118:
  
 
<br/>
 
<br/>
 +
 
== Assignment ==
 
== Assignment ==
 
#  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.
 
#  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.
##  Display the square of all numbers from 1-100
+
##  Enter user name.
##  Enter a word
+
##  Enter exam scores.
##  Enter Midterm scores and calculate average.
+
##  Display average exam scores.
 +
##  Display summary.
 
##  Quit
 
##  Quit
#  For choice 1, use a '''for''' loop, and using a single variable, your output should be similar to:
+
#  For choice 1, scanf a string, and store it to a username char array.
#: Square of 1 is 1
+
For choice 2, use a for loop to enter 3 exam scores.
#:  Square of 2 is 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"
#  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.
+
#  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.
#  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.
+
#: Example: "Hello Preet, your exam scores were 80, 90, and 100.  Your average is 90.0 with letter grade: A"
 
#  When the Quit option is chosen, end the primary loop that contains the menu.
 
#  When the Quit option is chosen, end the primary loop that contains the menu.
  
Line 136: Line 140:
 
{
 
{
 
     int option = 0;
 
     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 {
 
     do {
         printf("1. Menu item 1\n");
+
         printf("1. Enter name\n");
         printf("2. Menu item 2\n");
+
         printf("2. Display name\n");
 
         printf("3. Quit\n");
 
         printf("3. Quit\n");
 +
     
 +
        scanf("%i",&option);
  
 
         if(1 == option) {
 
         if(1 == option) {
             // do something here
+
             name_entered = true;
 +
            printf("Enter your name: ");
 +
            scanf("%s", name);
 
         }
 
         }
 
         else if(2 == option) {
 
         else if(2 == option) {
             // do something else here
+
             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);
 
     } while(option != 3);
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>

Latest revision as of 18:31, 10 October 2014

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);
}