C Programming
C Programming
BSC NOTES
    PDF
COLLECTION
 www.avashkattel.com.np/bscnotes
1         Introduction
1.1        Computer
Basically it is a fast caleulating machine which is now a days nsed for variety of uses
ranging from house hold works to space technology. The credit of invention of this
machine goes to the
                    English Mathematician Charles Babbage.
1.2           Types    of   Computer
Based         on   nature, computers          classified
                                      into Analog computers and
                                        are
                                                                Digital computers.
The former one deals with measuring physical quantiies (concerned with continuous
variables) which are of late rarely used. The digital computer operates by counting and
it deals with the discrete
                           variables. There is a combined form called Hybrid computer,
which has both features.
 Based on application computers are classified as special purpose computers and gen-
 eral computers. As the name tells special computers are designed to performn certain
 specifie tasks where as the other category is designed to cater the needs of rariety of
    lusers.
Control Unit
                              Input                                          Output
                             Device                 Arithmetic/logic Unit|   Devce
Memory Unit
      The ma         conponents of a conmputer are lnput unit (1U), Central Processing nit (CPU)
      ad Output mit (OU). The inlormation like data. prograns ete are passed to the com-
      puter through input devices. The keyboard. mouse, Iloppr disk. CD. DVD. joyst ick etc
                                                                                              from          à    colpter
                                            out put device is to get information
     t a m input              devices. "The
                                                                           disk, CD                   etc
                                                                                                                are otplut
                                                           Printer, Ploppy
     DIOCeSsing          .
                              VDU (Visual DisDlay Unit),
     devices.
                                                  components- Memory unit,           unit               Control
                                                                      of                    instructions stored
  The O r o l luit is for controlling the execution and interpreting
                                                arithmetic  and logical  operations are pe-
    e
       nemory. ALU is the mit where the                             of binary digits, called
                                             transformed  to groups
        h e infomation to a computer is
  edl                                                         from 8 to 64. A group of 8
                                                  computer,
                                  varies from computer to
 O hee length of bit                                   one alphanumeric (
                                                                             Alphabets and
 1 s Called a Byte and a byte generally
                                           represents
                                                                 are called hardwares.
                                                                                       But
                                                 of a computer
 Nnerals) character. The physical components              A set of instructios 1s called
                                                                                          a
 lOr the nachine to work it requires certain progran1s (
 of communication between a computer and the user. DOS, Windows, Linux, Unix etc
 are Operating Systems.
Compiler and interpreter are used to convert the high level language into machine level
language. The program written in high level language is known as source program and
the corresponding machine level language program is called as object program. Both
compiler and interpreter perform the same task but there working is different. Compiler
read the program at-a-time and searches the error and lists them. If the program is error
free then it is coverted into object program. When program size is large then compiler
is preferred. Whereas interpreter read only one line of the source code and covert it to
object code. If it check error, statement by statement and hence of take more time.
      First and foremost step of solving a problem is knowing about the nature of problem in
      order to solve it. Almost all types of problems can be solved with computer. However,
     correct fornmulation of the problem in computer understandable terms is essential to
     formulate the problem and solve it using computer.
technologies of today. Then the solution may not be feasible to the problem.
                                                                                                                                  be
   by step procedure for developing                a   problem          is called   an   algorithm.Algorithns               can
                                numbers       as a     and b
         (a) Stepl: Input
       (b) Step2: Sum = x +y
Varous symbols can be used to represent ditterent actions like taking input, making
                                                          10
                   Symbol               Name                Function
stort/end
. Iiitsiit%}
The flow chart for tlhe addition of two numbers whose algorithm has becn stated above
can be drawn as
2.5    Implementation
After a program has been Written and tested it necds to be implemented to the target
environmcnt to solve the problem. Various necds of physical hardware and accessories
rcqnired by the program to solve the intended problem necds to be present upon implo-
 mcntation. Once the program is implemcnted it starts to work.
2.6   Evaluation and Maintenance
The evaluation of the performance of the program needs to be done at frequent interval
once the program or software is implemented. The advent of new technology, upscaling
and downscaling of the business, request for the change from customers, finding ofa
new bug are the major reasons for the maintenance and change of the softwares. Once
changes have been continuous monitoring of the software perfornance needs to done to
discover the flaws in the software.
2.7   Documentation
The same workforce that developed the program may have left the project and gone in
search of opportunities. So a program must be well documented in order for the new
people to understand how the software was developed and how can it be modified. The
documentation start from the very beginning of the problem formulation to the very
end of the Evaluation and Maintenance.
3      Variables and Data Types
3.1       Constant and Variables
The smallest meaningful units in C programming is called C Token. Keywords. vari-
ables. various special characters fall nder c tokens.
Const ants refer to fixed values that the program may not alter during its execution.
These fixed values are also called literals. Constants can be of any of the basic data
types like an integer const ant, a floating constant, a character constant, or a string
literal. There are enumeration constants as well.Constants are treated just like regilar
variables except that their values cannot be modified after their definition.
      variable is nothing but a name given to a storage area that our programs can ma
nipulate. Each variable in C has a sperific type, which determines the size and layout
of the variable's memory: the range of values that can be stored within that memory:
and the set of operations that can be applied to the variable.The name of a variable
can be composed of letters, digits, and the underscore character. It must begin with
either a letfer or an underscore.              Upper and lowercase letters are distinct because (C15
case-sensitive.
2.147,483.647
    #include <stdio.h>
    extern          int       a.    b:
    exter           1nt       C:
    extern          float          I:
    iut mai1 ()
          int       a,     b:
          iut       c:
          Iloat          f:
=10
b = 20:
                                                         3
                                                c
                      valne
                                          ol
      printl(
                                                                    \u          1)
                 70.0/3.0
                                                f:
                                                         %l
                      value of
      printi(
Ieturn 0
                                                                     name
                                                                                  in C
                               writing
                                                    variable
                                                                                                     and
                                                                                                                 lowercase
                                                                                                                                     ers), digits
                                                                                                                                 letters)
   I. A
             variable
                                                                                                                                      Ho
        and underscore only                                                                  letter      or an
                                                                                                                     underscore.
                                                                                                                                             ever,
                                                                                either   a
                                               variable
                                                          should           be
                                                                                               u d e r s c o r e .
                                                                                                                      It is because
                                                                                                                                        vari
                                                                                                                                            uiable
                       of                 a                                      With a l                                     and
      The first letter                                variable
                                                                      name
                                                                                                             à    system name   d              1lay
   2.                                                                                              with
                                         to start                               can
                                                                                      colilct
                 discouraged
        it is                                       an
                                                         underscore
                           starts
                                          with
          name
                  that
                      in   a           program
          variables
                                          Function
