CS3 Tutorial
CS3 Tutorial
Lecture 1-2
Character set, Variables and Identifiers, Built-in Data Types, Variable
 Definition ,Expressions,Constants and Literals ,Simple assignment
   statement, Basic input/output statement, Simple C Programs
                                                                     1
          C Programming Language
• What is C?
  – C is a structured, relatively low-level, portable
    programming language.
• Why study C?
  – Many popular software tools are written in C.
  – Has strongly influenced many other languages.
     • C-shell, java, C++, Perl, etc.
  – Forces the user to understand fundamental aspects of
    programming.
  – Very concise language.
                                                           2
           History of C
• C
  – Evolved by Ritchie from two previous
    programming languages, BCPL and B
  – Used to develop UNIX
  – Used to write modern operating systems
• Hardware independent (portable)
  – By late 1970's C had evolved to "traditional C"
                                                3
                          C, cont.
• Is C object-oriented?
   – No. C++ (its successor) is.
• Can a non OO language be useful?
   – Yes.
• Is C a hard language to learn?
   – No, but it does take a little getting used to.
• What is the ANSI part?
   – American national standards institute – uniform standard
     definition of C for portability.
                                                                4
         A Hello World Program
/*The first program.*/
                                Result is :
#include <stdio.h>             Hello,world!
int main(void)      //main function
{
  printf(“Hello, world!\n”);
  return 0;
}
                                              5
                   Terms
• Source code
  – Text of a program.
  – The input to the C compiler.
• Object code
  – Translation of the source code of a program into
    machine code.
  – The input to the linker.
• Linker
  – A program that links separately compiled modules
    into one program.
  – The output is an executable program.
                                                       6
             Terms (cont.)
• Library
  – The file containing the standard functions that
    a program can use.
• Complier time
  – The time during which a program is being
    compiled.
• Run time
  – The time during which a program is executing.
                                                  7
                Language Types
•   Three types of programming languages
    1. Machine languages
       • Strings of numbers giving machine specific instructions
       • Example:
               +1300042774
               +1400593419
               +1200274027
    2. Assembly languages
       • English-like abbreviations representing elementary
          computer operations (translated via assemblers)
       • Example:
               Load     BASEPAY
               Add      overpay
               Store    GROSSPAY
                                                                   8
        Language Types, Cont.
3. High-level languages
   • Codes similar to everyday English
   • Use mathematical notations (translated via compilers)
   • Example:
      grossPay = basePay + overTimePay
                                                             9
            High-level Languages
• “high-level” is a relative term
• C is a relatively low-level high-level language
• Pascal, Fortran, COBOL are typical high-level
  languages
• Java, Python, Perl, VB are examples of high-level
  high-level languages
• Application specific languages (Matlab, Javascript,
  VBScript) are even higher-level.
                                                        10
        What is Data types in C
• A Data type is a collection of values with
  shared properties
• Using types makes a program easier to read
  and understand
• Using types makes it easier for the compiler
• Types makes it easier to detect certain
  programming errors
                                                 11
         Data types Contd……
• Each variable has a type and a value
   – The type determines the meaning of the operations that
     can be applied to the value
       int i,j;
       double d;
       float x;
     determine the operations and space requirements of the
     variables
• The data type of every variable must be declared before that
  particular variable can appear in a statement
                                                          12
            Data types Contd….
• Four basic types
   – char – a single byte capable of holding just one
     character
   – int – an integer
   – float – single-precision floating point
   – double – double precision floating point
• No boolean type in C
   – True and false are represented by 1 and 0
                                                        13
        Fundamental Data Types
char          signed char unsigned char
                                          14
                  Declaring types
• Declaration allocates a block of memory
  – Type dictates the size of this block
     • char – 1 byte (8 bits)
          – ASCII character code
     •   int – 4 bytes
     •   long int – 4 bytes
     •   float – 4 bytes
     •   double – 8 bytes
                                            15
                              int
• int is short for integer
• Integers are whole numbers
    – (no fractional part, no decimal point)
• Can be positive and negative
• Short and long
• Signed and unsigned
• C has no specific standard on the size of an “int”, it
  varies from one C system to another
• Normally, an int is stored in 2 bytes or 4 bytes
                                                           16
                   int contd…..
• Integer variables are declared
      int variable_name;
      e.g. int a; declares that you want to create an int
      variable called a
• int is considered the “natural” type for working with
  integers
• Sometimes extra digits are needed to store large
  numbers not allowed in int
      long int variable_name;        /* 32 bits, not 16 */
• Whereas less storage is indicated
       short int variable_name;
                                                             17
               int contd….
• Unsigned integers contain only positive
  values, e.g. unsigned int variable_name;
• Signed integers allow both positive and
  negative numbers
• All int declarations default to signed, i.e.
    signed int variable_name;
   Is equivalent to
    int variable_name;
                                                 18
            Example
main()
{    int a, b, c, ;//declaration
    unsigned u=10;// declaration
     a =12; b =-24; //assignment
     c =a+u;d=b+u;// assignment
  printf(“a+u=%d,b+u=%d\n”,c, d);
}
a+u=22, b+u=-14
                                19
             Integer overflow
• At run-time a variable may be assigned an
  incorrect value. If a value is greater than the
  maximum value which can be stored in a
  variable of type int, we get integer overflow
                                                    20
                Floating points
                                                        21
        Floating points contd….
• The type float denotes normal precision real
  numbers
• Single precision floating point numbers are
  declared
     float variable_name;
                                                 22
        Floating points contd….
• The type double denotes double precision real
  numbers
• Double precision floating point numbers are
  declared
     double variable_name;
                                              23
        Floating points contd….
• The possible values assigned to a floating type
  are described in terms of attributes called
  precision and range
  – The number of significant decimal places that a
    floating value carries is called precision
  – The limits of the largest and smallest positive
    floating point values that can be represented in a
    variable of that type is called range
                                                         24
   Lexical Elements of the C Language
   – Keywords.
   – Identifiers.
   – Constants.
   – String constants.
   – Operators.
   – Punctuators.
                                                  25
                 Keywords
• Reserved words.
• Cannot be redefined or used in other
  contexts.
• Case sensitive.
• Have a special predefined meaning.
                                         26
    Reserved Words (Keywords) in C
                         int         long
•   auto      break      register    return
•   case      char       short      signed
•   const     continue
                         sizeof      static
•   default   do
•   double    else       struct      switch
•   enum      extern     typedef     union
•   float     for        unsigned    void
•   goto      if         volatile    while
                                              27
                  Constants
• They refer to fixed values that the program
  may not alter.
• They can be of any of the basic data types.
  Integer: 1. Decimal 0, 77
                    23.7
                  .16
                  1.604
                  2e3
                                                      29
              String Constant
• A character, or more likely a sequence of
  characters, enclosed in “double quotes”.
      A string is an array of characters.
    “A” and ‘A’ are not the same.
    ‘A’ is a string containing only one letter.
              H e l l o ! \0
“A” is actually A followed by the null character
  ‘\0’.
                                                   30
           String Constants (cont.)
“a string of text”
“ a = b + c; ” // nothing is executed
                                                    31
             Punctuators
