introduction to c programming ปรีดา เลิศพงศ์วิภูษณะ...

Post on 14-Dec-2015

235 Views

Category:

Documents

6 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Introduction To C Introduction To C ProgrammingProgramming

ปรี�ดา เลิศพงศ วิภู�ษณะplw@ku.ac.th

ภูาควิชาวิศวิกรีรีมคอมพวิเตอรี คณะวิศวิกรีรีมศาสตรี มหาวิทยาลิ�ย

เกษตรีศาสตรี

C Programming Language 204212 Abstract Data Type an

d Problem Solver

2

Why use CWhy use C• General-purpose programming language• Closely associated with the UNIX and Linux

system– C was developed on UNIX– UNIX, Linux and its software are written in C.

•13,000 lines of code•800 lines at the very lowest level in

assembly• System programming language• Low-Level language with High-Level structure• High-Level language with Low-Level efficiency

C Programming Language 204212 Abstract Data Type an

d Problem Solver

3

The C Programming The C Programming LanguageLanguage

• A block structured language• The language is weakly typed (explicit

type conversion not required). For example,– arithmetic expressions may involve

operand of type character and integer;

– no type checking between actual and format parameters in a procedure call

C Programming Language 204212 Abstract Data Type an

d Problem Solver

4

• Operation systems• System programming• Compilers• Commercial applications• Database management systems

C has many application C has many application areasareas

C Programming Language 204212 Abstract Data Type an

d Problem Solver

5

Characteristics of CCharacteristics of C• Structured• Modular (compiled separately)• Free format (read ability)• Single thread (one input, one output)• Relatively low level

C Programming Language 204212 Abstract Data Type an

d Problem Solver

6

• Flow control for structured program– decision making (if)– looping with the termination

•test at the top (while, for)•test at the bottom (do)•selecting one of a set of possible case (switch)

Characteristics of CCharacteristics of C

C Programming Language 204212 Abstract Data Type an

d Problem Solver

7

Characteristics of CCharacteristics of C• Call by value (array names are

passed as a location of the array of the array origin [call by reference])

• Any function may be called recursively

• Function definitions may not be nested

• Compact object code• Portable

C Programming Language 204212 Abstract Data Type an

d Problem Solver

8

Getting StartGetting Start• The only way to learn a new programm

ing Language is by writing program in it.

• I want to print thisHello, worldHello, world

using any editor (vi) to edit hello.c

main() { /* This is my first C program */main() { /* This is my first C program */ printf(“Hello, world\n”);printf(“Hello, world\n”);}}

C Programming Language 204212 Abstract Data Type an

d Problem Solver

9

• Compilinggcc -c hello.cgcc -c hello.cgcc -c -o hello hello.cgcc -c -o hello hello.c

gcc -c -o {O-FileName} {C-FileName}gcc -c -o {O-FileName} {C-FileName}

• Linkinggcc hello.ogcc hello.ogcc -o hello hello.ogcc -o hello hello.o

gcc -o {E-FileName} {O-FileName}gcc -o {E-FileName} {O-FileName}

Compiling & LinkingCompiling & Linking

gcc Compiler gcc CompilerHello.cHello.c Hello.o, a.outHello.o, a.out

gcc Compiler gcc CompilerHello.oHello.o Hello.o, a.outHello.o, a.out

C Programming Language 204212 Abstract Data Type an

d Problem Solver

10

• Runninghellohello{E-FileName}{E-FileName}

$ ./hello$ ./helloHello, worldHello, world

$ ./a.out$ ./a.outHello, worldHello, world$ _$ _

RunningRunning

C Programming Language 204212 Abstract Data Type an

d Problem Solver

11

Component of C programComponent of C programmain()main() function name function name {{ start of function start of function .. .. function body function body .. .. }} end of function end of function

C Programming Language 204212 Abstract Data Type an

d Problem Solver

12

function name mainmain is special function name. Every program must have a main()main() function to show the compiler where the program start, this function can be used only once.– C dose make a distinction between upper and

lowercase letter. MAIN, Main, main are not the same.

– a-z, A-Z, 0-9, _– first character cannot be a digit, may be more

than 8 char long, but on some system not all characters are significant

Component of C programComponent of C program

C Programming Language 204212 Abstract Data Type an

d Problem Solver

13

Lexical ElementsLexical Elements• Whitespace and Line Termination

In C source programs the blank (space), end-of-line, vertical-tab, form feed, and horizontal-tab are know collectively as whitespace character. They are used to separate when they appear in character or string constants.

C Programming Language 204212 Abstract Data Type an

d Problem Solver

14

• Character Encodings

Each character in a computer’s charact er set will have some conventional enc

oding.

‘‘A’ = 65A’ = 65‘‘Z’ = 90Z’ = 90‘‘Z’- ‘A’ + 1 = ? (26)Z’- ‘A’ + 1 = ? (26)