3.4       Input Output                                                                                   to read                   given input
                                                                                      built-in functions
                                                               many        of the
                         language provides
C programming
                               screen,         printer    or       in any file.
and write data        on
                                          functions
scanf     () and printf()
void main ()
  int      i:
 printf( Enter a value")
 scanf("d",&i );
  printf\nYou entered: d " ,i );
 getch ():
3.5       Operators in C
An operator is a symbol that tells the compiler to perform specific mathematica                                                                 r
logical    functions.          C
                                        Janguage     is rich in           built-in operators and provides the
ypes of perators.                                                                                                                     followl
   Arithnet ic Operator
   Relational Operator
   .Logical Operator
   .Bitwise Operator
   A             ent )erator
   Mise (Operalor
3.5.1              Arithmetic Operator
The basic operators for performing arithmetic are the same in many computer languages:
      1.       +                   Addition
      2.   -
                                  Subtraction
               *
      3.                          Multiplication
      4.                           Division
      5.                           Modulus (Remainder)
                                                       The   order of precedence of these
 For exponentiations we use  the library function pow.
 operators is % /* + - . it can be overruled by parenthesis.
i n t X, Y
2 =sizeof(x )
                                                   of        integer type             data is 2 that of float is 4, that of
     The value of y is 2. The           sizeof()        an
     or cqual to ).
                             ==
 i n t i j ,k:
 2    i=l:
 3 j=2:
 =i+)
                                                         the                     expression     k<5 evaluates to true.
      The expression          k>5 evaluates to lalse and
               1. && AND
      2. OR
      3.   ! NOTT
     a + = 5 results
                     in increasing                                      a=a/3
                                              in a and it is cquivalent
            results in storing the value a/3
     a/=3
i n t a,b,c,d,e;:
 2 a=3;       b=5;        c=8;
                     ?    a       b;
3 d=(a<b)
 4e=(b>c)            ?    b       C
                                                                                                     3 and    e    =
                                                                                                                        8.
                                                                 results the value of d
                                                                                                =
bitwise AND
bitwise OR
bitwise cxclusive OR
shift left
                                                   slilt riglht
 3.6      Operator Precedence                       in C
 Operator precedence determines the grouping of terms in an expression and decides how
 an expression is evaluated.                 Certain operators have higher precedence than others; for
 example,      the   multiplication          operator has           higher precedence      than the addition
                                                                a
                                                                                                                      operator
 oexample, x                =   7+3*          2;   here,   x   is assigned   13,    not    20 b e c a u s e o p e r a t o r   *   has
a higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.An
 arithmetic expression without parenthesis will be evaluated from left to right using the
 Tules of precedence. There are two distinct priority levels of arithmetic operators in C.
    .Higher Priority */
       .Lower Priority +
 The expression x=a-b/3+c*2-1 where a=9, b=12 and c=3 will be evaluated as
 stepl: x=9-12/3+3*2-1 Higher priority operators left to right division first
 step2: x=9-4+3*2-1 Higher priority operators left to right multiply
 step3: x=9-4+6-1 Lower priority operators left to right subtraction
 step4: x=5+6-1 Lower priority operators left to right additio
 step5: x=11-1 Lower priority operators left to right subtraction
 step6: x=10 Final Result
I f parentheses are nested, the evaluation begins with innermost sub expression.
          sub expressions.
       Arithmetic expressions are evaluated from left to right using the rules of prece-
          dence.
       When parentheses are used. the expressions within the parent heses assume highest
priority.
                                                      Function
 3.7       Simple Input Output
                                                                                                              func-
                                                   data    we use    library function .the important of these
 For    inputting and outputting
                                                         gets( ), puts().
 tions    are getch( ). putchar( ), scanf( ), printf( ),
  3.7.1        getchar() function
                                                                                                                         is
  It is used to read            a      (char type) from keyboard. The syntax
                                    single   character
  char variable name = getchar( ;
  For reading an array of character's or a string we can use getchar( ) functio
                                                                       17
               3.7.2      putchar() function
                                                                                  is
               It is used to   display single    character. The          syntax
               putchar(char c);
              #include <stdio.h>
          2 #include <conio.h>
          3 void main ()
          s char alphabet
          6 printf(*Enter-an.alphabet):
            putchar '\n ');
          8 alphabet=getchar ();
          9 putchar (alphabet ) ;
         10
         #include<st dio          .
                                      h>
    2 #include<conio .h>
3 void             main ()
5 int X
6Scanf"%d",&x);
7 X=X * X ;
                                                                        I8
Note that in this list of arguments the variable names are without & symbol unlike inn
the case of scanf() function.                   In the conversion string one can include the message to
                                                                                                displayed   and is
be           displayed. In the above       example       "The square of the number is" is
followed by the value of x.
##include<stdio .h>
2 #include<conio .h>
3 int main ()
                                                                               to stdout up to but
                                                                                                   not   including the
                                 function int   puts()   writes   a   string
             The C    library                                    to the output.
             null   character.   A newline character is appended
             #include <stdio.h>
                              .h>
     2       #include <string
     3 int           main ()
     9puts(strl );
     10 puts ( str2):
         11 return (0);
         12
                                                                               19
   4      Control Statements in C
         Branching Structure
        Looping Structure
   4.1        Branching Structure
   Branching is deciding what actions to take and looping is deciding how many times to
   take a certain action.Decision making structures
                                                    require that the programmer specifies
   one or more conditions to be evaluated or tested by the program, along with a statement
   or   statenments to be executed if the condition is determined to be
                                                                        true, and   optionally,
   other statements to be executed if the condition is determined to be false. Show below is
   the general form of a typical decision
                                          making structure found in most of the programming
   languages.
conditlon
                                           fiscondition|
                                               true
                                                                 fs condition
                                                                   false
                                                  conditional
                                                     code
