# #C Programming (I) - 3
## Variable operation
English: Lei KuoLiang
nicolaslouis@mail.fcu.edu.tw
Chinese(TW): Wang M.H
---
### This week's course catalog
0. Review
Operator (operator)
* Arithmetic operator
* Assign operator (assignment operator)
* Incremental decrement operator
* bit operator
2. ASCII code
3. scanf - read variables, but not save
---
## Last week's course review
----
|type | byte | format specified word
| -------- |- |--
| char| 1 |%hhd(integer)/%c(character)
| int| 4 |%d
| long long int| 8 |%lld
| float | 4 |%f
| double | 8 |%lf
* long long int can also be omitted, written as long long
----
* printf()
* Format: printf ("output format", variable 1, variable 2, ...);
The variables to be output are filled in sequentially according to the format specified words (%d, %f...) in the output format.
* Understand the changes in the format specified words, such as %+5d, %-6d, %.3f, %05.2f, etc.
* scanf()
* Format: scanf ("input format", & variable 1, & variable 2, ...);
Note that scanf needs to add & in front of the variable, and take the memory address, the computer knows which address to store the data.
* Note that you don't need to use \n when the end of the input format
---
## Operator (operator)
* Arithmetic operator
* Assign operator (assignment operator)
* Incremental decrement operator
* bit operator
-----
* Relational operator (next week course)
* Logical operator (next week course)
---
### Arithmetic operator
| Name | Operator | For example |
| -------- | -------- | -------- |
Addition | `+` | `a + b` |
| Subtraction | `-` | `a - b` |
Multiplication | `*` | `a * b` |
| Division | `/` | `a / b` |
| remainder (mod) | `%` | `a % b` (a, b are integers) |
| Brackets | `()` | `a / (b + C)` |
----
The rules are the same as mathematics. Add and subtract after multiplication and division, and parentheses must be calculated first, from left to right.
The remainder (mod) is the same as the multiplication and division.
----
### Note the integer type division
In C, integer/integer results are still integers, so integer division only preserves the integer part, and the fractional part is automatically rounded off.
The result of floating point / integer, integer / floating point, floating point / floating point number will be a floating point number, retaining the integer and fractional parts.
(Please refer to the final supplement of the briefing for the solution)
---
### Assign operator (assignment operator)
The = that we used before declaring variables is the assignment operator.
In the C language, =** is not ** mathematically equal, equal meaning, but the meaning of assignment, assignment, please pay more attention to this point.
Operator | Example | Explanation
-|-|-
`=`|`a = b`| assign the value of b to a
The order of assigning operators is from right to left (= the calculation of the right is calculated first, and then the result is given to the variable on the left)
----
#### More extension
Operator | Example | Explanation
-|-|-
`+=`|`a += b`|`a = a + b`
`-=`|`a -= b`|`a = a - b`
`*=`|`a *= b`|`a = a * b`
`/=`|`a /= b`|`a = a / b`
`%=`|`a %= b`|`a = a % b`
---
### Exercise 1
Give the prompt to let the user input the formula of adding, dividing, and taking the remainder in order, and use integer type operation and output. Sample results:
```
Input addition formula: 12+24 // output "input addition formula:" and let the user input
12+24=36 //output the result of the operation, and so on
Input division formula: 50/12
50/12=4
Enter the remainder calculation formula: 110%17
110% 17=8
```
---
## Incremental decrement operator
When writing a program, we often need to use a = a + 1 operation.
Since incrementing and decrementing are too common, they are separated into an arithmetic symbol.
Increment: \+\+a, a\+\+ Decrement: \-\-a, a\-\-
----
++ and \-\- write before and after the variable is different!
```c=
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a = 5, b = 5;
printf("a = %d\n", a++); //When ++ is placed behind, it will run first and then +1.
printf("a = %d\n", a);
printf("b = %d\n", ++b); //When ++ is placed in front, it will run +1 first.
printf("b = %d\n", b);
return 0;
}
```
Results of the
```
a = 5
a = 6
b = 6
b = 6
```
----
Example 2
```c=
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a = 3, b = 5, p, q;
p = a + b++; //When ++ is placed behind, it will run first and then +1.
q = a + ++b; //When ++ is placed in front, it will run +1 first.
printf("p = %d\n", p);
printf("q = %d\n", q);
return 0;
}
```
Results of the
```
p = 8 //First execute a+b=3+5=8, assign 8 to p, then execute b++, then b=6
q = 10 //First execute ++b, b=7, then execute a+b=3+7=10, and assign 10 to q.
```
---
## n carry
Before learning the bit operator, you must first understand the n carry.
Last week, when teaching integer output, %d, %o, and %x were mentioned, which are 10-bit, 8-bit, and 16-bit output modes.
----
In fact, in the C language, we can not only use 10 decimal to represent integers, but also use 2, 8, and 16 carry to represent integers.
n carry | Number at the beginning
-|-
2 carry (binary) | 0b
8 carry (octal) | 0
10 decimal (decimal) | (none)
16 carry (hexadecimal)| 0x
Note that C language does not support direct input and output with 2-bit integers.
----
```c=
#include <stdio.h>
#include <stdlib.h>
int main()
{
int bin, oct, dec, hex;
bin = 0b1010;
oct = 01010;
dec = 1010;
hex = 0x1010;
printf("bin = %d oct = %d dec = %d hex = %d\n",
bin, oct, dec, hex); //1 narrative is too long to be divided into multiple lines
return 0;
}
```
Results of the
```
bin = 10 oct = 520 dec = 1010 hex = 4112
```
---
## Bit operator
| Operator | Name | Syntax |
| -------- | -------- | -------- |
| `&` | Bit AND | `a & b` |
| `|` | Bit OR | `a | b` |
| `^` | Bit XOR | `a ^ b` |
| `~` | 1's complement| `~a` |
| `<<` | left shift | `a << n` |
| `>>` | right shift| `a >> n` |
----
| Bits AND|&| 0 | 1 |
| -------|- | -------- | -------- |
|(As long as there are 0 results, it is 0)| **0** | 0 | 0 |
| |**1** | 0 | 1 |
```c=
#include <stdio.h>
#include <stdlib.h>
int main()
{
char val1 = 0b00101100;
char val2 = 0b11000111;
printf("%d\n", val1 & val2);
return 0;
}
```
Results of the
```
4 //0000 0100
```
----
| Bit OR |\|| 0 | 1 |
| ------|-- | -------- | -------- |
| |**0** | 0 | 1 |
|(As long as 1 result is 1) |**1** | 1 | 1 |
```c=
#include <stdio.h>
#include <stdlib.h>
int main()
{
char val1 = 0b00101100;
char val2 = 0b11000111;
printf("%d\n", val1 | val2);
return 0;
}
```
Results of the
```
-17 //1110 1111
```
----
| Bit XOR|^ | 0 | 1 |
| -------|- | -------- | -------- |
| (same as 0 instead of 1) |**0** | 0 | 1 |
| | **1** | 1 | 0 |
```c=
#include <stdio.h>
#include <stdlib.h>
int main()
{
char val1 = 0b00101100;
char val2 = 0b11000111;
printf("%d\n", val1 ^ val2);
return 0;
}
```
Results of the
```
-21 //1110 1011
```
----
| 1 complement ~ | 0 | 1 |
| -------- | -------- | -------- |
| (opposite) | 1 | 0 |
```c=
#include <stdio.h>
#include <stdlib.h>
int main()
{
char val = 0b00101100;
printf("%d\n", ~val1);
return 0;
}
```
Results of the
```
-45 //1101 0011
```
----
## >> 、 << (shift)
* The left shift operator `<<` will shift all the bits to the left by the specified number of digits. The left-extracted bit will be discarded and the right will be padded with 0.
* Right shift operator `>>` will move all the bits to the right by the specified number of digits. The bit that is squeezed out on the right will be discarded. As for the left bit, 0 or 1 is not necessary:
If the variable is declared as `unsigned`, it will be filled with 0 (logical shift)
Otherwise, the number of the complement is the same as the original highest digit (arithmetic shift)
---
### Exercise 2
Use bitwise operations (&, |, ^, <<, >>, ~)
Take the last 4 bits of val1 and the first 4 bits of val2, and finally merge them. (not necessarily declared with int)
```c
int val1 = 0b01100001; //0x61 = 0110 0001
int val2 = 0b00111010; //0x3a = 0011 1010
//Bit operation↓
int ans = 0x6a; //0x6a = 0110 1010
```
```
val1 = 61
val2 = 3a
ans = 6a
```
---
## ASCII code
* American Standard Code for Information Interchange, referred to as ASCII, pronounced ass-kee.
* It is a standard code exchange standard code, a kind of coding method for information transmission.
* In C language, char is based on this table to compare characters with integers.
* In memory, char is stored in integer form, and it is determined by %c or %hhd whether the output type is to be converted into the corresponding character.
----
[Click here to link to the chart](https://i.imgur.com/nI1eeN4.png)
ASCII code contains two parts
* Control characters (0~31)
* Includes invisible jump characters such as '\n', '\t', '\a'
* Displayable characters (32~127)
* Includes 0\~9, A\~Z, a\~z, punctuation
* '0' = 48, 'A' = 65, 'a' = 97
----
### Skip character
|character |dec|oct|hex|description|
|-|-|-|-|-
\a |7|007|07|alert bell
\b |8|010|08|backspace
==\t== |9|011|09|horizontal tab
==\n== |10|012|0a|newline
\v |11|013|0b|vertical tab
\f |12|014|0c|formfeed(page change)
\r |13|015|0d|carriage return
----
### Skip character
|character |dec|oct|hex|description|
|-|-|-|-|-
==\\"== |34|042|22|double quotes
==\\'== |39|047|27|Single quotes
==\\\\== |92|134|5c|Backslash
\ddd ||ddd||8 carry ASCII code
\xdd |||dd|16 carry ASCII code
---
## scanf - Read variables but not save
----
Sometimes, when we read the user's input, we must ignore some information. For example, if we want to repeatedly read the characters entered by the user, if the user is allowed to input line by line, as follows
```
a
b
C
```
The data stream for scanf will be:
```
a\nb\nc\n
```
If you use %c to read repeatedly, you will read the '\n' that you don't need to read.
----
At this time, add \* (for example, %\*c) after the % of the format specified word (for example: %c), the scanf will read the data, but not the variable.
----
When not using *:
```c=
#include <stdio.h>
#include <stdlib.h>
int main()
{
char word;
scanf("%c", &word);
printf("%d\n", word);
scanf("%c", &word);
printf("%d\n", word);
return 0;
}
```
Results of the
```
A //Input "A\n", read 'A' on line 7, put '\n' into buffer
65 //'A'
10 //'\n', line 9 reads the '\n' of the buffer directly and prints it on line 10.
```
----
When using *:
```c=
#include <stdio.h>
#include <stdlib.h>
int main()
{
char word;
scanf("%c%*c", &word); //%*c will ignore the next character of %c
printf("%d\n", word);
scanf("%c", &word);
printf("%d\n", word);
return 0;
}
```
Results of the
```
A //Entered "A\n"
65 //'A'
B //Entered "B\n"
66 //'B'
```
---
### Exercise 3
Observe the distance between the uppercase and lowercase letters of the ASCII code table, and then write a program to let the user input a lowercase English word and convert it to uppercase. This action is repeated twice. Sample results:
```
Please enter a lowercase English letter: k
The uppercase of k is K
Please enter a lowercase English letter: j
The capital of j is J
```
---
## Homework - 1
From the last week's homework modification, the character strength prediction is printed on the next line of the role information (in 2 decimal places)
```
Intensity prediction = ( blood volume * 1.0 + attack * 0.8 + defense * 0.5 - 50 ) * 6.5
```
----
```
Role 1
Name: Han Dao
Attribute: W Attack: 15
Blood volume: 50 Defense: 5
Character strength prediction: 94.25
Role 2
Name: Yasna
Attribute: A Attack: 20
Blood volume: 40 Defense: 8
Role strength forecast: 65.00
Role 3
Name: Rem
Attribute: F Attack: 17
Blood volume: 45 Defense: 7
Character strength prediction: 78.65
Add role // here let the user enter
Attribute: F
Blood volume: 46
Attack: 18
Defense: 10
Role 4
Name: Custom Role
Attribute: F Attack: 18
Blood volume: 46 Defense: 10
Role strength prediction: 100.10
```
---
## Homework - 2
----
Xiao Ming, who graduated from college, is reviewing his "European" record for his four-year career at the university. He thinks that a char only accounts for 8 bits of memory, and the university has just 8 semester in 4 years (first year, big one, sophomore, sophomore...). If you can use a char to record the "European" status of the university for a total of 8 semesters, it is really too memory space!
※Note: European means that no class was destroyed during the semester.
----
The following is a summary of the Xiao Ming 4 years of course events:
```
1. When I was a little older, Xiao Ming had too many classes because of calculus. At the end of the period, she took 58 points and was taken down.
2. When I was a sophomore, I did cryptography, but because I had to count a lot of mathematics, I was wrong. I took 57 points and was taken.
3. At the end of the semester on the sophomore year, go to the cryptographer’s office and ask him for help. The teacher helped him add 60 points.
4. In the junior year, because I was sleeping in English class, I took 50 points at the end of the period and was taken down.
5. During the senior year, I studied deep learning, but the learning situation was not good. I only took 40 points at the end of the period and was taken out.
```
----
### Request Description - 1
* Ask the students to write a program that uses a char variable to record the 8 semester of the semester of Xiao Ming. The first bit records the freshman, the second bit records the big one, and so on.
* For each bit of char, 1 means Euro, and 0 means no Euro.
* From the events listed on the previous page, each event must be written with the appropriate code.
* At the end of the program, print out the big ones under the big ones (see the output example below for details).
----
### Request Description - 2
* In the code, please note the ++ event number and content ++** corresponding to the code ** in the previous line of the code.
* In the code, ++ can not use ++ arithmetic operators, please use the bit operator (&, |, ^, >>, <<, ~).
----
### Output example
```
Freshman Spring Semester: 1
Freshman Fall Semester: 0
Sophomore Spring Semester: 1
Sophomore Fall Semester: 1
Junior Spring Semester: 0
Junior Fall Semester: 1
Senior Spring Semester: 0
Senior Fall Semester: 1
```
---
## Supplement - type conversion
Make the result of an integer/integer a decimal
----
As mentioned earlier, integer/integer results are still integers, so integer division only preserves the integer part, and the fractional part is automatically rounded off.
The result of floating point / integer, integer / floating point, floating point / floating point number will be a floating point number, retaining the integer and fractional parts.
----
The solution is then to temporarily convert one of the integers into a floating point number.
----
Use the (variable type) variable to temporarily convert the variable type:
```c
int value = 5;
printf("%f\n", (float)value);
```
The output will be "5.000000" and the output success represents a true temporary transition.
----
Convert (variable) variables to this conversion:
```c
int a = 5, b = 2;
printf("%d、%f\n", a / b, (float)a / b);
```
The output will be "2, 2.500000"
* The first result is an integer / integer = integer
* The second result is because the a is converted to a float, becomes a floating point number / integer = floating point number, the answer becomes a float form
---
###### tags: `108 Ai-Mod-Eng-LKL`
{"metaMigratedAt":"2023-06-15T01:36:57.916Z","metaMigratedFrom":"YAML","title":"W3 - Variable operation","breaks":true,"slideOptions":"{\"transition\":\"slide\"}","contributors":"[{\"id\":\"befaa4d9-75b6-4c05-baa7-7949e0ffa1e2\",\"add\":19639,\"del\":3905}]"}