500 likes | 560 Views
C Fundamentals. Chapter 2. Printing a Pun. #include <stdio.h> int main() { printf("To C, or not to C: that is the question.<br>"); return 0; }. To C, or not to C: that is the question. Writing a Simple Program. directives. #include <stdio.h> int main() {
E N D
C Fundamentals Chapter 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.
Writing a Simple Program directives #include <stdio.h> int main() { printf("Hello World!\n"); return 0; } statements function call
Function • Borrowed from math • But not only numerical functions f(x) = x + 1 g(y, z) = y2 – z2 int f(int x) { return x + 1; } int g(int y, int z) { return y * y – z * z; } return valueof a function int main() { int a, b; a = f(7); b = g(a, 3); }
Writing a Simple Program #include <stdio.h> int main() { printf("Hello World!\n"); return 0; } function return value of the main function
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 中文嘛也通喔 _
printf() – 換行符號 • \n換行符號 (newline) • printf("Welcome to C!\n"); Execution result • printf("Welcome\nto\nC!"); Execution result Welcome to C! _ Welcome to C! _
printf() Function (Cont.) • 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!
Remember to Print Spaces! • printf("Welcome"); printf("to"); printf("C!\n"); Execution result: WelcometoC! _
Font Width • Width of a symbol is fixed in some fonts but varied in other fonts. • Lucida Console abcdefghijk abcdefghijk • Times New Roman abcdefghijk abcdefghijkl
printf • Try to print out: $ $$$ $$$$$$$$$$$$ printf(" $\n"); printf(" $$$\n"); printf(" $$$$$\n"); printf("$$$$$$$\n");
printf • Try to print out: JJ J J J JJJJJJJJJ
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; }
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
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;
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 * ************************************/
Comments (註解) • Examples int main() { int price; /* 價錢 */ int tip; // 服務費 price = 500; /* 價錢是500元 */ tip = 50; // 小費50元 int total = price + tip; /* 應付總額 */ return 0; }
Comments (註解) • Examples int main() { int price; /* 價錢 (這個註解忘了結束) int tip; // 服務費 price = 500;/* 價錢是500元 (註解才結束)*/ tip = 50; // 小費50元 int total = price + tip; /* 應付總額 */ return 0; }
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 number • 0.1 would become 0.09999999999999987
Variable Declaration (宣告變數) • Variables must be declared. • Declaration: varType varName; Ex: int score; • score: name of the variable • int declares that score is an integer
Variable Declaration • Examples int main() { int price; /* 價錢 */ int tip; // 服務費 price = 500; /* 價錢是500元 */ tip = 50; // 小費50元 return 0; } declarations statements
Variable Declaration • A variable must be declared before using it. • Ex:int score;score = 95; () • Ex:score = 95;int score; ()
Variable Declaration (Cont.) • Declare two or more variables • int price; int tip; int total; • int price, tip, total; • Case sensitive • a1 and A1 are different.
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 怪怪
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 怪怪 5 8
Assignment • a = 5; • a = b + c; • d = 3 * 5 + sum / 2; • d = max(a,b);// return value of maxfunction • a = a + 2; CError 2.6放結果的變數是在等號左邊,不能寫成b + c = a。
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 a 5 7
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;
用 %d 來印出整數資料 Print Out an Integer #include<stdio.h> int main() { int score; score = 85; printf("成績是:%d\n", score); return 0; } 要印出的變數 逗號
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; }
Print Out an Integer #include<stdio.h> int main() { int price, tip, total; price = 500; tip = 50; printf("總共要付:%d\n", price + tip); return 0; }
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; }
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; }
2.5 Reading Input An integer variable • 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. &
2.5 Reading Input A floating-point variable • Syntax: scanf("%f", &varName); • Ex: scanf("%f", &radius); &
2.6 Defining Constants • 語法#define 常數巨集名稱 所要取代成的文字 • Ex: 定義常數#define PI 3.14159 • 所有出現的地方,都會被取代成要取代的文字 • Ex:int area = r * r * PI ; 3.14159
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; }
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; }
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.
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
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.
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
Preserve Words, Keywords auto enum restrict* unsigned break extern return void case float short volatile char for signed while const goto sizeof _Bool* continue if static _Complex* default inline* struct _Imaginary* do int switch double long typedef else register union *C99 only
Layout of a C Program • A C program is a series of tokens. • Tokens include: • Identifiers • Keywords • Operators • Punctuation • Constants • String literals
Layout of a C Program • The statement printf("Height: %d\n", height); consists of seven tokens. identifiers String literals punctuations • Tokens: • Identifiers • Keywords • Operators • Punctuation • Constants • String literals
Layout of a C Program identifiers punctuations • The statement int inch = feet * 12; consists of seven tokens. keywords operators constants • Tokens: • Identifiers • Keywords • Operators • Punctuation • Constants • String literals
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.
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;}
. . . . . . . . . . . . Typical C Program Development Environment Program is created in the editor and stored on disk. 1. Edit Editor Disk 2. Preprocess Preprocessor Preprocessor program processes the code. Disk 3. Compile Compiler Compiler creates object code and stores it on disk. Disk 4. Link Linker Disk Linker links the object code with the libraries Memory Loader 5. Load Loader puts program in memory. Disk Memory CPU takes each instruction and executes it, possibly storing new data values as the program executes. 6. Execute CPU