SlideShare a Scribd company logo
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)
Ad

Recommended

SysProg-Tutor 03 Unix Shell Script Programming
SysProg-Tutor 03 Unix Shell Script Programming
Wongyos Keardsri
 
Learning the C Language
Learning the C Language
nTier Custom Solutions
 
Introduction to programming with c,
Introduction to programming with c,
Hossain Md Shakhawat
 
Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge
imtiazalijoono
 
C programming session 14
C programming session 14
AjayBahoriya
 
Brief introduction to the c programming language
Brief introduction to the c programming language
Kumar Gaurav
 
Java chapter 1
Java chapter 1
Mukesh Tekwani
 
Introduction to c programming
Introduction to c programming
Akshay Ithape
 
Java chapter 5
Java chapter 5
Mukesh Tekwani
 
C programming part1
C programming part1
Gaddam Kowshik
 
Different phases of a compiler
Different phases of a compiler
Sumit Sinha
 
Assembly Language
Assembly Language
Ibrahimcommunication Al Ani
 
Introduction to c programming
Introduction to c programming
Manoj Tyagi
 
Compiler an overview
Compiler an overview
amudha arul
 
Unit 2 introduction to c programming
Unit 2 introduction to c programming
Mithun DSouza
 
C by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
Srichandan Sobhanayak
 
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
IJCI JOURNAL
 
Introduction to C programming
Introduction to C programming
Rutvik Pensionwar
 
Why C is Called Structured Programming Language
Why C is Called Structured Programming Language
Sinbad Konick
 
Lec 01 basic concepts
Lec 01 basic concepts
Abdul 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
 
OOP Poster Presentation
OOP Poster Presentation
Md Mofijul Haque
 
Unit1 cd
Unit1 cd
PRIST University
 
C programming
C programming
Rohan Gajre
 
Compiler Engineering Lab#1
Compiler Engineering Lab#1
MashaelQ
 
Introduction to Assembly Language Programming
Introduction to Assembly Language Programming
Rahul P
 
Basics1
Basics1
phanleson
 
what is compiler and five phases of compiler
what is compiler and five phases of compiler
adilmehmood93
 
How to Study and Research in Computer-related Master Program
How to Study and Research in Computer-related Master Program
Wongyos Keardsri
 
IP address anonymization
IP address anonymization
Wongyos Keardsri
 

More Related Content

What's hot (20)

Java chapter 5
Java chapter 5
Mukesh Tekwani
 
C programming part1
C programming part1
Gaddam Kowshik
 
Different phases of a compiler
Different phases of a compiler
Sumit Sinha
 
Assembly Language
Assembly Language
Ibrahimcommunication Al Ani
 
Introduction to c programming
Introduction to c programming
Manoj Tyagi
 
Compiler an overview
Compiler an overview
amudha arul
 
Unit 2 introduction to c programming
Unit 2 introduction to c programming
Mithun DSouza
 
C by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
Srichandan Sobhanayak
 
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
IJCI JOURNAL
 
Introduction to C programming
Introduction to C programming
Rutvik Pensionwar
 
Why C is Called Structured Programming Language
Why C is Called Structured Programming Language
Sinbad Konick
 
Lec 01 basic concepts
Lec 01 basic concepts
Abdul 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
 
OOP Poster Presentation
OOP Poster Presentation
Md Mofijul Haque
 
Unit1 cd
Unit1 cd
PRIST University
 
C programming
C programming
Rohan Gajre
 
Compiler Engineering Lab#1
Compiler Engineering Lab#1
MashaelQ
 
Introduction to Assembly Language Programming
Introduction to Assembly Language Programming
Rahul P
 
Basics1
Basics1
phanleson
 
what is compiler and five phases of compiler
what is compiler and five phases of compiler
adilmehmood93
 
Different phases of a compiler
Different phases of a compiler
Sumit Sinha
 
Introduction to c programming
Introduction to c programming
Manoj Tyagi
 
Compiler an overview
Compiler an overview
amudha arul
 
Unit 2 introduction to c programming
Unit 2 introduction to c programming
Mithun DSouza
 
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
IJCI JOURNAL
 
Introduction to C programming
Introduction to C programming
Rutvik Pensionwar
 
Why C is Called Structured Programming Language
Why C is Called Structured Programming Language
Sinbad Konick
 
