Difference between revisions of "ES101 - Lesson 6 : Arrays and Loops Continued"
(Created page with "== 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. T...") |
Proj user12 (talk | contribs) (→Sample Code) |
||
(9 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 | + | '''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"> | ||
int quit = 0; | int quit = 0; | ||
− | / | + | /** |
+ | * 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 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 28: | ||
<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. | ||
Line 46: | Line 54: | ||
continue; | continue; | ||
printf("This will not print, continue immediately restarts the loop."); | printf("This will not print, continue immediately restarts the loop."); | ||
+ | } | ||
+ | else { | ||
+ | break; | ||
} | } | ||
} | } | ||
Line 53: | Line 64: | ||
<br/> | <br/> | ||
+ | |||
== Pre and Post Increment == | == 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. | 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. | ||
Line 93: | Line 105: | ||
for(int i=0; i<len; i++) { | for(int i=0; i<len; i++) { | ||
− | // Call | + | // Call toupper() function to capitalize a char |
− | // assign the | + | // assign the upper-cased version back to name[i] |
− | name[i] = | + | name[i] = toupper( name[i] ); |
} | } | ||
Line 106: | 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. | ||
− | ## | + | ## Enter user name. |
− | ## Enter | + | ## Enter exam scores. |
− | ## | + | ## Display average exam scores. |
+ | ## Display summary. | ||
## Quit | ## Quit | ||
− | # For choice 1, | + | # For choice 1, scanf a string, and store it to a username char array. |
− | + | # For choice 2, use a for loop to enter 3 exam scores. | |
− | + | # 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, | + | # 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" | |
− | # For choice 3, | ||
− | |||
− | the user | ||
# 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 129: | 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. | + | printf("1. Enter name\n"); |
− | printf("2. | + | printf("2. Display name\n"); |
printf("3. Quit\n"); | printf("3. Quit\n"); | ||
+ | |||
+ | scanf("%i",&option); | ||
if(1 == option) { | if(1 == option) { | ||
− | + | name_entered = true; | |
+ | printf("Enter your name: "); | ||
+ | scanf("%s", name); | ||
} | } | ||
else if(2 == option) { | 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); | } while(option != 3); | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> |
Latest revision as of 18:31, 10 October 2014
Contents
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
- 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.
- Enter user name.
- Enter exam scores.
- Display average exam scores.
- Display summary.
- Quit
- For choice 1, scanf a string, and store it to a username char array.
- For choice 2, use a for loop to enter 3 exam scores.
- 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 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"
- 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);
}