SysProg-Tutor 01 Introduction to C Programming Language

75
Chulalongkorn University 2110313 Operating Systems and System Programs (1/2010) Tutor Session - 1 Introduction to C Programming Language Tutor Session I: Wongyos Keardsri (P’Bank) Department of Computer Engineering Faculty of Engineering, Chulalongkorn University Bangkok, Thailand Mobile Phone: 089-5993490 E-mail: [email protected], MSN: [email protected] Twitter: @wongyos

description

 

Transcript of SysProg-Tutor 01 Introduction to C Programming Language

Page 1: SysProg-Tutor 01 Introduction to C Programming Language

Chulalongkorn University

2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Introduction to C Programming Language

Tutor Session I:

Wongyos Keardsri (P’Bank)Department of Computer EngineeringFaculty of Engineering, Chulalongkorn UniversityBangkok, Thailand

Mobile Phone: 089-5993490E-mail: [email protected], MSN: [email protected]: @wongyos

Page 2: SysProg-Tutor 01 Introduction to C Programming Language

2 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Tutor Outline

IntroductionC HistoryC Language VS Java LanguageC Language Structure

Types, Operators and ExpressionsData Input and Output

printf()scanf()

Control FlowIf-ElseSwitch

WhileDo-WhileFor

Functions and Program Structure

Non-Return FunctionReturn FunctionThe Standard C Library Functions

Array, Pointer and StringStructuresFile Operations

Page 3: SysProg-Tutor 01 Introduction to C Programming Language

3 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

C is a structured computer programming languageAppeared in1972 (1970s)Designed and Developed by Dennis Ritchie at the Bell Telephone LaboratoriesDerived from B and BCPL programming languageDeveloped for the UNIX operating system

IntroductionC History

Page 4: SysProg-Tutor 01 Introduction to C Programming Language

4 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Used and Implemented for: System programmingOperating systemsEmbedded system applications

C standard: ANSI C and ISO CBook: The C Programming Language, 2nd edition

http://en.wikipedia.org/wiki/C_(programming_language)

IntroductionC History (Cont)

Page 5: SysProg-Tutor 01 Introduction to C Programming Language

5 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

public class Hello {public static void main(String[] args) {

System.out.print("Hello CP\n");}

}

Example Java Code (Hello.java)

Example C Code (Hello.c)#include <stdio.h>main() {

printf("Hello CP\n");}

IntroductionC Language VS Java Language

Page 6: SysProg-Tutor 01 Introduction to C Programming Language

6 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

C: Structured ProgrammingC CompilerEditor: Turbo C, vi, etc.Compile: (UNIX)gcc Hello.c

After compilea.out

Run:./a.outHello CP

Java: Object-Oriented ProgrammingJava Compiler (JVM)Editor: JLab, Eclipse, etc.Compile:javac Hello.java

After compileHello.class

Run:java HelloHello CP Show an exampleShow an example

IntroductionC Language VS Java Language (Cont)

Page 7: SysProg-Tutor 01 Introduction to C Programming Language

7 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

General format#include <stdio.h>#include <…………………>

main() {

[function-body];

}

type func() {

[function-body];

}

Preprocessor / Including Library

Function main:[declaration-list] + [statement-list]

Function func:[declaration-list] + [statement-list]

Begin

End... Semicolon

IntroductionC Language Structure

Page 8: SysProg-Tutor 01 Introduction to C Programming Language

8 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Introduction

An example C code

#include <stdio.h>main() {

int sum; /* Variable declaration */sum = 15 + 25; /* Value assignment */printf("The sum of 15 and 25 is %d\n", sum);

}

The sum of 15 and 25 is 40

C Language Structure (Cont)

Page 9: SysProg-Tutor 01 Introduction to C Programming Language

9 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Compile C by UNIX command

cc option file1 file2 …

Example 1gcc example.c

a.out

./a.out

Compile

Run

IntroductionC Language Structure (Cont)

Page 10: SysProg-Tutor 01 Introduction to C Programming Language

10 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Example 2

gcc –c example.c

example.o

gcc –o example.run example.o

Compile

Convert to Executable file

Object file

./example.run

example.run Executable file