4.1.1 if Statement
        if a < 20
           printf(auis~less ~than20\n" )
        printfvalue ol -a 1S~ d\n", a );
        return        0;
                                                            20
                                                                            If condition
                                                                              true
                                                          condition
                                                                       If condition
                                                                       IS true
conditon
                                           If condition                          if code
                                           is false
else code
        if( a =          10)
              printf"Valucofauis10\n                              );
       else if( a = 20  1
          printfValueof-auis~20 n ) :
13    else
                                                               21
               PrinttNoneofthe.ValuesisnaLehing\
                           Exactvalue~ofa-is : d\n"
                                                                             ,
                                                                                 )
         printt
17       return        0;
                                                                                                                            enumerated
                                                       must have an integral or
         T h e expression used in a switch statement
                                                          has a single conversion
                                                                                  function to
                       of   class type in which the class
           type, or be    a
.When a brcak statement is reached, the switch terminates, and the flow of control
         Not every case needs to contain a break. lf no break appears, the fow of control
                                         to    subsequent       cases   until    a    break is reached.
              will fall through
         . A switch stateinent can have an optional dletault case, which must appear at the
           end of the switch. The default case can be used for performing a task when none
           of the cases is true. No break is needed in the default case.
# i n c l u d e <stdio.h>
     i n tmain ()
        /   local variable                      definition */
         char        grade = B
         switch( grade)
                                                                        22
                                             expresslon
              case A :
                    printf(t Excellent !\n"                   ):
                    break;
              case        B
              case        C
                    printf( Welldone\n" );
                    break
              case        DD
4
                    printf("You passed \n" ):
                    break;
              case'F
                    printf( Bettertry~again \n
18                  break;
 9
              default
                    printf(Invalid grade \n" );
        printf("Your-grade-is - c \ n , grade )
22
23
        return       U;
24
      while loop
      do while loop
for loop
while( condition )
               statement(s)
                                                                                             The condition
                                               statement or a       block of   statements.
                           be a single
 Here, statement(s) may                                               The loop iterates while
                                                                                                the
                                                             value.
                            and true is any  n o n z e r o
while( condition )
conditional code
condition
                                                     If condition
                                                      is true
                                                           21
            4.2.2       for loop
            A    Or   lo0p     1s a    repetition control structure that            allows you     to efficiently write a   100p
                h e i i t step is executed first, and only once. This step allows you to declare and
                   1itialize any loop control variables. You are not required to put a statement here,
                   as
                        long    as a   semicolon appears.
                2. Next, the condition is evaluated. If it is true, the body of the loop is executed. lf
                   it is false, the body of the loop does not execute and the flow of control jumps to
                  the next statement just after the for loop.
            3. Next, the condition is evaluated. If it is true, the body of the loop is executed. If
                  it is false, the body of the loop does not execute and the fow of control jumps to
                  the next statement just after the 'for loop.
            4. The condition is now evaluated again.                             If it is true, the loop executes and the
                 process repeats itself (body of loop, then increment step, and then again condition).
                 After the condition becomes false, the 'for' loop terminates.
Conditional code
Init
conditlon
                                                                             If condition
                                                                         is true
increment
                                                                                 flowchart
                                                    Figure 8: for loop
                                                            do (
                                                                   conditional code
                                                             }while (condition)
code block
                                         f condition
                                         is true
condition
                                                            If condition
                                                            s false
statement (s);
while (condition)
            while (condition)
                statement (s )
statemeint(s):
                                                             26
      do
statement (s)
do
                 statement (s);
           while ( condition
  9while condition ):
      Find Prime numbers between 2 to 100 using prime number
The break statement terminates the loop (for, while and do..while loop) immediately
when it is encountered. The break statement is used with decision
                                                                                          making statement
such as if...else. The syntax of the statement is
break;
Example of Goto Statement
Enter loop
                                                                   False
                                              testexpression
                                                 of loop
True
                                                                    Yes
                                                  break?
                                                      No
                                                                           Exit Loop
                                              Remaining body
                                                 of loop
 6 int 1
          double     number,      sum    =    0.0:
10 printfEter~a~n%d:" ,i):
11SCantf(%lf,knumber );
12            J    user     enlerS      negalave num ber,              loop    1s   Lermi n aled
 13 i f (num ber <              0.0)
 14
 15 break;
 16
 17S u n + = n u n b e r ; / / sum=                  sun1    + UUnber
 19 printf'Sum=%.21f ,sum):
 20 return            0;
     21
                                                                 odes
                                                             if (condition for break)
break;
break;
Enter loop
                                                                                             False
                                                                       testexpression
                                                                          of loop
True
                                                             Yes
                                                                         continue?
                                                                              No
                                                                                                      EXit Loop
                                                                      Remaining body
                                                                         floop
                                                                                                     numbers
              /Program             to        calculate        sum of marimum of 10
              2// Ne.galive            numbeTs         are    skipp ed Jrom calculalt0
              3include <stdio.h>
              i n t main ()
              6 lnt   i;
                                                 =     0.0:
               double       number,      sum
10 printf(Enteruand:,i):
      11 SCanf(*%1f*,knumber );                                                         is    terminated
                                  enters       negative            number,    l0 0p
     1 2 / 1 J user
     13 i f (umber <0.0)
     14
     15 Continue;
19
          printf("Sium.=%.21r"                  , sum ) :
20        return       0:
21
                                                Statement
                             Continue
      Working of
                                               while (test Expression)
                                                          continue
                                                    }
                                                         Codes
continue;
codes
           The goto statement is used to alter the normal sequence of a C program. The syntax
           of goto statement is
goto label;
         5label:
         6 statements;
         6int
     7 double number,              average, sum=0.0;
          for(i=l; i<=maxlnput: +i)
16
17 JunP:
i         Velape=sun/i - ):
1print               Su11         .2T\n", suln);
                                                                  300
20 printt(Average=-%.2f"|
                                     average );
21 return    0;
22
. T h e use of goto statement may lead to code that is buggy and hard to tollow.
     In the second case the compiler determines the size of an array by calculating the number
     of elements in an array.
                                                         32
     5.2      MultiDimensional Array
     programming language allows programmer                                  to create
     tidimensional arrays.                                                                      arrays of arrays   known   as mul-
float a |2]|6]:
9 Muit diensionói À a y
17              scanf("%f*,&b[i]|i]):
18
19
28
                          if (j==l1)
                              printf(n"):
2"
30
31 return 0;
32
                                              matrices
     Program         to   Multiply Two
     #include <stdio . h>
                                                                       33
        i nt    ain)
           int, n           ,                                   d, k, sum=0;
           int first|10]|10]                                        Second10)|10], multiply |10][I0];
           printtmteTroWs.andcolumnsof.first ~mat riX \n
          scanf"d7d , n, kn):
           printiEnter -theuelements of-first-matrix \n
           for (c       =
                                 0:          c<1;                   c+)
              for (d  = 0; d < n: d++)
                 scanf( "%d", k first |c|d)
