SlideShare a Scribd company logo
1 of 75
Download to read offline
Tutor Session - 1




Chulalongkorn
                                                                             Tutor Session I:


               Introduction to C
 University




         Programming Language

                Wongyos Keardsri (P’Bank)
                Department of Computer Engineering
                Faculty of Engineering, Chulalongkorn University
                Bangkok, Thailand
                Mobile Phone: 089-5993490
                E-mail: wongyos@gmail.com, MSN: bankberrer@hotmail.com
                Twitter: @wongyos
                                                 2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                                                         Tutor Outline
Chulalongkorn
 University



                Introduction                                  While
                   C History                                  Do-While
                   C Language VS Java Language                For
                   C Language Structure                  Functions and Program
                Types, Operators and                     Structure
                Expressions                                   Non-Return Function
                Data Input and Output                         Return Function
                   printf()                                   The Standard C Library
                                                              Functions
                   scanf()
                Control Flow                             Array, Pointer and String
                   If-Else                               Structures
                   Switch                                File Operations

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



                                                 Introduction
Chulalongkorn
 University                                                         C History
                C is a structured computer
                programming language
                Appeared in1972 (1970s)
                Designed and Developed by Dennis
                Ritchie at the Bell Telephone
                Laboratories
                Derived from B and BCPL programming
                language
                Developed for the UNIX operating
                system
         3                          2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                                                           Introduction
Chulalongkorn
 University                                                     C History (Cont)
                Used and Implemented for:
                  System programming
                  Operating systems
                  Embedded system applications
                C standard: ANSI C and ISO C
                Book: The C Programming
                Language, 2nd edition


             http://en.wikipedia.org/wiki/C_(programming_language)
         4                                    2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                                                   Introduction
Chulalongkorn
 University                          C Language VS Java Language
                Example C Code (Hello.c)
                #include <stdio.h>
                main() {
                   printf("Hello CPn");
                }

                Example Java Code (Hello.java)
                public class Hello {
                   public static void main(String[] args) {
                       System.out.print("Hello CPn");
                   }
                }

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



                                                         Introduction
Chulalongkorn
 University                       C Language VS Java Language (Cont)
                C: Structured                      Java: Object-Oriented
                Programming                        Programming
                C Compiler                         Java Compiler (JVM)
                Editor: Turbo C, vi, etc.          Editor: JLab, Eclipse, etc.
                Compile: (UNIX)                    Compile:
                gcc Hello.c                         javac Hello.java
                After compile                      After compile
                   a.out                                Hello.class
                Run:                               Run:
                ./a.out                             java Hello
                Hello CP                            Hello CP
                            Show an example                           Show an example
         6                                  2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                                                     Introduction
Chulalongkorn
 University                                       C Language Structure
                General format
                 #include <stdio.h>            Preprocessor / Including Library
                 #include <…………………>

                 main() {     Begin
                                               Function main:
                     [function-body];
                                               [declaration-list] + [statement-list]
                 }     End
                  .
                  .                                Semicolon
                  .
                 type func() {
                                               Function func:
                     [function-body];          [declaration-list] + [statement-list]
                 }
         7                              2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                                                    Introduction
Chulalongkorn
 University                          C Language Structure (Cont)
                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 %dn", sum);
                }




                The sum of 15 and 25 is 40

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



                                               Introduction
Chulalongkorn
 University                      C Language Structure (Cont)
                Compile C by UNIX command
                cc option file1 file2 …

                Example 1
                gcc example.c                               Compile

                  a.out

                ./a.out                                        Run



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



                                                            Introduction
Chulalongkorn
 University                                   C Language Structure (Cont)
                Example 2
                gcc –c example.c                                         Compile

                example.o       Object file

                                                                            Convert to
                gcc –o example.run example.o
                                                                           Executable file

                example.run     Executable file

                ./example.run                                              Run


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



                                                         Introduction
Chulalongkorn
 University                               C Language Structure (Cont)
                Example 3
                gcc –o example.run example.c                          Compile

                example.run     Executable file

                ./example.run                                           Run



                                    Wow



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



                Types, Operators and Expressions
Chulalongkorn
 University                                   Data Types and Sizes

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



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



                 Types, Operators and Expressions
Chulalongkorn
 University                                    Variable Declaration


           type-specifier       list-of-variables;

                Example
                  int 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;
         13                       2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                 Types, Operators and Expressions
Chulalongkorn
 University                                    Constant Declaration


           #define VARIABLE constant-value
                                                     Note
                Example
                  #define MAX   500       #include <stdio.h>
                                          #define XX 0
                  #define STEP 20
                                          main() {
                  #define PI 3.14159265      // Body program
                  #define VTAB 't'       }

                  const char msg[] = "warning: ";
                  const double e = 2.71828182845905;
         14                         2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                 Types, Operators and Expressions
Chulalongkorn
 University                            Expression and Operations
                Arithmetic Operators
                  Addition             +
                  Subtraction          -
                  Multiplication       *
                  Division             /
                  Modulation           %
                Example
                  fag = x % y;
                  c = a – (a/b)*b;
                  sum = var1 + var2 + var3;

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



                 Types, Operators and Expressions
Chulalongkorn
 University                     Expression and Operations (Cont)
                Relational Operators
                  Less than            <                a   < 5
                  Less than or equal   <=               a   <= b
                  More than            >                a   > b+c
                  More than or equal   >=               a   >= b + 5
                  Equal                ==               a   == -6
                  Not equal            !=               a   != 0
                Logical Operators
                  AND                  &&               (a > 0) && (b > 0)
                  OR                   ||               (a <= 0) || (b <= 0)
                  Negation             !                !(a && c)
         16                            2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                 Types, Operators and Expressions
Chulalongkorn
 University                     Expression and Operations (Cont)
                Bitwise Operators
                  Bitwise AND                               &
                  Bitwise OR (Inclusive OR)                 |
                  Bitwise XOR (Exclusive OR)                ^
                  Left shift                                <<
                  Right shift                               >>
                  One's complement                          ~
                Example
                  x = 01001011        y = 00101100     ~x = 10110100
                  x & y = 00001000    x | y = 01101111
                  x ^ y = 01100111    x << 2 = 00101100
         17                            2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                 Types, Operators and Expressions
Chulalongkorn
 University                       Expression and Operations (Cont)
                Assignment Operators and Expressions
                  op is + - * / % << >> &                                  ^      |
                  If expr1 and expr2 are expressions, then
                  expr1 op= expr2
                  Equivalent to
                  expr1 = (expr1) op (expr2)

                Example
                  X += 1;
                                    Equivalent
                  X = X + 1;
         18                              2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                 Types, Operators and Expressions
Chulalongkorn
 University                      Expression and Operations (Cont)
                Conditional Expressions
                  expr1 ? expr2 : expr3

                  If expr1 is true do expr2
                  If expr1 is false do expr3
                Example
                  a = 5;
                  b = 10;
                  min = (a < b) ? a : b;

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



                 Types, Operators and Expressions
Chulalongkorn
 University                     Expression and Operations (Cont)
                Increment and Decrement Operators
                  Pre-increment operation         ++variable
                  Post-increment operation        variable++
                  Pre-decrement operation         --variable
                  Post-decrement operation        variable--
                Example
                  x   =   4;
                  y   =   x++ + 5;           //x = 5, y = 9
                  x   =   4;
                  y   =   ++x + 5;           //x = 5, y = 10

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



                 Types, Operators and Expressions
Chulalongkorn
 University                    Expression and Operations (Cont)
                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;

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



                               Data Input and Output
Chulalongkorn
 University                                              printf() Statement
              printf() is a function for display result to standard
              output (Monitor, Screen)

                printf(format, arg1, arg2, …);

              Example
                printf(“Hellon”);
                //Hello
                int num = 2;
                printf(“%d is integer”, num);
                //2 is integer
         22                             2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                               Data Input and Output
Chulalongkorn
 University                                     printf() Statement (Cont)
                Conversion Operation [printf()]
                  d      signed decimal conversion of an int or a long
                  u      unsigned decimal conversion of unsigned
                  o      unsigned octal conversion of unsigned
                  x, X   unsigned hexadecimal conversion of unsigned
                         x = [a – f], X = [A - F]
                  c      single character conversion
                  s      string conversion
                  f      signed decimal floating point conversion
                  e, E   signed decimal floating point conversion in scientific
                         notation

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



                              Data Input and Output
Chulalongkorn
 University                                 printf() Statement (Cont)
              Example of printf()
           int     j = 45, k = -123;
           float   x = 12.34;
           char    c = ‘w’;
                                                          Result
           char    *m = “Hello”;
           printf(“Hello 55”);                           Hello 55
           printf(“Tax is %d”, j);                       Tax is 45
           printf(“%d”, j+k);                            -78
           printf(“%3d %d”, j, k);                        45 -123
           printf(“%f %.2f”, x, x);                      12.340000 12.34
           printf(“%c”, c);                              w
           printf(“%sn”, m);                            Hello
           printf(“%sn”, “Hello”);                      Hello
           printf(“%10sn”, “Hello”);                          Hello
         24                             2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                              Data Input and Output
Chulalongkorn
 University                                              scanf() Statement
              scanf() is a function for read input from standard
              input (Keyboard)

                scanf(format, arg1, arg2, …);

              Example
                scanf(“%d %d %d”, &day, &month, &year);
                int num;
                printf(“Enter integer : ”);
                scanf(“%d”, &num);
                // Enter integer : 23
         25                            2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                               Data Input and Output
Chulalongkorn
 University                                       scanf() Statement (Cont)
                Conversion Operation [scanf()]
                  d      signed decimal conversion of an int or a long
                  u      unsigned decimal conversion of unsigned
                  o      unsigned octal conversion of unsigned
                  x, X   unsigned hexadecimal conversion of unsigned
                         x = [a – f], X = [A - F]
                  c      single character conversion
                  s      string conversion
                  f      signed decimal floating point conversion
                  e, E   signed decimal floating point conversion in scientific
                         notation
                  []     read only character in [ ], if [^ ] read different character
         26                                  2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                              Data Input and Output
Chulalongkorn
 University                                 scanf() Statement (Cont)
              Example of scanf()
           int d,m,y,x;
           char ch1,ch2;
                                                  Result
           float f;
           scanf(“%d”, &x);                       4
                                                  // x=4
           scanf(“%2d%2d%4d”, &d,&m,&y);          22062007
                                                  // d=22, m=6, y=2007
           scanf(“%d/%d/%d”, &d,&m,&y);           22/06/2007
                                                  // d=22, m=6, y=2007
           scanf(“%c%c”, &ch1,&ch2);              Ab
                                                  // ch1=‘A’, ch2=‘b’
           scanf(“%f”, &f);                       2.3
                                                  // f=2.300000

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



                                                    Control Flow
Chulalongkorn
 University                                            Decision Statements
                If-Else Statement
                  The if-else statement is used to express decisions.
                  Formally the syntax is

                  if (expression) {
                     true statement
                  } else {
                     false statement
                  }


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



                                                    Control Flow
Chulalongkorn
 University                               Decision Statements (Cont)
                Nested If-Else
                  The 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
                  }
         29                               2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                                               Control Flow