Lexical ElementsLexical Elements

C Programming Language 204212 Abstract Data Type an

d Problem Solver

15

CommentsCommentsComments may contain any

number of character and are always treated as whitespace

• Begin with /*, end with */• Legal anywhere a space is legal

/* in-line comment *//* in-line comment */

/*/* ** * Header Comment* Header Comment ** */*/

C Programming Language 204212 Abstract Data Type an

d Problem Solver

16

CommentsComments• แบบครี�!งลิะบรีรีท�ดใช# //...EOL

เช$นprintf(“Test Program”) //ป&ดหน#าต$าง

• แบบหลิายบรีรีท�ดใช# /*...*/ เช$น

/*The purpose of this script is to calculate the total from three difference variable.*/

C Programming Language 204212 Abstract Data Type an

d Problem Solver

17

void Squares() /* no arguments */void Squares() /* no arguments */

{{

int i;int i;

/*/*

loop from 1 to 10loop from 1 to 10

printing out the squaresprinting out the squares

*/*/

for (i = 1; i <= 10; i++)for (i = 1; i <= 10; i++)

printf(“%d squared is %d\n”, i, i*i);printf(“%d squared is %d\n”, i, i*i);

}}

Example of CommentsExample of Comments

C Programming Language 204212 Abstract Data Type an

d Problem Solver

18

IdentifiersIdentifiersAn identifieridentifier, also called name in

C is a sequence of letters, digits, and underscores. An identifiers must not must not begin with a digitbegin with a digit, and it must not it must not have the same as a reserved have the same as a reserved word.word.

averyaverylongidentifierlongidentifier avery_long_identifieravery_long_identifier AveryLongIdentifierAveryLongIdentifier

C Programming Language 204212 Abstract Data Type an

d Problem Solver

19

Identifier NameIdentifier Name• ต#องเรี'มต#นด#วิยต�วิอ�กษรี• ยาวิส(ดไม$เกน 40 ต�วิอ�กษรี• จะต#องไม$ม�ช$องวิ$าง• สามารีถใช#ต�วิเลิขได#• ใช#อ�กษรีพเศษต$อไปน�!ได# _• ม�ควิามแตกต$างรีะหวิ$างอ�กษรีต�วิใหญ่$แลิะต�วิเลิ.ก

C Programming Language 204212 Abstract Data Type an

d Problem Solver

20

Reserved wordReserved wordThe following identifier have been

reserved and must not be used as program identifiers

asm default float registerasm default float register auto do for returnauto do for return break double fortran shortbreak double fortran short case else goto signedcase else goto signed const enum int staticconst enum int static continue extern long structcontinue extern long struct

C Programming Language 204212 Abstract Data Type an

d Problem Solver

21

Integer ConstantsInteger Constants• decimal-constants

123 123L123 123L456 456L456 456L789 789L789 789L

C Programming Language 204212 Abstract Data Type an

d Problem Solver

22

• octal-constants

077 077L077 077L076 076L076 076L012 012L012 012L

• hexadecimal-constants

0xFF 0xFFL0xFF 0xFFL0x1A 0x1AL0x1A 0x1AL0x2A 0x2AL0x2A 0x2AL

Integer ConstantsInteger Constants

C Programming Language 204212 Abstract Data Type an

d Problem Solver

23

Floating-point ConstantsFloating-point Constants• Fix-point Constants

0.0 0.0F 0.0L0.0 0.0F 0.0L1.0 1.0F 1.0L1.0 1.0F 1.0L1.5 1.5F 1.5l1.5 1.5F 1.5l

• Floating-point Constants

3E1 3E1L3E1 3E1L1.0E-3 1.0E-3L1.0E-3 1.0E-3L1.0E67 1.0E67L1.0E67 1.0E67L

C Programming Language 204212 Abstract Data Type an

d Problem Solver

24

Character ConstantsCharacter Constants CHARACTER VALUECHARACTER VALUE ‘ ‘a’ 97a’ 97 ‘ ’ ‘ ’ 3232 ‘ ‘/r’ 13/r’ 13 ‘ ‘A’ 65A’ 65 ‘ ‘?’ 63?’ 63 ‘ ‘\O’ O\O’ O ‘ ‘\377’ 255\377’ 255 ‘ ‘%’ 37%’ 37 ‘ ‘8’ 568’ 56 ‘ ‘\23’ 19\23’ 19 ‘ ‘\\’ 92\\’ 92

C Programming Language 204212 Abstract Data Type an

d Problem Solver

25