Lec 01 basic concepts
Lec 01 basic concepts
Abdul 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
 
Compiler Engineering Lab#1
Compiler Engineering Lab#1
MashaelQ
 
Introduction to Assembly Language Programming
Introduction to Assembly Language Programming
Rahul P
 
what is compiler and five phases of compiler
what is compiler and five phases of compiler
adilmehmood93
 

Viewers also liked (20)

How to Study and Research in Computer-related Master Program
How to Study and Research in Computer-related Master Program
Wongyos Keardsri
 
IP address anonymization
IP address anonymization
Wongyos Keardsri
 
SysProg-Tutor 02 Introduction to Unix Operating System
SysProg-Tutor 02 Introduction to Unix Operating System
Wongyos Keardsri
 
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)
Wongyos Keardsri
 
Java-Chapter 12 Classes and Objects
Java-Chapter 12 Classes and Objects
Wongyos Keardsri
 
Java-Chapter 13 Advanced Classes and Objects
Java-Chapter 13 Advanced Classes and Objects
Wongyos Keardsri
 
Introduction C Programming
Introduction C Programming
rattanano
 
The next generation intelligent transport systems: standards and applications
The next generation intelligent transport systems: standards and applications
Wongyos Keardsri
 
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 Pascal
Marcus Vinicius
 
Programando com pascal
Programando com pascal
Ramon Souza
 
Apostila programação "pascalzim"
Apostila programação "pascalzim"
deniscody
 
Introduction of c programming
Introduction of c programming
Tarun Sharma
 
Algoritmos - Pascal
Algoritmos - Pascal
Elaine Cecília Gatto
 
C# aprenda a programar
C# aprenda a programar
Yuri Barzola
 
Lógica de programação pascal
Lógica de programação pascal
Jocelma Rios
 
Aula 04 estruturas de repetição
Aula 04 estruturas de repetição
Tácito Graça
 
Discrete mathematics Ch1 sets Theory_Dr.Khaled.Bakro د. خالد بكرو
Discrete mathematics Ch1 sets Theory_Dr.Khaled.Bakro د. خالد بكرو
Dr. Khaled Bakro
 
How to Study and Research in Computer-related Master Program
How to Study and Research in Computer-related Master Program
Wongyos Keardsri
 
SysProg-Tutor 02 Introduction to Unix Operating System
SysProg-Tutor 02 Introduction to Unix Operating System
Wongyos Keardsri
 
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)
Wongyos Keardsri
 
Java-Chapter 12 Classes and Objects
Java-Chapter 12 Classes and Objects
Wongyos Keardsri
 
Java-Chapter 13 Advanced Classes and Objects
Java-Chapter 13 Advanced Classes and Objects
Wongyos Keardsri
 
Introduction C Programming
Introduction C Programming
rattanano
 
The next generation intelligent transport systems: standards and applications
The next generation intelligent transport systems: standards and applications
Wongyos Keardsri
 
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 Pascal
Marcus Vinicius
 
Programando com pascal
Programando com pascal
Ramon Souza
 
Apostila programação "pascalzim"
Apostila programação "pascalzim"
deniscody
 
Introduction of c programming
Introduction of c programming
Tarun Sharma
 
C# aprenda a programar
C# aprenda a programar
Yuri Barzola
 
Lógica de programação pascal
Lógica de programação pascal
Jocelma Rios
 
Aula 04 estruturas de repetição
Aula 04 estruturas de repetição
Tácito Graça
 
Discrete mathematics Ch1 sets Theory_Dr.Khaled.Bakro د. خالد بكرو
Discrete mathematics Ch1 sets Theory_Dr.Khaled.Bakro د. خالد بكرو
Dr. Khaled Bakro
 
Ad

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

cmp104 lec 8
cmp104 lec 8
kapil078
 
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
Muhammad Ulhaque
 
INTRO.pptx
INTRO.pptx
GOBINATH KANDASAMY
 
C LANGUAGE UNIT-1 PREPARED BY MVB REDDY
C LANGUAGE UNIT-1 PREPARED BY MVB REDDY
Rajeshkumar Reddy
 
C tutorials
C tutorials
Amit Kapoor
 
Basic c
Basic c
Veera Karthi
 
C101 – Intro to Programming with C
C101 – Intro to Programming with C
gpsoft_sk
 
