w3- c fundamentals (2)

40
C Fundamentals (2) Program Design (I) 2021 Fall Fu-Yin Cherng Dept. CSIE, National Chung Cheng University

Upload: others

Post on 15-Jan-2022

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: W3- C Fundamentals (2)

C Fundamentals (2)Program Design (I)

2021 Fall Fu-Yin Cherng

Dept. CSIE, National Chung Cheng University

Page 2: W3- C Fundamentals (2)

Important notice about Homework 1

● Due: 2021/10/5 13:00pm● Remember to upload your homework in pdf format to your Github repo linked

to our Github classroom

** the program exercise in quiz section is not the homework, so you still need to hand in your homework even if you pass the demo in quiz section of that week**

2

Page 3: W3- C Fundamentals (2)

Please enrolled in quiz sections (實習課)

● Except for very few students, please enroll in one of the quiz sections if you enroll in this course

○ 410410092 陳美杉 資工系

○ 410515045 邱郁珊 財金系

3

Page 4: W3- C Fundamentals (2)

Information to Team 5 of the Quiz Section on Monday

● Your TA has emailed you a link of the Line group for the quiz section

● Please remember to check your email 😉

4

Page 5: W3- C Fundamentals (2)

In next week, after 10/3,

● Still remote lessons for the Program Design (1) using the same Google meeting room

○ We just have too many students to do physical lessons 😅● However, the quiz section will be in-person at Room 341, Innovation Building

(創新大樓341)○ We will separate each team in different corners of the classroom○ Make sure you wear a mask during the entire quiz section○ For those who can’t attend quiz section in person, TA of your team will help you to join the

group online

5

Page 6: W3- C Fundamentals (2)

Where is the Room 341, Innovation Building (創新大樓341)?

● Google map: https://goo.gl/maps/mV3HVcQL2VWfhQAn8● Please arrive at the innovation building earlier so that you will have more time

to find Room 341● Since the innovation building might be dark at night, it’s a good idea to find

your teammates and go to Room 341 together :) ● Moreover, because innovation building may only allow people of CS dept.

during night time, we will suggest those of other dept. contact your teammate who is from CS dept. so that you can enter the innovation building.

6

Page 7: W3- C Fundamentals (2)

Outline

● Printing the Value of a Variable● Reading Input● Definining Names for Constants● Identifiers● Layout of a C program

7

Page 8: W3- C Fundamentals (2)

Printing the Value of a Variable

● printf can be used to display the current value of a variable.● To write the message:

○ where h is the current value of the height variable● We use the following call

8

Height: h

printf("Height: %d\n", height);

%d is a placeholder indicating where the value of height is to be filled in.

Page 9: W3- C Fundamentals (2)

Printing the Value of a Variable

● %d works only for int variables; to print a float variable, use %f instead.● By default, %f displays a number with six digits after the decimal point.● To force %f to display p digits after decimal point, put .p between % and f.

○ for example, %.2f (2 digits), %.6f (6 digits)

9

//Profit: $2150.4812

printf("Profit: $%.2f\n", profit); //output: 2150.48

printf("Profit: $%.4f\n", profit); //output: 2150.4812

Page 10: W3- C Fundamentals (2)

Printing the Value of a Variable

● There’s no limit to the number of variables that can be printed by a single call of printf

10

printf("Height: %d Length: %d\n", height, length);

Page 11: W3- C Fundamentals (2)

Printing Expressions

● printf can display the value of any numeric expression.

11

volume = height * length * width;

printf("%d\n", volume);

printf("%d\n", height * length * width);

Page 12: W3- C Fundamentals (2)

Reading Input

● scanf is the C library’s counterpart to printf.● scanf requires a format string to specify the appearance of the input data.

○ f for printf and scanf stands for ”formatted”○ printf and scanf required format string to specify the input/output data (the shape of data)

● The & symbol is usually (but not always) required when using scanf○ hard to explain the meaning of & now, so just remember to add it when using scanf

12

printf("Height: %d Length: %d\n", height, length);

scanf("%d", &i);

tell the printf that that output data is two integar (%d)

reads an integer (%d); stores into i users will input data

Page 13: W3- C Fundamentals (2)

Reading Input

● Like printf, reading a float value requires a slightly different call of scanf● %f tells scanf to look for an input value in float format

○ the input number may contain a decimal point, but doesn’t have to○ for example, 9.1 or 9 (9.0)

13

scanf("%f", &x); reads an float (%f); stores into x

users will input float data

Page 16: W3- C Fundamentals (2)

Initialization

● A variable that doesn’t have a default value and hasn’t yet been assigned a value by the program is said to be uninitialized.

● Attempting to access the value of an uninitialized variable may yield an unpredictable result.

○ With some compilers, worse behavior—even a program crash—may occur.