Chulalongkorn
 University                          Decision Statements (Cont)
                Example of If-Else

          if (a < b) {                      if (score >= 80)
             printf(“a less than                 grade = ‘A’;
                    bn”);                  else if (score >= 70)
          } else {                               grade = ‘B’;
             temp = a;                      else if (score >= 50)
             a = b;    /* swap a */
                                                 grade = ‘C’;
             b = temp; /* and b */          else if (score >= 40)
             printf(“Interchange a               grade = ‘D’;
                    and bn”);
                                            else
          }
                                                 grade = ‘F’;


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



                                                     Control Flow
Chulalongkorn
 University                               Decision Statements (Cont)
                Switch Statement
                  The 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: statements
                     case const-expr: statements
                     default: statements
                  }

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



                                               Control Flow
Chulalongkorn
 University                          Decision Statements (Cont)
                Example of Switch
                c = getchar();
                switch (c) {
                   case '0': printf(“Zeron”); break;
                   case '1': case '2': case '3': case '4':
                   case '5': case '6': case '7': case '8':
                   case '9': printf(“Ninen”); break;
                   case ' ':
                   case 'n': newln++; break;
                   case 't': tabs++; break;
                   default: printf(“missing charn”); break;
                }

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



                                                      Control Flow
Chulalongkorn
 University                                              Iteration Statements
                While Statement
                  The 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;
                     ...
                  }

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



                                               Control Flow
Chulalongkorn
 University                          Iteration Statements (Cont)
                Example of While
                #include <stdio.h>
                #define DOT ‘.’
                main() {
                   char C;
                   while ((C = getchar())!= DOT)
                      putchar(C);
                   printf(“Good Bye.n”);
                }

                           Result?



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



                                                   Control Flow
Chulalongkorn
 University                              Iteration Statements (Cont)
                Do-While Statement
                  The 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);

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



                                                Control Flow
Chulalongkorn
 University                           Iteration Statements (Cont)
                Example of Do-While
                int i = 1, sum = 0;
                do {
                  sum += i;
                  i++;
                } while (i <= 50);
                printf(“The sum of 1 to 50 is %dn”, sum);



                           Result?



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



                                                Control Flow
Chulalongkorn
 University                           Iteration Statements (Cont)
                For Statement
                  The for statement

                  for (initial; expression; update) {
                    statement;
                  }

                  Equivalent to
                  initial;
                  while (expression) {
                     statement;
                     update;
                  }
         37                           2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                                             Control Flow
Chulalongkorn
 University                       Iteration Statements (Cont)
                Example of For
           for (i=1;i<=100;i++) {
              x += i;
              if ((x % i) == 0) { i--; }
           }

           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 %dn”, count);
         38                        2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                                                    Control Flow
Chulalongkorn
 University                                         Sequential Statements
                Break and Continue Statement
                  The 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;
         39                               2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                                               Control Flow
Chulalongkorn
 University                         Sequential Statements (Cont)
                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”);


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



                   Functions and Program Structure
Chulalongkorn
 University




                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 ]
                }

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



                  Functions and Program Structure
Chulalongkorn
 University                                                                 (Cont)
                Example of Function
          /* 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 secondsn”,
                     total_time);
          }

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



                   Functions and Program Structure
Chulalongkorn
 University                                                                 (Cont)
                Example of Function (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 */
          }




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



                  Functions and Program Structure
Chulalongkorn
 University                                      Non-Return Function
                Example of Non-Return Function
                 /* Main */
                 main() {
                    void display();
                    display();
                 }

                 /* Function Part */
                 void display() {
                    printf(“*** Hello and Good bye ***”);
                 }

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



                   Functions and Program Structure
Chulalongkorn
 University                                                Return Function
                Example of Return Function
                 /*   Main Function   */
                 main() {
                    float sq,x;
                    float square();
                    sq = square(x);
                    printf(“The square of x is %fn”, sq);
                 }

                 /* Function: square   */
                 float square(x) {
                    return(x * x);
                 }
         45                            2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                   Functions and Program Structure
Chulalongkorn
 University                                                External Variable
                Example of External Variable
                 main() {
                      int k = 15;                               k = 5
                      func1();                                  k = 5
                      func2();                                  k = 15
                      printf(“k = %dn”, k);
                 }

                 int   k = 5; /* External Variable */

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

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



                   Functions and Program Structure
Chulalongkorn
 University                                            Recursive Function
                Example of Recursive Function
                 main() { /* Main Part */
                    int j;
                    long int factorial();
                    for (j = 0; j <= 10; j++)
                       printf(“%2d! is %ldn”, j, factorial(j));
                 }

                 long int factorial(n) /* Function Part */
                 int n;
                 { if (n == 0) return (1);
                    else return (n * factorial(n-1));
                 }
         47                             2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                  Functions and Program Structure
Chulalongkorn
 University                  The Standard C Library Functions
                #include <stdio.h>
                  clearerr   fprintf             fwrite                  rewind
                  fclose     fputc               getc                    scanf
                  feof       fputs               getchar                 sprintf
                  ferror     Fread               gets                    sscanf
                  fflush     freopen             printf                  ungetc
                  fgetc      fscanf              putc
                  fgets      fseek               putchar
                  fopen      ftell               puts

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



                  Functions and Program Structure
Chulalongkorn
 University             The Standard C Library Functions (Cont)
                #include <math.h>
                  acos(x)     floor(x)             atan2(x,y)
                  asin(x)     log(x)               power(x,y)
                  atan(x)     log10(x)
                  ceil(x)     sin(x)
                  cos(x)      sinh(x)
                  cosh(x)     sqrt(x)
                  exp(x)      tan(x)
                  fabs(x)     tanh(x)

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



                  Functions and Program Structure
Chulalongkorn
 University             The Standard C Library Functions (Cont)
                #include <ctype.h>
                  isalnum     ispunct
                  isalpha     isspace
                  isascii     isupper
                  iscntrl     tolower
                  isdigit     toupper
                  isgraph
                  islower
                  isprint

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



                           Array, Pointer and String
Chulalongkorn
 University                                                                    Array
                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];       a[0], a[1], a[2], … , a[14] = 15 Element

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



                          Array, Pointer and String
Chulalongkorn
 University                                                      Array (Cont)
                In the main memory
                       Value    Address

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

                         …      …                           int a[15];
                         …      …
                         …      …

                        a[14]   5514



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



                            Array, Pointer and String
Chulalongkorn
 University                                                        Array (Cont)
                Example of Array
                /* Read five integers from the standard input and
                display them in reverse order */

                #define MAX 5
                main() {
                   int j;
                   int a[MAX];

                    for (j = 0; j < MAX; j++)
                         scanf(“%d”, &a[j]);
                    for (j = MAX - 1; j >= 0; j--)
                         printf(“%dn”, a[j]);
                }
         53                              2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                              Array, Pointer and String
