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
75
Embed
SysProg-Tutor 01 Introduction to C Programming Language
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
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
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
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
Examplefag = x % y;c = a – (a/b)*b;sum = var1 + var2 + var3;
Expression and Operations
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)
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)
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
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)
20 2110313 Operating Systems and System Programs (1/2010)
Types, Operators and ExpressionsExpression and Operations (Cont)
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
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)
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)
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)
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)
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
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
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)
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”);}
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.
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;
}
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
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)
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)
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)
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)
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; }
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
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)
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.
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
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];
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]);
}
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
55 2110313 Operating Systems and System Programs (1/2010)
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!!
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 */
59 2110313 Operating Systems and System Programs (1/2010)
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)
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.
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
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)
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
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:
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)
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
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”);
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”);
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)
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);
}
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() {