Run

IntroductionC Language Structure (Cont)

Page 11: SysProg-Tutor 01 Introduction to C Programming Language

11 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Example 3

gcc –o example.run example.c Compile

./example.run

example.run Executable file

Run

Wow

IntroductionC Language Structure (Cont)

Page 12: SysProg-Tutor 01 Introduction to C Programming Language

12 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Types, Operators and Expressions

char Character (8 bit) Ex. ‘A’, ‘a’, ‘F’int Integer (16 bit) Ex. 12, -2456, 99851float Real single (32 bit) Ex. 23.82, 567.008double Real double (64 bit) Ex. 0.0002100009short Shot integer (16 bit) Ex. -4, 18long Long integer (32 bit) Ex. 9547604608456unsigned Unsigned integer (16 bit) Ex. 2, 908, 1392

Data Types and Sizes

Page 13: SysProg-Tutor 01 Introduction to C Programming Language

13 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Types, Operators and Expressions

Exampleint x, y, x = 5;float eps = 1.0e-5;int limit = MAXLINE+1;char s_name = 'A';char str[] = "Hello CP";double dd = 0.000000000001;

Variable Declaration

type-specifier list-of-variables;

Page 14: SysProg-Tutor 01 Introduction to C Programming Language

14 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Types, Operators and Expressions

Example#define MAX 500#define STEP 20#define PI 3.14159265#define VTAB '\t'const char msg[] = "warning: ";const double e = 2.71828182845905;

Constant Declaration

#define VARIABLE constant-value

Note

#include <stdio.h>#define XX 0

main() {// Body program

}

Page 15: SysProg-Tutor 01 Introduction to C Programming Language

15 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Types, Operators and Expressions

Arithmetic OperatorsAddition +Subtraction -Multiplication *Division /Modulation %

Examplefag = x % y;c = a – (a/b)*b;sum = var1 + var2 + var3;

Expression and Operations

Page 16: SysProg-Tutor 01 Introduction to C Programming Language

16 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Types, Operators and Expressions

Relational OperatorsLess than < a < 5Less than or equal <= a <= bMore than > a > b + cMore than or equal >= a >= b + 5Equal == a == -6Not equal != a != 0

Logical OperatorsAND && (a > 0) && (b > 0)OR || (a <= 0) || (b <= 0)Negation ! !(a && c)

Expression and Operations (Cont)

Page 17: SysProg-Tutor 01 Introduction to C Programming Language

17 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Types, Operators and Expressions

Bitwise OperatorsBitwise AND &Bitwise OR (Inclusive OR) |Bitwise XOR (Exclusive OR) ^Left shift <<Right shift >>One's complement ~

Examplex = 01001011 y = 00101100 ~x = 10110100x & y = 00001000 x | y = 01101111x ^ y = 01100111 x << 2 = 00101100

Expression and Operations (Cont)

Page 18: SysProg-Tutor 01 Introduction to C Programming Language

18 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Types, Operators and Expressions

Assignment Operators and Expressionsop is + - * / % << >> & ^ |If expr1 and expr2 are expressions, then

expr1 op= expr2

Equivalent to

expr1 = (expr1) op (expr2)

ExampleX += 1;X = X + 1;

Expression and Operations (Cont)

Equivalent

Page 19: SysProg-Tutor 01 Introduction to C Programming Language

19 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Conditional Expressions

expr1 ? expr2 : expr3

If expr1 is true do expr2If expr1 is false do expr3

Examplea = 5;b = 10;min = (a < b) ? a : b;

Types, Operators and ExpressionsExpression and Operations (Cont)

Page 20: SysProg-Tutor 01 Introduction to C Programming Language

20 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Increment and Decrement OperatorsPre-increment operation ++variablePost-increment operation variable++Pre-decrement operation --variablePost-decrement operation variable--

Examplex = 4;y = x++ + 5; //x = 5, y = 9x = 4;y = ++x + 5; //x = 5, y = 10

Types, Operators and ExpressionsExpression and Operations (Cont)

Page 21: SysProg-Tutor 01 Introduction to C Programming Language

21 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Type Cast Operator (Casting)

(type-specifier) expression;