Chulalongkorn
 University                                                                        Pointer
                A pointer is a variable that contains the address of
                a variable.
                Example of pointer
                        Value        Address

                   x     25          7960           x = 25            int x = 25;
                                                                      int *px;
                          …                                           px = &x;
                                                                      int y = *px;
                  px     7960        8132          px = &x            //y = x = 25


                   y       y = *px
         54                                    2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                             Array, Pointer and String
Chulalongkorn
 University                                                       Pointer (Cont)
                Example (Cont)
                 main() {
                    int x = 5, *px;
                    px = &x;
                    int y = *px;
                    printf("x = %dn", x);                x = 5
                    printf("y = %dn", y);                y = 5
                    printf("*px = %dn", *px);            *px = 5
                    printf("&x = %dn", &x);              &x = -4195036
                    printf("px = %dn", px);              px = -4195036
                    printf("&y = %dn", &y);              &y = -4195044
                    x = 34;
                    printf("px = %dn", px);              px = -4195036
                    printf("*px = %dn", *px);            *px = 34
                    printf("y = %dn", y);                y = 5
                 }
         55                                2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                           Array, Pointer and String
Chulalongkorn
 University                                                      Pointer (Cont)
                Example
                int x;
                int *px, *py;
                                                           px              x
                px = &x;                                    py
                py = px;

                main()  {
                   int  t[10];
                   int  *pt;
                   for  (pt = t; pt < &t[10]; pt++)
                          scanf(“%d”, pt);
                    for (pt = &t[10]; pt >= t; pt--)
                          printf(“%dn”, *pt);
                }
         56                             2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                          Array, Pointer and String
Chulalongkorn
 University                                                     Pointer (Cont)
                Example (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!!




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



                            Array, Pointer and String
Chulalongkorn
 University                                                                    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
                char amessage[] = "now is the time";
                /* an array */
                char *pmessage = "now is the time";
                /* a pointer */

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



                           Array, Pointer and String
Chulalongkorn
 University                                                     String (Cont)
                Example of String
                 char s1[] = “xyz”;
                 char s2[] = {‘x’, ‘y’, ‘z’, ‘0’};
                 char *s3 = “xyz”;



                           x
                           y
                           z
                           0

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



                           Array, Pointer and String
Chulalongkorn
 University                                                        String (Cont)
                Example
            /* COUNT THE LENGTH OF STRING */
            main() {
               char *w = “good morning”;
               int len();
               printf(“Lengths of string is %dn”, 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);
            }
         60                              2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                                                            Structures
Chulalongkorn
 University



                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
                   ...
                };
         61                              2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                                                      Structures
Chulalongkorn
 University                                                              (Cont)
                Example of Structure
            struct person {                        Record = Node
               int code;
               char name[30];            int      string       string        float
               char address[40];        code      name        address       salary
               float salary;
            };


                                struct point {
                                   int x;
                                                                 int x      int y
                                   int y;
                                };

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



                                                           Structures
Chulalongkorn
 University                                                                   (Cont)
                A struct declaration defines a type.

                struct structure-name variable-name,…;


                Or declare in
                struct structure-name {
                   type-specifier variable;
                   ...
                }variable-name;

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



                                                           Structures
Chulalongkorn
 University                                                                   (Cont)
                Example of Structure Declaration
                 struct person {                 struct person {
                    int code;                        int code;
                    char name[30];                   char name[30];
                    char address[40];     or         char address[40];
                    float salary;                    float salary;
                 };                              }p;
                 struct person p;




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



                                                          Structures
Chulalongkorn
 University                                                                  (Cont)
                A member of a particular structure is referred to
                in an expression by a construction of the form

                struct-variable-name.member-name

                Example
                p.code;
                p.name;
                p.address;
                p.salary;

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



                                                           Structures
Chulalongkorn
 University                                                                   (Cont)
                Example of Struct Program
                /* ASSIGN AND PRINT A DATE */
                main() {
                   struct date {                 //Result
                      int dd = 22;               Date is 22/ 6/2007
                      int mm;
                      int yyyy;
                   };
                   struct date today;
                   today.mm = 6;
                   today.yyyy = 2007;
                   printf(“Date is %2d/%2d/%4dn”, today.dd,
                           today.mm, today.yyyy);
                }
         66                             2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                                           File Operations
Chulalongkorn
 University



                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();

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



                                               File Operations
Chulalongkorn
 University                                                                     (Cont)
           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
         68                               2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                                            File Operations
Chulalongkorn
 University                                                                  (Cont)
           Example of fopen() to open file
                FILE *file;       File Pointer
                FILE *fopen();

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




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



                                              File Operations
Chulalongkorn
 University                                                                    (Cont)
                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
                int fclose();
                ...
                if (fclose(file) != EOF)
                    printf(“Cannot close filen”;
                else printf(“Now file is closedn”);
         70                              2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                                                 File Operations
Chulalongkorn
 University                                                                       (Cont)
                feof() – check for end of file.
                if (!feof(file))
                   printf(“It is not the end of file nown”);

                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);
         71                                 2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                                               File Operations
Chulalongkorn
 University                                                                     (Cont)
                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, ...)




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



                                             File Operations
