c fundamentals

50
C Fundamentals Chapter 2

Upload: sheila-harris

Post on 02-Jan-2016

15 views

Category:

Documents


1 download

DESCRIPTION

C Fundamentals. Chapter 2. Printing a Pun. #include int main() { printf("To C, or not to C: that is the question.\n"); return 0; }. To C, or not to C: that is the question. Writing a Simple Program. directives. #include int main() { - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: C Fundamentals

C Fundamentals

Chapter 2

Page 2: C Fundamentals

2

Printing a Pun#include <stdio.h>

int main(){ printf("To C, or not to C: that is the question.\n"); return 0; }

To C, or not to C: that is the question.

Page 3: C Fundamentals

3

Writing a Simple Program

#include <stdio.h>int main(){ printf("Hello World!\n"); return 0; }

directives

statements function call

Page 4: C Fundamentals

4

Function

• Borrowed from math

• But not only numerical functions

f(x) = x + 1g(y, z) = y2 – z2

int main(){ int a, b; a = f(7); b = g(a, 3);}

int f(int x){ return x + 1;}

int g(int y, int z){ return y * y – z * z;}

return valueof a function

Page 5: C Fundamentals

5

Writing a Simple Program

#include <stdio.h>int main(){ printf("Hello World!\n"); return 0; }

function

return value of the main function

Page 6: C Fundamentals

6

printf() Function• Syntax: printf("your message");

Ex: printf("Welcome to C!\n");Quoted the message with " ".Message can be in Chinese as well.Ex: printf(" 中文嘛也通喔 \n");

中文嘛也通喔_

Execution result

Page 7: C Fundamentals

7

printf() – 換行符號 \n 換行符號 (newline)• printf("Welcome to C!\n");Execution result

• printf("Welcome\nto\nC!");Execution result

Welcome to C!_

WelcometoC!_

Page 8: C Fundamentals

8

• Tips– Without a newline, the message will not break

into two lines. For example, printf(“Hello World!"); printf(“Welcome to C!");

Execution result: Hello World!Welcome to C!

printf() Function (Cont.)

_

Page 9: C Fundamentals

9

Remember to Print Spaces!

• printf("Welcome");printf("to");printf("C!\n");

Execution result:WelcometoC!_

Page 10: C Fundamentals

10

Font Width

• Width of a symbol is fixed in some fonts but varied in other fonts.– Lucida Console abcdefghijkabcdefghijk

– Times New Roman abcdefghijk

abcdefghijkl

Page 11: C Fundamentals

11

printf• Try to print out:

$ $$$ $$$$$$$$$$$$

printf(" $\n");printf(" $$$\n");printf(" $$$$$\n");printf("$$$$$$$\n");

Page 12: C Fundamentals

12

printf• Try to print out:

JJ JJ J JJJJJJJJJ

Page 13: C Fundamentals

13

2.3 Comments ( 註解 )• Documentation of a program• Make the program more readable

/* Name: hello.c *//* Purpose: prints my first message *//* Author: me */#include <stdio.h>int main(){ printf("Hello World!\n"); return 0; }

Page 14: C Fundamentals

14

Comments ( 註解 )• Two formats

/* All text in between is a comment, no matter how long */

• Starts with /* and end with */• Can be one line or multiple lines

// here after is a comment• A new comment format in C99

Page 15: C Fundamentals

15

Comments (Cont.)

• Examples Statement; /* a comment here */

/* * a comment again */ but not a comment here

/************************************ A more fancy comment. Always seen in the beginning of a program to record its history... *************************************/

turn++; // comment on why turn++ not a comment next line;

Page 16: C Fundamentals

16

Comments (Cont.)

• /* Name: hello.c *//* Purpose: prints my first message *//* Author: me */

• /* Name: hello.c Purpose: prints my first message Author: me */

• /* Name: hello.c * Purpose: prints my first message * Author: me */

• /************************************ * Name: hello.c * * Purpose: prints my first message * * Author: me * ************************************/

Page 17: C Fundamentals

17

Comments ( 註解 )• Examples