Example(double) date;float var1 = 2.7;int var2 = (int) var1; //var2 = 2(char) x;(int) d1 + d2;

Types, Operators and ExpressionsExpression and Operations (Cont)

Page 22: SysProg-Tutor 01 Introduction to C Programming Language

22 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Data Input and Output

printf() is a function for display result to standard output (Monitor, Screen)

printf(format, arg1, arg2, …);

Exampleprintf(“Hello\n”);//Helloint num = 2;printf(“%d is integer”, num);//2 is integer

printf() Statement

Page 23: SysProg-Tutor 01 Introduction to C Programming Language

23 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Conversion Operation [printf()]d signed decimal conversion of an int or a longu unsigned decimal conversion of unsignedo unsigned octal conversion of unsignedx, X unsigned hexadecimal conversion of unsigned

x = [a – f], X = [A - F]c single character conversions string conversionf signed decimal floating point conversione, E signed decimal floating point conversion in scientific

notation

Data Input and Outputprintf() Statement (Cont)

Page 24: SysProg-Tutor 01 Introduction to C Programming Language

24 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

int j = 45, k = -123;float x = 12.34;char c = ‘w’;char *m = “Hello”;printf(“Hello 55”); Hello 55printf(“Tax is %d”, j); Tax is 45printf(“%d”, j+k); -78printf(“%3d %d”, j, k); 45 -123printf(“%f %.2f”, x, x); 12.340000 12.34printf(“%c”, c); wprintf(“%s\n”, m); Helloprintf(“%s\n”, “Hello”); Helloprintf(“%10s\n”, “Hello”); Hello

Example of printf()

Result

Data Input and Outputprintf() Statement (Cont)

Page 25: SysProg-Tutor 01 Introduction to C Programming Language

25 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

scanf() is a function for read input from standard input (Keyboard)

scanf(format, arg1, arg2, …);

Examplescanf(“%d %d %d”, &day, &month, &year);int num;printf(“Enter integer : ”);scanf(“%d”, &num);// Enter integer : 23

Data Input and Outputscanf() Statement

Page 26: SysProg-Tutor 01 Introduction to C Programming Language

26 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Conversion Operation [scanf()]d signed decimal conversion of an int or a longu unsigned decimal conversion of unsignedo unsigned octal conversion of unsignedx, X unsigned hexadecimal conversion of unsigned

x = [a – f], X = [A - F]c single character conversions string conversionf signed decimal floating point conversione, E signed decimal floating point conversion in scientific

notation[] read only character in [ ], if [^ ] read different character

Data Input and Outputscanf() Statement (Cont)

Page 27: SysProg-Tutor 01 Introduction to C Programming Language

27 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

int d,m,y,x;char ch1,ch2;float f;scanf(“%d”, &x); 4

// x=4scanf(“%2d%2d%4d”, &d,&m,&y); 22062007

// d=22, m=6, y=2007scanf(“%d/%d/%d”, &d,&m,&y); 22/06/2007

// d=22, m=6, y=2007scanf(“%c%c”, &ch1,&ch2); Ab

// ch1=‘A’, ch2=‘b’scanf(“%f”, &f); 2.3

// f=2.300000

Example of scanf()

Result

Data Input and Outputscanf() Statement (Cont)

Page 28: SysProg-Tutor 01 Introduction to C Programming Language

28 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Control Flow

If-Else StatementThe if-else statement is used to express decisions. Formally the syntax is

if (expression) {true statement

} else {false statement

}

Decision Statements

Page 29: SysProg-Tutor 01 Introduction to C Programming Language

29 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Control Flow

Nested If-ElseThe sequence of if statements is the most general way of writing a multi-way decision. Formally the syntax is

if (expression) {statement

} else if (expression) {statement

} else if (expression) {statement

} else {statement

}

Decision Statements (Cont)

Page 30: SysProg-Tutor 01 Introduction to C Programming Language

30 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Control Flow

Example of If-ElseDecision Statements (Cont)

if (score >= 80)grade = ‘A’;

else if (score >= 70)grade = ‘B’;

else if (score >= 50)grade = ‘C’;

else if (score >= 40)grade = ‘D’;