Chulalongkorn
 University                                                                   (Cont)
                Example of File Operations Program
                /* 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 belown”);
                   while (c != ‘n’) {
                        c = getchar();
                        putc(c, fp);
                   }
                   fclose(fp);
                }
         73                             2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                                             File Operations
Chulalongkorn
 University                                                                   (Cont)
                Example of File Operations Program (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 openedn”);
                   else
                        while ((c = getc(fp) != EOF) putchar(c);
                   fclose(fp);
                }
         74                             2110313 Operating Systems and System Programs (1/2010)
Tutor Session - 1



                                                               End
Chulalongkorn
 University




                Question ?


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

More Related Content

What's hot

Different phases of a compiler
Different phases of a compilerDifferent phases of a compiler
Different phases of a compilerSumit Sinha
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programmingManoj Tyagi
 
Compiler an overview
Compiler  an overviewCompiler  an overview
Compiler an overviewamudha arul
 
Unit 2 introduction to c programming
Unit 2   introduction to c programmingUnit 2   introduction to c programming
Unit 2 introduction to c programmingMithun DSouza
 
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGESOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGEIJCI JOURNAL
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programmingRutvik Pensionwar
 
Why C is Called Structured Programming Language
Why C is Called Structured Programming LanguageWhy C is Called Structured Programming Language
Why C is Called Structured Programming LanguageSinbad Konick
 
Lec 01 basic concepts
Lec 01 basic conceptsLec 01 basic concepts
Lec 01 basic conceptsAbdul Khan
 
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...Prof Chethan Raj C
 
Compiler Engineering Lab#1
Compiler Engineering Lab#1Compiler Engineering Lab#1
Compiler Engineering Lab#1MashaelQ
 
Introduction to Assembly Language Programming
Introduction to Assembly Language ProgrammingIntroduction to Assembly Language Programming
Introduction to Assembly Language ProgrammingRahul P
 
what is compiler and five phases of compiler
what is compiler and five phases of compilerwhat is compiler and five phases of compiler
what is compiler and five phases of compileradilmehmood93
 

What's hot (20)

Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
C programming part1
C programming part1C programming part1
C programming part1
 
Different phases of a compiler
Different phases of a compilerDifferent phases of a compiler
Different phases of a compiler
 
Assembly Language
Assembly LanguageAssembly Language
Assembly Language
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Compiler an overview
Compiler  an overviewCompiler  an overview
Compiler an overview
 
Unit 2 introduction to c programming
Unit 2   introduction to c programmingUnit 2   introduction to c programming
Unit 2 introduction to c programming
 
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
 
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGESOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
Why C is Called Structured Programming Language
Why C is Called Structured Programming LanguageWhy C is Called Structured Programming Language
Why C is Called Structured Programming Language
 
Lec 01 basic concepts
Lec 01 basic conceptsLec 01 basic concepts
Lec 01 basic concepts
 
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...
 
OOP Poster Presentation
OOP Poster PresentationOOP Poster Presentation
OOP Poster Presentation
 
Unit1 cd
Unit1 cdUnit1 cd
Unit1 cd
 
C programming
C programming C programming
C programming
 
Compiler Engineering Lab#1
Compiler Engineering Lab#1Compiler Engineering Lab#1
Compiler Engineering Lab#1
 
Introduction to Assembly Language Programming
Introduction to Assembly Language ProgrammingIntroduction to Assembly Language Programming
Introduction to Assembly Language Programming
 
Basics1
Basics1Basics1
Basics1
 
what is compiler and five phases of compiler
what is compiler and five phases of compilerwhat is compiler and five phases of compiler
what is compiler and five phases of compiler
 

Viewers also liked

How to Study and Research in Computer-related Master Program
How to Study and Research in Computer-related Master ProgramHow to Study and Research in Computer-related Master Program
How to Study and Research in Computer-related Master ProgramWongyos Keardsri
 
SysProg-Tutor 02 Introduction to Unix Operating System
SysProg-Tutor 02 Introduction to Unix Operating SystemSysProg-Tutor 02 Introduction to Unix Operating System
SysProg-Tutor 02 Introduction to Unix Operating SystemWongyos Keardsri
 
Java-Answer Chapter 12-13 (For Print)
Java-Answer Chapter 12-13 (For Print)Java-Answer Chapter 12-13 (For Print)
Java-Answer Chapter 12-13 (For Print)Wongyos Keardsri
 
Java-Answer Chapter 01-04 (For Print)
Java-Answer Chapter 01-04 (For Print)Java-Answer Chapter 01-04 (For Print)
Java-Answer Chapter 01-04 (For Print)Wongyos Keardsri
 
Java-Chapter 12 Classes and Objects
Java-Chapter 12 Classes and ObjectsJava-Chapter 12 Classes and Objects
Java-Chapter 12 Classes and ObjectsWongyos Keardsri
 
Java-Chapter 13 Advanced Classes and Objects
Java-Chapter 13 Advanced Classes and ObjectsJava-Chapter 13 Advanced Classes and Objects
Java-Chapter 13 Advanced Classes and ObjectsWongyos Keardsri
 
Introduction C Programming
Introduction C ProgrammingIntroduction C Programming
Introduction C Programmingrattanano
 
The next generation intelligent transport systems: standards and applications
The next generation intelligent transport systems: standards and applicationsThe next generation intelligent transport systems: standards and applications
The next generation intelligent transport systems: standards and applicationsWongyos Keardsri
 
Comandos de pascal e estrutura de repetição (para...fazer)
Comandos de pascal e estrutura de repetição (para...fazer)Comandos de pascal e estrutura de repetição (para...fazer)
Comandos de pascal e estrutura de repetição (para...fazer)111111119
 
Linguagem de Programação Pascal
Linguagem de Programação PascalLinguagem de Programação Pascal
Linguagem de Programação PascalMarcus Vinicius
 
Programando com pascal
Programando com pascalProgramando com pascal
Programando com pascalRamon Souza
 
Apostila programação "pascalzim"
Apostila programação "pascalzim"Apostila programação "pascalzim"
Apostila programação "pascalzim"deniscody
 
Introduction of c programming
Introduction of c programmingIntroduction of c programming
Introduction of c programmingTarun Sharma
 
C# aprenda a programar
C# aprenda a programar C# aprenda a programar
C# aprenda a programar Yuri Barzola
 
Lógica de programação pascal
Lógica de programação   pascalLógica de programação   pascal
Lógica de programação pascalJocelma Rios
 
Aula 04 estruturas de repetição
Aula 04   estruturas de repetiçãoAula 04   estruturas de repetição
Aula 04 estruturas de repetiçãoTácito Graça
 
Discrete mathematics Ch1 sets Theory_Dr.Khaled.Bakro د. خالد بكرو
Discrete mathematics Ch1 sets Theory_Dr.Khaled.Bakro د. خالد بكروDiscrete mathematics Ch1 sets Theory_Dr.Khaled.Bakro د. خالد بكرو
Discrete mathematics Ch1 sets Theory_Dr.Khaled.Bakro د. خالد بكروDr. Khaled Bakro
 

Viewers also liked (20)

How to Study and Research in Computer-related Master Program
How to Study and Research in Computer-related Master ProgramHow to Study and Research in Computer-related Master Program
How to Study and Research in Computer-related Master Program
 
IP address anonymization
IP address anonymizationIP address anonymization
IP address anonymization
 
SysProg-Tutor 02 Introduction to Unix Operating System
SysProg-Tutor 02 Introduction to Unix Operating SystemSysProg-Tutor 02 Introduction to Unix Operating System
SysProg-Tutor 02 Introduction to Unix Operating System
 
Java-Answer Chapter 12-13 (For Print)
Java-Answer Chapter 12-13 (For Print)Java-Answer Chapter 12-13 (For Print)
Java-Answer Chapter 12-13 (For Print)
 
Java-Answer Chapter 01-04 (For Print)
Java-Answer Chapter 01-04 (For Print)Java-Answer Chapter 01-04 (For Print)
Java-Answer Chapter 01-04 (For Print)
 
Java-Chapter 12 Classes and Objects
Java-Chapter 12 Classes and ObjectsJava-Chapter 12 Classes and Objects
Java-Chapter 12 Classes and Objects
 
Java-Chapter 13 Advanced Classes and Objects
Java-Chapter 13 Advanced Classes and ObjectsJava-Chapter 13 Advanced Classes and Objects
Java-Chapter 13 Advanced Classes and Objects
 
Java-Answer Chapter 01-04
Java-Answer Chapter 01-04Java-Answer Chapter 01-04
Java-Answer Chapter 01-04
 
Introduction C Programming
Introduction C ProgrammingIntroduction C Programming
Introduction C Programming
 
The next generation intelligent transport systems: standards and applications
The next generation intelligent transport systems: standards and applicationsThe next generation intelligent transport systems: standards and applications
The next generation intelligent transport systems: standards and applications
 
Comandos de pascal e estrutura de repetição (para...fazer)
Comandos de pascal e estrutura de repetição (para...fazer)Comandos de pascal e estrutura de repetição (para...fazer)
Comandos de pascal e estrutura de repetição (para...fazer)
 
Linguagem de Programação Pascal
Linguagem de Programação PascalLinguagem de Programação Pascal
Linguagem de Programação Pascal
 
Programando com pascal
Programando com pascalProgramando com pascal
Programando com pascal
 
Apostila programação "pascalzim"
Apostila programação "pascalzim"Apostila programação "pascalzim"
Apostila programação "pascalzim"
 
Introduction of c programming
Introduction of c programmingIntroduction of c programming
Introduction of c programming
 
Algoritmos - Pascal
Algoritmos - PascalAlgoritmos - Pascal
Algoritmos - Pascal
 
C# aprenda a programar
C# aprenda a programar C# aprenda a programar
C# aprenda a programar
 
Lógica de programação pascal
Lógica de programação   pascalLógica de programação   pascal
Lógica de programação pascal
 
Aula 04 estruturas de repetição
Aula 04   estruturas de repetiçãoAula 04   estruturas de repetição
Aula 04 estruturas de repetição
 
Discrete mathematics Ch1 sets Theory_Dr.Khaled.Bakro د. خالد بكرو
Discrete mathematics Ch1 sets Theory_Dr.Khaled.Bakro د. خالد بكروDiscrete mathematics Ch1 sets Theory_Dr.Khaled.Bakro د. خالد بكرو
Discrete mathematics Ch1 sets Theory_Dr.Khaled.Bakro د. خالد بكرو
 

Similar to SysProg-Tutor 01 Introduction to C Programming Language

Chapter 1 - Basic concepts of programming.pdf
Chapter 1 - Basic concepts of programming.pdfChapter 1 - Basic concepts of programming.pdf
Chapter 1 - Basic concepts of programming.pdfKirubelWondwoson1
 
Lecture01-Introduction-to-C-programming-converted (4).pptx
Lecture01-Introduction-to-C-programming-converted (4).pptxLecture01-Introduction-to-C-programming-converted (4).pptx
Lecture01-Introduction-to-C-programming-converted (4).pptxMdMuaz2
 
An Overview of Programming C
An Overview of Programming CAn Overview of Programming C
An Overview of Programming CNishargo Nigar
 
Extending Rotor with Structural Reflection to support Reflective Languages
Extending Rotor with Structural Reflection to support Reflective LanguagesExtending Rotor with Structural Reflection to support Reflective Languages
Extending Rotor with Structural Reflection to support Reflective Languagesfranciscoortin
 
1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docxtarifarmarie
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using ReflectionGanesh Samarthyam
 
C language by Dr. D. R. Gholkar
C language by Dr. D. R. GholkarC language by Dr. D. R. Gholkar
C language by Dr. D. R. GholkarPRAVIN GHOLKAR
 
.NET 4 Demystified - Sandeep Joshi
.NET 4 Demystified - Sandeep Joshi.NET 4 Demystified - Sandeep Joshi
.NET 4 Demystified - Sandeep JoshiSpiffy
 
C#_01_CLROverview.ppt
C#_01_CLROverview.pptC#_01_CLROverview.ppt
C#_01_CLROverview.pptMarcEdwards35
 
Unit 1 of c++ part 1 basic introduction
Unit 1 of c++ part 1 basic introductionUnit 1 of c++ part 1 basic introduction
Unit 1 of c++ part 1 basic introductionAKR Education
 
Introduction of c language
Introduction of c languageIntroduction of c language
Introduction of c languagefarishah
 
C programming course material
C programming course materialC programming course material
C programming course materialRanjitha Murthy
 
intro-slides.pdf very important for computer science students
intro-slides.pdf very important for computer science studentsintro-slides.pdf very important for computer science students
intro-slides.pdf very important for computer science studentssairevanth504
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesRaffi Khatchadourian
 
Basic structure of C++ program
Basic structure of C++ programBasic structure of C++ program
Basic structure of C++ programmatiur rahman
 

Similar to SysProg-Tutor 01 Introduction to C Programming Language (20)

Chapter 1 - Basic concepts of programming.pdf
Chapter 1 - Basic concepts of programming.pdfChapter 1 - Basic concepts of programming.pdf
Chapter 1 - Basic concepts of programming.pdf
 
Lecture01-Introduction-to-C-programming-converted (4).pptx
Lecture01-Introduction-to-C-programming-converted (4).pptxLecture01-Introduction-to-C-programming-converted (4).pptx
Lecture01-Introduction-to-C-programming-converted (4).pptx
 
An Overview of Programming C
An Overview of Programming CAn Overview of Programming C
An Overview of Programming C
 
Extending Rotor with Structural Reflection to support Reflective Languages
Extending Rotor with Structural Reflection to support Reflective LanguagesExtending Rotor with Structural Reflection to support Reflective Languages
Extending Rotor with Structural Reflection to support Reflective Languages
 
1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
C language by Dr. D. R. Gholkar
C language by Dr. D. R. GholkarC language by Dr. D. R. Gholkar
C language by Dr. D. R. Gholkar
 
chapter 1.pptx
chapter 1.pptxchapter 1.pptx
chapter 1.pptx
 
.NET 4 Demystified - Sandeep Joshi
.NET 4 Demystified - Sandeep Joshi.NET 4 Demystified - Sandeep Joshi
.NET 4 Demystified - Sandeep Joshi
 
C#_01_CLROverview.ppt
C#_01_CLROverview.pptC#_01_CLROverview.ppt
C#_01_CLROverview.ppt
 
Unit 1 of c++ part 1 basic introduction
Unit 1 of c++ part 1 basic introductionUnit 1 of c++ part 1 basic introduction
Unit 1 of c++ part 1 basic introduction
 
Introduction of c language
Introduction of c languageIntroduction of c language
Introduction of c language
 
Introduction to java programming part 2
Introduction to java programming  part 2Introduction to java programming  part 2
Introduction to java programming part 2
 
C programming course material
C programming course materialC programming course material
C programming course material
 
intro-slides.pdf very important for computer science students
intro-slides.pdf very important for computer science studentsintro-slides.pdf very important for computer science students
intro-slides.pdf very important for computer science students
 
Lecture01 (introduction to c programming)
Lecture01 (introduction to c programming)Lecture01 (introduction to c programming)
Lecture01 (introduction to c programming)
 
Training 8051Report
Training 8051ReportTraining 8051Report
Training 8051Report
 
Java introduction
Java introductionJava introduction
Java introduction
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to Interfaces
 
Basic structure of C++ program
Basic structure of C++ programBasic structure of C++ program
Basic structure of C++ program
 

More from Wongyos Keardsri

Discrete-Chapter 11 Graphs Part III
Discrete-Chapter 11 Graphs Part IIIDiscrete-Chapter 11 Graphs Part III
Discrete-Chapter 11 Graphs Part IIIWongyos Keardsri
 
Discrete-Chapter 11 Graphs Part II
Discrete-Chapter 11 Graphs Part IIDiscrete-Chapter 11 Graphs Part II
Discrete-Chapter 11 Graphs Part IIWongyos Keardsri
 
Discrete-Chapter 11 Graphs Part I
Discrete-Chapter 11 Graphs Part IDiscrete-Chapter 11 Graphs Part I
Discrete-Chapter 11 Graphs Part IWongyos Keardsri
 
Discrete-Chapter 09 Algorithms
Discrete-Chapter 09 AlgorithmsDiscrete-Chapter 09 Algorithms
Discrete-Chapter 09 AlgorithmsWongyos Keardsri
 
Discrete-Chapter 08 Relations
Discrete-Chapter 08 RelationsDiscrete-Chapter 08 Relations
Discrete-Chapter 08 RelationsWongyos Keardsri
 
Discrete-Chapter 07 Probability
Discrete-Chapter 07 ProbabilityDiscrete-Chapter 07 Probability
Discrete-Chapter 07 ProbabilityWongyos Keardsri
 
Discrete-Chapter 06 Counting
Discrete-Chapter 06 CountingDiscrete-Chapter 06 Counting
Discrete-Chapter 06 CountingWongyos Keardsri
 
Discrete-Chapter 05 Inference and Proofs
Discrete-Chapter 05 Inference and ProofsDiscrete-Chapter 05 Inference and Proofs
Discrete-Chapter 05 Inference and ProofsWongyos Keardsri
 
Discrete-Chapter 04 Logic Part II
Discrete-Chapter 04 Logic Part IIDiscrete-Chapter 04 Logic Part II
Discrete-Chapter 04 Logic Part IIWongyos Keardsri
 
Discrete-Chapter 04 Logic Part I
Discrete-Chapter 04 Logic Part IDiscrete-Chapter 04 Logic Part I
Discrete-Chapter 04 Logic Part IWongyos Keardsri
 
Discrete-Chapter 03 Matrices
Discrete-Chapter 03 MatricesDiscrete-Chapter 03 Matrices
Discrete-Chapter 03 MatricesWongyos Keardsri
 
Discrete-Chapter 02 Functions and Sequences
Discrete-Chapter 02 Functions and SequencesDiscrete-Chapter 02 Functions and Sequences
Discrete-Chapter 02 Functions and SequencesWongyos Keardsri
 
Discrete-Chapter 12 Modeling Computation
Discrete-Chapter 12 Modeling ComputationDiscrete-Chapter 12 Modeling Computation
Discrete-Chapter 12 Modeling ComputationWongyos Keardsri
 
Java-Chapter 14 Creating Graphics with DWindow
Java-Chapter 14 Creating Graphics with DWindowJava-Chapter 14 Creating Graphics with DWindow
Java-Chapter 14 Creating Graphics with DWindowWongyos Keardsri
 
Java-Chapter 11 Recursions
Java-Chapter 11 RecursionsJava-Chapter 11 Recursions
Java-Chapter 11 RecursionsWongyos Keardsri
 
Java-Chapter 10 Two Dimensional Arrays
Java-Chapter 10 Two Dimensional ArraysJava-Chapter 10 Two Dimensional Arrays
Java-Chapter 10 Two Dimensional ArraysWongyos Keardsri
 
Java-Chapter 09 Advanced Statements and Applications
Java-Chapter 09 Advanced Statements and ApplicationsJava-Chapter 09 Advanced Statements and Applications
Java-Chapter 09 Advanced Statements and ApplicationsWongyos Keardsri
 

More from Wongyos Keardsri (20)

Discrete-Chapter 11 Graphs Part III
Discrete-Chapter 11 Graphs Part IIIDiscrete-Chapter 11 Graphs Part III
Discrete-Chapter 11 Graphs Part III
 
Discrete-Chapter 11 Graphs Part II
Discrete-Chapter 11 Graphs Part IIDiscrete-Chapter 11 Graphs Part II
Discrete-Chapter 11 Graphs Part II
 
Discrete-Chapter 11 Graphs Part I
Discrete-Chapter 11 Graphs Part IDiscrete-Chapter 11 Graphs Part I
Discrete-Chapter 11 Graphs Part I
 
Discrete-Chapter 10 Trees
Discrete-Chapter 10 TreesDiscrete-Chapter 10 Trees
Discrete-Chapter 10 Trees
 
Discrete-Chapter 09 Algorithms
Discrete-Chapter 09 AlgorithmsDiscrete-Chapter 09 Algorithms
Discrete-Chapter 09 Algorithms
 
Discrete-Chapter 08 Relations
Discrete-Chapter 08 RelationsDiscrete-Chapter 08 Relations
Discrete-Chapter 08 Relations
 
Discrete-Chapter 07 Probability
Discrete-Chapter 07 ProbabilityDiscrete-Chapter 07 Probability
Discrete-Chapter 07 Probability
 
Discrete-Chapter 06 Counting
Discrete-Chapter 06 CountingDiscrete-Chapter 06 Counting
Discrete-Chapter 06 Counting
 
Discrete-Chapter 05 Inference and Proofs
Discrete-Chapter 05 Inference and ProofsDiscrete-Chapter 05 Inference and Proofs
Discrete-Chapter 05 Inference and Proofs
 
Discrete-Chapter 04 Logic Part II
Discrete-Chapter 04 Logic Part IIDiscrete-Chapter 04 Logic Part II
Discrete-Chapter 04 Logic Part II
 
Discrete-Chapter 04 Logic Part I
Discrete-Chapter 04 Logic Part IDiscrete-Chapter 04 Logic Part I
Discrete-Chapter 04 Logic Part I
 
Discrete-Chapter 03 Matrices
Discrete-Chapter 03 MatricesDiscrete-Chapter 03 Matrices
Discrete-Chapter 03 Matrices
 
Discrete-Chapter 02 Functions and Sequences
Discrete-Chapter 02 Functions and SequencesDiscrete-Chapter 02 Functions and Sequences
Discrete-Chapter 02 Functions and Sequences
 
Discrete-Chapter 01 Sets
Discrete-Chapter 01 SetsDiscrete-Chapter 01 Sets
Discrete-Chapter 01 Sets
 
Discrete-Chapter 12 Modeling Computation
Discrete-Chapter 12 Modeling ComputationDiscrete-Chapter 12 Modeling Computation
Discrete-Chapter 12 Modeling Computation
 
Java-Chapter 14 Creating Graphics with DWindow
Java-Chapter 14 Creating Graphics with DWindowJava-Chapter 14 Creating Graphics with DWindow
Java-Chapter 14 Creating Graphics with DWindow
 
Java-Chapter 11 Recursions
Java-Chapter 11 RecursionsJava-Chapter 11 Recursions
Java-Chapter 11 Recursions
 
Java-Chapter 10 Two Dimensional Arrays
Java-Chapter 10 Two Dimensional ArraysJava-Chapter 10 Two Dimensional Arrays
Java-Chapter 10 Two Dimensional Arrays
 
Java-Chapter 09 Advanced Statements and Applications
Java-Chapter 09 Advanced Statements and ApplicationsJava-Chapter 09 Advanced Statements and Applications
Java-Chapter 09 Advanced Statements and Applications
 
Java-Chapter 08 Methods
Java-Chapter 08 MethodsJava-Chapter 08 Methods
Java-Chapter 08 Methods
 

Recently uploaded

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 

Recently uploaded (20)

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 

SysProg-Tutor 01 Introduction to C Programming Language

  • 1. Tutor Session - 1 Chulalongkorn Tutor Session I: Introduction to C University Programming Language Wongyos Keardsri (P’Bank) Department of Computer Engineering Faculty of Engineering, Chulalongkorn University Bangkok, Thailand Mobile Phone: 089-5993490 E-mail: wongyos@gmail.com, MSN: bankberrer@hotmail.com Twitter: @wongyos 2110313 Operating Systems and System Programs (1/2010)
  • 2. Tutor Session - 1 Tutor Outline Chulalongkorn University Introduction While C History Do-While C Language VS Java Language For C Language Structure Functions and Program Types, Operators and Structure Expressions Non-Return Function Data Input and Output Return Function printf() The Standard C Library Functions scanf() Control Flow Array, Pointer and String If-Else Structures Switch File Operations 2 2110313 Operating Systems and System Programs (1/2010)
  • 3. Tutor Session - 1 Introduction Chulalongkorn University C History C is a structured computer programming language Appeared in1972 (1970s) Designed and Developed by Dennis Ritchie at the Bell Telephone Laboratories Derived from B and BCPL programming language Developed for the UNIX operating system 3 2110313 Operating Systems and System Programs (1/2010)
  • 4. Tutor Session - 1 Introduction Chulalongkorn University C History (Cont) Used and Implemented for: System programming Operating systems Embedded system applications C standard: ANSI C and ISO C Book: The C Programming Language, 2nd edition http://en.wikipedia.org/wiki/C_(programming_language) 4 2110313 Operating Systems and System Programs (1/2010)
  • 5. Tutor Session - 1 Introduction Chulalongkorn University C Language VS Java Language Example C Code (Hello.c) #include <stdio.h> main() { printf("Hello CPn"); } Example Java Code (Hello.java) public class Hello { public static void main(String[] args) { System.out.print("Hello CPn"); } } 5 2110313 Operating Systems and System Programs (1/2010)
  • 6. Tutor Session - 1 Introduction Chulalongkorn University C Language VS Java Language (Cont) C: Structured Java: Object-Oriented Programming Programming C Compiler Java Compiler (JVM) Editor: Turbo C, vi, etc. Editor: JLab, Eclipse, etc. Compile: (UNIX) Compile: gcc Hello.c javac Hello.java After compile After compile a.out Hello.class Run: Run: ./a.out java Hello Hello CP Hello CP Show an example Show an example 6 2110313 Operating Systems and System Programs (1/2010)
  • 7. Tutor Session - 1 Introduction Chulalongkorn University C Language Structure General format #include <stdio.h> Preprocessor / Including Library #include <…………………> main() { Begin Function main: [function-body]; [declaration-list] + [statement-list] } End . . Semicolon . type func() { Function func: [function-body]; [declaration-list] + [statement-list] } 7 2110313 Operating Systems and System Programs (1/2010)
  • 8. Tutor Session - 1 Introduction Chulalongkorn University C Language Structure (Cont) 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 %dn", sum); } The sum of 15 and 25 is 40 8 2110313 Operating Systems and System Programs (1/2010)
  • 9. Tutor Session - 1 Introduction Chulalongkorn University C Language Structure (Cont) Compile C by UNIX command cc option file1 file2 … Example 1 gcc example.c Compile a.out ./a.out Run 9 2110313 Operating Systems and System Programs (1/2010)
  • 10. Tutor Session - 1 Introduction Chulalongkorn University C Language Structure (Cont) Example 2 gcc –c example.c Compile example.o Object file Convert to gcc –o example.run example.o Executable file example.run Executable file ./example.run Run 10 2110313 Operating Systems and System Programs (1/2010)
  • 11. Tutor Session - 1 Introduction Chulalongkorn University C Language Structure (Cont) Example 3 gcc –o example.run example.c Compile example.run Executable file ./example.run Run Wow 11 2110313 Operating Systems and System Programs (1/2010)
  • 12. Tutor Session - 1 Types, Operators and Expressions Chulalongkorn University Data Types and Sizes char Character (8 bit) Ex. ‘A’, ‘a’, ‘F’ int Integer (16 bit) Ex. 12, -2456, 99851 float Real single (32 bit) Ex. 23.82, 567.008 double Real double (64 bit) Ex. 0.0002100009 short Shot integer (16 bit) Ex. -4, 18 long Long integer (32 bit) Ex. 9547604608456 unsigned Unsigned integer (16 bit) Ex. 2, 908, 1392 12 2110313 Operating Systems and System Programs (1/2010)
  • 13. Tutor Session - 1 Types, Operators and Expressions Chulalongkorn University Variable Declaration type-specifier list-of-variables; Example int 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; 13 2110313 Operating Systems and System Programs (1/2010)
  • 14. Tutor Session - 1 Types, Operators and Expressions Chulalongkorn University Constant Declaration #define VARIABLE constant-value Note Example #define MAX 500 #include <stdio.h> #define XX 0 #define STEP 20 main() { #define PI 3.14159265 // Body program #define VTAB 't' } const char msg[] = "warning: "; const double e = 2.71828182845905; 14 2110313 Operating Systems and System Programs (1/2010)
  • 15. Tutor Session - 1 Types, Operators and Expressions Chulalongkorn University Expression and Operations Arithmetic Operators Addition + Subtraction - Multiplication * Division / Modulation % Example fag = x % y; c = a – (a/b)*b; sum = var1 + var2 + var3; 15 2110313 Operating Systems and System Programs (1/2010)
  • 16. Tutor Session - 1 Types, Operators and Expressions Chulalongkorn University Expression and Operations (Cont) Relational Operators Less than < a < 5 Less than or equal <= a <= b More than > a > b+c More than or equal >= a >= b + 5 Equal == a == -6 Not equal != a != 0 Logical Operators AND && (a > 0) && (b > 0) OR || (a <= 0) || (b <= 0) Negation ! !(a && c) 16 2110313 Operating Systems and System Programs (1/2010)
  • 17. Tutor Session - 1 Types, Operators and Expressions Chulalongkorn University Expression and Operations (Cont) Bitwise Operators Bitwise AND & Bitwise OR (Inclusive OR) | Bitwise XOR (Exclusive OR) ^ Left shift << Right shift >> One's complement ~ Example x = 01001011 y = 00101100 ~x = 10110100 x & y = 00001000 x | y = 01101111 x ^ y = 01100111 x << 2 = 00101100 17 2110313 Operating Systems and System Programs (1/2010)
  • 18. Tutor Session - 1 Types, Operators and Expressions Chulalongkorn University Expression and Operations (Cont) Assignment Operators and Expressions op is + - * / % << >> & ^ | If expr1 and expr2 are expressions, then expr1 op= expr2 Equivalent to expr1 = (expr1) op (expr2) Example X += 1; Equivalent X = X + 1; 18 2110313 Operating Systems and System Programs (1/2010)
  • 19. Tutor Session - 1 Types, Operators and Expressions Chulalongkorn University Expression and Operations (Cont) Conditional Expressions expr1 ? expr2 : expr3 If expr1 is true do expr2 If expr1 is false do expr3 Example a = 5; b = 10; min = (a < b) ? a : b; 19 2110313 Operating Systems and System Programs (1/2010)
  • 20. Tutor Session - 1 Types, Operators and Expressions Chulalongkorn University Expression and Operations (Cont) Increment and Decrement Operators Pre-increment operation ++variable Post-increment operation variable++ Pre-decrement operation --variable Post-decrement operation variable-- Example x = 4; y = x++ + 5; //x = 5, y = 9 x = 4; y = ++x + 5; //x = 5, y = 10 20 2110313 Operating Systems and System Programs (1/2010)
  • 21. Tutor Session - 1 Types, Operators and Expressions Chulalongkorn University Expression and Operations (Cont) 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; 21 2110313 Operating Systems and System Programs (1/2010)
  • 22. Tutor Session - 1 Data Input and Output Chulalongkorn University printf() Statement printf() is a function for display result to standard output (Monitor, Screen) printf(format, arg1, arg2, …); Example printf(“Hellon”); //Hello int num = 2; printf(“%d is integer”, num); //2 is integer 22 2110313 Operating Systems and System Programs (1/2010)
  • 23. Tutor Session - 1 Data Input and Output Chulalongkorn University printf() Statement (Cont) Conversion Operation [printf()] d signed decimal conversion of an int or a long u unsigned decimal conversion of unsigned o unsigned octal conversion of unsigned x, X unsigned hexadecimal conversion of unsigned x = [a – f], X = [A - F] c single character conversion s string conversion f signed decimal floating point conversion e, E signed decimal floating point conversion in scientific notation 23 2110313 Operating Systems and System Programs (1/2010)
  • 24. Tutor Session - 1 Data Input and Output Chulalongkorn University printf() Statement (Cont) Example of printf() int j = 45, k = -123; float x = 12.34; char c = ‘w’; Result char *m = “Hello”; printf(“Hello 55”); Hello 55 printf(“Tax is %d”, j); Tax is 45 printf(“%d”, j+k); -78 printf(“%3d %d”, j, k); 45 -123 printf(“%f %.2f”, x, x); 12.340000 12.34 printf(“%c”, c); w printf(“%sn”, m); Hello printf(“%sn”, “Hello”); Hello printf(“%10sn”, “Hello”); Hello 24 2110313 Operating Systems and System Programs (1/2010)
  • 25. Tutor Session - 1 Data Input and Output Chulalongkorn University scanf() Statement scanf() is a function for read input from standard input (Keyboard) scanf(format, arg1, arg2, …); Example scanf(“%d %d %d”, &day, &month, &year); int num; printf(“Enter integer : ”); scanf(“%d”, &num); // Enter integer : 23 25 2110313 Operating Systems and System Programs (1/2010)
  • 26. Tutor Session - 1 Data Input and Output Chulalongkorn University scanf() Statement (Cont) Conversion Operation [scanf()] d signed decimal conversion of an int or a long u unsigned decimal conversion of unsigned o unsigned octal conversion of unsigned x, X unsigned hexadecimal conversion of unsigned x = [a – f], X = [A - F] c single character conversion s string conversion f signed decimal floating point conversion e, E signed decimal floating point conversion in scientific notation [] read only character in [ ], if [^ ] read different character 26 2110313 Operating Systems and System Programs (1/2010)
  • 27. Tutor Session - 1 Data Input and Output Chulalongkorn University scanf() Statement (Cont) Example of scanf() int d,m,y,x; char ch1,ch2; Result float f; scanf(“%d”, &x); 4 // x=4 scanf(“%2d%2d%4d”, &d,&m,&y); 22062007 // d=22, m=6, y=2007 scanf(“%d/%d/%d”, &d,&m,&y); 22/06/2007 // d=22, m=6, y=2007 scanf(“%c%c”, &ch1,&ch2); Ab // ch1=‘A’, ch2=‘b’ scanf(“%f”, &f); 2.3 // f=2.300000 27 2110313 Operating Systems and System Programs (1/2010)
  • 28. Tutor Session - 1 Control Flow Chulalongkorn University Decision Statements If-Else Statement The if-else statement is used to express decisions. Formally the syntax is if (expression) { true statement } else { false statement } 28 2110313 Operating Systems and System Programs (1/2010)
  • 29. Tutor Session - 1 Control Flow Chulalongkorn University Decision Statements (Cont) Nested If-Else The 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 } 29 2110313 Operating Systems and System Programs (1/2010)
  • 30. Tutor Session - 1 Control Flow Chulalongkorn University Decision Statements (Cont) Example of If-Else if (a < b) { if (score >= 80) printf(“a less than grade = ‘A’; bn”); else if (score >= 70) } else { grade = ‘B’; temp = a; else if (score >= 50) a = b; /* swap a */ grade = ‘C’; b = temp; /* and b */ else if (score >= 40) printf(“Interchange a grade = ‘D’; and bn”); else } grade = ‘F’; 30 2110313 Operating Systems and System Programs (1/2010)
  • 31. Tutor Session - 1 Control Flow Chulalongkorn University Decision Statements (Cont) Switch Statement The 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: statements case const-expr: statements default: statements } 31 2110313 Operating Systems and System Programs (1/2010)
  • 32. Tutor Session - 1 Control Flow Chulalongkorn University Decision Statements (Cont) Example of Switch c = getchar(); switch (c) { case '0': printf(“Zeron”); break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': printf(“Ninen”); break; case ' ': case 'n': newln++; break; case 't': tabs++; break; default: printf(“missing charn”); break; } 32 2110313 Operating Systems and System Programs (1/2010)
  • 33. Tutor Session - 1 Control Flow Chulalongkorn University Iteration Statements While Statement The 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; ... } 33 2110313 Operating Systems and System Programs (1/2010)
  • 34. Tutor Session - 1 Control Flow Chulalongkorn University Iteration Statements (Cont) Example of While #include <stdio.h> #define DOT ‘.’ main() { char C; while ((C = getchar())!= DOT) putchar(C); printf(“Good Bye.n”); } Result? 34 2110313 Operating Systems and System Programs (1/2010)
  • 35. Tutor Session - 1 Control Flow Chulalongkorn University Iteration Statements (Cont) Do-While Statement The 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); 35 2110313 Operating Systems and System Programs (1/2010)
  • 36. Tutor Session - 1 Control Flow Chulalongkorn University Iteration Statements (Cont) Example of Do-While int i = 1, sum = 0; do { sum += i; i++; } while (i <= 50); printf(“The sum of 1 to 50 is %dn”, sum); Result? 36 2110313 Operating Systems and System Programs (1/2010)
  • 37. Tutor Session - 1 Control Flow Chulalongkorn University Iteration Statements (Cont) For Statement The for statement for (initial; expression; update) { statement; } Equivalent to initial; while (expression) { statement; update; } 37 2110313 Operating Systems and System Programs (1/2010)
  • 38. Tutor Session - 1 Control Flow Chulalongkorn University Iteration Statements (Cont) Example of For for (i=1;i<=100;i++) { x += i; if ((x % i) == 0) { i--; } } 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 %dn”, count); 38 2110313 Operating Systems and System Programs (1/2010)
  • 39. Tutor Session - 1 Control Flow Chulalongkorn University Sequential Statements Break and Continue Statement The 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; 39 2110313 Operating Systems and System Programs (1/2010)
  • 40. Tutor Session - 1 Control Flow Chulalongkorn University Sequential Statements (Cont) 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”); 40 2110313 Operating Systems and System Programs (1/2010)
  • 41. Tutor Session - 1 Functions and Program Structure Chulalongkorn University 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 ] } 41 2110313 Operating Systems and System Programs (1/2010)
  • 42. Tutor Session - 1 Functions and Program Structure Chulalongkorn University (Cont) Example of Function /* 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 secondsn”, total_time); } 42 2110313 Operating Systems and System Programs (1/2010)
  • 43. Tutor Session - 1 Functions and Program Structure Chulalongkorn University (Cont) Example of Function (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 */ } 43 2110313 Operating Systems and System Programs (1/2010)
  • 44. Tutor Session - 1 Functions and Program Structure Chulalongkorn University Non-Return Function Example of Non-Return Function /* Main */ main() { void display(); display(); } /* Function Part */ void display() { printf(“*** Hello and Good bye ***”); } 44 2110313 Operating Systems and System Programs (1/2010)
  • 45. Tutor Session - 1 Functions and Program Structure Chulalongkorn University Return Function Example of Return Function /* Main Function */ main() { float sq,x; float square(); sq = square(x); printf(“The square of x is %fn”, sq); } /* Function: square */ float square(x) { return(x * x); } 45 2110313 Operating Systems and System Programs (1/2010)
  • 46. Tutor Session - 1 Functions and Program Structure Chulalongkorn University External Variable Example of External Variable main() { int k = 15; k = 5 func1(); k = 5 func2(); k = 15 printf(“k = %dn”, k); } int k = 5; /* External Variable */ func1() { printf(“k = %dn”, k); } /*Function 1*/ func2() { printf(“k = %dn”, k); } /*Function 2*/ 46 2110313 Operating Systems and System Programs (1/2010)
  • 47. Tutor Session - 1 Functions and Program Structure Chulalongkorn University Recursive Function Example of Recursive Function main() { /* Main Part */ int j; long int factorial(); for (j = 0; j <= 10; j++) printf(“%2d! is %ldn”, j, factorial(j)); } long int factorial(n) /* Function Part */ int n; { if (n == 0) return (1); else return (n * factorial(n-1)); } 47 2110313 Operating Systems and System Programs (1/2010)
  • 48. Tutor Session - 1 Functions and Program Structure Chulalongkorn University The Standard C Library Functions #include <stdio.h> clearerr fprintf fwrite rewind fclose fputc getc scanf feof fputs getchar sprintf ferror Fread gets sscanf fflush freopen printf ungetc fgetc fscanf putc fgets fseek putchar fopen ftell puts 48 2110313 Operating Systems and System Programs (1/2010)
  • 49. Tutor Session - 1 Functions and Program Structure Chulalongkorn University The Standard C Library Functions (Cont) #include <math.h> acos(x) floor(x) atan2(x,y) asin(x) log(x) power(x,y) atan(x) log10(x) ceil(x) sin(x) cos(x) sinh(x) cosh(x) sqrt(x) exp(x) tan(x) fabs(x) tanh(x) 49 2110313 Operating Systems and System Programs (1/2010)
  • 50. Tutor Session - 1 Functions and Program Structure Chulalongkorn University The Standard C Library Functions (Cont) #include <ctype.h> isalnum ispunct isalpha isspace isascii isupper iscntrl tolower isdigit toupper isgraph islower isprint 50 2110313 Operating Systems and System Programs (1/2010)
  • 51. Tutor Session - 1 Array, Pointer and String Chulalongkorn University Array 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]; a[0], a[1], a[2], … , a[14] = 15 Element 51 2110313 Operating Systems and System Programs (1/2010)
  • 52. Tutor Session - 1 Array, Pointer and String Chulalongkorn University Array (Cont) In the main memory Value Address a a[0] 5501 a[1] 5502 a[2] 5503 … … int a[15]; … … … … a[14] 5514 52 2110313 Operating Systems and System Programs (1/2010)
  • 53. Tutor Session - 1 Array, Pointer and String Chulalongkorn University Array (Cont) Example of Array /* Read five integers from the standard input and display them in reverse order */ #define MAX 5 main() { int j; int a[MAX]; for (j = 0; j < MAX; j++) scanf(“%d”, &a[j]); for (j = MAX - 1; j >= 0; j--) printf(“%dn”, a[j]); } 53 2110313 Operating Systems and System Programs (1/2010)
  • 54. Tutor Session - 1 Array, Pointer and String Chulalongkorn University Pointer A pointer is a variable that contains the address of a variable. Example of pointer Value Address x 25 7960 x = 25 int x = 25; int *px; … px = &x; int y = *px; px 7960 8132 px = &x //y = x = 25 y y = *px 54 2110313 Operating Systems and System Programs (1/2010)
  • 55. Tutor Session - 1 Array, Pointer and String Chulalongkorn University Pointer (Cont) Example (Cont) main() { int x = 5, *px; px = &x; int y = *px; printf("x = %dn", x); x = 5 printf("y = %dn", y); y = 5 printf("*px = %dn", *px); *px = 5 printf("&x = %dn", &x); &x = -4195036 printf("px = %dn", px); px = -4195036 printf("&y = %dn", &y); &y = -4195044 x = 34; printf("px = %dn", px); px = -4195036 printf("*px = %dn", *px); *px = 34 printf("y = %dn", y); y = 5 } 55 2110313 Operating Systems and System Programs (1/2010)
  • 56. Tutor Session - 1 Array, Pointer and String Chulalongkorn University Pointer (Cont) Example int x; int *px, *py; px x px = &x; py py = px; main() { int t[10]; int *pt; for (pt = t; pt < &t[10]; pt++) scanf(“%d”, pt); for (pt = &t[10]; pt >= t; pt--) printf(“%dn”, *pt); } 56 2110313 Operating Systems and System Programs (1/2010)
  • 57. Tutor Session - 1 Array, Pointer and String Chulalongkorn University Pointer (Cont) Example (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!! 57 2110313 Operating Systems and System Programs (1/2010)
  • 58. Tutor Session - 1 Array, Pointer and String Chulalongkorn University 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 char amessage[] = "now is the time"; /* an array */ char *pmessage = "now is the time"; /* a pointer */ 58 2110313 Operating Systems and System Programs (1/2010)
  • 59. Tutor Session - 1 Array, Pointer and String Chulalongkorn University String (Cont) Example of String char s1[] = “xyz”; char s2[] = {‘x’, ‘y’, ‘z’, ‘0’}; char *s3 = “xyz”; x y z 0 59 2110313 Operating Systems and System Programs (1/2010)
  • 60. Tutor Session - 1 Array, Pointer and String Chulalongkorn University String (Cont) Example /* COUNT THE LENGTH OF STRING */ main() { char *w = “good morning”; int len(); printf(“Lengths of string is %dn”, 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); } 60 2110313 Operating Systems and System Programs (1/2010)
  • 61. Tutor Session - 1 Structures Chulalongkorn University 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 ... }; 61 2110313 Operating Systems and System Programs (1/2010)
  • 62. Tutor Session - 1 Structures Chulalongkorn University (Cont) Example of Structure struct person { Record = Node int code; char name[30]; int string string float char address[40]; code name address salary float salary; }; struct point { int x; int x int y int y; }; 62 2110313 Operating Systems and System Programs (1/2010)
  • 63. Tutor Session - 1 Structures Chulalongkorn University (Cont) A struct declaration defines a type. struct structure-name variable-name,…; Or declare in struct structure-name { type-specifier variable; ... }variable-name; 63 2110313 Operating Systems and System Programs (1/2010)
  • 64. Tutor Session - 1 Structures Chulalongkorn University (Cont) Example of Structure Declaration struct person { struct person { int code; int code; char name[30]; char name[30]; char address[40]; or char address[40]; float salary; float salary; }; }p; struct person p; 64 2110313 Operating Systems and System Programs (1/2010)
  • 65. Tutor Session - 1 Structures Chulalongkorn University (Cont) A member of a particular structure is referred to in an expression by a construction of the form struct-variable-name.member-name Example p.code; p.name; p.address; p.salary; 65 2110313 Operating Systems and System Programs (1/2010)
  • 66. Tutor Session - 1 Structures Chulalongkorn University (Cont) Example of Struct Program /* ASSIGN AND PRINT A DATE */ main() { struct date { //Result int dd = 22; Date is 22/ 6/2007 int mm; int yyyy; }; struct date today; today.mm = 6; today.yyyy = 2007; printf(“Date is %2d/%2d/%4dn”, today.dd, today.mm, today.yyyy); } 66 2110313 Operating Systems and System Programs (1/2010)
  • 67. Tutor Session - 1 File Operations Chulalongkorn University 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(); 67 2110313 Operating Systems and System Programs (1/2010)
  • 68. Tutor Session - 1 File Operations Chulalongkorn University (Cont) 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 68 2110313 Operating Systems and System Programs (1/2010)
  • 69. Tutor Session - 1 File Operations Chulalongkorn University (Cont) Example of fopen() to open file FILE *file; File Pointer FILE *fopen(); if ((file = fopen(“person.dat”, “r”)) == NULL) printf(“Cannot open a data filen”); else ... 69 2110313 Operating Systems and System Programs (1/2010)
  • 70. Tutor Session - 1 File Operations Chulalongkorn University (Cont) 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 int fclose(); ... if (fclose(file) != EOF) printf(“Cannot close filen”; else printf(“Now file is closedn”); 70 2110313 Operating Systems and System Programs (1/2010)
  • 71. Tutor Session - 1 File Operations Chulalongkorn University (Cont) feof() – check for end of file. if (!feof(file)) printf(“It is not the end of file nown”); 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); 71 2110313 Operating Systems and System Programs (1/2010)
  • 72. Tutor Session - 1 File Operations Chulalongkorn University (Cont) 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, ...) 72 2110313 Operating Systems and System Programs (1/2010)
  • 73. Tutor Session - 1 File Operations Chulalongkorn University (Cont) Example of File Operations Program /* 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 belown”); while (c != ‘n’) { c = getchar(); putc(c, fp); } fclose(fp); } 73 2110313 Operating Systems and System Programs (1/2010)
  • 74. Tutor Session - 1 File Operations Chulalongkorn University (Cont) Example of File Operations Program (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 openedn”); else while ((c = getc(fp) != EOF) putchar(c); fclose(fp); } 74 2110313 Operating Systems and System Programs (1/2010)
  • 75. Tutor Session - 1 End Chulalongkorn University Question ? … Answer 75 2110313 Operating Systems and System Programs (1/2010)