C_Programming_Notes_ICE
C_Programming_Notes_ICE
Gilbert NZABONITEGEKA
 
Switch case and looping
Switch case and looping
patricia Hidalgo
 
Unit 1.pptx
Unit 1.pptx
DrSnehaSharma3
 
Example PseudocodeProblem Given a sorted array a with n elements .docx
Example PseudocodeProblem Given a sorted array a with n elements .docx
cravennichole326
 
3150 Chapter 2 Part 1
3150 Chapter 2 Part 1
Mole Wong
 
C Languagel Classroom Training
C Languagel Classroom Training
Srihitha Technologies
 
67404923-C-Programming-Tutorials-Doc.pdf
67404923-C-Programming-Tutorials-Doc.pdf
Rajb54
 
UNIT - 1jhjhjbkjhkjhkjhkjhkjhhkkhhh.pptx
UNIT - 1jhjhjbkjhkjhkjhkjhkjhhkkhhh.pptx
RoselinLourd
 
Example PseudocodeProblem Given a sorted array a with n elements .docx
Example PseudocodeProblem Given a sorted array a with n elements .docx
elbanglis
 
Introduction to c programming
Introduction to c programming
Alpana Gupta
 
Introduction to ‘C’ Language
Introduction to ‘C’ Language
Thesis Scientist Private Limited
 
An intro to programming
An intro to programming
WolfFlight
 
C tutorial
C tutorial
Anurag Sukhija
 
cmp104 lec 8
cmp104 lec 8
kapil078
 
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
Muhammad Ulhaque
 
C LANGUAGE UNIT-1 PREPARED BY MVB REDDY
C LANGUAGE UNIT-1 PREPARED BY MVB REDDY
Rajeshkumar Reddy
 
C101 – Intro to Programming with C
C101 – Intro to Programming with C
gpsoft_sk
 
Example PseudocodeProblem Given a sorted array a with n elements .docx
Example PseudocodeProblem Given a sorted array a with n elements .docx
cravennichole326
 
3150 Chapter 2 Part 1
3150 Chapter 2 Part 1
Mole Wong
 
67404923-C-Programming-Tutorials-Doc.pdf
67404923-C-Programming-Tutorials-Doc.pdf
Rajb54
 
UNIT - 1jhjhjbkjhkjhkjhkjhkjhhkkhhh.pptx
UNIT - 1jhjhjbkjhkjhkjhkjhkjhhkkhhh.pptx
RoselinLourd
 
Example PseudocodeProblem Given a sorted array a with n elements .docx
Example PseudocodeProblem Given a sorted array a with n elements .docx
elbanglis
 
Introduction to c programming
Introduction to c programming
Alpana Gupta
 
An intro to programming
An intro to programming
WolfFlight
 
Ad

More from Wongyos Keardsri (20)

Discrete-Chapter 11 Graphs Part III
Discrete-Chapter 11 Graphs Part III
Wongyos Keardsri
 
Discrete-Chapter 11 Graphs Part II
Discrete-Chapter 11 Graphs Part II
Wongyos Keardsri
 
Discrete-Chapter 11 Graphs Part I
Discrete-Chapter 11 Graphs Part I
Wongyos Keardsri
 
Discrete-Chapter 10 Trees
Discrete-Chapter 10 Trees
Wongyos Keardsri
 
Discrete-Chapter 09 Algorithms
Discrete-Chapter 09 Algorithms
Wongyos Keardsri
 
Discrete-Chapter 08 Relations
Discrete-Chapter 08 Relations
Wongyos Keardsri
 
Discrete-Chapter 07 Probability
Discrete-Chapter 07 Probability
Wongyos Keardsri
 
Discrete-Chapter 06 Counting
Discrete-Chapter 06 Counting
Wongyos Keardsri
 
Discrete-Chapter 05 Inference and Proofs
Discrete-Chapter 05 Inference and Proofs
Wongyos Keardsri
 
Discrete-Chapter 04 Logic Part II
Discrete-Chapter 04 Logic Part II
Wongyos Keardsri
 
Discrete-Chapter 04 Logic Part I
Discrete-Chapter 04 Logic Part I
Wongyos Keardsri
 
Discrete-Chapter 03 Matrices
Discrete-Chapter 03 Matrices
Wongyos Keardsri
 