elsegrade = ‘F’;

if (a < b) {printf(“a less than

b\n”);} else {

temp = a;a = b; /* swap a */b = temp; /* and b */printf(“Interchange a

and b\n”);}

Page 31: SysProg-Tutor 01 Introduction to C Programming Language

31 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Control Flow

Switch StatementThe switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer values, and branches accordingly.

switch (expression) {case const-expr: statementscase const-expr: statementsdefault: statements

}

Decision Statements (Cont)

Page 32: SysProg-Tutor 01 Introduction to C Programming Language

32 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Control Flow

Example of SwitchDecision Statements (Cont)

c = getchar();switch (c) {

case '0': printf(“Zero\n”); break;case '1': case '2': case '3': case '4':case '5': case '6': case '7': case '8':case '9': printf(“Nine\n”); break;case ' ':case '\n': newln++; break;case '\t': tabs++; break;default: printf(“missing char\n”); break;

}

Page 33: SysProg-Tutor 01 Introduction to C Programming Language

33 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Control Flow

While StatementThe expression is evaluated. If it is true, statement is executed and expression is reevaluated. This cycle continues until expression becomes false.

while (expression) {Statement1;Statement2;...

}

Iteration Statements

Page 34: SysProg-Tutor 01 Introduction to C Programming Language

34 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Control Flow

Example of While

#include <stdio.h>#define DOT ‘.’main() {

char C;while ((C = getchar())!= DOT)

putchar(C);printf(“Good Bye.\n”);

}

Result?

Iteration Statements (Cont)

Page 35: SysProg-Tutor 01 Introduction to C Programming Language

35 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Control Flow

Do-While StatementThe do-while, tests at the bottom after making each pass through the loop body; the body is always executed at least once.

do {statement1;statement2;…

} while (expression);

Iteration Statements (Cont)

Page 36: SysProg-Tutor 01 Introduction to C Programming Language

36 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Control Flow

Example of Do-While

int i = 1, sum = 0;do {

sum += i;i++;

} while (i <= 50);printf(“The sum of 1 to 50 is %d\n”, sum);

Result?

Iteration Statements (Cont)

Page 37: SysProg-Tutor 01 Introduction to C Programming Language

37 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Control Flow

For StatementThe for statement

for (initial; expression; update) {statement;

}

Equivalent to

initial;while (expression) {

statement;update;

}

Iteration Statements (Cont)

Page 38: SysProg-Tutor 01 Introduction to C Programming Language

38 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Control Flow

Example of Forfor (i=1;i<=100;i++) {

x += i;if ((x % i) == 0) { i--; }

}

Iteration Statements (Cont)

for (i=0, j=strlen(s)-1; i<j; i++,j--){ c = s[i], s[i] = s[j], s[j] = c; }

char c;int count;for (count=0; (c=getchar() != ‘.’); count++)

{ }printf(“Number of characters is %d\n”, count);

Page 39: SysProg-Tutor 01 Introduction to C Programming Language

39 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Control Flow

Break and Continue StatementThe break statement provides an early exit from for, while, and do-while.

break;

The continue statement is related to break, but less often used; it causes the next iteration of the enclosing for, while, or do-while loop to begin.

continue;

Sequential Statements

Page 40: SysProg-Tutor 01 Introduction to C Programming Language

40 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Control Flow

Example of Break and Continue

int c;while ((c = getchar()) != -1) {

if (C == ‘.’)break;

else if (c >= ‘0’ && c <= ‘9’)continue;

else putchar(c);}printf(“*** Good Bye ***\n”);

Sequential Statements (Cont)

Page 41: SysProg-Tutor 01 Introduction to C Programming Language

41 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Functions and Program Structure

Functions (Method in Java) break large computing tasks into smaller ones, and enable people to build on what others have done instead of starting over from scratch.

function-name (argument declarations) {[ declaration-list][ statement-list ]

}

Page 42: SysProg-Tutor 01 Introduction to C Programming Language

42 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Functions and Program Structure

Example of Function

(Cont)