• They are located by the compiler as tokens and
  are used to separate language elements.
     Parentheses ( )     Braces      {}
     Commas        ,     Semicolons ;
             int main(void)
             {
                   int a, b=3, c=6;
                   a = 17 * (b + c);
                   …
             }
                                                   32
                  Comments
• Multi-Line comments:         /* this is a multiline
                               comment */
                                                        34
                  Variables in C
Topics
•   Naming Variables
•   Declaring Variables
•   Using Variables
•   The Assignment Statement
                                   35
        What Are Variables in C?
• Variables in C have the same meaning as
  variables in algebra. That is, they represent
  some unknown, or variable, value.
                      x=a+b
                   z + 2 = 3(y - 5)
• Remember that variables in algebra are
  represented by a single alphabetic character.
                                                  36
              Naming Variables
• Variables in C may be given representations
  containing multiple characters. But there are
  rules for these representations.
• Variable names in C
  – May only consist of letters, digits, and underscores
  – May be as long as you like, but only the first 31
    characters are significant
  – May not begin with a number
  – May not be a C reserved word (keyword)
                                                           37
              Naming Conventions
• C programmers generally agree on the following
  conventions for naming variables.
  – Begin variable names with lowercase letters
  – Use meaningful identifiers
  – Separate “words” within identifiers with underscores
    or mixed upper and lower case.
  – Examples: surfaceArea surface_Area
         surface_area
                                                       38
               Case Sensitivity
• C is case sensitive
  – It matters whether an identifier, such as a variable
    name, is uppercase or lowercase.
  – Example:
             area
             Area
             AREA
             ArEa
    are all seen as different variables by the compiler.
                                                           39
          Declaring Variables
• Before using a variable, you must give the
  compiler some information about the
  variable; i.e., you must declare it.
• The declaration statement includes the data
  type of the variable.
• Examples of variable declarations:
                   int balls ;
                   float area ;
                                                40
          Declaring Variables (con’t)
• When we declare a variable
  – Space is set aside in memory to hold a value of the
    specified data type
  – That space is associated with the variable name
  – That space is associated with a unique address
• Visualization of the declaration
    int balls ;         balls
garbage
                                                          41
       More About Variables
C has three basic predefined data types:
• Integers (whole numbers)
  – int, long int, short int, unsigned int
• Floating point (real numbers)
  – float, double
• Characters
  – char
                                             42
   Using Variables: Initialization
• Variables may be be given initial values, or
  initialized, when declared. Examples:
                                length
int length = 7 ; 7
diameter
                                initial
     char initial = ‘A’ ;                 ‘A’
                                                 43
  Using Variables: Initialization (con’t)
• Do not “hide” the initialization
  – put initialized variables on a separate line
  – a comment is always a good idea
  – Example:
             int height ;    /* rectangle height */
             int width = 6 ; /* rectangle width */
             int area ;     /* rectangle area */
                                                      44
      Using Variables: Assignment
• Variables may have values assigned to them through the
  use of an assignment statement.
• Such a statement uses the assignment operator =
• This operator does not denote equality. It assigns the
  value of the righthand side of the statement (the
  expression) to the variable on the lefthand side.
• Examples:
      diameter = 5.9 ;
      area = length * width ;
  Note that only single variables may appear on the
  lefthand side of the assignment operator.
                                                     45
     Example: Declarations and
          Assignments
                                  inches
                                  garbage
#include <stdio.h>                feet
                                  garbage
int main( )                       fathoms
                                  garbage
{
    int inches, feet, fathoms ;   fathoms
                                        7
                                   feet
    fathoms = 7 ;                       42
    feet = 6 * fathoms ;          inches
       –
       –
       –
                                             46
    Example: Declarations and Assignments
                   (cont’d)
         –
         –
         –
      printf (“Its depth at sea: \n”) ;
      printf (“ %d fathoms \n”, fathoms) ;
      printf (“ %d feet \n”, feet) ;
      printf (“ %d inches \n”, inches) ;
     return 0 ;
}
                                             47
  Input and Output Using stdio.h
• printf
   – Provides formatted input and output
   – Input for printf is a format specification followed
     by a list of variable names to be displayed
   – printf(“variable %d is %f\n”, myint, myfloat);
• scanf
   – Provided an input format and a list of variables
   – scanf(“%d”, &myint);
                                                           48
         Escape characters
Escape    Description
  Sequenc
  e
\n         Newline, position cursor at the start of a new
             line
\t         Horizontal tab, move cursor to the next tab
             stop
\r         Carriage return. Position cursor to the
             beginning of the current line; do not
             advance to the next line.
\a         Alert, sound system warning beep
\\         Backslash, print a backslash character in a
             printf statement
\”         Double quote print a double quote character
                                                            49
             in a printf statement.
            Format Specifiers for printf and scanf
Data Type           Printf specifier      Scanf specifier
long double         %Lf                   %Lf
double              %f                    %lf
float               %f                    %f
unsigned long       %lu                   %lu
int
long int            %ld                   %ld
unsigned int        %u                    %u
int                 %d                    %d
short               %hd                   %hd
char                %c                    %c
                                                            50
A simple C Program that reads in two
numbers,stores them and prints out the sum
main()
{
int x,y; /* places to store numbers */
printf("Enter x ");
scanf("%d",&x);
printf("Enter y ");
scanf("%d",&y);
printf("The sum of x and y was %d\n",x+y);
}
                                             51