String ConstantsString ConstantsCHARACTER VALUECHARACTER VALUE “” ‘ “” ‘\0’\0’ “ “\\” ‘\’,‘\0’\\” ‘\’,‘\0’ “ “Total” ‘T’,‘o’,‘t’,‘a’,‘l’,‘\0’Total” ‘T’,‘o’,‘t’,‘a’,‘l’,‘\0’ “ “Copyright 1982” ‘C’,‘o’,‘p’,‘y’,‘r’,‘i’,‘g’,‘h’,‘t’,Copyright 1982” ‘C’,‘o’,‘p’,‘y’,‘r’,‘i’,‘g’,‘h’,‘t’, ‘ ’ ‘ ’,’1’,’9’,’8’,’2’,’\0’,’1’,’9’,’8’,’2’,’\0’ ‘ ‘Total’ = ‘T’Total’ = ‘T’

C Programming Language 204212 Abstract Data Type an

d Problem Solver

26

Escape CharactersEscape Characters‘‘\Escape-Code’\Escape-Code’

ff Form FeedForm Feednnrrttvv\\‘‘““??

bbaa

Escape codeEscape code TranslationTranslationAlert,BellAlert,BellBackspaceBackspace

Question maskQuestion mask

New LineNew LineCarriage ReturnCarriage ReturnHorizontal tabHorizontal tabVertical tabVertical tabBackslashBackslash

Single QuoteSingle QuoteDouble QuoteDouble Quote

C Programming Language 204212 Abstract Data Type an

d Problem Solver

27

The C preprocessorThe C preprocessor• The C preprocessor is a simple macro

processor conceptually processes the source text of a C program before the compiler reads the source program.

C Programming Language 204212 Abstract Data Type an

d Problem Solver

28

Definition and Definition and ReplacementReplacement

#define {First-String} {Second-String}#define {First-String} {Second-String}

ExampleExample#define sum(x,y) x+y#define sum(x,y) x+y

result = sum(5,a*b);result = sum(5,a*b);

the preprocessor replaces the source program line with

result = 5+a*b;result = 5+a*b;

C Programming Language 204212 Abstract Data Type an

d Problem Solver

29

Simple macro DefinitionsSimple macro Definitions#define name Sequence-of-Token#define name Sequence-of-Token

When the name is encountered in the source program text

or other appropriate context, the name is replaced by the body

#define BLOCK_SIZE 0*100#define BLOCK_SIZE 0*100#define EOF ‘\004’#define EOF ‘\004’#define ERRMSG “***Error***”#define ERRMSG “***Error***”

C Programming Language 204212 Abstract Data Type an

d Problem Solver

30

#define NUMBER_OF_TAPE_DRIVERS 5#define NUMBER_OF_TAPE_DRIVERS 5

count = NUMBER_OF_TAPE_DRIVEScount = NUMBER_OF_TAPE_DRIVES

count = 5;count = 5;

Simple macro DefinitionsSimple macro Definitions

C Programming Language 204212 Abstract Data Type an

d Problem Solver

31

Define Macros with Define Macros with ParametersParameters

#define name(n1, n2, ..., nn) Sequence-of-Token#define name(n1, n2, ..., nn) Sequence-of-Token

#define product(x,y) ((x)+(y))#define product(x,y) ((x)+(y))produtct(a+3, b);produtct(a+3, b);

((a+3)+(b));((a+3)+(b));

C Programming Language 204212 Abstract Data Type an

d Problem Solver

32

Undefining and Undefining and Redefining MacroRedefining Macro

#undef name#undef name

#define NULL 0#define NULL 0#define FUNC(x) x+4#define FUNC(x) x+4

#define NULL 0#define NULL 0#define FUNC(x) x+4#define FUNC(x) x+4

#undef FUNC(x)#undef FUNC(x)#define FUNC(y) y+4#define FUNC(y) y+4

C Programming Language 204212 Abstract Data Type an

d Problem Solver

33

#define ON 1#define ON 1

#undef ON#undef ON

#define ON 1#define ON 1

if (ON == 1)if (ON == 1) printf ();printf ();

#undef ON#undef ON

Undefining and Undefining and Redefining MacroRedefining Macro

C Programming Language 204212 Abstract Data Type an

d Problem Solver

34

File InclusionFile Inclusion#include <#include <namename>>

Search for the file in certain standard places

#include “#include “namename””

Search for the file in current directory

#include “third.h”#include “third.h”#include <stdio.h>#include <stdio.h>

C Programming Language 204212 Abstract Data Type an

d Problem Solver

35

Condition CompilationCondition Compilation#if#if#else#else#endif#endif#elif#elif

#if Constant-Expression-1#if Constant-Expression-1 Group-of-Lines-1Group-of-Lines-1#elif Constant-Expression-2#elif Constant-Expression-2 Group-of-Lines-2Group-of-Lines-2#else#else Group-of-Lines-3Group-of-Lines-3#endif#endif

#ifdef name#ifdef name#ifdef name#ifdef name#if defined name#if defined name

C Programming Language 204212 Abstract Data Type an

d Problem Solver

36