15
           pTlnti           EnterrOWSand.columnsofusecond-matrix \n
16
           scanf("7d7d", kp, kqD
1s         if    (n=             p)
19              printt can                        tbe-multiplied -with ~eaclh -other.\n):
20         elIsc
 3
34                      nultiply [c]|d]                                  =    sum;
                      Sum=                        0;
                   printf("\u):|
    7
19 return 0:
          5.3      String
          Strings ale actnally one-dinensi0nal array of clharacters terminated by a uull character.
          Thus a ull-teminated string contains the characters that comprise the string followed
          by a ull.The followiug derlaration and initialization ereate a string consist ing of tl
          word "Hllo". To lod tlhe nll character at the eud of tlhe array, the size of the charaeter
          array coutaining tie stri                                          1s o        I1ore tha    the number of clharactes in the word
Hll
                                                                                                31
    char    greeting 6|=" Hello"
    char
            greeting 16]={ 'I', 'e' , '1','T , 'o, \0
Index
Variable H
                        Address
                                         Ow23451Ox23452    x23453x23454 x2345s 023455
5printf("%s" ,greeting ):
6piuts(8reetig):
    5.3.2     String related fuctions
       strcmp(s1,s2) returns 0 if sl and s2 are the same, less than 0 if sl <s2 and greater
            than 0 if sl>s2
                                                      and    places    it in sl
       strrev(sl)     reverses     the string sl
                                                             35
    6      Function
    6.1     Function Definition
    A function is a group of statements that togetner perform a task.                              Every C progra
    has at least one function, which is main(), and all the mOst trivial programs can defin
    additional functions.A function declaration tells the compiler about a function's name.
    return type, and parameters. A function definition provides the artual body of th
    function.
                                    function
    6.2     Types of C
    There    are   two   types of C functions
          Library Function
          .UserDefined Function
main ()
printf ()
3 Scanf()
strepy ()
5 strcat ()
6strcmp()
    are the examples of Library functions available in C.
    Function Prototype(Declaration)
                                                         should be declared before    they   are   used. These type
    Every function in C programming
    of declaration are also called function prototype.                      Function prototype gives compiler
    information about function name, type of arguments to be passed and return type.
                                                         parameter   list   )
return_type              function-name
2          body    of    the    function
Function Name This is tle actual naue of the lunction. Tlhe lunction ane ad
                                                                36
                    raraneters A parameter is like a placeholder. When a function is invoked, YOu
                      pass     a   value to the                    This value is      referred to as actual parameter
                      O   argunent.
                                                      paraneter.
                                                 The parameter list refers to the      type, order, and number or                e
                    nCton               Body The fhunction body contains a collection of statements that deline
                      what the function does.
                           X+=          10:
                           printf                Inside.function -x_=_d-after ~adding-10.\n"                      x)
     6
     7 int          main ( )
                           int      a=10;
    10
                          printf("a=_Tdubefore function .\n, a):
                          call-by-value (a);
    12
                           printf(a=dlafter~function.\n", a);
    13
                          return            0;
14
                                                                                                               iformation at
             In the main()         we  integer that has the value of 10. We print some
                                        create     a
                                                                    37
                                                                                                                                b):
                                                                                                                          ,
unetiOn.|
               man int       b          0:
     inl
                                                              b e t o r e .
                                                                                                                              b);
                      Call.hv-relerence(ab)
                      P r n t t
                                    ..after.Iuuetio.I
                                        h.
                                                      ..
                                        b.
                      Tntl
r e t u r n
                                                                                                                 10.
                                                                                                                 10.
                                                                                                                        The
                                                                                                                                    function         call. by.reference       is
                                                                                                         value
                                                                                                                                    function
                                                                                             the
                                                                         has                                         to this
                                                      b
                                                              that                                        passed                    there is 10 added to the vahe
                                        integer
                                                                variable
                                                                                                 b is           done
                                                                                                                        and
                      with   an
                                                                                                                                                     the
                                                                                                                                                     the   valie is 20.
     We     start
                             address
                                                of   the
                                                                 print
                                                                                     statement
                                                                                                                     Of
                                                                                                                              the
                                                                                                                                    function
                                                                                                                                                                          Then
                 and the
                                                                                                               end
                                                     alter                                               the                     an see the value is changed
     alled                   before
                                             a
                                             anned
                                                               T ' h e r e f o r e
                                                                                                  at
                                                                                                               as    you
                                                                                                                              can                                           (as
                                                byy.
                    some
     there     is                                                                                b
                                                                                                       and
                              pointed                            v   a   r   i   a   b   l   e
           the
                 memory                               the
                                             print
     t                 we   ag
     in main(0
     expected) to 20.                                                                                                f u m c t i o n
                                                                                                           to    a
                                                                   argument
                                                                                                                                                           funet
                                                                                                                                                              ction
                                                          an                                                                                    to   the
                                                 as                                                                           a r g u m e n t
                                 array                                                                           as an
                 Passing                                                                 be passcd
     O.6
                                                                     can
                                              array
                                    floats an
                     int and
     LIkewise
                                                     all.int
                                                                                     size
                                                                                                     )
                                        float
         float
                    largest         (
                                                              1.6,3.4,6.8
     main ()1                    (4]={2.5,
                                                          -
3
          float      value
                                         largest
                                                              (value                 , 4 ));
                       Y\n°,
          printf
                                                                                     s1ze)t
                                    (float           al|, int
         float       Targest
 6
                       int i
                       float            max;
                       max-a | 0 ;
                                                                i++):
                                    =l:i<size;
                       for(i                 if(maxca i])