16

declare a box without initializing it open/use a box without initialization(you don’t know what will be inside the box/variable)

Page 17: W3- C Fundamentals (2)

Initialization

● The initial value of a variable may be included in its declaration● Any number of variables (with same type) can be initialized in the same

declaration● Each variable requires its own initializer.

17

int height = 8; 👍int height = 8, length = 12, width = 10; 👍int height, length, width = 10; // initializes only width 👎

Page 18: W3- C Fundamentals (2)

Defining Names for Constants

● What is constants? There are some contant value may be use multiple times during calculation

○ pi (3.1415), 12 months, 365 days, …● If you directly use these value in your program, the statements may not be clear to

someone reading the program.○ x / 12 (what is 12 stands for?)

● Using a feature known as macro definition, we can name constants○ macro (宏) vs micro (微)

18

#define MONTHS_PER_YEAR 12

int main(void){

int x = 24;

int year = 0;

year = x / MONTHS_PER_YEAR;

}easy to understand we want to compute the number of years

directives

the rest part of program knew the definition of MONTHS_PER_YEAR

Page 19: W3- C Fundamentals (2)

Defining Names for Constants

● When a program is compiled, the preprocessor replaces each macro by the value that it represents.

19

#define MONTHS_PER_YEAR 12

int main(void){

int x = 24;

int year = 0;

year = x / MONTHS_PER_YEAR;

//after preprocessing: year = x / 12;

return 0;

}

directives

replace

Page 20: W3- C Fundamentals (2)

Defining Names for Constants

● The value of a macro can be an expression● If it contains operators, the expression should be enclosed in parentheses.● Using only upper-case letters in macro names is a common convention.

20

#define MONTHS_PER_YEAR 12

#define RECIPROCAL_OF_PI (1.0f / 3.14159f)

operator (division)

Page 21: W3- C Fundamentals (2)

#define MONTHS_PER_YEAR 12

int main(void){

int x = 24;

int year = 0;

year = x / MONTHS_PER_YEAR;

return 0;

}

Identifiers

● What is identifiers?● Names for variables, functions, macros, and other entities are called identifiers.

21

Page 22: W3- C Fundamentals (2)

Identifiers

● An identifier may contain letters, digits, and underscores, but must begin with a letter or underscore

○ for example, times10 get_next_char○ It’s usually a best practice to avoid identifiers that begin with an underscore (e.g., _done)