DeclarationDeclaration C TypeC Type

Void Scalar Function Union AggregateVoid Scalar Function Union Aggregate Type Type Type TypeType Type Type Type

pointer Arithmetic array structurepointer Arithmetic array structure type type type typetype type type type

integral floating-pointintegral floating-point type typetype type

enumerated characterenumerated character type typetype type

C Programming Language 204212 Abstract Data Type an

d Problem Solver

37

Signed Integer TypesSigned Integer Types

short 16 bitshort 16 bitint 16-32 bitint 16-32 bitlong 32 bitlong 32 bit

MicroSoft CMicroSoft C

short 16 bit -32,768 --> 32,767short 16 bit -32,768 --> 32,767int 16 bit -32,768 --> 32,767int 16 bit -32,768 --> 32,767long 32 bit -2,147,483,648 --> 2,147,483,647long 32 bit -2,147,483,648 --> 2,147,483,647

Data TypeData Type

C Programming Language 204212 Abstract Data Type an

d Problem Solver

38

Unsigned Integer TypeUnsigned Integer Type

unsigned short 16 bitunsigned short 16 bitunsigned int 16-32 bitunsigned int 16-32 bitunsigned long 32 bitunsigned long 32 bit

MicroSoft CMicroSoft C

unsigned short 16 bit 0 --> 65,535unsigned short 16 bit 0 --> 65,535unsigned int 16 bit 0 --> 65,535unsigned int 16 bit 0 --> 65,535unsigned long 32 bit 0 --> 4,294,967,296unsigned long 32 bit 0 --> 4,294,967,296

Data TypeData Type

C Programming Language 204212 Abstract Data Type an

d Problem Solver

39

Character TypeCharacter Type

unsigned char 8 bitunsigned char 8 bitsigned char 8 bitsigned char 8 bit

MicroSoft CMicroSoft C

unsigned char 8 bit 0 --> 255unsigned char 8 bit 0 --> 255signed char 8 bit -128 --> 127signed char 8 bit -128 --> 127

Data TypeData Type

C Programming Language 204212 Abstract Data Type an

d Problem Solver

40

Pointer TypesPointer Typestype_name *variable;type_name *variable;

Generic PointersGeneric Pointers void *G_Ptr;void *G_Ptr; int *I_Ptr;int *I_Ptr; char *C_Ptr;char *C_Ptr; G_Ptr = I_Ptr;G_Ptr = I_Ptr; C_Ptr = G_Ptr;C_Ptr = G_Ptr; C_Ptr = I_Ptr;C_Ptr = I_Ptr;

Null PointerNull Pointer (void *) 0(void *) 0

AddressAddress && int Data;int Data; int *DataPtr = &Data;int *DataPtr = &Data;

C Programming Language 204212 Abstract Data Type an

d Problem Solver

41

Array TypesArray Typestype_name variable[N]type_name variable[N]

Array and PointerArray and Pointerint a[10], *ip;int a[10], *ip;ip = a;ip = a;ip = &a[0];ip = &a[0];

a[i]a[i]

*((a)+(i))*((a)+(i))

C Programming Language 204212 Abstract Data Type an

d Problem Solver

42

Multidimensional ArraysMultidimensional Arraystype_name variable[n1], [n2]...[nn]type_name variable[n1], [n2]...[nn]

int matrix [10][10];int matrix [10][10];int t[2][3];int t[2][3];

t[1][2]t[1][2]

*(*(t+1)+2)*(*(t+1)+2)

C Programming Language 204212 Abstract Data Type an

d Problem Solver

43

C Programming Language 204212 Abstract Data Type an

d Problem Solver

44

Structure typesStructure typesstruct struct_name {Declaration_1;struct struct_name {Declaration_1; Declaration_2;Declaration_2; .;.; .;.; .;.; Declaration_N;};Declaration_N;};

ExampleExample

struct complex { double real;struct complex { double real; double real; };double real; };

C Programming Language 204212 Abstract Data Type an

d Problem Solver

45

ExampleExample

struct A {int X, Y, Z;};struct A {int X, Y, Z;};struct A Data, *DataPtr;struct A Data, *DataPtr;

Data.x = 0;Data.x = 0;Data.y = 1;Data.y = 1;Data.z = 2;Data.z = 2;

DataPtr -> x = 0;DataPtr -> x = 0;DataPtr -> y = 1;DataPtr -> y = 1;DataPtr -> z = 2;DataPtr -> z = 2;

Structure typesStructure types

C Programming Language 204212 Abstract Data Type an

d Problem Solver

46

Structure types 2Structure types 2struct u { double d;struct u { double d; char c[2];char c[2]; int i;int i;};};

d {double} (8 bytes)

c {char} (2 bytes)

i {int} (4 bytes)

C Programming Language 204212 Abstract Data Type an

d Problem Solver

47

