# #C Programming (I) - 5
## Loop Control
English: Lei KuoLiang
nicolaslouis@mail.fcu.edu.tw
Chinese(TW): Wang M.H
---
### This week's course catalog
0. Review
1. while, do while, for loop
2. Global variables, regional variables
3. break, continue
4. Common end methods for continuous input
---
## Last week's course review
----
### Relational operator
| Name | Operator | Grammar |
| -------- | -------- | -------- |
| Greater than | `>` | `a > b` |
| Greater than or equal to | `>=` | `a >= b` |
| Less than | `<` | `a < b` |
| Less than or equal to | `<=` | `a <= b` |
| equals | `==` | `a == b` |
| Not equal | `!=` | `a != b` |
* `==`(equal) Don't confuse with `=` (assignment)!
----
### Logical operator
| Name | Operator | Grammar |
| -------- | -------- | -------- |
| logical AND | `&&` | `a && b` |
| Logic OR | `||` | `a || b` |
| Logic NOT | |!` | `!a` |
----
### if...else if...else.
```c
if(Conditional sentence){
Narrative sentence 1;
Narrative sentence 2;
...
}
else if(Conditional sentence){
Narrative sentence 1;
Narrative sentence 2;
...
}
else{
Narrative sentence 1;
Narrative sentence 2;
...
}
```
----
### Conditional operator ?
```c
Conditional formula ? Set return value : Failure return value
```
E.g:
```c
if(a > b)
max = a;
else
max = b;
```
Equivalent to
```c
max = (a > b) ? a : b;
```
----
### switch case default
The format of the switch, and the equivalent if

---
## Loop
* while
* do while
* for
----
Sometimes, we need the computer to do something differently. In this case, we can use the loop to shorten the number of lines of code.
---
## while
----
```c
while ( Judgment sentence ) {
Narrative sentence 1;
Narrative sentence 2;
......
}
```
```flow
st=>start: Enter the while loop
e=>end: Leave the while loop
stat=>operation: Loop body
cond=>condition: Test expression
st->cond(yes,right)->stat(top)->cond
cond(no)->e
```
----
The following is a code excerpt from "Repeat 3 times and judge a few negative numbers"
```c
int value;
int count_negative = 0; // A count flag used to count negative numbers
//Enter an integer. If the number entered is negative, the counter ++ is repeated 3 times.
scanf("%d", &value);
if(value < 0)
count_negative++;
scanf("%d", &value);
if(value < 0)
count_negative++;
scanf("%d", &value);
if(value < 0)
count_negative++;
printf("Appeared in 3 inputs %d Negative number\n", count_negative);
```
----
Can be changed to
```c
int value;
int count_negative = 0; // a count flag used to count negative numbers
//Enter an integer. If the number entered is negative, the counter ++ is repeated 3 times.
int count_time = 0;
while(count_time < 3){
scanf("%d", &value);
if(value < 0)
count_negative++;
count_time++;
}
printf("Appeared in 3 inputs %d Negative number\n", count_negative);
```
----
Example: print out the number of powers of 2 below 100
```c=
#include <stdio.h>
#include <stdlib.h>
int main()
{
int val = 2;
while (val < 100){
printf("%d ",val);
val *= 2;
}
printf("\n");
return 0;
}
```
Results of the
```
2 4 8 16 32 64
```
---
## do while
----
```c
do {
Narrative sentence 1;
Narrative sentence 2;
......
} while ( Judgment sentence ); //Attention!!!! semicolon is needed here (;)!!!
```
```flow
st=>start: Enter the do while loop
e=>end: Leave the while loop
stat=>operation: Loop body
cond=>condition: Test expression
st->stat->cond
cond(yes, right)->stat
cond(no)->e
```
----
While is to judge whether you can do it, then do things
Do while is done 1 time, then judge whether you can continue to do
----
Print the result of the squared integer
(allows the user to decide whether to continue)
```c=
#include <stdio.h>
int main() {
int val, is_continue;
do{
printf("input: ");
scanf("%d", &val);
val *= val; //square
printf("result: %d\n",val);
printf("continue(0.No 1.Yes)?");
scanf("%d", &is_continue);
printf("\n"); //Blank line
} while (is_continue); //Notice the semicolon
return 0;
}
```
----
Input and execution results of the above example
```
input: 6
result: 36
continue(0.No 1.Yes)?1
input: 100
result: 10000
continue(0.No 1.Yes)?1
input: 8
result: 64
continue(0.No 1.Yes)?0
```
---
### Exercise 1
* Enter an integer n
* Print all the factors of n
Sample results:
```
100
1 2 4 5 10 20 25 50 100
```
---
## for
----
```c
for ( Enter the loop narrative sentence; judgment sentence; loop narrative sentence ){
Narrative sentence 1;
Narrative sentence 2;
...
}
```
```flow
st=>start: Enter for loop
e=>end: Leave for the loop
init=>operation: Enter the loop narrative
loop=>operation: Increment
stat=>operation: Initial
cond=>condition: Condition
st->init->cond
cond(no,bottom)->e
cond(yes)->stat(right)->loop(right)->cond
```
----
Example:
```c
int main()
{
int i; //counter
for(i = 0; i < 10; i++)
{
printf("*");
}
printf("\n");
printf("Total %d*\n", i);
}
```
Output
```
**********
10 in total*
```
----
Declare variables in "Entering a Circle Narrative"
```c
for(int i = 0; i < 10; i++){
printf("*");
}
```
At this time, "i" can only be used in the for loop, which is the area variable for.
----
Only after the standard C99 can the variables be declared in the parentheses of for
If you are using dev-C++, please go to Tools→Compiler Options→Red circle position below to change to -std=c99 or -std=c11

---
<!--
### Exercise 2
Please change the code below to for loop
```c=
#include <stdio.h>
Int main(){
Int count = 0, sum = 0, times;
Scanf("%d", ×);
While(count < times){
Sum += count;
Printf("%d: %d\n", count, sum);
Count++;
}
}
```
-->
### Exercise 2
* Enter two positive integers n and m, and calculate the sum of n to m
(using for loop)
Sample results:
```
2 100
5049
```
---
### Exercise 3
* Enter a positive integer n,0 < n < 2^8^
* The positive integer n is represented by binary digits. If the output is less than 8 digits, the complement is 0 to 8 digits.
Example result 1:
```
63
00111111
```
Sample result 2:
```
100
01100100
```
---
## Global variable, regional variable
----
* If you declare a variable in a brace, you can't use that variable after you leave that braces.
* Variables declared in braces are called regional variables
* Variables declared in the outermost area of the program (outside main) are called global variables
----

<!--
```c=
#include <stdio.h>
#include <stdlib.h>
Int val1 = 100; //Global variable
Int main(){
Int val2 = 200;
//can use val1, val2
While(val2 < 1000){
Int val3 = val2 / 3;
Printf("%d\n", val2);
Val2 += val1 + val3;
/ / Can use val1, val2, val3
}
/ / Can use val1, val2
}
```
-->
---
## break、continue
----
### break
In the switch pattern, we have used the break keyword.
"break;" will jump away from the innermost switch, do, for, or while block (block)
----
```c=
#include <stdio.h>
#include <stdlib.h>
int main()
{
int respond;
while(1){ //Constant true, infinite loop
printf("In the loop, do you want to jump out?(0.No 1.Yes)?");
scanf("%d", &respond);
if(respond)
break;
}
printf("Jumped out!\n");
return 0;
}
```
----
### continue
"continue;" will pass the control to the next iteration of the innermost do, for, or while, and skip the rest of the statement.
----
```c=
#include <stdio.h>
#include <stdlib.h>
int main()
{
for(int i = 1; i <= 6; i++){
if(i & 1) //When "i" is odd
continue;
printf("%d\n", i);
}
return 0;
}
```
Results of the
```
2
4
6
```
---
### Exercise 4
* Enter an integer n, if Prime is printed for the prime number, otherwise print a number greater than 1 and divisible by n.
Example result 1:
```
91
7
```
Example result 2:
```
43
Prime
```
---
## Common end method for continuous input
1. Enter n to end the input
2. Enter 0 to end the input (or other specified data)
3. EOF (End Of File)
----
### Enter n to end the input
```c
int input;
scanf("%d", &input);
for(int i = 0; i < input; i++){
//Processing data
}
```
----
### Enter 0 to end the input
Method 1
```c
int input;
while(1){
scanf("%d", &input);
if(input == 0)
break;
//Processing data
}
```
Method 2
```c
int input;
while(scanf("%d", &input) && input != 0){
//Processing data
}
```
----
### Enter until there is no data (EOF)
```c
int input;
while(scanf("%d", &input) != EOF){
//Processing data
}
```
----
### EOF

* EOF is a constant defined in stdio.h with a value of -1
* When scanf reads the end of the input file, it will return EOF.
----
* When using the cloud test platform, it is usually entered by file
* When using a small black window such as CMD (windows system) or Terminal (Linux system) to execute the program, you can also use the file input.
* EOF keyboard input is Ctrl+Z (^Z will be displayed)
* When scanf reads the end of the input file, it will return EOF.
----
Demonstration using CMD to execute .exe and using file input

---
### Exercise 5
* Let the user repeatedly input 1 English letter, if the character is uppercase, output lowercase; if the character is lowercase, output uppercase. Repeat the input until you enter 0 to end the program.
* Example results:
```
a
upper is A
G
lower is g
k
upper is K
0
```
---
## Homework
----
### Work requirements:
1. Continue last week's homework, ++ If the user enters an error message, let the user re-enter ++
2. After selecting the first attack and then attack, use the loop to fight and judge the winner (if the opponent's blood volume is less than or equal to 0, then the party wins)
3. The battle uses a turn-based system. The first attack character is attacked after the attack and the attack character attack. After the attack, the character attack is the first attack attack role, and so on.
4. The damage caused by the attack is based on the formula:
```
Attack damage = attacker attack power - attacker's defense
```
----
#### Output requirements:
1. After selecting the first attack and the rear attack character, the result of the selection is displayed, and the "start of battle" is printed on the next line.
2. Every attack needs to show who is attacking and how much damage is caused.
3. On the next line of the attack, the remaining amount of blood (HP) on both sides must be displayed and blanked.
4. The winning character must be determined and displayed after the battle is over.
----
User input correct

----
User input is incorrect (requires user to re-enter)

----
#### Prompt:
After the selection of the first attack and the attack, before the start of the battle, the data of the first attack and the attack can be taken out, so that it can be used during the battle.
----

---
## Thinking - If for loop...
For (into the loop narrative; judgment sentence; loop narrative) { ... }
What happens if "into the loop narrative sentence", "judgment sentence", and "circular narrative sentence" do not fill in anything or not?
---
## Thinking - The greatest common factor - Division method
----
a, b's greatest common factor (GCD),
Study to see how the program works.
```c=
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a, b, gcd;
scanf("%d%d", &a, &b);
while(a != 0 && b != 0)
if(a >= b)
a = a % b;
else if(b > a)
b = b % a;
gcd = a + b;
printf("The greatest common factor is %d\n", gcd);
}
```
----
Think about other ways of writing??
---
###### tags: `108 Ai-Mod-Eng-LKL`
{"metaMigratedAt":"2023-06-15T01:38:27.215Z","metaMigratedFrom":"YAML","title":"W5 - Loop Control","breaks":true,"slideOptions":"{\"transition\":\"slide\"}","contributors":"[{\"id\":\"befaa4d9-75b6-4c05-baa7-7949e0ffa1e2\",\"add\":17065,\"del\":3618}]"}