C Program Read string and show output.
#include <stdio.h>
int main(void)
{
  char str[80];
  printf("Enter a string: ");
  scanf(''%s", str);
  printf("Here's your string: %s", str);
  return 0;}
                                           52
        How to read characters
• You can read char values with the scanf
  function
• C provides a function called getchar() which
  allows you to read characters one at a time
  from a line of input.
                                                 53
                  getchar()
• Function contained in stdio.h
• getchar() returns an int code for a character
  typed on the standard input (the keyboard)
  char c;
  c = getchar() ;
                                                  54
            How to print a char
• Can use printf with a format control string of %c.
• For example,
   printf( “The character is %c\n”, c );
• Can use another function in stdio.h called putchar()
• For example,
   putchar( c ) ;
                                                         55
                  putchar()
• Prints a character to the standard output
  (screen)
• Is a function also referenced in stdio.h
                                              56
      Using getchar() example
#include <stdio.h>
int main()
{char c; /* declare character variable */
    /* read a character and store it in c */
    c = getchar() ;
    /* print it twice, two different ways */
    printf("%c\n", c );
    putchar( c ) ;/* one character at a time so here’s the
       newline */
    c = '\n' ;
    putchar( c );} /* end program */
                                                             57
            Field Width Specification
                  x_ _ _ _ y
                  _ _ _z
                                           59
                 Review questions
1.    C's output function printf() is
•     part of the 'C' language
•     a library function
•     a function users must write as part of every 'C'
      program
•     another name for the function print
 2.   An escape character can be included in a 'C'
      string by including the following characters in the
      string
•     \e
•     ESC
•     \033
•     \0x1B                                                 60
                     Contd……..
3.Conventionally 'C' source files have names ending in
•.c
•.cpp
•.bas
•.html
4.The effect of writing print() rather than printf() is that
•The program will not compile
•The program will work as expected
•The program will display "hello world" in inverse video
•The program will not link correctly
                                                          61
              Contd………..
5. All 'C' programs must include
• The keyword 'program'
• A function called 'main'
• The name of the author
• A lest one use of the printf() function
                                            62
                  Contd…..
                     True/False
•   ___, ___, ____, _____, _______ are the
    different data types in C.
•   . String variables are terminated
    automatically with _______ .
•   . _____ is the escape sequence for bell.
•   . Floating-point constant contains either a
    _______ or an _______ or both.
•   . Signed integers can range ______ and
    unsigned integers can range ______
                                                  63
Programming With Integers
       - Exercises
Write a C program to print out the sum of
 two numbers in the form
The sum of 3 and 4 is 7 I.e. display the
 numbers as well as their sum.
                                            64
 Operators
   And
Expressions
 Lecture 3
              65
                 Operators
• Arithmetic Operators
• Special Operators
                                     66
     Arithmetic Operators
Operator         Action
 –         Subtraction, also unary minus
 +         Addition
 *         Multiplication
 /         Division
 %         Modulus
 --        Decrement
 ++        Increment
                                           67
   Precedence and Associativity
• Precedence of the Arithmetic operators:
     High      ++ --
               - (unary minus)
               * / %
     Low       + -
-a*b–c ((- a) * b) – c
                                            68
• Expressions inside parentheses are evaluated
  first.
1 * (2 - 3)
1 + 2 + 3 + 4 –5
            (((1 + 2) + 3) + 4) –5
                                                  69
       Increment & Decrement Operators
• Provide a concise notation for incrementing or
  decrementing a variable by 1.
Are unary operators.
• ++x or x++          --x or x--
x = x + 1;
int i = 3, j = 2, k;
i++;                              i   4
j = ++i;                          j   5   i 5
k = i++;                          k   5   i 6
k = (--j+3)                       k   7   j 4
                                                73
l = 4;
n = 3;
m = 2;
x = l * n + m++; x 14
                                          74
int a, b, c=0;
a = ++c;
b = c++;
a = ? b = ? c= ?
int b = 2, d = 4;
7--b*++d                           7-((-
   b)*(++d))               ?
int j = 2, k = 3, m = 4;
j*=k=m+5
   j=(j*(k=(m+5)))             ?
                                           75
int a,b;
a = 1;
b = 12;
                                                77
Relational Operators:
      Operator Action
        >        Greater than
        >=       Greater than or equal
        <        Less than
        <=       Less than or equal
        ==       Equal
        !=       Not equal
Logical Operators:
     Operator Action
         &&      AND
          ||     OR
          !      NOT
                                         78
  Precedence and Associativity
High         !
             >   >= < <=
             = = !=
             &&
Low          ||
                                    79
            int x;
            x = 100;
            printf(''%d", x>10);        __?
5 && 3            ?
                                              81
   int   i, j = 1;
1) (i=2) i 2
2) &&           j    1   && 2
                     true && true          1
3) =            j     1
                                                 82
       j   1        i 2
           j = j && (i = = 3);      ( ) not needed
1) (i = = 3) false 0
2) && j 1 && 0 0
3) = j 0
                                                     83
       j 0          i   2
1) (i/2) (2/2) 1
2) ||                   0    j   || 1           true
     1
                 1
3) =         j
                                                         84
     j 1            i 2
      j = !j && (i = i + 1);
1) i+1 3
2) = i 3
3) ! !j !1 0
4) && 0 && 3
5)   =              j 0
                                        85
        The Comma Operator
Lowest precedence of all the operators.
Causes a sequence of operations, “do this
 and this and this…”.
Is a binary operator.
     expression_1, expression_2
Associates left to right.
           int     i = 2;
                   j = 4;
            j = i++, i - j;
 *i   3
 *j   -1   (3-4)
                                        87
• It allows multiple initializations and
  multiple processing of indices.
 will output?
3rd expression in the for statement is a
 comma expression.
                       x = 10;
x = 10;
y = x>9 ? 100 : 200;   if(x>9)
                            y = 100;
                       else
                            y = 200;
                                   92
int i, h, j = 2;    ( ) not needed
    ;         /* an NULL statement */                95
Null Statement:    ; [A semi-colon
                      alone by itself].
               x=10/y-(127/x);
               x = 10 / y - (127/x);
• Redundant or additional parentheses do not
  cause errors or slow down the execution of an
  expression.
             x = y/3-34*temp+127;
             x = (y/3) - (34*temp) + 127;
                                              97
               Exercises
• Given a as 4. If b=a++, then b will be ___
  and if b=++a, b will be ____ .
• The order of the evaluation of the
  expression depends on ______ and ______
• In assignment operator, assignment is
  done from _____ to ______ .
• The logical operators in C are ___________
• ?: is similar to __________ construct of C.
                                            98
           Exercise Contd….
• The type of a variable decides the operators that
  can at on them.
• Unary * has a greater precedence over ++.
• The ! Operator converts a zero to one and a non-
  zero value to zero.
• = = is a logical operator to check the equality of
  two operands.
• Type conversions involve converting a narrow
  type to wider type
• += is one of the ternary operator in C.
• & and * are also kinds of unary bit wise
  operators.
• ++p and p++ means the same in an assignment
  expression                                         99
            Exercise contd….
•Write a program to read in 3 integers and
print their sum.
•Write a program to read in two integers and
display both the quotient and the remainder
when they are divided.
•How does your computer treat the results of
division by a negative number? What happens
when you try and divide by zero?
•What error message does your compiler give
when you write
 x+1=x in a program?                           100
         Exercise contd…..
• Write a program to test the
  behaviour of your computer
  system when it processes
• printf("%d %d\n",x++,++x);
                                  101
Control constructs
Conditional Execution
    Lecture 4
                        102
           Selection
• if
• switch
                       103
              if statement
• Conditional execution:
                                                 104
if – logic:       if (Boolean Expression)           Yes-
                         statement_1;               For a
                                                  Semi-colon
                                             106
                     Example contd……
• General form:
  if (expression) statement;
     else
       if (expression) statement;
         else
           if (expression) statement;
            .
            .
            .
               else statement;
                                        110
• The conditions are evaluated from the top
  downward.
• As soon as a true condition is found, the
  statement associated with it is executed and
  the rest of the ladder is bypassed.
                                             112
double sales, bonus;
printf (“please enter total sales”);
scanf (“%lf”, &sales);
                                                    114
       The ?: Alternative
        Exp1 ? Exp2: Exp3
                        x = 10;
x = 10;
y = x>9 ? 100 : 200;    if(x>9)
                             y = 100;
                        else
                             y = 200;
                                    115
#include <stdio.h>
int f1(int n);
int f2(void);
int main(void)
{
  int t;
  printf("Enter a number: ");
  scanf("%d", &t);
  t ? f1(t) + f2() : printf("zero entered.");
  printf("\n");
  return 0;
}
                                                116