Union typesUnion typesunion union_name {Declaration_1;union union_name {Declaration_1; Declaration_2;Declaration_2; .;.; .;.; .;.; Declaration_N;};Declaration_N;};

ExampleExample

union single_data { char cData;union single_data { char cData; int iData;int iData; long lData;long lData; float fData;float fData; double dData; };double dData; };

C Programming Language 204212 Abstract Data Type an

d Problem Solver

48

Union types 2Union types 2union u { double d;union u { double d; char c[2];char c[2]; int i;int i;};};

d {double} (8 bytes)c {char} (2 bytes)

i {int} (4 bytes)

C Programming Language 204212 Abstract Data Type an

d Problem Solver

49

Type definedType definedtypedef oldtype newtypetypedef oldtype newtype

ExampleExample

typedef long bigint;typedef long bigint; typedef struct s { int a;typedef struct s { int a; int b;int b; } Stype;} Stype;

C Programming Language 204212 Abstract Data Type an

d Problem Solver

50

Enumerted TypesEnumerted Typesenum enum_identifier {n1,n2, ..., nn}enum enum_identifier {n1,n2, ..., nn}

enum colour {red, blue, green};enum colour {red, blue, green};enum colour c;enum colour c;

The first enumeration constant receives the value 0 if no explicit value is specified

ExampleExample enum boy {Bill = 10,enum boy {Bill = 10, John = Bill + 2,John = Bill + 2, Fred = John + 2};Fred = John + 2};

C Programming Language 204212 Abstract Data Type an

d Problem Solver

51

Function TypesFunction TypesReturn_Type function_name( Parameter_1,Return_Type function_name( Parameter_1, Parameter_2,Parameter_2, .,., .,., .,., Parameter_n) {Parameter_n) { .. .. ..}}

C Programming Language 204212 Abstract Data Type an

d Problem Solver

52

ExampleExample

int square(int x) {int square(int x) { return x*x;return x*x;}}

Function TypesFunction Types

C Programming Language 204212 Abstract Data Type an

d Problem Solver

53

Pointer to FunctionPointer to Functionvoid (*fptr)();void (*fptr)();

int *ptr[10];int *ptr[10];

int (*fptr[])();int (*fptr[])();

double (*fptr[])(double) = {sin, cos, tan};double (*fptr[])(double) = {sin, cos, tan};

(*fptr)(-1.0);(*fptr)(-1.0);(*(double(*)())fptr)(-1.0);(*(double(*)())fptr)(-1.0);(*(double(*)(double))fptr)(-1.0);(*(double(*)(double))fptr)(-1.0);

C Programming Language 204212 Abstract Data Type an

d Problem Solver

54

qsort Functionqsort FunctionVoid qsort(void *base, int num, int width, int Void qsort(void *base, int num, int width, int

(*compare)(void *elem1, void *elem2));(*compare)(void *elem1, void *elem2));

<0 elem1 < elem2<0 elem1 < elem2=0 elem1 = elem2=0 elem1 = elem2>0 elem1 > elem2>0 elem1 > elem2

C Programming Language 204212 Abstract Data Type an

d Problem Solver

55

Memory FunctionMemory Function#include <stdlib.h>#include <stdlib.h>#include <malloc.h>#include <malloc.h>

Buffer CompareBuffer Compare int memcmp(void *buf1, void *buf2, int size);int memcmp(void *buf1, void *buf2, int size); void *memchr(void *buf, int c, int size);void *memchr(void *buf, int c, int size);

Buffer copyBuffer copy void *memcpy(void *dest, void *src, int size);void *memcpy(void *dest, void *src, int size); void *memmove(void *dest, void *src, int size);void *memmove(void *dest, void *src, int size);

Buffer InitializationBuffer Initialization void *memset(void *dest, int c, int size);void *memset(void *dest, int c, int size);

C Programming Language 204212 Abstract Data Type an

d Problem Solver

56

Memory FunctionMemory FunctionAllocate memory initializedAllocate memory initialized void *malloc(int size);void *malloc(int size);

Allocate memory uninitializedAllocate memory uninitialized void *calloc(int num, int size);void *calloc(int num, int size);

Free memoryFree memory void free(void *);void free(void *);

Reallocate memoryReallocate memory void *realloc(void *buf,int newsize);void *realloc(void *buf,int newsize);

Calculate sizeCalculate size sizeof();sizeof();

C Programming Language 204212 Abstract Data Type an

d Problem Solver

57

PointerPointerint Data[3];int Data[3];int *DataPtr;int *DataPtr;

int Data[3][4];int Data[3][4];int *DataPtr[4];int *DataPtr[4];int (*DataPtr)[4];int (*DataPtr)[4];

int Data[3][4][5];int Data[3][4][5];int *DataPtr[4][5];int *DataPtr[4][5];int (*DataPtr)[4][5];int (*DataPtr)[4][5];