/* Programming in function */main() {

int hours, minutes, seconds;int total_time = 0;int convert(); printf(“Enter time in hours-minutes-seconds : “);scanf(“%d %d %d”, &hours, &minutes, &seconds);total_time = convert(hours, minutes, seconds);

/* calling point */printf(“The converted time is %d seconds\n”,

total_time);}

Page 43: SysProg-Tutor 01 Introduction to C Programming Language

43 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Functions and Program Structure

Example of Function (Cont)

(Cont)

/* Function (called function) */int convert (h, m, s)int h, m, s;{

int time; /* return-value variable */time = (60 * h + m) * 60 + s;return time; /* exiting point */

}

Page 44: SysProg-Tutor 01 Introduction to C Programming Language

44 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Functions and Program Structure

Example of Non-Return Function

Non-Return Function

/* Main */main() {

void display();display();

}

/* Function Part */void display() {

printf(“*** Hello and Good bye ***”);}

Page 45: SysProg-Tutor 01 Introduction to C Programming Language

45 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Functions and Program Structure

Example of Return Function

Return Function

/* Main Function */main() {

float sq,x;float square();sq = square(x);printf(“The square of x is %f\n”, sq);

}

/* Function: square */float square(x) {

return(x * x);}

Page 46: SysProg-Tutor 01 Introduction to C Programming Language

46 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Functions and Program Structure

Example of External Variable

External Variable

main() {int k = 15;func1();func2();printf(“k = %d\n”, k);

}

int k = 5; /* External Variable */

func1() { printf(“k = %d\n”, k); } /*Function 1*/func2() { printf(“k = %d\n”, k); } /*Function 2*/

k = 5k = 5k = 15

Page 47: SysProg-Tutor 01 Introduction to C Programming Language

47 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Functions and Program Structure

Example of Recursive Function

Recursive Function

main() { /* Main Part */int j;long int factorial();for (j = 0; j <= 10; j++)

printf(“%2d! is %ld\n”, j, factorial(j));}

long int factorial(n) /* Function Part */int n;{ if (n == 0) return (1);

else return (n * factorial(n-1));}

Page 48: SysProg-Tutor 01 Introduction to C Programming Language

48 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Functions and Program Structure

#include <stdio.h>

clearerrfclosefeofferrorfflushfgetcfgetsfopen

fprintffputcfputsFreadfreopenfscanffseekftell

fwritegetcgetchargetsprintfputcputcharputs

rewindscanfsprintfsscanfungetc

The Standard C Library Functions

Page 49: SysProg-Tutor 01 Introduction to C Programming Language

49 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Functions and Program Structure

#include <math.h>

acos(x)asin(x)atan(x)ceil(x)cos(x)cosh(x)exp(x)fabs(x)

floor(x)log(x)log10(x)sin(x)sinh(x)sqrt(x)tan(x)tanh(x)

atan2(x,y)power(x,y)

The Standard C Library Functions (Cont)

Page 50: SysProg-Tutor 01 Introduction to C Programming Language

50 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Functions and Program Structure

#include <ctype.h>

The Standard C Library Functions (Cont)

isalnumisalphaisasciiiscntrlisdigitisgraphislowerisprint

ispunctisspaceisuppertolowertoupper

Page 51: SysProg-Tutor 01 Introduction to C Programming Language

51 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Array, Pointer and String

Array is a group of related data items. In C, there is a strong relationship between pointers and arrays, strong enough that pointers and arrays should be discussed simultaneously.The declaration of one-dimensional array

type array-name[number-of-elements];

int a[15];

Array

a[0], a[1], a[2], … , a[14] = 15 Element

Page 52: SysProg-Tutor 01 Introduction to C Programming Language

52 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Array, Pointer and String

In the main memory

Array (Cont)

a a[0] 5501a[1] 5502a[2] 5503

… …… …… …

a[14] 5514

Value Address

int a[15];

Page 53: SysProg-Tutor 01 Introduction to C Programming Language

53 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Array, Pointer and String

Example of Array

Array (Cont)

/* Read five integers from the standard input and display them in reverse order */

#define MAX 5main() {

int j;int a[MAX];

for (j = 0; j < MAX; j++)scanf(“%d”, &a[j]);