/* Divide the first number by the second. */
#include <stdio.h>
int main(void)
{
  int a, b;
  printf("Enter two numbers: ");
  scanf(''%d%d", &a, &b);
  if(b) printf("%d\n", a/b); if(b != 0) printf("%d\n", a/b);
  else printf("Cannot divide by zero.\n");
    return 0;
}
                                                        117
         switch statement
• switch is a multiple-branch selection
  statement, which successively tests the
  value of an expression against a list of
  integer or character constants (floating
  point expression, for example, are not
  allowed).
 void menu(void)
 {
   char ch;
    case '2':
     correct_errors ();
     break;
    case '3':
     display_errors ();
     break;
    default :
     printf("No option selected");
}
}                                    123
                  int flag, k;    /* Assume k is initialized */
•The break inside flag = -1;
the switch is
                    switch(k) {
optional.             case 1: /* These cases have common */
                      case 2: /* statement sequences. */
•If the break is      case 3:
omitted,                      flag = 0;
execution will                break;
                      case 4:
continue on into
                              flag = 1;
the next case until case 5:
either a break or             error(flag);
the end of the                break;
switch is reached. default:
                              process(k);
                    }                                    124
Calculates the range of marks a student has scored
Int calculate_marks (char grade)
{ switch (grade)
    { case `S’:
printf (“Marks between 91-100”); break;
   case `A’:
    printf (“Marks between 81-90”); break;
  case `B’:
    printf (“Marks between 71-80”); break;
 case `C’:
    printf (“Marks between 61-70”); break;
case `P’:
    printf (“Marks less than 50”);   break;
 default:
    printf (“Invalid grade”); break; }}
                                                     125
              Nested Switch
• You can have a switch as a part of the
  statement sequence of an outer switch.
                                                126
switch(x) {
 case 1:
  switch(y) {
    case 0:
         printf(''Divide by zero error.\n");
         break;
    case 1:
         process(x, y);
         break;
  }
  break;
 case 2:
  ….                                           127
                 Exercise
• control constructs in C are ___________
  and ___________.
• If- else statement is used for
  ____________.
• The case statement values are
  necessarily_____________.
• If values do not match any of the cases in
  switch-case then the control is transferred
  to ___________, if present.
                                                128
               Exercise contd….
                 True / False
• if-then-else is an selective statement of C
• None of the case statements in switch- case
  construct can have identical values.
• Case can exist where none of the code in switch-
  case is executed.
• break statements should be compulsorily present in
  every case.
• break statements can be used in iterative blocks
  also.
• break passes the control to the first statement in the
  iterative block.
•                                                      129
Exercise contd….
                   130
      Loops
For,do-while ,while
    Lecture 5-6
                      131
             Iteration
• Iteration statements (also called
  loops) allow a set of instructions to be
  repeatedly executed until a certain
  condition is reached.
• This condition may be predetermined
  (as in the for and while loop) or open
  ended (as do-while loops).
                                        132
                    for loop
• General form
      for (initialization; testing; increment)
              Loop Body;
• The initialization is an assignment statement
  that is used to set the loop control variable.
                                                 134
   #include <stdio.h>
   int main(void)
   {
     int x;
     for(x=1; x <= 100; x++)
            printf("%d ", x);
    return 0;
   }
for(x=100; x != 65; x -= 5)
{
  z = x*x;
  printf(''The square of %d, %d", x, z);
}
                                           135
    The Elements of the For-loop
• The initialization, testing and
  incrementation can be any valid C
  expression.
                                           136
• Pieces of the loop definition need not be
  there.
     for(x=0; x != 123; ) scanf("%d", &x);
                   for( ; ; ) {
•Terminate           ch = getchar();      /* get a character */
the infinite         if(ch == 'A') break; /* exit the loop */
                   }
loop               printf("you typed an A");
                                                             138
  For Loops With No Bodies
• A loop body may be empty.
                                                139
Declaring Variables within a For Loop
• Execution:
   – Check the test condition at the top of the loop.
   – The loop iterates while the condition is true.
   – When the condition becomes false, program control
     passes to the line of code immediately following the
     loop.
                                                            141
      Example
char wait_for_char(void)
{
  char ch;
  ch = '\0'; /* initialize ch */
  while(ch != 'A') ch = getchar();
  return ch;
}
 while((ch=getchar()) != 'A') ;
                                     142
Example 2:
void func1()
{
  int working;
  working = 1;       /* i.e., true */
    while (working) {
      working = process1();
      if (working)
         working = process2();
      if (working)
         working = process3();
    }
}                                       143
         For loop Vs While Loop
A-(Assignment), T-(testing), I-(Increment)
                           A;
   for (A; T; I)
                           While (T)
   {
                           {
        Body;
   }                           Body;
                               I;
                           }
                                             144
                  NESTED LOOPS
Nested              1 loop syntax coded inside another
Loop               syntax.
main()
{ int cnt = 0, j , k , m,n;
       n=7;
     for(j = 0; j <= N; ++j)
     for( k = 0; k <= N; ++k)
         for( m = 0: m <= N; ++m)
            if ( j + k + m == N) {
                  ++cnt;
                   printf(“%d%d%d”, j , k , m);    }
   printf(“\n Count: %d\n”, cnt);
 }
                                                   147
How many times will “if” be executed?
8 * 8 * 8 = 512
                                    148
           do-while Loop
• General form:
     do {
       statement;
     } while(condition);
• Execution:
  – Always executes at least once.
  – Iterates until condition becomes false.
           do {
            scanf(''%d", &num);
           } while(num > 100);
                                              149
•The most common use of the do-while
loop is in a menu selection function.
  void menu(void)
  {
    char ch;
                                             150
do {
  ch = getchar(); /* read the selection from
                   the keyboard */
  switch(ch) {
    case '1':
     check_spelling();
     break;
    case '2':
     correct_errors();
     break;
    case '3':
     display_errors();
     break;
  }
                                         152
         break Statement
                                #include <stdio.h>
Two uses:
                                int main (void)
You can use it to terminate     {
a case in the switch              int t;
                                               156
• continue can expedite the exit from a loop
  by forcing the conditional test to be
  performed sooner.
                                                157
void code(void)       This function codes a
{                     message by shifting all
  char done, ch;      characters you type
                      one letter higher. For
  done = 0;
                      example, an A
  while(!done) {      becomes a B. The
   ch = getchar();    function will terminate
   if(ch == ‘S') {    when you type a S.
     done = 1;
     continue;} /* test the condition now */
 putchar(ch+1);
}}
                                            158
                          Exercise
What will be displayed in each of the following :
 a) a = 7;
      b = a++;
      printf ("%d", b);
 b) a = 7
      b = ++a;
      printf ("%d", b);
 c) a = 5;
      while(a)
      {
      printf("Hello");
      a--;
      }
                                                    159
• Exercise Contd……..
d) a = 5;
        while(--a) printf("hello");
 e)     a = 5;
        while(a--) printf("hello");
2.Write a program that converts each lower-case character
   in the standard input to            uppercase and each
   uppercase character to lower case. Pass all other
   characters unchanged.
3. Write a program that reads nos. from the standard input
   and prints the largest
     value entered, the smallest value, the sum of all
   values read and the mean of all values inputted.
                                                             160
 About Arrays
one-dimensional
multidimensional
  Lecture 7-9
                   161
                    Arrays
• What is an "array"?
• A way to collect together data of a single
  type in a single object
• A linear sequence of data objects e.g.
  – array of ints
  – array of chars (string)
                                               162
       Creating and using arrays
• Arrays can be
  – initialized
  – partially initialized
  – not initialized
• Uninitialized space contains?
  – "garbage"
                                  164
  One-dimensional arrays (2)
• Examples:
int my_array[10];
  /* not initialized */
int my_array[5] = { 1, 2, 3, 4, 5 };
  /* initialized */
int my_array[] = { 1, 2, 3, 4, 5 };
  /* OK, initialized */
int my_array[4] = { 1, 2, 3, 4, 5 };
  /* warning */
int my_array[10] = { 1, 2, 3, 4, 5 };
  /* OK, partially initialized */
                                        165
   One-dimensional arrays (3)
                                        166
  One-dimensional arrays (4)
int i;
int my_array[10];
for (i = 0; i < 10; i++) {
  my_array[i] = 2 * i;
}
Usually the best approach
                                       167
   One-dimensional arrays (5)
                                                         169
        PROGRAM TO MAXIMUM OF 25 GIVEN
            ELEMENTS IN AN ARRAY
# include <stdio.h>
int main (void)
{
   int a [25];
   int i, max = a[0]
for (i = 0; I< 25; i++)
{ printf(“Enter the %d number: “, i +1 );
   scanf( “%d” , &a[i ]);
}
for ( i = 1, i <25; i ++ )
   if(a [i ] > max )
         max = a [ i ];
printf ( “The maximum number in the array is: %d” , max);
}
                                                            170
    program to find kth Smallest Element
# include <stdio.h>
 int main (void)
{ int u,j,k, temp,no_elements,array [20];
   printf (“Enter the number of elements: “);
   scanf (“%d”,&no_elements);
   printf(“Enter the list of elements:\n “);
   for (i=0;I<no_elements;i++)
        scanf (“%d”,&array[i]);
   for( i=0; i<no_elements; i++)
         for( j=0; j<no_elements; j++)
        if(array[i] > array [j])
        { temp = array[i]
             array [i] = array [j]
             array[j] = temp; }                 171
       find kth Smallest Element contd…..
/* The nested loop to sort the array. The if loop is used to swap the
   element of the array in ascending order. So the Kth smallest
   element will be the element */
     array[k-1]
                                                                        172
           program to perform Insertion Sort
# include <stdio.h>
int main (void)
{int a [MAX], n, i, k, temp;
   printf (“Size of the array : “);
   scanf (“%d”, &n);
   printf (Elements of the array:\n”);
   for (k = 0 ; k < n ; k++)
     scanf (“%d”, &a[k]);
   for(k = 1 ; k < n ; k++)
   { temp = a[k];
    for(I = k-1 ; i >= 0&&temp < a[i] ; i - )
   a [i+1] = a [ i ];
      a[ i+1 ] = temp;}                         173
          Insertion Sort contd….
                                            174
  Two-dimensional arrays (1)
                                176
     Two-dimensional arrays (3)
int arr[2][3];
/* initialize... */
/* arr[0] is array of 3 ints */
/* arr[1] is another array of 3 ints */
                                             177
     Two-dimensional arrays (4)
• Picture of arr:
1 23 -12 arr[0]
85 46 99 arr[1]
                                             178
     Two-dimensional arrays (5)
int arr[2][]
  = { { 1, 2, 3 }, { 4, 5, 6 } };
  /* invalid */
int arr[][]
  = { { 1, 2, 3 }, { 4, 5, 6 } };
  /* invalid */
int arr[][3]
  = { { 1, 2, 3 }, { 4, 5, 6 } };
  /* OK */
                                    180
      Two-dimensional arrays (7)
int my_array[][3]
  = { 1, 2, 3, 4, 5, 6 };
    /* warning with -Wall */
int my_array[][3]
  = { { 1, 2, 3 }, { 4, 5 } };
    /* OK; missing value = 0 */
                                                189
Strings
          190
               String
• The most common array is the string,
  which is simply an one-dimensional
  array of characters terminated by a
  null.
• The End-of-String Sentinel (delimiter)
  \0.               #define MAXWORD 100
                   int main(void){
                   char w[MAXWORD];
                   w[0] = ‘A’;
                   w[1] = ‘\0’;
                   /*….*/                  191
• When declaring a character array that
  will hold a string, you need to declare it
  to be one character longer than the
  largest string that it will hold.
• WHY?
char str[11];
                                            192
          String Initialization
• General form:
    char array_name[size] = “string”;
char str[9] = {'I', ' ', 'l', 'i', 'k', 'e',' ', 'C', '\0'};
                                                               193
• The format %s is used for a string.
     scanf(“%s”, w); //if w is a string var
     printf(“%s”, w);
                                              194
    String-Handling Functions
• Standard header <string.h>
strcpy(s1, s2) Copies s2 into s1
strcat(s1, s2) Concatenates s2 onto the
  end
               of s1.
strlen(s1)      Returns the length of s1
strcmp(s1, s2) Returns 0 if s1 and s2 are the
               same; less than 0 if s1<s2;
               greater than 0 if s1>s2
                                            195
strchr(s1, ch)   Returns a pointer to
                 the first occurrence of
                 ch in s1.
strstr(s1, s2)   Returns a pointer to
                 the first occurrence of
                 s2 in s1.
                                           196
#include <stdio.h>
#include <string.h>                Hello
int main(void){                    Hello
 char s1[80], s2[80];              lengths: 5 5
 gets(s1);                         The strings are equal
 gets(s2);
 if(!strcmp(s1, s2))
       printf("The strings are equal\n");
                                                      197
strcat(s1, s2);                          hellohello
printf (''%s\n", s1);                    This is a test
                                         e is in hello
                                         found hi
strcpy(s1, "This is a test.\n");
printf(s1);
                                               199
/* Allocate space for a string dynamically, request user
   input, and then print the string backwards. */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
  char *s;
  int t;
  s = malloc(80);
  if(!s) {
    printf(''Memory request failed.\n");
    exit (1);
  }
  gets(s);
  for(t=strlen(s)-2; t>=0; t--) putchar(s[t]);
  free(s); return 0;
                                                        200
}
STORAGE CLASSES
                  201
Every variable or function in C has 2 attributes:
General form:
                                              203
               Auto Variables
The storage class auto can only be used in a block:
    it cannot be used at the global level.
                                                     204
            Impact of Auto
• Auto is the default SC for local vars because it
  makes the most efficient use of memory.
                                                     205
                  auto
• Most common of the four storage classes.
                                              206
Unintentional interference between
functions is minimized and, making it
much easier to debug large programs.
                                         207
When a block is entered, the system allocates
  memory for the auto variables.
“LOCAL”         i.e., Those declared in the
                       block.
  IF re-enter the
      Block? _________
  Memory is reallocated.
                                           208
 Call by Reference with Auto
          Parameters
1) When the block is suspended, such as when it
  calls another function,the variable is suspended
  but can still be accessed and changed(e.g. actual
  argument in a func call).
                                                 209
                Extern
• Primary purpose is to make variables
  visible to other compilation units.
                                              210
       Extern Characteristics
• Spatial Limitation(global): It is visible
  from its definition to the end of the
  program. It can be referred to and
  changed by all blocks that come after it as
  well as by other programs that are aware
  of its existence.
                                              212
       Register Storage Class
                                              214
It is an attempt to improve execution speed.
Most frequently accessed variable – loop control
    variable or function parameters.
  register int i ;
      for (i = d, i <LIMIT, ++i){
              …
           }
  register i ;
                                                       215
       Static Storage Class
A static variable can be defined inside a
  block(local) or in the global area of the
  program. Its characteristics differ slightly
  depending on where it is defined.
                                                 216
      Local Static Variables
Static variable is defined inside a block:
                                               217
Locally defined Static variables are one of the truly
    significant features of the “C” language.
                                                    218
Void f(void)
{
  static int cnt = 0;
   ++ cnt;
   if (cnt % 2 == 0)
        . . . . . .
   else . . . . .
  }
* 1st Time Function Invoked cnt is set to 0.
* Upon EXIT cnt NOT cleared from memory
* Next invocation ,retains previous value.
                                               219
        Global Static Variables
Global variables-that is, variables defined
  outside the scope of all blocks-can be
  referred to by other compilation units.
                                              220
    Global Static Characteristics:
1) Spatial Limitation(scope): Global.
   Visible from its definition to the end of
   the compile unit. Guarantees that the
   scope does not extend beyond its
   spatial area, i.e., the current
   compilation unit.
       void f(int a)
        {
           ……..         /* g() is available here,
         }                 but not in other files */
                                              224
            Type Qualifiers
• Two type qualifiers:   const   volatile
int main(void)
{
  sp_to_dash("this is a test");
  return 0;
}
           230
Functions and Structured
     Programming
Lecture 10-13
                           231
   Structured Programming
• Structured programming is a problem-solving
  strategy and a programming methodology.
  – The construction of a program should embody top-
    down design of the overall problem into finite
    subtasks.
  – Function types
  – Function variables
  – Function arguments
  – Function scopes
  – Return values
  – Function prototypes
  – Recursion
                                           233
General syntax:
                                          236
• Where variables are declared:
  – Inside functions:
            local variables
                                                237
                 Local variable
• Declared inside a function.          void func1(void)
• Can be used only by statements       {
                                         int x;
  that are inside the block in
                                         x = 10;
  which the variables are declared.    }
• A local variable is created upon
                                       void func2(void)
  entry into its block and destroyed   {
  upon exit.                             int x;
                                         x = -199;
                                       }
                                                     238
void f(void)
{
  int t;
  scanf("%d", &t);
    if(t==l) {
      char s[80]; /* this is created only upon
                      entry into this block */
                  /* do something . . . */
    }
                        if(x == 10) {
                          int x; /* this masks the outer x */
                          x = 99;
                          printf("Inner x: %d\n", x); 99
                        }
                                                     244
      Function Parameters
• General form:
                                                   245
        The Scope of a Function
• Each function is a discrete block of code.
                                                  246
• Variables that are defined within a
  function are local variables. Such
  variables are freed from memory when
  their function completes execution.
– Call by Value.
– Call by Reference.
                                        249
             Call by Value
* When an Argument (variable, constant, or
  expression) is passed to a matching parameter
  (declared in Function Heading), A Copy of the
  Argument is made and is passed to the
  parameter.
      Arguments         Parameters
      in calling             in called
      Module.                Module.
* Changes made to the parameter have no effect
  on the argument. i.e., the parameter is
  implemented as a local variable which is
  initialized to the value passed from the     250
          Call by Reference
• It is often convenient to have functions modify
  the values of the variables referred to in the
  Argument list.
int main(void)
{
  int t=10;
  printf("%d %d", sqr(t), t);
  return 0;
}
int sqr(int t)
{
  t = t*t;
  return t;
}                               252
Placement of Functions:
    Before the compiler sees a call to a function
    it wants to know the Number and Type of its
    Parameters and the type of the Return Value
    of the Function.
                                                 253
#include <stdio.h>
int main(void) {
   int test1, test2, test3;
   double avg;
   scanf(“%d%d%d%d”, &test1, &test2, &test3);
   avg = average(test1, test2, test3);
   printf(“ The average is: %f”’, avg);
}
                                                257
/* This function returns the average of 3 exam
  scores which are passed call-by-value. */
                                                  258
      Returning from a Function
• A function terminates execution and returns
  to the caller in two ways.
                                                     259
• General form:
           return expression;
                                                262
• As long as a function is not declared as
  void, it can be used as an operand in an
  expression.
x = power(y);
for(ch=getchar(); isdigit(ch); ) . . . ;
                                                   263
        The exit( ) Function
• General form
     void exit(int return_code);
#include <stdlib.h>
      int main(void)
      {
        if(!virtual_graphics()) exit(1);
        play();
         ...
      }
                                           265
                             Exercise
                        Fill in the blanks
•   The region where a variable name can be used is called
    the _______ of the variable.
•   The variables declared inside a function or blocks have
    ______ scope.
•   The three kinds of score are ____, _______ and ________.
•   ________ and _______ variables have block scope by
    default.
•   Auto variable cannot be _______ variables.
•   Functions have _________ scope.
•   Functions have _______ scope.
•   Labels have _____ scope.
•   Variable declared outside a block have _______ scope.
•   Function declaration should be done ______ a function
    call.
                                                               266
             Exercise Contd…. (true/false)
• Function scope can be told as a form of block scope.
• Allocated memory in a block is automatically released
  before the block ends.
• Variables with the same name in different block use the
  same memory locations.
• Block variables can be global variables also.
• File scope variables can be accessed by all functions in the
  file.
• File scope variables can be local variables also.
• It is possible to jump out of functions using labels.
• Using global variables allows sharing of data between
  functions.
• Using global variables increased the structural
  organization of a program.
• It is must to declare functions before they are used.
                                                                 267
                Exercise contd…..
                                            269
                     Recursion
• A function calls itself (circular definition).
    /* non-recursive */       /* recursive */
    int fact(int n) {         int factr(int n) {
     int t, answer;            int answer;
                                                         272
Pointers
           273
           Why Pointers
• They provide the means by which
  functions can modify arguments in the
  calling function.
                                            274
        What Are Pointers
• A pointer is the memory address of an
  object.
• General syntax:
    type *name;
Dereference Operator: *
     m = &count;
     m receives the address of count.
           m      count
                         100
                                               279
             * Operator
     q = *m;
     q receives the value at address m.    ?
                                               280
               #include <stdio.h>
               int main(void)
               {
Put the          int target, source=10;
value 10         int *m;
into a           m = &source;
variable         target = *m;
called target. printf("%d", target);
                   return 0;
               }
                                          281
          Pointer Assignments
• You can use a pointer variable on the right-
  hand side of an assignment statement to
  assign its value to another pointer.
                                                 282
#include <stdio.h>
int main(void)
{
  int x = 99;
  int *p1, *p2;
  p1 = &x;
  p2 = p1;
  printf("%p %p", p1, p2);
  printf(''%d %d\n", *p1, *p2);
  return 0;
}
                                  283
   Illustrates Distinction between a pointer var value & a
  Dereferenced var.
main( )
  {     int i = 777, *p = &i;
        printf (“value of i:%d\n”, *p);
        printf (“Addr of i:%u or %p\n”, p, p);
   }
Output           Value of i: 777
                 Address of i: 234880259 or dfffcfc
                                                             284
                         Example 1
int i = 1, *j, *k;
Assume addresses of i, j, k are respectively Byte addresses
      10, 20, 30
      1                        ?                      ?
    i:10                      j:20                  k:30
1. j = &i;
      1                10                     ?
    i:10              j:20                   k:30
                                                              285
2. *j = 2;
     1 2            10            ?
    i:10            j:20      k:30
    Stores 2 at the memory location pointed to by j.
3. i = *j + 1;
     12 3           10            ?
    i:10           j:20         k:30
     3            10    10
   i:10          j:20   k:30
              output:   3
                               287
       Example 2
int a=42, b=53, *p1, *p2;
p1 = &a;
p2 = p1;
p2 = &b;
  p2            9   p2           9
*p1 = *p2;
      before             after
  p1         8      p1           9
 p2             9   p2           9   291
                    Example 4
# include <stdio.h>
main( )
{
      int j, i, *intptr;
       scanf(“%d%d”, &i, &,j);
       intptr = i > j ? &i:&j;
       printf(“%d\n”, *intptr);
 }
 Address of the larger var is stored in ? : then
   the larger number is output.
                                               292
                               Example 5
int a=3,b=7,*p;          p = &b;
        3                7
       a             b             p
*p=2**p–a;
1) 2 * *p       2*7
2) 14 – 3       11
3) Which is assigned?                           b 11         293
     Pointer Initialization
p = (int *) 1307;
            cast to pointer to int.
            1307 is an absolute address in
        memory.
                                              295
int i = 3, j = 5, *p = &i, *q = &j, *r;
double x;
                                            r
     3                    5                          ?
     i:10                 j
                   p:50             q           ?x
i:10 p:5
4) 7 * *p / *q + 7                                  i:10     j
                                                      3              5
       Dereference Right to Left                   p             q
1.   *q 5
2.   *p 3
3.   7 * 3 [21]
4.   21/5 4
5    4 + 7 11
                                                                     298
5) *(r = &j) *= *p
     4 2 1 5 3                                   j - int var
                                                 p - pointer to int
         j                   i                   r - pointer to int
     5                   3
              r                  p
1. &j - Address of j 1
2. r = 1 r points to j
3. *p    contents of thing
         pointed to by p i.e., 3
4. *( ) Location pointed to by r, i.e., j.
5. *=        *r *= *p;           *r = *r * *p;
                                                                 299
         Pointer Arithmetic
int *v=(int *)100; Byte Address.
                  100          v
                  102          v+1
                  104          v+2
                  106          v+3
                  108          v+4
assume int
are 2 bytes long.
                                     300
    Pointer Arithmetic (cont.)
                                 301
    Pointer Arithmetic (cont.)
• Only two operations are allowed.
  – Addition and subtraction.
  e.g. p++;      p--;   p1=p1+12;
                                         302
            Call by Reference
• Passing a ADDRESS of the argument to a
  formal parameter which is a POINTER of the
  same type as the argument.
                                               303
                  Steps
1) Declare a function parameter to be a
   pointer.
                                             304
#include <stdio.h>
void swap(int *x, int *y);
    return 0;
}                                                      305
void swap(int *x, int *y)
{
    int temp;
                                                 306
                      Exercise
                       Fill in the blanks
• _________gives C the power to deal with machine
   architecture.
• _______ gets the value stored by location pointed by a
   pointer.
• If int *ptr = &temp;, then ptr = ____________.
• NULL is defined in _________.
• Address of different data types assigned to pointers of
   different data types give rise to ________ errors.
• If int a = 0, b = 1;
   int *pl = &a, *ps = &b;
   *p1 = p1+p2;
   *p = ________(taking &a = 1000 and &b =20).
7. float a =1.5, *ptr = &a;
   ptr = (int) (ptr + a);
   thus p = _______ (taking &p = 100).                 307
                 Exercise Contd……
                         True / False
1. Pointers hold address of memory locations.
2. ‘&’ is called the indirection operator.
3. p = * (&p)
4. p = &(*p)
5. Addition of pointers is illegal.
6. We can apply bit operations on pointers.
7. NULL points to nothing.
8. (ptr1-ptr2) = (ptr1+ptr2)/size of object pointed by
    ptr1. (given ptr1 and ptr2 point to elements of the
    same array.
9. Pointers of the same type can be compared.
10. Pointers cannot be compared for equality at any time.
                                                            308
Structures
             309
        Derived Data Type
                                             311
           Structure Declaration
• A structure declaration forms a template that can be
  used to create structure objects (instances of a
  structure).
                                                        312
           General Form
struct tag {
     type member-name;
     type member-name;
     type member-name;
     .
     .
     .
  } structure-variable(s);
                             313
keyword              structure tag name
    struct addr
    {
      char name[30];
      char street[40];
      char city[20];
      char state[3];
      unsigned long int zip;
    };      Terminated by a semicolon
No variable has actually been created.
                                     314
     Structure Variable Declaration
           struct addr addr_info;
                                                 315
     Memory allocated for addr_info
        Name     30 bytes
        Street   40 bytes
        City     20 bytes
        State    3 bytes
       Zip       4 bytes
Assume 4-byte long integers           316
You can declare one or more
objects when declare a struct type
     struct addr {
      char name[30];
      char street[40];
      char city[20];
      char state[3];
      unsigned long int zip;
     } addr_info, binfo, cinfo;
                                     317
        Initialization of Structures
                                                318
Accessing Structure Members
• General form:
object-name.member-name
                                          319
e.g., addr_info.zip = 12345;
      printf("%lu", addr_info.zip);
gets(addr_info.name);
                                            320
       Structure Assignments
#include <stdio.h>
int main(void)
{
  struct {
    int a;
    int b;        Do not need to assign
  } x, y;         the value of each
                  member separately
   x.a = 10;
   y = x; /* assign one structure to another */
printf("%d", y.a);
    return 0;
}                                                 321
         Array of Structures
WHY?
                                             322
       Arrays of Structures
• To declare an array of structures, you must
  first define a structure and then declare
  an array variable of that type.
printf("%lu", addr_list[2].zip);
     addr_list[2].name[0] = 'X';
                                            323
 Passing Structures to Functions
                                            324
Passing Structure Members to Functions
• When you pass a member of a structure to
  a function, you are passing the value of
  that member to the function. It is
  irrelevant that the value is obtained from a
  member of a structure.
                           struct friend
                           { char x;
                             int y;
                             float z;
                             char s[10];
                           } mike;
                                            325
func(mike.x); /* passes character value of x         */
func2(mike.y); /* passes integer value of y          */
func3(mike.z); /* passes float value of z            */
func4(mike.s); /* passes address of string s         */
func(mike.s[2]); /* passes character value of s[2]   */
#include <stdio.h>
              struct Example_type {
               int a, b;
               char ch;
              };
                                      327
void f1(struct Example_type parm);
int main(void)
{
  struct Example_type arg;
    arg.a = 1000;
    f1(arg);
    return 0; struct_type
}            must match
void f1(struct Example_type parm)
{
  printf(''%d", parm.a);
}                                    328
In Header File:      cl_info.h
                                           330
    Declaring a Structure Pointer
• Like other pointers, structure pointers are
  declared by placing * in front of a structure
  variable's name.
                                                  331
        Using Structure Pointers
• To pass a structure to a function using call by
  reference.
                                                    332
struct bal {
 float balance;
 char name[80];
} person;
p = &person;
                                              333
      The Structure Pointer Operator
                      –>
Used to access the members of a structure via a
  pointer.
                p–>balance
Forms:
         (*pointer-To-Struct). member
                     or
          pointer-To-Struct     member
                                                  334
  struct student temp, *p = &temp;
temp.grade = ‘A’;
temp.last_name = “Bushker”;
temp.student_id = 590017;
        struct student {
        char    *last_name;
        int      student_id;
        char     grade;
        };
                                     335
Expression         Equivalent          Value
(*p).student_id                  590017
       Parenthesis are necessary
           (dot) has higher priority than *
                                                 336
     Arrays and Structures Within
              Structures
                                             337
      Arrays Within Structures
    struct x {
     int a[10] [10]; /* 10 x 10 array of ints */
     float b;
    } y;
Structure y.
               y.a[3][7]                           338
Structures within Structures
struct emp {
 struct addr address; /* nested structure */
 float wage;
} worker;
worker.address.zip = 93456;
                                          339
 Using sizeof to Ensure Portability
Type Size in Bytes             struct s {
char     1                      char ch;
int      4                      int i;
double   8                      double f;
                               } s_var;
sizeof(s_var) is 13 (8+4+1).
       struct s *p;
       p = malloc(sizeof(struct s));
                                            340
                      typedef
• You can define new data type names by using
  the keyword typedef
BALANCE over_due;
                                  342
E.g.,   The declaration for an array of
        pointers to strings.
Char * stringPtrAry[20];
STRING StrPtrAry[20];
                                          343
          Typedef with Structures
typedef struct
   { char id[10];
      char name[26];
       int gradepts;
    } STUDENT;       A typename not
                      a variable.
STUDENT pupil;
                                      344
  File handling
                          345
              Classes of Files
There are two broad classes of files:
Text Files: All the data are stored as
  characters which must be converted to
  internal formats when entered into
  memory. Text files are organized around
  lines which end with a new line(“|n”).
                                             348
               Files and Streams
• The computer looks at input and output data,
  whether from a physical device such as a
  keyboard, or from secondary files, as a stream of
  characters or bytes.
                                                 349
• The term file table implies that several things are
  stored. It contains ALL the info needed to locate
  your file wherever it is stored outside of the
  computer. It also contains info such as the file
  name, the location of its file buffer, and the
  current state of the file.
                                                    350
             File System Basics
• The header <stdio.h> contains:
                                                        351
   The file pointers(stdin, stdout, stderr-
i.e., Tables) are automatically opened
when the program starts.
                                              352
    Three File Pointers
stdin    Standard input      Connected
         file                to the
                             keyboard
Stdout   Standard output Connected
         file                to the
                             screen
stderr   Standard error file Connected
                             to the
                             screen
fopen( ) Opens a file                           Commonly
fclose( ) Closes a file
putc( ) Writes a char. to a file                used C file-
fputc( ) Same as putc( )                        system
getc( ) Reads a character from a file
fgetc( ) Same as getc( )                        functions
fgets( ) Reads a string from a file
fputs( ) Writes a string to a file
fseek( ) Seeks to a specified byte in a file
ftell( ) Returns the current file position
fprintf( ) Is to a file what printf( ) is to the console
fscanf( ) Is to a file what scanf( ) is to the console
feof( ) Returns true if end-of-file is reached
rewind( ) Resets the file position indicator to the begin of the file
remove( ) Erases a file
Fflush() Flushes a file
                                                               354
              The File Pointer
• In order to read or write files, your program
  needs to use file pointers.
• A file pointer is a pointer to a structure of
  type FILE.
• It points to information that defines various
  things about the file, including its name,
  status, and the current position of the file.
                  FILE *fp;
                                                  355
          Opening a File
• The fopen( ) function opens a stream for
  use and links a file with that stream. Then
  it returns the file pointer associated with
  that file.
• General form:
                                            356
• filename is a pointer to a string of
  characters that make up a valid filename
  and may include a path specification.
                                                       361
                Closing a File
• General form:
                                                        362
• fclose( ) closes a stream that was opened
  by a call to fopen( ).
                                              363
• Failure to close a stream invites all kinds
  of trouble, including :lost data, destroyed
  files, and possible intermittent errors in
  your program.
                                                364
           Writing a Character
                 To a File
• putc( ) and fputc( )
• General form:
                                            365
        Reading a Character
• getc( ) and fgetc( )
• General form:
     int getc(FILE *fp);
  Returns EOF when the end of the file has
  been reached.
         do {
          ch = getc(fp);
         } while(ch!=EOF);                   366
/* KTOD: A key to disk program. */
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{                  KTOD TEST
  FILE *fp;        Reads characters from the
  char ch;         keyboard and writes them to a
                   disk file until the user types a
 if(argc!=2) {     dollar sign.
   printf(''You forgot to enter the filename.\n");
  exit(1);
 }
                                                      367
    if((fp=fopen(argv[1], "w"))==NULL) {
      printf(''Cannot open file.\n");
      exit (1);
    }
    do {
       ch = getchar();
       putc(ch, fp);
    } while (ch != '$');
    fclose(fp);
    return 0;
}                                          368
                  feof( )
• General form:
    int feof(FILE *fp);
     while(!feof(fp)) ch = getc(fp);
                                             369
        Working with Strings
• fputs( )
• General form:
                                          370
• fgets( )
• General form:
                                              371
If a newline is read, it will be part of the
string (unlike the gets( ) function).
                                               372
                   rewind( )
General Format:
    void rewind(FILE *fp);
                                                  373
• A common use of REWIND is to change a
  work file from a write state to a read state.
                                                377
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>                         Double check
                                           before erasing
int main(int argc, char *argv[]){
 char str[80];                             .
 if(argc!=2) {
   printf(''usage: erase <filename>\n");
   exit(1);
 }
                                                       378
printf("Erase %s? (Y/N): ", argv[1]);
gets(str);
if(toupper(*str)= ='Y')
      if(remove(argv[1])) {
        printf("Cannot erase file.\n");
        exit(1);
      }
return 0;
                                          379
            fprintf( ) and fscanf( )
• General form:
                                                          380
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main(void)
{
  FILE *fp;
  char s[80];
  int t;
    if((fp=fopen("test","r")) == NULL) {
        printf("Cannot open file.\n");
        exit(1);
       }
    return 0;
                                                            382
}
LINKED LIST
              383
                 LINKED LIST
               DATA STRUCTURE
                                                          385
       Self-Referential Structures
• The node in a linked list are called self-
  referential structures: Each instance of the
  structure contains a pointer member to
  another instance of the same type.
                                            386
     Type Definition for a Linked List
typedef int KEY_TYPE;
 typedef struct
{ KEY_TYPE key;
   …              /* other data fields */
} DATA;