C Programming Language 204212 Abstract Data Type an

d Problem Solver

58

Arithmetic OperatorsArithmetic Operators• Simple assignment = assignment= assignment

• Binary Arithmetic + addition+ addition - subtraction- subtraction * multiplication* multiplication / division/ division % modulus% modulus

C Programming Language 204212 Abstract Data Type an

d Problem Solver

59

• Binary Comparative == equal== equal != not equal!= not equal > greater than> greater than >= greater than or equal to>= greater than or equal to < less than< less than <= less than or equal to<= less than or equal to

Comparative OperatorsComparative Operators

C Programming Language 204212 Abstract Data Type an

d Problem Solver

60

Logical OperatorsLogical Operators• Binary Logical && Boolean AND&& Boolean AND || Boolean OR|| Boolean OR

• Unary Logical ! NOT! NOT

C Programming Language 204212 Abstract Data Type an

d Problem Solver

61

ExampleExample

x = a + 1;x = a + 1;if ((i >= MAX) || (C[i] = ‘ ’)) {if ((i >= MAX) || (C[i] = ‘ ’)) { .. . . ..}}

Logical OperatorsLogical Operators

C Programming Language 204212 Abstract Data Type an

d Problem Solver

62

Operator PerferenceOperator Perference( ) [ ] -> .( ) [ ] -> .! ~ ++ -- * & sizeof(type)! ~ ++ -- * & sizeof(type)* / %* / %+ -+ -<< >><< >>< <= > =>< <= > =>== !=== !=&&^̂||&&&&||||??

C Programming Language 204212 Abstract Data Type an

d Problem Solver

63

Assignment Operators Assignment Operators and Expressionsand Expressions

i = i + 2;i = i + 2;i += 2;i += 2;

Most binary operators have a corresponding assignment operator (op=)

C Programming Language 204212 Abstract Data Type an

d Problem Solver

64

Assignment Operators Assignment Operators and Expressionsand Expressions

x = y++; y = y+1; x = y;

x += y+5; x = x+y+5;

Operator Example Equivalent ++ i++ i=i+1 -- i-- i=i-1 += i+=5 i=i+5 -= i-=5 i=i-5 *= i*=2 i=i*2 /= i/=2 i=i/2 ^= i^=2 i=i^2

C Programming Language 204212 Abstract Data Type an

d Problem Solver

65

x += 2; --> x = x + 2;x += 2; --> x = x + 2; x -= 2; --> x = x - 2;x -= 2; --> x = x - 2; x *= 2; --> x = x * 2;x *= 2; --> x = x * 2; x /= 2; --> x = x / 2;x /= 2; --> x = x / 2; x %= 2; --> x = x % 2;x %= 2; --> x = x % 2; x <<= 2; --> x = x << 2;x <<= 2; --> x = x << 2; x >>= 2; --> x = x >> 2;x >>= 2; --> x = x >> 2; x &= 2; --> x = x $ 2;x &= 2; --> x = x $ 2; x |= 2; --> x = x | 2;x |= 2; --> x = x | 2;

Assignment Operators Assignment Operators and Expressionsand Expressions

C Programming Language 204212 Abstract Data Type an

d Problem Solver

66

StatementsStatementsAn expression such as x = 0x = 0 or i++i++ becomes a statement when it is followed by a semicolon, as in

x = 0;x = 0; i++;i++; printf(...);printf(...);

C Programming Language 204212 Abstract Data Type an

d Problem Solver

67

The braces { { and } } are used to group declarations and statement

together into a compound statement or block.there is never a semicolon after the right brace that ends a block.

{{ statementstatement .. .. .. }}

Blocks StatementsBlocks Statements

Flow Control Flow Control StatementStatement

ปรี�ดา เลิศพงศ วิภู�ษณะplw@nontri.ku.ac.th

ภูาควิชาวิศวิกรีรีมคอมพวิเตอรี คณะวิศวิกรีรีมศาสตรี มหาวิทยาลิ�ย

เกษตรีศาสตรี

C Programming Language 204212 Abstract Data Type an

d Problem Solver

69

Flow Control StatementFlow Control Statement• if then Statement• if then else Statement• else if Statement• switch Statement• for Statement• do while Statement• do util Statement

C Programming Language 204212 Abstract Data Type an

d Problem Solver

70

IF THEN StatementIF THEN Statement• Single Line Format• Multi Line Format

IF

งานท�'ต#องการีท/า

จรีง

เท.จ

C Programming Language 204212 Abstract Data Type an

d Problem Solver

71

Single Line FormatSingle Line Formatif (LogicalExpression) Statement;

Exampleif (Score > 95) Grade = ‘A’;

C Programming Language 204212 Abstract Data Type an

d Problem Solver

72

Multiline FormatMultiline Formatif (LogicalExpression) { StatementBlock

}

