c fundamentals
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 PresentationTRANSCRIPT
C Fundamentals
Chapter 2
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.
3
Writing a Simple Program
#include <stdio.h>int main(){ printf("Hello World!\n"); return 0; }
directives
statements function call
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
5
Writing a Simple Program
#include <stdio.h>int main(){ printf("Hello World!\n"); return 0; }
function
return value of the main function
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
7
printf() – 換行符號 \n 換行符號 (newline)• printf("Welcome to C!\n");Execution result
• printf("Welcome\nto\nC!");Execution result
Welcome to C!_
WelcometoC!_
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.)
_
9
Remember to Print Spaces!
• printf("Welcome");printf("to");printf("C!\n");
Execution result:WelcometoC!_
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
11
printf• Try to print out:
$ $$$ $$$$$$$$$$$$
printf(" $\n");printf(" $$$\n");printf(" $$$$$\n");printf("$$$$$$$\n");
12
printf• Try to print out:
JJ JJ J JJJJJJJJJ
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; }
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
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;
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 * ************************************/
17
Comments ( 註解 )• Examples
int main(){ int price; /* 價錢 */ int tip; // 服務費 price = 500; /* 價錢是 500 元 */ tip = 50; // 小費 50 元 int total = price + tip; /* 應付總額 */ return 0;}
18
Comments ( 註解 )• Examples
int main(){ int price; /* 價錢 ( 這個註解忘了結束 ) int tip; // 服務費 price = 500; /* 價錢是 500 元 ( 註解才結束 )*/ tip = 50; // 小費 50 元 int total = price + tip; /* 應付總額 */ return 0;}
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
20
Variable Declaration ( 宣告變數 )• Variables must be declared.
• Declaration: varType varName;Ex: int score;score: name of the variableint declares that score is an integer
21
Variable Declaration
• Examples
int main(){ int price; /* 價錢 */ int tip; // 服務費 price = 500; /* 價錢是 500 元 */ tip = 50; // 小費 50 元 return 0;}
declarations
statements
22
Variable Declaration
• A variable must be declared before using it.Ex:int score;score = 95; ()
Ex:score = 95;int score; ()
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.
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怪怪
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
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 。
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
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;
29
Print Out an Integer
#include <stdio.h>
int main(){ int score; score = 85; printf(" 成績是: %d\n", score);
return 0;} 用 %d 來印出整數資料
逗號 要印出的變數
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;}
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;}
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;}
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;}
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
35
2.5 Reading Input
• Syntax:
scanf("%f", &varName);
– Ex: scanf("%f", &radius);&
A floating-point variable
36
2.6 Defining Constants
• 語法#define 常數巨集名稱 所要取代成的文字– Ex: 定義常數#define PI 3.14159
• 所有出現的地方,都會被取代成要取代的文字– Ex:int area = r * r * PI ;
3.14159
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;}
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;}
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.
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
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.
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
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
44
Layout of a C Program
• A C program is a series of tokens.
• Tokens include:– Identifiers– Keywords– Operators– Punctuation– Constants– String literals
45
Layout of a C Program
• The statement
printf("Height: %d\n", height);
consists of seven tokens.
Tokens:IdentifiersKeywordsOperatorsPunctuationConstantsString literals
identifiers punctuationsString literals
46
Layout of a C Program
• The statement
int inch = feet * 12;
consists of seven tokens.
Tokens:IdentifiersKeywordsOperatorsPunctuationConstantsString literals
identifiers punctuations
operatorskeywords constants
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.
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;}
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.
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