for (j = MAX - 1; j >= 0; j--)printf(“%d\n”, a[j]);

}

Page 54: SysProg-Tutor 01 Introduction to C Programming Language

54 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Array, Pointer and String

A pointer is a variable that contains the address of a variable.Example of pointer

Pointer

Value Address

x 25 7960

px 8132

px = &x

int x = 25;int *px;px = &x;int y = *px;//y = x = 25

x = 25

y = *pxy

7960

Page 55: SysProg-Tutor 01 Introduction to C Programming Language

55 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Array, Pointer and String

Example (Cont)Pointer (Cont)

main() {int x = 5, *px;px = &x;int y = *px;printf("x = %d\n", x);printf("y = %d\n", y);printf("*px = %d\n", *px);printf("&x = %d\n", &x);printf("px = %d\n", px);printf("&y = %d\n", &y);x = 34;printf("px = %d\n", px);printf("*px = %d\n", *px);printf("y = %d\n", y);

}

x = 5y = 5*px = 5&x = -4195036px = -4195036&y = -4195044

px = -4195036*px = 34y = 5

Page 56: SysProg-Tutor 01 Introduction to C Programming Language

56 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Array, Pointer and String

Example

Pointer (Cont)

main() {int t[10];int *pt;for (pt = t; pt < &t[10]; pt++)

scanf(“%d”, pt);for (pt = &t[10]; pt >= t; pt--)

printf(“%d\n”, *pt);}

int x;int *px, *py;px = &x;py = px;

xpx

py

Page 57: SysProg-Tutor 01 Introduction to C Programming Language

57 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Array, Pointer and String

Example (Cont)

Pointer (Cont)

int x = 1, y = 2, z[10];int *ip; /* ip is a pointer to int */ip = &x; /* ip now points to x */y = *ip; /* y is now 1 */*ip = 0; /* x is now 0 */ip = &z[0]; /* ip now points to z[0] */

Help me!!

Page 58: SysProg-Tutor 01 Introduction to C Programming Language

58 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Array, Pointer and String

A string constant, written as "I am a string" is an array of characters. In the internal representation, the array is terminated with the null character '\0'so that programs can find the end.Example

String

char amessage[] = "now is the time";/* an array */char *pmessage = "now is the time";/* a pointer */

Page 59: SysProg-Tutor 01 Introduction to C Programming Language

59 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Array, Pointer and String

Example of String

String (Cont)

char s1[] = “xyz”;char s2[] = {‘x’, ‘y’, ‘z’, ‘\0’};char *s3 = “xyz”;

x

y

z

\0

Page 60: SysProg-Tutor 01 Introduction to C Programming Language

60 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Array, Pointer and String

Example/* COUNT THE LENGTH OF STRING */main() {

char *w = “good morning”;int len();printf(“Lengths of string is %d\n”, len(w));

}

/* FUNCTION: len() for counting the length of string */int len(string)char string[]; // char *string;{

int count = 0;while (string[count] != NULL) count++;return (count);

}

String (Cont)

Page 61: SysProg-Tutor 01 Introduction to C Programming Language

61 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Structures

A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling.Structures are called "records'' insome languages, notably Pascal.

struct structure-name { type-specifier variable;...

};

Members

Page 62: SysProg-Tutor 01 Introduction to C Programming Language

62 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Structures

Example of Structure(Cont)

struct person {int code;char name[30];char address[40];float salary;

};

struct point {int x;int y;

};

int x int y

int code

string name

string address

float salary

Record = Node

Page 63: SysProg-Tutor 01 Introduction to C Programming Language

63 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Structures

A struct declaration defines a type.

struct structure-name variable-name,…;

Or declare in

struct structure-name { type-specifier variable;...

}variable-name;

(Cont)

Page 64: SysProg-Tutor 01 Introduction to C Programming Language

64 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Structures

Example of Structure Declaration

(Cont)

struct person {int code;char name[30];char address[40];float salary;

}p;

struct person {int code;char name[30];char address[40];float salary;

};struct person p;

or

Page 65: SysProg-Tutor 01 Introduction to C Programming Language

65 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Structures

A member of a particular structure is referred to in an expression by a construction of the form