Example if (G == h) { a = a + 1; b = b + 1;}

C Programming Language 204212 Abstract Data Type an

d Problem Solver

73

IF THEN ELSE StatementIF THEN ELSE Statement• Single Line Format• Multi Line Format

IF

จรีง เท.จ

งานท�' 1 งานท�' 2

C Programming Language 204212 Abstract Data Type an

d Problem Solver

74

Single Line FormatSingle Line Formatif (LogicalExpression) Statement1;else Statement2;

Example if (Score > 94) Grade = ‘A’;else Grade = ‘F’;

C Programming Language 204212 Abstract Data Type an

d Problem Solver

75

Multiline FormatMultiline Formatif (LogicalExpression) { StatementBlock

}else { StatementBlock

}

Example

if (Score > 94) {

Grade = ‘A’;

a = a + 1;

}

else {

Grade = ‘F’;

a = a - 1;

}

C Programming Language 204212 Abstract Data Type an

d Problem Solver

76

ELSE IF StatementELSE IF Statement

IF

จรีง เท.จ

งานท�' 1

งานท�' 4

• Multi Line Format

ELSE IF

เท.จ

งานท�' 2ELSE IF

เท.จ

งานท�' 3

จรีง

จรีง

C Programming Language 204212 Abstract Data Type an

d Problem Solver

77

Multiline FormatMultiline Formatif (LogicalExpression) { StatementBlock

} else if (LogicalExpression) { StatementBlock

} else { StatementBlock

}

Example

if (Mark > 90) {

Grade = ‘A’;

}

else if (Mark > 80) {

Grade = ‘B’;

}

else {

Grade = ‘C’;

}

C Programming Language 204212 Abstract Data Type an

d Problem Solver

78

SWITCH CASE SWITCH CASE StatementStatementswitch (Expression) {

case constant_1: StatementBlock_1;

break; case constant_2: StatementBlock_2;

break; default: StatementBlock_n; break;}

CASE

งานท�' 1

งานท�' 4งานท�' 2

งานท�' 3

C Programming Language 204212 Abstract Data Type an

d Problem Solver

79

BREAK StatementBREAK Statement

break; ใช#ค/าส�'งน�!เม0'อต#องการีหย(ดการีท/างาน แลิะออกจาก

ค/าส�'งน�!นไปท/าค/าส�'งถ�ดไป

C Programming Language 204212 Abstract Data Type an

d Problem Solver

80

Looping with the termination test at thetop

• Single Line Format• Multi Line Format

WHILE DO StatementWHILE DO Statement

WHILE

เท.จ

งานท�'ต#องการีท/า

จรีง

C Programming Language 204212 Abstract Data Type an

d Problem Solver

81

Single Line FormatSingle Line Formatwhile (LogicalExpression) Statement;

Example X = 0; while (X < 5) X = X + 1;

while ((C = gechar()) ! = EOF) putchar(C);

C Programming Language 204212 Abstract Data Type an

d Problem Solver

82

MultiLine FormatMultiLine Formatwhile (LogicalExpression) { StatementBlock; .}

Example X = 0; while (X < 5) { X = X + 1; }

C = gechar(); while (C != EOF) { putchar(C); C = getchar(); }

while ((C = gechar()) != EOF)while ((C = gechar()) != EOF) putchar(C);putchar(C);

C Programming Language 204212 Abstract Data Type an

d Problem Solver

83

Looping with the termination test at the bottom.

do StatementBlock; . .while (LogicalExpression);

The statement is executed, then exp ression is evaluated. If true, statem

ent is evaluated again, and so on. If t heexpression becomes false, the loo

p terminates. The statement is alwa ys executed at least once.

DO WHILE StatementDO WHILE Statement

WHILE

เท.จ

งานท�'ต#องการีท/า

จรีง

C Programming Language 204212 Abstract Data Type an

d Problem Solver

84

DO WHILE FormatDO WHILE Formatdo StatementBlock;while (LogicalExpression);Example X = 0; do X = X + 1 while (X < 5); X = 5; do X = X - 1 while (x > 0);

C Programming Language 204212 Abstract Data Type an

d Problem Solver

85

Create LoopCreate Loop