Discrete-Chapter 02 Functions and Sequences
Discrete-Chapter 02 Functions and Sequences
Wongyos Keardsri
 
Discrete-Chapter 01 Sets
Discrete-Chapter 01 Sets
Wongyos Keardsri
 
Discrete-Chapter 12 Modeling Computation
Discrete-Chapter 12 Modeling Computation
Wongyos Keardsri
 
Java-Chapter 14 Creating Graphics with DWindow
Java-Chapter 14 Creating Graphics with DWindow
Wongyos Keardsri
 
Java-Chapter 11 Recursions
Java-Chapter 11 Recursions
Wongyos Keardsri
 
Java-Chapter 10 Two Dimensional Arrays
Java-Chapter 10 Two Dimensional Arrays
Wongyos Keardsri
 
Java-Chapter 09 Advanced Statements and Applications
Java-Chapter 09 Advanced Statements and Applications
Wongyos Keardsri
 
Java-Chapter 08 Methods
Java-Chapter 08 Methods
Wongyos Keardsri
 
Discrete-Chapter 11 Graphs Part III
Discrete-Chapter 11 Graphs Part III
Wongyos Keardsri
 
Discrete-Chapter 11 Graphs Part II
Discrete-Chapter 11 Graphs Part II
Wongyos Keardsri
 
Discrete-Chapter 11 Graphs Part I
Discrete-Chapter 11 Graphs Part I
Wongyos Keardsri
 
Discrete-Chapter 09 Algorithms
Discrete-Chapter 09 Algorithms
Wongyos Keardsri
 
Discrete-Chapter 08 Relations
Discrete-Chapter 08 Relations
Wongyos Keardsri
 
Discrete-Chapter 07 Probability
Discrete-Chapter 07 Probability
Wongyos Keardsri
 
Discrete-Chapter 06 Counting
Discrete-Chapter 06 Counting
Wongyos Keardsri
 
Discrete-Chapter 05 Inference and Proofs
Discrete-Chapter 05 Inference and Proofs
Wongyos Keardsri
 
Discrete-Chapter 04 Logic Part II
Discrete-Chapter 04 Logic Part II
Wongyos Keardsri
 
Discrete-Chapter 04 Logic Part I
Discrete-Chapter 04 Logic Part I
Wongyos Keardsri
 
Discrete-Chapter 03 Matrices
Discrete-Chapter 03 Matrices
Wongyos Keardsri
 
Discrete-Chapter 02 Functions and Sequences
Discrete-Chapter 02 Functions and Sequences
Wongyos Keardsri
 
Discrete-Chapter 12 Modeling Computation
Discrete-Chapter 12 Modeling Computation
Wongyos Keardsri
 
Java-Chapter 14 Creating Graphics with DWindow
Java-Chapter 14 Creating Graphics with DWindow
Wongyos Keardsri
 
Java-Chapter 11 Recursions
Java-Chapter 11 Recursions
Wongyos Keardsri
 
Java-Chapter 10 Two Dimensional Arrays
Java-Chapter 10 Two Dimensional Arrays
Wongyos Keardsri
 
Java-Chapter 09 Advanced Statements and Applications
Java-Chapter 09 Advanced Statements and Applications
Wongyos Keardsri
 

Recently uploaded (20)

Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
janeliewang985
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
OpenPOWER Foundation & Open-Source Core Innovations
OpenPOWER Foundation & Open-Source Core Innovations
IBM
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
"Scaling in space and time with Temporal", Andriy Lupa.pdf
"Scaling in space and time with Temporal", Andriy Lupa.pdf
Fwdays
 
The Future of Technology: 2025-2125 by Saikat Basu.pdf
The Future of Technology: 2025-2125 by Saikat Basu.pdf
Saikat Basu
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
janeliewang985
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
OpenPOWER Foundation & Open-Source Core Innovations
OpenPOWER Foundation & Open-Source Core Innovations
IBM
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
"Scaling in space and time with Temporal", Andriy Lupa.pdf
"Scaling in space and time with Temporal", Andriy Lupa.pdf
Fwdays
 
The Future of Technology: 2025-2125 by Saikat Basu.pdf
The Future of Technology: 2025-2125 by Saikat Basu.pdf
Saikat Basu
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 

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: [email protected], MSN: [email protected] 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)