11
                                             max=a| i;
                                             return(max)
                                        Class in C
         6.9        Storage
         6.9.1       auto
                                                            class for all local variables.
                               class is the default storage
         The   auto    storage
               int    mount;
               auto     it       month;
         6.9.2       register
                              class is used to define local variables that should be stored
         The register storage                                                               the
         register instead of RAMI. This means that the variable has a maximum size eq12a1 t
                                                                                                                                                                            it (a
         register size (usually one word) and can't have the unary '&' operator applie
         it does not have a memory location).
      hardware        and
                             implementation restrictions.
      6.9.3     Static
      ne static storage class instructs the compiler to keepa local variable in existence aurE
     the nie-time of the program instead of creating and destroying it each time it comes
      and goes out of scope. Therefore, making local variables static allows them to mainti
     es                 between function calls. The static modifier may also be applied to globa
                                                                                                           to the nie
      varldles.       When this is     done,     it that variable's scope to be restricted
                                                      causes
                                                                                                            member,
     WC           t    1s   declared.In C programming, when static is used on a class data
      causes only one copy of that member to be shared by all the objects of its class
     #include <stdio.h>
 2    void func        (void );
 3 static        int        cont =    ;     /*        global    rariable     +/
      main()
         while (count--)
                func ();
return 0;
10       u n clion definition */
11void func( void) {
12
          static        int    i =   5:    /*    local      static    variable      */
         1++
         printf"iuis%d.and-count -is d                            \n", i , count)
14
15
     6.9.4      extern
                                                        a reference of a global
                                                                                  variable that is visible
     The extern storage     class  is  used   to   give
                                        When               'extern',  the variable cannot be initialized
     to ALL the progran       files.             you   use
     6.10       Recursion
                                              recursive function          technique and this               is known   as
     A function that calls itself is known as
                                               is more elegant and requires few variables
                                                                                          which
     recursion in C programming.Recursion
     make program clean. Recursio1n can be used to replace complex nesting code by dividing
                                         of its sub-type.In  other hand, it is hard to think the
     the problem   into  same  problem
                          function. It is also diffhcult to debug the
                                                                      code containing recursion.
     logic of a recursive
1#include<stdio .h>
2 int factorial (int n);
3 int nain ()
                int    n
                Pnt                 Enter..an-positiveinteger                            )
                scanf( d",kn):
                int("Factorial.ofYd=%ld" , , a c t o r ial(n)):
                return          0:
13              i f(n'= 1)
4
                  retur              n*      fac torial (n-1);
                                                                            Recursion
          6.10.2       Fibonacci Series                             Using
      #include<stdio.h>
          int     Fibonacci (int ):
31ai )
                int    n,       i    =       0.       c:
                scanf("%d ,kn):
                printf               Fibonacci~series \n);
                Ior         C        =1               C<= n ; C++)
12
     13           return            0;
     14
                  if   n=
                       return                0:
                  clse      if           n        =        1    )
      0
                       retur                 1:
     21           else
      2              return                       Fibonacci (n-1) +             Fibonacci (n-2)        ):
      23
                                                                                    40
            Preprocessor              Syntax                     Description
            Macro                     # define                   macro     defines          con-
                                                                 data types
            Header          Iiclusion#include<file-name>|        sourcecode of the file
            Files                                                            included
                                                                 filename is
                                                                 in the program at the
                                                                 specified place
                                                                                             are
            Conditional Conpi-        #ifedt,           #en-set of commands
                                                                 included or excluded
            lation                    dif, #if,#clse
                                                                 in     source     program
                                                                 before      compilation
                                                                 with    respect       to    tlhe
                                                                 condition
                                                                  #undef          is        used
            Other directives          #ndef, #pragma             to     undefine       a     de-
                                                                           macro            vari-
                                                                 fined
                                                                                               1s
                                                                 able.#pragina
                                                                  used to call a func-
                                                                 tion   before               and
                                                                 after fnction             in C
                                                                  program.
                                                      sample.c
                                                                                                                              /macro,
                Sourcecode                                                                       replaces
                                                                                                                   #define
                                                                       Preprocessor
                                                                                                      conditional
                                                                                                                           compilation
                                                                            #include (files),                               their
                          Preprocessor
                                                                                       #ifdef,
                                                                                                        #ifndef       by                          file
                                                                            codes like                                     codes    in   source
                                                                                             values     &    source
Respective
                                                      sample.i
                Expanded source code                                                                                        source       code
                                                                                                         expanded
                                                                       -    Compiler compiles
                                                                                        s o u r c e code
Compiler to assembly
                                                      sample.s
                Assembly source codej                                                                 that
                                                                                                             converts       assembly
                                                                                       program
                                                                       It is a         code to        object
                                                                                                                   code.
                          ASsembler                                         SOurce
                                                      sample.o
                Object code                                                                              that
                                                                                                             object code
                                                                                                                    converts
                 Execution
                                                                                         Compilation
                                                Figure 18: C
                                                                           program
7          Pointer                                                                                                                            address
                                                                                                 another variable,               i.e., direct
                                                            the address of                                                                     before
                          variable           whose value is                                                                 declare a pointer
                                                                                                               must
A pointer is          a
                                                             variable        or
                                                                                  constant.      you                                               declaration
                           location.           Like any                                                                             variable
of the     memory                                                                            form of           a    pointer
                                                                       The general
                                        variable address.
                to store any
using it
 S
                Using Pointers
     7.1
     #include <stdio . h>