● Examples of illegal identifiers:○ 10times (why? ○ get-next-char (why?

22

Do you know why?

Page 23: W3- C Fundamentals (2)

Identifiers

● An identifier may contain letters, digits, and underscores, but must begin with a letter or underscore

○ for example, times10 get_next_char○ It’s usually a best practice to avoid identifiers that begin with an underscore (e.g., _done)

● Examples of illegal identifiers:○ 10times (begin with digit, not a letter or underscore ○ get-next-char (contains minus signs, not underscore

23

Page 24: W3- C Fundamentals (2)

Identifiers

● C is case-sensitive● it distinguishes between upper-case and lower-case letters in identifiers.● For example, the following identifiers are all different● However, a good programmer will try to make identfiers look different unless

they are related

24

job joB jOb jOB Job JoB JOb JOB

Are you sure you can tell that job is different identifiers from jOb in a short time?

Page 25: W3- C Fundamentals (2)

Identifiers - Naming conventions

● Many programmers use only lower-case letters in identifiers (other than macros), with underscores inserted for legibility (易讀性)○ symbol_table current_page name_and_address

● Other use an upper-case letter to begin each word within an identifier:○ symbolTable currentPage nameAndAddress

● Either one is good, just ensure that you stick to one naming convention

● There is no limit on the maximum length of an identifier! So don’t be afraid to use long and descriptive names to write understandable code○ current_page is a lot easier to understand than a cp

25

Page 26: W3- C Fundamentals (2)

Identifiers - Keywords

● The following keywords can’t be used as identifiers● Also avoid the identifiers in the standard library (e.g., printf and scanf)

26

auto enum restrict* unsignedbreak extern return voidcase float short volatilechar for signed whileconst goto sizeof _Bool*continue if static _Complex*default inline* struct _Imaginary*do int switchdouble long typedefelse register union

usually can avoid this issue by using long and descriptive names

Page 28: W3- C Fundamentals (2)

Layout of a C Program

● A C program is a series of tokens.○ group of characters that can’t be split up without changing their meaning○ for example, printf() is different from print f() (and you’ll get error message by using

this one!)● For example, identifiers, keywords, operators (+, -), punctuation mark (,),

string literals (“Hello CCU.”) ● There are 7 tokens in the following line, can you label all the token?

28

printf("Height: %d\n", height);

Page 29: W3- C Fundamentals (2)

Layout of a C Program

29

printf ( "Height: %d\n" , height ) ;1 2

● A C program is a series of tokens.○ group of characters that can’t be split up without changing their meaning○ for example, printf() is different from print f() (and you’ll get error message by using

this one!)● For example, identifiers, keywords, operators (+, -), punctuation mark (,),

string literals (“Hello CCU.”) ● There are 7 tokens in the following line, can you label all the token?

Page 30: W3- C Fundamentals (2)

Layout of a C Program

30

printf ( "Height: %d\n" , height ) ;1 23

● A C program is a series of tokens.○ group of characters that can’t be split up without changing their meaning○ for example, printf() is different from print f() (and you’ll get error message by using

this one!)● For example, identifiers, keywords, operators (+, -), punctuation mark (,),

string literals (“Hello CCU.”) ● There are 7 tokens in the following line, can you label all the token?

Page 31: W3- C Fundamentals (2)

Layout of a C Program

31

printf ( "Height: %d\n" , height ) ;1 234 5 6 7

● A C program is a series of tokens.○ group of characters that can’t be split up without changing their meaning○ for example, printf() is different from print f() (and you’ll get error message by using

this one!)● For example, identifiers, keywords, operators (+, -), punctuation mark (,),

string literals (“Hello CCU.”) ● There are 7 tokens in the following line, can you label all the token?

Page 32: W3- C Fundamentals (2)

Layout of a C Program

● Amount of space between tokens isn’t critical in most cases○ the following three lines are identical in a C program

● Adding spaces and blank lines to a program can make it easier to read and understand

● But, how should we add spaces and blank lines between tokens exactly?

32

printf ( "Height: %d\n" , height ) ;

printf( "Height: %d\n", height) ;

printf("Height: %d\n",height);

Page 33: W3- C Fundamentals (2)

Layout of a C Program

33

● A C program is a series of tokens.○ group of characters that can’t be split up without changing their meaning○ for example, printf() is different from print f() (and you’ll get error message by using

this one!)● That’s why CS people usually don’t put space in their user name, filenames,

and almost any other names. Since we know how a computer reads and understands.

○ Fuyin Cherng -> Fuyin_Cherng or FuyinCherng (so that the PC can recognize it as one token)

Page 34: W3- C Fundamentals (2)

Layout of a C Program

1. We can divide long statements into multiple lines. Some statements is just too long to put in one line

34

printf(“Dimensional weight (pounds): %d\n”,

(volume + INCHES_PER_POUND - 1)/ INCHES_PER_POUND)

notice that the blank line is between two token , and (

Page 35: W3- C Fundamentals (2)

Layout of a C Program

2. Add space between tokens makes it easier to separate them and make them stand out

35

volume = height * length * width;

volume=height*length*width;

which one is better?

Page 36: W3- C Fundamentals (2)

Layout of a C Program

3. Indentation (縮排) make nesting easier to spot. For example, we should indent statements to make it clear that they’re nested inside main

36

int main(void){

int height = 8;

int width = 10;

return 0;

}

int main(void){

int height = 8;

int width = 10;

return 0;

}

Which one is better?

Page 37: W3- C Fundamentals (2)

Layout of a C Program

37

4. Blank lines can divide a program into logical units, easier to tell the program’s structure. A programwith no blank lines is like a book with no chapter

#define MONTHS_PER_YEAR 12

int main(void){

int x = 24;

int year = 0;

year = x / MONTHS_PER_YEAR;

return 0;

}

#define MONTHS_PER_YEAR 12

int main(void){

int x = 24;

int year = 0;

year = x / MONTHS_PER_YEAR;

return 0;

}

Page 38: W3- C Fundamentals (2)

Layout of a C Program

38

#define MONTHS_PER_YEAR 12

int main(void){

int x = 24;

int year = 0;

year = x / MONTHS_PER_YEAR;

return 0;

}

#define MONTHS_PER_YEAR 12

int main(void){

int x = 24;

int year = 0;

year = x / MONTHS_PER_YEAR;

return 0;

}

directives

declaration, initialization

end of program

calculation

4. Blank lines can divide a program into logical units, easier to tell the program’s structure. A programwith no blank lines is like a book with no chapter

Page 39: W3- C Fundamentals (2)

39https://github.com/TheAlgorithms/C/blob/master/sorting/bubble_sort.c

Page 40: W3- C Fundamentals (2)

Summary

● Printing the Value of a Variable○ int: %d, float: %f

● Reading Input○ scanf

● Definining Names for Constants○ #define MONTHS_PER_YEAR 12

● Identifiers○ naming rules: an identifier may contain letters, digits, and underscores, but must begin with a

letter or underscore○ C is case sensitive

● Layout of a C program

40