struct-variable-name.member-name

Examplep.code;p.name;p.address;p.salary;

(Cont)

Page 66: SysProg-Tutor 01 Introduction to C Programming Language

66 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Structures

Example of Struct Program(Cont)

/* ASSIGN AND PRINT A DATE */main() {

struct date {int dd = 22;int mm;int yyyy;

};struct date today;today.mm = 6;today.yyyy = 2007;printf(“Date is %2d/%2d/%4d\n”, today.dd,

today.mm, today.yyyy);}

//ResultDate is 22/ 6/2007

Page 67: SysProg-Tutor 01 Introduction to C Programming Language

67 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

File Operations

The input and output functions, types, and macros defined in <stdio.h> represent nearly one third of the library.The following functions deal with operations on files:

fopen(filename, mode);fclose(file pointer);feof(file pointer);getc();putc();

Page 68: SysProg-Tutor 01 Introduction to C Programming Language

68 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

File Operations

fopen() - opens the named file, and returns a stream, or NULL if the attempt fails. Legal values for mode include:

"r" open text file for reading"w" create text file for writing; discard previous contents if

any"a" append; open or create text file for writing at end of file"r+" open text file for update (reading and writing)"w+" create text file for update, discard previous contents if

any"a+" append; open or create text file for update, writing at

end

(Cont)

Page 69: SysProg-Tutor 01 Introduction to C Programming Language

69 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

File Operations

Example of fopen() to open file

(Cont)

FILE *file;FILE *fopen();

if ((file = fopen(“person.dat”, “r”)) == NULL)printf(“Cannot open a data file\n”);

else...

File Pointer

Page 70: SysProg-Tutor 01 Introduction to C Programming Language

70 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

File Operations

fclose() – close file, flushes any unwritten data for stream, discards any unread buffered input, frees any automatically allocated buffer, then closes the stream. It returns EOF if any errors occurred, and zero otherwise.Example

(Cont)

int fclose();...if (fclose(file) != EOF)

printf(“Cannot close file\n”;else printf(“Now file is closed\n”);

Page 71: SysProg-Tutor 01 Introduction to C Programming Language

71 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

File Operations

feof() – check for end of file.

getc() is equivalent to fgetc except that if it is a macro, it may evaluate stream more than once.

int getc(file pointer);

putc() is equivalent to fputc except that if it is a macro, it may evaluate stream more than once.

int putc(char c, file pointer);

putchar(c) is equivalent to putc(c,stdout).int putchar(char c);

(Cont)

if (!feof(file))printf(“It is not the end of file now\n”);

Page 72: SysProg-Tutor 01 Introduction to C Programming Language

72 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

File Operations

fprintf() converts and writes output to stream under the control of format. The return value is the number of characters written, or negative if an error occurred.

int fprintf(file pointer, format, ...)

fscanf() reads from stream under control of format, and assigns converted values through subsequent arguments, each of which must be a pointer.

int fscanf(file pointer, format, ...)

(Cont)

Page 73: SysProg-Tutor 01 Introduction to C Programming Language

73 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Example of File Operations Program

File Operations(Cont)

/* A PROGRAM TO WRITE ONE LINE TO sample.txt */#include <stdio.h>main() {

FILE *fp;char c = ‘ ‘;fp = fopen(“sample.txt”, “w”);printf(“Enter text below\n”);while (c != ‘\n’) {

c = getchar();putc(c, fp);

}fclose(fp);

}

Page 74: SysProg-Tutor 01 Introduction to C Programming Language

74 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

Example of File Operations Program (Cont)

File Operations(Cont)

/* A PROGRAM TO READ TEXT FROM sample.txt AND DISPLAY ON A MONITOR */#include <stdio.h>main() {

FILE *fp;char c;fp = fopen(“sample.txt”, “r”);if (fp == NULL)

printf(“The file cannot be opened\n”);else

while ((c = getc(fp) != EOF) putchar(c);fclose(fp);

}

Page 75: SysProg-Tutor 01 Introduction to C Programming Language

75 2110313 Operating Systems and System Programs (1/2010)

Tutor Session - 1

Chulalongkorn University

End

Question ?

… Answer