int main(){ int price; /* 價錢 */ int tip; // 服務費 price = 500; /*  價錢是 500 元 */ tip = 50; // 小費 50 元 int total = price + tip; /* 應付總額 */ return 0;}

Page 18: C Fundamentals

18

Comments ( 註解 )• Examples

int main(){ int price; /* 價錢 ( 這個註解忘了結束 ) int tip; // 服務費 price = 500; /*  價錢是 500 元 ( 註解才結束 )*/ tip = 50; // 小費 50 元 int total = price + tip; /* 應付總額 */ return 0;}

Page 19: C Fundamentals

19

2.4 Variables ( 變數 )• Type

A variable of type int can store an integer, e.g. 1392, 0, -2553

A variable of type float can store a real number (stored in the floating-point fashion), e.g. 34.124, -45.435, 0,NOTE: float is just an approximation of the number0.1 would become 0.09999999999999987

Page 20: C Fundamentals

20

Variable Declaration ( 宣告變數 )• Variables must be declared.

• Declaration: varType varName;Ex: int score;score: name of the variableint declares that score is an integer

Page 21: C Fundamentals

21

Variable Declaration

• Examples

int main(){ int price; /* 價錢 */ int tip; // 服務費 price = 500; /*  價錢是 500 元 */ tip = 50; // 小費 50 元 return 0;}

declarations

statements

Page 22: C Fundamentals

22

Variable Declaration

• A variable must be declared before using it.Ex:int score;score = 95; ()

Ex:score = 95;int score; ()

Page 23: C Fundamentals

23

Variable Declaration (Cont.)

• Declare two or more variablesint price;int tip;int total;

int price, tip, total;• Case sensitive

–a1 and A1 are different.

Page 24: C Fundamentals

24

Memory Concepts

• A variable actually corresponds to a location in the memory where its value is stored.– Ex: int score;

• Note: Before assignment, the value in the location is a meaningless value.

score怪怪

Page 25: C Fundamentals

25

Assignment

• Calculate the value of the right side of "=", then assign it to be the new value of the variable in the left side.

• int a;• a = 5;

–執行後 a 的值變成 5• a = 3 + 5;

–執行後 a 的值變成 3 加 5 以後的結果

a怪怪58

Page 26: C Fundamentals

26

Assignment

• a = 5;• a = b + c;• d = 3 * 5 + sum / 2;• d = max(a,b);// return value of max function• a = a + 2;

CError 2.6CError 2.6 放結果的變數是在等號左邊,不能寫成 b + c = a 。

Page 27: C Fundamentals

27

Assignment

• Assume that a's value is 5 at first.

a = a + 2;– a's new value becomes the sum of 2 and the

original value of a

a57

Page 28: C Fundamentals

28

Initializer• You can set initial values when defining.

int price = 450;int tip = 50;int total = price + tip;

int price = 450, tip = 50;int total = price + tip;

int price = 450;int total = price * 1.05;

Page 29: C Fundamentals

29

Print Out an Integer

#include <stdio.h>

int main(){ int score; score = 85; printf(" 成績是: %d\n", score);

return 0;} 用 %d 來印出整數資料

逗號 要印出的變數

Page 30: C Fundamentals

30

Print Out an Integer

#include <stdio.h>

int main(){ int price, tip, total; price = 500; tip = 50; total = price + tip; printf(" 總共要付: %d\n", total); return 0;}

Page 31: C Fundamentals

31

Print Out an Integer

#include <stdio.h>

int main(){ int price, tip, total; price = 500; tip = 50; printf(" 總共要付: %d\n", price + tip); return 0;}

Page 32: C Fundamentals

32

Print Out Many Integers#include <stdio.h>

int main(){ int price, tip, total; price = 500; tip = 50; total = price + tip; printf(" 原價 %d 元 , 小費 %d 元 \n", price, tip); printf(" 總共要付: %d 元 \n", total); return 0;}

Page 33: C Fundamentals

33

Print Out Real Numbers

#include <stdio.h>

int main(){ float radius = 2; float area; area = 3.1416f * radius * radius; printf(" 半徑 %f,\n", radius); printf(" 面積 %.2f\n", area); return 0;}

Page 34: C Fundamentals

34

2.5 Reading Input

• Syntax:

scanf("%d", &varName);

– Ex: scanf("%d", &score);

• The program will read in an integer from the keyboard, then set it as the value of the variable.

&

An integer variable

Page 35: C Fundamentals

35

2.5 Reading Input

• Syntax:

scanf("%f", &varName);

– Ex: scanf("%f", &radius);&

A floating-point variable

Page 36: C Fundamentals

36

2.6 Defining Constants

• 語法#define 常數巨集名稱 所要取代成的文字– Ex: 定義常數#define PI 3.14159

• 所有出現的地方,都會被取代成要取代的文字– Ex:int area = r * r * PI ;

3.14159

Page 37: C Fundamentals

37

Defining Constants#include <stdio.h>

#define PI 3.1416f

int main(){ float radius = 2; float area; area = PI * radius * radius; printf(" 半徑 %f,\n", radius); printf(" 面積 %.2f\n", area); return 0;}

Page 38: C Fundamentals

38

Example: celsius.c#include <stdio.h>

#define FREEZING_PT 32.0f#define SCALE_FACTOR (5.0f / 9.0f)

int main(void){ float fahrenheit, celsius;

printf(" 請輸入華氏溫度 : "); scanf("%f", &fahrenheit); celsius = (fahrenheit - FREEZING_PT) * SCALE_FACTOR; printf(" 換算成攝式溫度 : %.1f\n", celsius);

return 0;}

Page 39: C Fundamentals

39

2.7 Identifiers

• Names for variables, functions, macros, and other entities are called identifiers.

• Legal symbols in an identifier are: English alphabets: abcde…ABCD…Underline: _Digits: 0123456789

But an identifier cannot start with a digit.No other symbol is allowed, including Chinese

characters.

Page 40: C Fundamentals

40

Identifiers

• Examples of illegal identifiers:times10 get_next_char _done

It’s usually best to avoid identifiers that begin with an underscore.

• Examples of illegal identifiers:10times get-next-char

Page 41: C Fundamentals

41

Identifiers

• C is case-sensitive: it distinguishes between upper-case and lower-case letters in identifiers.

• For example, the following identifiers are all different:job joB jOb jOB Job JoB JOb JOB

• C places no limit on the maximum length of an identifier.

Page 42: C Fundamentals

42

Identifiers

• 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 programmers use an upper-case letter to begin each word within an identifier:symbolTable currentPage nameAndAddress

Page 43: C Fundamentals

43

Preserve Words, Keywordsauto 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*C99 only

Page 44: C Fundamentals

44

Layout of a C Program

• A C program is a series of tokens.

• Tokens include:– Identifiers– Keywords– Operators– Punctuation– Constants– String literals

Page 45: C Fundamentals

45

Layout of a C Program

• The statement

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

consists of seven tokens.

Tokens:IdentifiersKeywordsOperatorsPunctuationConstantsString literals

identifiers punctuationsString literals

Page 46: C Fundamentals

46

Layout of a C Program

• The statement

int inch = feet * 12;

consists of seven tokens.

Tokens:IdentifiersKeywordsOperatorsPunctuationConstantsString literals

identifiers punctuations

operatorskeywords constants

Page 47: C Fundamentals

47

Layout of a C Program

• The amount of space between tokens usually isn’t critical.

• At one extreme, tokens can be crammed together with no space between them, except where this would cause two tokens to merge.

Page 48: C Fundamentals

48

Layout of a C Program/* Converts a Fahrenheit temperature to Celsius */#include <stdio.h>#define FREEZING_PT 32.0f#define SCALE_FACTOR (5.0f/9.0f)int main(void){float fahrenheit,celsius;printf("Enter Fahrenheit temperature: ");scanf("%f", &fahrenheit);celsius=(fahrenheit-FREEZING_PT)*SCALE_FACTOR;printf("Celsius equivalent: %.1f\n", celsius);return 0;}

Page 49: C Fundamentals

49

7.3 Escape Sequences

Escape sequence Description

\' Output the single quote (') character.

\" Output the double quote (") character.

\? Output the question mark (?) character.

\\ Output the backslash (\) character.

\a Cause an audible (bell) or visual alert. \b Move the cursor back one position on the current line. \f Move the cursor to the start of the next logical page. \n Move the cursor to the beginning of the next line. \r Move the cursor to the beginning of the current line. \t Move the cursor to the next horizontal tab position. \v Move the cursor to the next vertical tab position.

Page 50: C Fundamentals

Typical C Program Development Environment

Program is created in the editor and stored on disk.Preprocessor programprocesses the code.

Loader puts program in memory.

CPU takes each instruction and executes it, possibly storing new data values as the program executes.

Compiler creates object code and stores it on disk.

Linker links the objectcode with the libraries

.

.

.

.

.

.

.

.

.

.

.

.

Disk

Disk

Disk

Disk

Editor

Preprocessor

Compiler

Linker

Loader

Disk

Memory

MemoryCPU

1. Edit

2. Preprocess

3. Compile

4. Link

5. Load

6. Execute