c = 1;while (c <= 10) { // // คำ��สั่��งอื่�นๆ ที่��ต้�อื่งก�รให้�

ที่��ง�น // c = c + 1;}

C <= 10

1C =

งานท�'ต#องการีท/า

1C = C +Statement ท�' 3

Statement ท�' 2

Statement ท�' 1ตรีวิจสอบเง0'อนไข

ก/าหนดค$าเรี'มต#นให#ก�บต�วิน�บ

เพ'มค$าให#ก�บต�วิน�บ

C Programming Language 204212 Abstract Data Type an

d Problem Solver

86

FOR StatementFOR Statementfor (C = N1;C <= N2;C = C + N3) { // // คำ��สั่��งอื่�นๆ ที่��ต้�อื่งก�รให้�ที่��ง�น //}

C <= N2

1C = N

เท.จ

งานท�'ต#องการีท/า

+ ++=+ 3

จรีง

C Programming Language 204212 Abstract Data Type an

d Problem Solver

87

FOR NEXT StatementFOR NEXT Statementfor (FirstState; SecondState; ThirdState) { StatementBlock}Example for (i = 1;i <= 1;i++) { k = k + i }

for (i = 2;i <= 20;i++) { k = k + i }

for (i = -2;i >= -20; i--) { k = k + i }

C Programming Language 204212 Abstract Data Type an

d Problem Solver

88

Break Exiting a loopBreak Exiting a loop• Control loop exists other than by

testing at the top or bottom.• The break statement provides an

early exit from for, while, and do, just as from switch.

• A break statement cause the innermost enclosing loop (or switch) to be exited immediately.

C Programming Language 204212 Abstract Data Type an

d Problem Solver

89

ExampleExample

while ((ch = getchar()) != EOF) {while ((ch = getchar()) != EOF) { if (ch == ‘\n’)if (ch == ‘\n’) break ;break ; putchar(ch);putchar(ch);}}

Break Exiting a loopBreak Exiting a loop

C Programming Language 204212 Abstract Data Type an

d Problem Solver

90

Continue a loopContinue a loop• Continue ignoring Code within a loop

causes the next itera tion of the enclosing loop (for, while, do) to begin:

ExampleExample

while ((ch = getchar()) != EOF) {while ((ch = getchar()) != EOF) { if (ch == ‘\n’)if (ch == ‘\n’) continue;continue; putchar();putchar();};};

C Programming Language 204212 Abstract Data Type an

d Problem Solver

91

CONTINUE and BREAK CONTINUE and BREAK Statement 1Statement 1

continue กลิ�บไปตรีวิจสอบเง0'อนไขแลิ#วิท/า LOOP ถ�ดไป

break ออกจาก LOOP หน2'งลิ/าด�บช�!น

C Programming Language 204212 Abstract Data Type an

d Problem Solver

92

Example for (i = 1;i <= 10;i++) if (i > 3) continue; do X = X + 1; if (X = 3) break; while (x <= 10); for (i = 1;i <= 10;i++) { do while (j < 5) { k = i + j; if (K > 25) break; } }

CONTINUE and BREAK CONTINUE and BREAK Statement 2Statement 2

C Programming Language 204212 Abstract Data Type an

d Problem Solver

93

GOTO and Label GOTO and Label StatementStatement

การีปรีะกาศ Label Identifier:Identifier:

การีใช#ค/าส�'ง gotogotogoto LabelName; LabelName;

Example

if (Flag = 1) goto JumpStep; Total = Total + 1;JumpStep: printf(“ที่ดสั่อื่บคำ��นวณถู�กต้�อื่ง”);

C Programming Language 204212 Abstract Data Type an

d Problem Solver

94

RETURN StatementRETURN Statement• เม0'อต#องการีหย(ดการีท/าค/าส�'งภูายใน Function

แลิะส$งค$าของข#อม�ลิกลิ�บใช#ค/าส�'ง returnreturn;; return VariableName;return VariableName;

C Programming Language 204212 Abstract Data Type an

d Problem Solver

95

DeclarationDeclaration{AccessControl}DataType Identifier{=Value, Identifier{=Value,...}}...

• Single VariableExample long ll_Temp; char lc_Temp;

• Multiple VariableExample long ll_t1, ll_t2, ll_t3;

C Programming Language 204212 Abstract Data Type an

d Problem Solver

96

ScopeScope• Local Variable• Global Variable

C Programming Language 204212 Abstract Data Type an

d Problem Solver

97

Local VariableLocal Variable• Local Variable ค0อการีปรีะกาศต�วิแปรีต$างๆท�'

ต#องการีใช#งาน ในช$วิงของการีเข�ยนโปรีแกรีม

C Programming Language 204212 Abstract Data Type an

d Problem Solver

98

Global VariableGlobal Variable• Global Variable ค0อการีปรีะกาศต�วิแปรีต$างๆท�'ต#องการี

ใช#งาน ตดต$อภูายในแอพพลิเคช�'นท�'ท/าการีปรีะกาศ

C Programming Language 204212 Abstract Data Type an

d Problem Solver

99

Assignment OperatorAssignment OperatorVariableName = Values;VariableName = VariableName;VariableName = FunctionName();

Example ll_t1 = 1; ls_t2 = “test”, s_test.il_t3 = 5;

s_test.CompCode[1] = 100;

C Programming Language 204212 Abstract Data Type an

d Problem Solver

100

Question & AnswerQuestion & Answer

top related