i n t main ()
                                                 /*    actual              var7able          declaralron                      *
                      Var=         20;
           int
                                                                                                                                  */
           int        * 1P                       /*    p01nler              v araable decl(aratio
                                              store     address              of    var       n         pointer              tartable */
           ID=&Val;                     /*
                                                                                  12
                printiAddress of_varvariable: -%x \n, var
                /*     001aress                       sloTed in      pointer         variable */
    10          Printi Address.ustored -in ip-variable: %x \n                                                      ip
                /acces$ the value using the poinler
                prntt
                                                       */
    12
    13
                       Valueofuip~variable : Id \n", *ip )
    14          return 0;
    15
               int         var
                                        |3        =
                                                        {10, 100, 200}
               int         i,           *ptr;
                            i                0: i < 3: i++){
               for     (            =
                                                                                                     i, ptr ):
                                              Addressof-var|%d)-=-%x\n,
                      printf("                                                                  I,    p t r );
                      printf("Value-ol-var|%d]                             =al\
2                                                                      location        */
                      /*    moUe                 lo     the   11ext
                      ptr++
15
         retur               0;
17
Decrenenting a Pointer
                                                                                            ter variable c
                                                                                                         can           decremon
                                                                                                           a n also be decremented wliich
     7.3.2                                                                                      variaDie
                                                                             the poiiter
                             increment                  of pointer
     Likewise          the
     shown as
 include <st dio . h>
              nmain      ()
2 int
 3                                                                100,       200:
                        var|3
                                            =
                                                  {10,
             int
             int        i,        *plr                                                  1.n    O1n
                                                                                                      teT    */
                                                                       a   ddresS
                                    have            array
                   e         us
           /*
           ptr         = kvar |2]
                                                                       i--)       1          ptr ):         i,
                i      2; i >= 0;
           for printf("Address-ofuvar
                              =
                                     [%d)=_%x \n"
                                                                                       i, * ptr );
                                                                            [%d]=%d\n,
                       intf("Value-of-var
                                                                                      locatro    n    */
                         noUe           to        the        previous
                   /*
                   ptr-
return 0;
15
                  Definition Pointer
                                     to                                     Arrays
     7.4                                                                                                          of the array.   Therefore, in the
                                                                                                      element
                                                                                  to the first
     An array           name       is   à       const ant pointer
     declaration
 double balance | 50|;
                                                       address of  the first element of tlie arrar
                                                is the
     balance is a pointer to
                             &balance|0|, which                      as the address
                                                                                     of the first
                                                         assigns  p
                                    progran1 fragnent
     balance. Thus, the following
     clement of balance.
 Idouble               *p:
 2 double balance | 10]
         =balance : //p=sbalance
                                 [0;
 3p
                                                                                                          v e r s a . Therefore, *(balance
                                                    names as
                                                                            constant   pointers. and vice
     It is   legal      to   use    array
                                                                                                                     you store the address
                                                                                   the data at balancel4|.Once
     +4)      is   a   legitimate way                    of accessing                                                 using *p. *(p+1), (p2)
                                                                           can   access     the array elements
     of the first element
                          in                        'p,          you
a n d so 0n.
 5         double
           double *p
             int
           P=balance; //p=balance (0
13
     e e une
                   printt\nsnn=%d\n ,sm );
                   base
     e     nt
                            address    of array
                                       x is
            poiited by the
                            pointer
                                            assigned to the pointer p. sum adds e he value
     ncreases the value              p using (*p)
                                                   ndirection                              of
                         of the                                operator and the inerene
     he address                 variable i by i and the
     the sum is pointed by p which is an integer and inerement p++ increase tn vvalue of
                caleulated and            printed.
                                                         infact increased   2                            by
                                                                                                              bytes.Uitimae
     7.5
                 Returning Multiple Values from
     Return
                                                                                a
                                                                                     function
     from
                 statement       can   return
                                    single value. however
                                                 a
             mnctions
                    using arguments that we                multiple values can be returnea
     1Sed to send out                          pass to a funetion.The
                      information are called ontput                     arguments that are
                      through arguments is achicvedparameters.
     back information                                           The mechanism of sending
     operator (&) and indirection operator (*). using what arc known as the address
 void
 2 main (O{
                mathoperation (int              x,int y,int               *s
                                                                               , int *d);
                    int x=20.y=20,s ,d:
                    mathoperation (x ,¥,&s,&d)
                   printf(" sum-7d\n.diff=d" ,s ,d);
                    }
                    void     mathoperation (int a, int                          b, int   *sum,     int
                                    *Sum=a+b;                                                             diff){
                                    * diff=a-b:
     1main(){
     2      char    *nane:
     3      int    lengt.h:
     4     char    *cptr=name;
 5         name="DELHI"
11length=cptr-name;
12         printf°\nm-Length of-String-is = d \ n                             name)
13
 ** ptr;
         #include<st dio .h>
         int     main ()
         printf("%d" , ** ptr2ptr )
         return ( 0);
10
         The exact size of array is unknown untill the compile time,i.e., time when a compier
         compiles code written in a programming language into a executable form. The size of
         array you have declared initially can be sometimes insufficient and sometimes more than
         required. Dynamic memory allocation allows a program to obtain more memory spaec,
         while running or to release space when no space is reqnired.
7.8.1 Malloc
     The name malloc stands for "memory allocation". The function malloc() reserves a
     block of memory of specified size and return a pointer of type void which can be casted
     into pointer of any form
                                                                    46
                 Fnnction         Use of Function
                 malloc           OcateS requcsted size of bytes and returis
nere, ptr 1s pointer of cast-type. The malloc() function returns a pointer to an aea of
memory with size of byte size. IfIt                                          allocation     fails and      retul
                        S17e.        the space
                                    the            insufficient,
                                          space is insutficient,             &id
NULL pointer        yc
 ptr=(int*) malloc (100»sizcof              (int   )):
      is statemeut       will allocate either 200 or 400 according to size of int                 2   or
 The nanie calloc stands for "contiguous allocation". The only difference betweeu
 C u i d calloc() is that, malloc() allocates single block of memory whereas cailoc
 allocates nultiple blocks of meniory each of sane size and sets all bytes to zerd.
  7.8.3        free
                                                                                       does not   get   return     on
      Dynamically       allocated memory with either      calloc()   or   malloc()
      its own. The programmer must use free() explicitly to release space.
      free (ptr);
             statement canse the space in memory          pointer by ptr     to be deallocatcd.
      This
      Find sum of n elements entered using malloc
 #include <stdio.l>
 2 #include <stdlib.h>
 3 int main ()1
       nt n,l ,* ptr , sum=0:
             p r i n t "Enter~numberof.elements:"
             scanf("Yd" ,&n );
                                                               //1malloc      allocation
             ptr=(it *) malloc (*sizeof(int));
             if(ptr=NULL)
                  printt("Error! nemory-not-allocated. )
                   Cxit (0):
printlEnterelemenisuolarray:
                       =);i<u:+++1)
 14          for ( i
16
                    Scanf(%a" , ptr+i)
18
                    Sum+=*(ptr+i):
I9
              printf (" Sum-%d" ,sum);
20
2
              free(ptr)
              return 0
22
13
     14       rintfEnteruelements-ofuarray:):
              for(i =0;i<n:++i)
     15
               {
                     scanf(7d" , ptr+i);
         18
                     sumt=*(ptr+i ):
         19
               printf( Sum=%d" ,sum);
         20
               free (ptr);
         21    return 0:
          2
                                                           A8
8     Structure and Unions
A structure is         a
                           collection of logically related data                                                               ler    a
                                                                                  items
Singie name, callecd structuretag The data itens enclosed within a structure are known
                                                                                                grouped togeie
as   members. The members                      be of
                                         can           same or   different data types.
struct structure_name
                data.type memberl
                datatype member2;
                data-type member3:
    7el, e2
                                                                                                                              witl
                                                                     are associated
                       a structure do not occupy memory until they
     Tne
         members of
     SUructure variable. Above examples shows the structure
                                                            variable el and e2 of structure
employee.
     struct-variable .member
     2 struct employee el
      3 el.emp-id;
      4 el.name
      5 el.salary
                                                                                          , value-n};
        2 struct       employee
                           int cmp-id
                           char name |25:
                           int age
                           float salary;
         9
                                                   ,25,80000.0}
        10    struct       employee el={555,"Sudip
                                                                                                are initialised   to 555,   "Sudip",25,80000.0
                                        variable el empd,name,age,salary
              The members of the
                    Array of Structure
            8.3                                                       structure
                                                                                  can   be initialised.
                                                                 of
                                               arrays
                                    data types
           LIkewise    the array of
float salary
         9 int    main ()
     10
                       struct employ ee el50:
     12
                       int    i n;
                       for ( i =0; i <50:i++)
                                                                       -and-Salary
                                                       -name,   -age                                age,&e [i ].   salar
                       p r i n t f E n t e r - i d ,
                                                                          elil.1name,vel1|.
                                        fi ].                   emp_id,
     b                 scanf(%%s%d%f",&e
                                        <50: i++){
    18                for (   i    =0;iprintfDataon-Employec_%d"                    ,i +1):
                                      printf(ID:%d,elij. emp_id );
    20
                                                      ,e[ ij.name);
                                          printf"Name:%s"
getch ( )
struct date{(
                     int     day , month , year;
3
4 Struct            employee{
                     int emp-id
                     char name |25]:
                     struct         date    dob;
struct employee{
                    int ep-id;
                    char name | 2 55:
                    struct         datet
                                    int day;
                                    int month
                                    int year;
                    } dob
                                                                 50
          ##includecstdlio.h>
          #include<conio.h>
       3struct employee
                    int   en p-id:
                    char ame |25:
                    int age
                    float salary
                    struct        date
     10
                                   int day;
                                   int month:
  12
                                   int   year;
  13
                    dob:
  14
                   getch (0:
36
pstr11etvar=kvaribale :
                                          stricture variable c a n be arcessed    and   proceSsed   as
     Likewise the pointer to the
                             ield-naune=variable:
I(*Struct-uame ).
struct-uamie->ield-ianile=va'iable
#include<stdio.h>
2 struct emplovee
                  int    enup-id
                      char ane | 25:
                      int age
                      float    salary:
8
                     getch ():
                    return      1;
19
20
                              Structure
     8.6     Self Referential
                                                                               structure v a r i a b l e
                                                                                                           ot the   same   type.
                                                             point   to   a
                              have members which
     A   structure can                                                       widely used in dy-
                                                              referential structure.
                                                                                                It is
                    structure a r e called
                                            self
     These types of
                                                             is the syntax of the self referent ial
                structure like linklist,
                                         trees etc.Following
     namic data
     structure
struct struct-name
21 data-type memberl;
                               struct-name *          next
                    struct
6
                                                                                        structure of       its   own  type. The
                                            of a pointer      variable to       point
     The   next     refers to the    name
                                                                                                        another     structure of
                                                       a member that                     points to
                              struct.name will contain
     structure      of type
     type struct_name.
     8.7     Union
                                                                     differences.Declaration               of the union is the
                     almost like     structures   with subtle
     Union    are
                                                                struct        the keyword union is used.
     s a m e as   structure.   Instead of the keyword
                                              Union
     8.8     Difference between Structure and
                                                                2
           Structure
           INeyword struct defiues                               Union
                                   structure                    ReyWord union defines Unio
                                                                    KeywOTu
           struct 1ystructurel
                                                                Sttuct      myun1on{
                               int id;
                                                                                int id
                               char name |20                                    char name ( 20;
                               float age                                        float age
          sl
                                                                    ul
                       a structure all member gets F o r a                nion     compiler allocates          he
          alloated                                                                                of all
                        members have address memory for
         that increase as
                                                                                  the   largest            e
                           the declarators are ber.
         read left to
         the
                       right.The total size of
             struct ure is the sum of all the
         members.
          WIthin structure all members gets| While retrieviing data r o n a
                       a
  9      File Handling in C
                                                                                                         stored.
  A Ie   represents        a   sequence of   bytes   on   the disk where    a   group of related data is
  File is created for permanent storage of data. It is a ready made structure.In C language
  we use a structure pointer of file type to declare a file
  FILE fp
  The fopen() function is used to create a new file or to open an existing ile.
1fp =     FILE *fopen (const char *filename,                             const char *mode )
2 fp=fopen (" text.txt","w");
3//0pens a file text. t r t in                   writing mode
 Here filename is the name of the file to be opened and mode specifies the purpose of
 opening the file. *fp is the FILE pointer (FILE *fp), which will hold the reference to
 the opened(or created) file.
                                                                                                    File xPIY >Nu
 9.2     Closing a File                                                                            Ptrz o p n t
 The fclose() function is used to close an already opened file.
1 int fclose ( FILE *fp );
 Here felose() lnction closes thc file and returns zero on success. or EOF il tlhere is au
 cror iu closing the tile. This EOF is a coust ant delied in the header file stdio.l1.
                                                            3
                                              7 p t s                           st
                            mode
                                            description
                                            opens a text file in rcading node
                                             opens or crcate a text nle in writing mode
6char ch;
          fp    = fopen ( o n e . txt",           w):
          printf( Enterdala" ):
 9        while ( (ch  getchar ())
                                 =                  !=   EOF) {
10
                putc (ch , fp );
11
12         fclose ( fp );
13         fp = fopen("oue. t x t " , r " ) ;
14         while(       (ch =        gete ()) !     EOF)
15
                printf("%¢" ,ch);
16         Iclose ( Ip );
17
9.4 Reading and Writing From a file using fprintf () and fscanf ()
     1#include<st dio.h>
     2 #include<couio .h>
     3 Struct         emp
     4
9 void main ()
                struct emp e
 2              FILE *p,*q
                p fopen ("one. txt,"a):
                =     fopen (one. t x t , r ) ;
 15
                printf(Enter Name and .Age);
                scanf("%s %d" ,e.name, ce. age ):
                fprintf (p, "%s _ l . e.anne,               e. age );
                fclose (p):
 19             do
                20
21
               22
                                        fscanf (q,"%s YA"
                                                       e.name, e.age)
                                   printt("/%s d", c .name,
                                                                       ,
               23
                                                            .age)
               24
                               while( !feof (q) );
               25
                               getch ();
               26
                #include<stdio .h>
               2 struct                 Student
                        int             rol1:
                        char name [25];
                        float               marks;
           7
           s    void           main          ()
           9
       0                       FILE fp
                               char ch
                               struct Student                   Stu;
                               fp       =    fopen (" Student. dat" , "w" ):
      14                       do
                                            printf (" \nEnter-Roll.:" )
     16
                                            scanf("%d" ,& Stu. roll):
  17
                                            printf ( EnteruName:                )
  18
                                            scanf(%s" ,Stu . name);
 19
                                        printf Enter Marks:");
 20
                                        scanf("%f" ,&Stu . marks);
 21
                                        fwrite(&Stu , sizeof (Stu) ,1,fp)
 22
                                        printf( nDo-you-wanttouaddanother ~data-(y/n) :");
 23                                     ch        =   get.che ( ):
 24
                               while (ch='y' | | ch= Y'):
25                              printf\nData-writt.en ~successfully ... "):
                                 fclose ( fp );
27
         #include<stdio.h>
2 struct Student
                    int    rolT
                    char name |25:
                    float narks;
             }:
 8           Void main       (){
                     FILEfpP:
10                   char ch
                     struct        Student   Stu;
12
                     fp     =fopen (* Student.dat,"r"):
T3                   i f(fp == NULL)
14
18
                              printf("\n\tRoll\tName\tMarks\n" );
 9
                              while (fread (&Stu , sizcof(Stu) ,1,fp)>0)
                                                                               Stu.   maTRS )
20
                              Printt(n\t%«d\ t%s \ \%f" , Stu. roll ,Stu.nane,
21
     2
                              fclose (fp);
              Write a program to write details of student to a file and read the same file a d display
the records.
     21                     rewind(Ip );
                             for (i =0;i <2; i ++)}
         23                              fread(&s [i],sizeof (s),1, fp );
     24                                  printf |1Nane: %s \tuAge: d \t Departnent: %s
     25                                  si.name,s | i|.age , sij.dept );
         2D
         2                   fclose (fp );
     2                       return 0;
         2
                          Write       a
                                              progrann    to
                                                               input       data of 100
                         employees living                in                              enmployee   to
                                                                                                     to   a   file and           records of thiose
                                                                                                                         display recor
                                                               "Kathmandu"
                    #include<stdio .h>
                    #include<string .h>
                    3    struct               employeet
            13          int
                        main (){
            14
                    struct cmplovce
           15           int     i:
                                                          c
                                                               |100]:
           16 FILE               fp;
           17
              fp=fopen ( employee. txt", "w");
           18for (int i= 0; <100;
           19
                                          ++i)
           20
                                          printi   nnter -nanne ):
                                          scanf     , i]. name)
                                          printf|nEnter~address"
                                          scanf(%s" ,c|il. address ):
                                                                      ):
                                          printf              nEnter.telephone" )
                                      scanf(%ld" ,&e[ij.telephone ):
      2                               printf\nEnter~salary);
                                     scanf ("%f" ,ke[ i]. salary );
                                      printf    nEnter~date -of.birt h -in dd-mn=yyyy" )
      29
                                     scanf( d-d-7d" ,ke [i].    db.dd,&e [i].db .mn&e|ij.db. YY)
      31                             fwrite(&e|il,sizeof(e) ,1,fp);
      32    for               (int        i    =
                                                   0;    i <        100:    ++i)
      33
      4
                                     if (strcmp ("Kathmandu
                                     {                                              ,eli].address)==0)
     3b
 37                                                     printf(n%s" ,elij.name);
 38
                                                        printfn%s" ,e[ij. address );
                                                        printf(\n%ld" ,e[ij.telephone):
 40
                                                        printf(u%f" ,eli]. salary );
                                                        printf(\n'%d-al-%d" ,e[i]. db.dd,e[i].db.mm, e [ i ]. db.
12
                                                                                                                  yy):
43        return                0;
44
                           FILE fp:
                           struct          book       b:
                           Tp=fopen ("library.dat." ,"r"):
3
21
22                         return          0;
23
             Write a program to create a 'student.txt" file to store the above records for 100 Stue
             Also display the records of st udents who are not from Pokhara.
          #include <stdio.h>
    2 #include <string.h>
    3 struct            student
    4
                           int roll
                           char name |20|
                           char address |20;
                            char faculty (20:
                            struct          dob
    14           int main ()
     5
                            FILE fp;
                            int       i;
                            struct studcnt s [100)
                            fp=fopen (" student . txt" , "w* );
                                for   (int        i    =    0:    i <100; +i)
     21
21
     22
                                                printf( EnteruRoll No. \n" ):
     23
                                                scanf("Ya ,&s|i]. roll);
        24                                      printi(nEnter~name" );
                                                scanf'"%s" ,s|ij.name);
         20                                     printf    nEnter-address" )              :
     2                                          scauf(%s,s|i . address );
                                                printf     nEnter-Facult y" ):
                                                scanf("%s" ,s[i. [aculiy );
                                                printf (" \nEnter~dale~of.birth-in -format ddmm-yyyy" )
                                                scanf("Zd-Zd-%a" ,ks [ij.db.dd,&s |ij.db.mk s[i.db.vy );
                                                fwrite(&cs | i , sizeof(s),1,fp);
             3
                                for    (int           i =    0:     i <   100;   ++i)
if(strcnp("Pokhara",siaddress)!=0)
43
44
45
        fclose (fp);
46
        return   0;
47
prin tF C   FZLE
                   Tta,
  FZLE *f2
   =    fa0en      c   tie na-   ode"))
                Contributed By