SlideShare a Scribd company logo
1 of 65
Download to read offline
Programming in ‘C’


                                   Programming in C
Introduction
       C is a programming language. It was developed by Dennis Ritchie at AT&T bell
laboratories in the early 1970’s. C was an offspring of the Basic Combined Programming
Language (BCPL) called B language. C language was designed from B language by adding
some modifications to the B language. But C language compilers were not readily available
for commercial use out side of the bell laboratories. So many programmers preferred C to
older languages like FORTRAN or PL/I of the newer ones like PASCAL and APL.
       Why c seems so popular is because it is reliable, simple, easy to use and easy to learn.
First time C language compilers are available for UNIX operating system. The first C
programming text is written by Brian Kernighan and Dennis Ritchie but this book not
provides complete information about C.

       In 1983’s American National Standards Institute (ANSI) is the organization forms a
committee for development of C language. ANSI C committee releases standardized
definition of C in 1990. International Standard Organization (ISO) is also involved soon for
development of C, because most of the world uses c language.
       C is a general purpose, structured programming language. C combines elements of
high level language with functionalism of assembly level languages (low level languages) so
we say C language is a middle language.

Features of C language:
  Programs written in ‘C’ are efficient and fast. This is due to its variety of data types and
     power full operators.
  There are only 32 keywords and its strength lies in its built-in-functions.
  Several standard functions are available witch can be used for developing programs.
  C language is well suited for structured programming, thus requiring the user to think of
     problem in terms of `functions’ of ` modules’. A proper collection of these modules of
     function would make a complete program. This modular structure makes program
     debugging, testing and maintenance easier.
  A c program is basically collection of functions that are supported by the C library.
     With the availability of a large numbers of functions, the programming task becomes
     simple.



                                              1
Programming in ‘C’


  C programs are highly portable. Portable means a C program written in one
     environment(O S) can run or executed in another environment with less or with out
     modifications.
  C language is also called middle level language. Because it has both features of high
     level as well as low level language.
  C is applied in system programming like operating systems, assemblers, language
     compilers, text editors and network devices.
  Using c we can solve scientific, business, mathematical, research applications.
  C language has an important facility called extendibility. It means you can write your
     own file and include in other programs.



 C fundamentals:
 Programming:
      Programming is a process to solve a particular problem by using the computer. When
 ever we need to computerize a particular, we have to solve those problems and write these
 solutions in the computer understandable code with the help of programming languages.
      Program: A program is a group of instructions which is used to perform particular
      task. The task’s like big number out of two numbers, billing process of a hotels or
      etc…

      Instruction: It is command given to the computer to perform any operation. These
      instructions may be addition, subtraction, relation between two numbers etc…

      Algorithm: A step by step procedure use to perform any task is called algorithm. Step
      by step represent of a program in general format is called algorithm.

      Flow chart: A pictorial representation of an algorithm is called flow chart. It can also
      show the flow of the program. Here we can use several symbols for several works in a
      program.

      These instructions and programs can be written in different languages like C, C++,
 java etc… these languages are called program languages.




                                               2
Programming in ‘C’


 Example of an algorithm:
  To find a number is an even or odd.
 Step1. Start.
 Step2. Take a number ‘N’.
 Step3. Divide the number by 2 => N/2.
 Step4. If the reminder is ‘0’ then goto Step5 other wise goto Step6.
 Step5. Print the number is even. goto Step7.
 Step6. Print the number is odd.
 Step7. Stop.



 High level languages:
       Initially (olden days) the computer programs were written in machine level languages
 like binary language. Write a program in binary language and learning binary language is
 very difficult. Later assembly languages were developed, with which a programmer can
 work with the machine slightly higher level.

       Assembly language: It is one of the programming languages. This is an advanced
       programming language than binary language. Write a program in assembly language
       is nothing; arrange the instructions in a sequence order to complete the task. In this
       language we can write instructions instead of sequence of binary numbers in binary
       language. Here instructions are represented in the form of symbolic names like
       ‘add’,’sub’, etc….

       Assembler: An assembler is used to convert the assembly language program into
       binary language or specified machine instructions.

       By using assembly languages we can write different programs for different machines.
A program write for one machine can not be run on another machine, so these languages are
called machine dependent languages.

       Later these assembly languages are replaced by high level languages. The first high
level language is FORTRAN (FORmula TRANsulator). One FORTRAN instruction or
statement can be executed in different machines unlike assembly language instruction. Then
high level languages ate called machine independent languages.




                                                3
Programming in ‘C’


Basic structure of a C-program:
Documentation section
Linking section
Definition section
Global value declaration
main()
{
    Local variable declaration part
    Executable statements
}
Sub program section
function1()
{
    Local variable declaration part
    Executable statements
}
.
.
function2()
  {
    Local variable declaration part
    Executable statements
}……….

Documentation Section: The documentation section consists of a set of comments. Here we
mention the name of the program and also write the comments for our program. The
comment text can be bounded with astricks (*) and enclose with in back slash (/). By using
these characters we can write comments for specified statements in our program.
       /* The program for addition of two numbers */
Link Section: The link section provides instructions to the compiler to link function from the
C-language library. In this section, we can write which header files are use in our program.
       #include<stdio.h>
Definition Section: The definition section defines all symbolic constants. We can use these
constants are use many times in our program. Which value is define in the definition section,
we can not modify or redefine those values any where in the program.
       #difine pi 3.14




                                               4
Programming in ‘C’


Global Declaration Section: There are some variables that are used in more than one
function. Such variable are called global variables and declared in the global declaration
section that is outside of all the function.
I       int a,b;
Main function section: Every C program must have one main() function. This section
contains two parts, declaration part and execution part. The declaration part declares all the
variables used in the executable part. There is at least one statement in the executable part.
These two parts must appear between the opening and the closing braces. The program
execution begins at the opening brace and ends at the closing brace. All statements in the
declaration and executable parts end with a semicolon.
        main()
Subprogram Section: The subprogram section contains all the user-defined functions that
are called by the main function. User defined function are generally declare, after, end of the
main function.
A Function is a subroutine that may include one or more statements designed to perform a
specific task


Example program for structure of C-program:

/* Example program */ /* Documentation section */
#include<stdio.h>          /* Linking section*/
#define a 10               /* Definition section */
int b;                    /* Global variable declaration */
main()                    /* Main function */
{
  int c;
  b=10;
  c=a+b;
  printf(“Sum : %d”,c);
  sub(b);
}
void sub(int y)    /* (Sub program or function) */
{
  int z;           / * Local variable declaration for function */
  z=a-y;
  printf(“Subt : %d”,z);
}




                                               5
Programming in ‘C’


Compiling program:
        Compiling of c- program is nothing, to generate binary code file for our program to
execute the program, with the help of compiler.
        Compiler: The compiler is a software program, used to convert the program into
        machine understandable code (binary code). The compiler analyzes a program, and
        then translates it into a form that is suitable to the running computer.
        The steps involved to create a program in C-language are entering program,
compiling program and running program. The program is typed in the computer with the help
of editor.
        Editor: Editors provide space to write our program in computer. We can also open
        the existed programs in the computer. The text editors are usually used to write C-
        programs in to file.
        Source program: The program that is entered into the file is known as the source
        program.



                                             Start


                                             Editor                         Source
                                                                           program
                                                                           Name.C
                                           Compiler

                            Yes              Errors?
                                                                           Object
                                                                          program
                                                 No                       Name.obj

                                            Linker
                      Library
                     and other
                      obj files                                          Exicutable
                                                                           code
                                                                         Name.exe
                                           Execute


                                  No         Result
                                              ok?

                                                 Yes

                                             Start


                                                 6
Programming in ‘C’


       We have to follow several steps to write, compile and a program in C-programming
language. They are:
  Open the C-programming language editor.
  Write your program or open an existing program in the system.
  When you create a new program, you have to save the program with a specific name.
     We have to follow the naming conventions (rules) to give name for C-program.
  Give the file name with the extension ‘.C’. This extension represents a file as a C-
     Program file.
  After saving the program, compile the program. The compilation process depends on
     the editor or running machines operating system.
  For example, if we want to run our program in dos operating system, we have to follow
     several steps to compile the program.
           o Go to compile menu in editor.
           o Then chose ‘compile to obj’ command or press ALT+F9 key combination
               from the key board.
           o The compiler will compile the program
  The compiler will give the syntax errors in our program. If we have any errors or
     warnings we have to rectify the errors, then open our source program, correct the errors
     then do the compile process again.
  When ever we have an error free program then the compiler can create a .OBJ(object)
     file for machine. It is also called binary code file.
  After creating the .OBJ file then run the program, go to run menu and choose run
     command or press CTRL+F9 key combination from the keyboard.
  When ever run a program the linker links the .OBJ file and library files then create
     .EXE (executable) file, execute the program by using this .EXE file.
 Linker: It also a software program. By using this compiler links the OBJ file and library
 files the produce executable file this process is called building.
  When ever execute our program, the steps in the program is executed sequentially this
     process is called top down approach. If our program get any data from the user is called
     input, then process the input and displays result on the output screen. If the output is




                                                7
Programming in ‘C’


     correct then completed our task other wise open the program change the logic according
     to our requirement.



Integrated development environment (IDE):
       The process of editing, compiling, running and debugging program is often managed
by a single integrated application is known as Integrated Development Environment (IDE).
The IDE’s are differing from form one operating system to n other. Some windows based
IDE’s are Turbo ‘C’, Turbo C++, Microsoft Visual Basics, Microsoft .NET, etc….
       Debugging: In the program does not produce desired results, it is necessary to go
       back and reanalyze the programs logic this process is called debugging. By using this
       process we can remove bugs (problems) in the program.



Language interpreters:
       Interpreters are another type used for analyzing and executing programs developed in
high-level languages. Interpreters are analyzed and execution of statements in a program is
same time. The method usually allows programs to be more easily debugging.
       Basic and java programming languages are use these interpreters for analyze and
execution of programs.




Character set:

       Character set means that the characters and symbols that a C program can accept.
These are grouped to form the commands, expressions, words, C statements and other tokens
for C language character set is the combination of alphabet or character, digit, special
characters and white spaces.

       1. Letters                            (A…….Z and a………z)           52

       2. Digits                             (……9)                       10

       3. Special characters                 (. , ; : ? / < >….)         29

       4. White spaces                       Blank, Horizontal tab,      5

                               Carriage return, new line, Form feeds     96


                                               8
Programming in ‘C’


C Tokens:

        In a passage of text, individual words and punctuation marks are called token.
Similarly in a C program the smallest individual units are known as c tokens.



        C TOKENS




Keywords          Identifiers            Constants    Strings        Operators        Special
symbols
Float             main                   50.00        “computer”     +-*/             { < [ ? ….
Int               a                      -21.43       “a”

While             cost


1. KEYWORDS:

        Every C word is classified as either a keyword or an identifier. All keywords have
fixed meaning and these meanings cannot be changed. Keywords serve as basic building
blocks for program statements. All keywords must be written in lower case.

        auto                    double                int                   struct
        break                   else                  long                  switch
        case                    enum                  register              typedef
        char                    exturn                return                union
        const                   float                 short                 unsigned
        continue                for                   signed                void
        default                 goto                  sizeof                vollatile
        do                      if                    static                while



2. IDENTIFIERS:

        Identifiers refer to the names of variables, function and arrays. These are user-defined
names and consist of a sequence of letters and digits with as a first character. Identifier
should not be a keyword.



                                                  9
Programming in ‘C’


      Variable: A variable is a data name that may be used to store a data value. A variable
      may take different values at different times during execution. The programmer can
      choose a variable name in a meaningful way.

      Rules for a variable:

              The first character of the variable name should be a letter (alphabet).

               A variable should not be a keyword.

              A variable name can be of any length in recent compilers but some
               implementations of C recognize the first eight characters as the valid variable
               name.

              No special characters are allowed in the variable name except underscore.

              The blank space characters are also not allowed while constructing variable
               names.

              Upped and lower case letters are different in variable names. Because C is case
               sensitive language.

              It is always useful to give the meaningful names to the variables.

      Some valid variable names are.

               ROLLNO, Area, arc, n1, n_1, n1_n2……

3. CONSTANTS:

      Constants in C refer to fixed values that do not change during the execution of a
program.

                                           Constants



               Numbered constants                               Character constants


           Integer              Float                  Single        String         Black slash


       Decimal
        Octal
        Hexa-
       decimal




                                                10
Programming in ‘C’


1. Numeric constants:

       These have numeric value having combination of sequence of digits i.e from 0-9 as
alone digits or combination of 0-9 ,with or without decimal

        Point having positive or negative sighn. These are further sub—divided into two
categories as:

                                       a) Integer Numeric constant
                                       b) Float Numeric constant
a) Integer numeric constant:

       Integer numeric constant have integer data combination of 0-9 without any decimal
point and with any + or – sign. These are further sub-divided into three parts.

       Decimal integer consists of a set of digits 0-9, preceded by an optional – or + sign.

       Examples:       q23    -321     +7546

       Embedded spaces, commas and no-digit characters are not permitted .

       An octal integer constant consists of any combination of digits from 0 to 7, with a
       leading 0.

       A sequence of digits proceeding by OX or ox is considered as hexadecimal integer.
       They may also include alphabets ‘A’ through ‘F’ or ‘a’ through ‘f’. The letter ‘A’
       through ‘F’ represents the numbers 10 through 15.

       Examples:       OX2             Ox9F                   Oxbcd

                       Note: We rarely         use octal and hexadecimal numbers               in
       programming.

b) Float Numeric constant

       Some constants which have a decimal point or a precision value with in having any
positive or negative sign is called floating point constant . Float constants has two parts. One
is mantissa and the other is exponent pat. These two parts in a real number are represented as:

                 Mantissa E exponent




                                               11
Programming in ‘C’


       The mantissa is either a real number expressed in decimal notation or an integer. The
exponent is an integer umber with an optional + or – sign. The letter E separating the
mantissa and the exponent can be written in either lowercase or uppercase.

                      Example:                 3.5x102 can be written as 3.5E2

2). Character constant:

a) Single character constant:

       It contains a single character enclosed within a pair of single quote marks.

                Example:              “Hellow”         “2007”          “X”            “9+22+17”

b) String character constant:

       String constant is a sequence of characters enclosed in double quotes. The characters
may be letters, umbers special characters and blank space.

       Example:       “hallow”        “2007”           “x”      “9+22+65”

c) Backslash characters:

       C supports some backslash character constants that are used in output functions.
These character combinations are known as escape sequence.

                           Constant    Meaning
                           ‘a’        Audible alert (bell)
                           ‘b’        Back space
                           ‘n’        New line
                           ‘t’        Horizontal
                           ‘0’        Null




4. OPERATORS: An operator is a symbol that tells the computer to perform certain
mathematical manipulations.
Types of Operators:
1. Arithmetic                         2. Relational             3. Logical            4.
Assignment
5. Increment and decrement            6. Conditional            7. Bitwise            8. Special




                                               12
Programming in ‘C’


1. Arithmetic Operators: Arithmetic operators are
                                                          Operator          Meaning
used for arithmetic operations like Addition,
                                                          +                 Addition
Subtraction, Multiplication, Division etc.
                                                          -                 Subtraction
        If all operands are integers, the result is an
                                                          *                 Multiplication
        integer.
                                                          /                 Division
        If an operand is a floating point or double
                                                          %                 Modulo Division (Remainder
        precision value, the result is a double.
                                                                            after division)

2. Relational Operators: We often compare two
                                                              Operator      Meaning
quantities, and depending on their relation, take
                                                              <             Is less than
certain decisions. These comparisions can be done
                                                              <=            Is less than or equal to
with the help of relational operators. Containing a
                                                              >             Is greater than
relation operator is termed as a relational expression
                                                              >=            Is greater than or equal to
is either 1(true) or (false).
                                                              ==            Is equal to
                                                              !=            Is not equal to


                                                              Operator                     Meaning
3.LogicalOperators:Anexpression,which combines
                                                              &&                           AND
two or more relational expression, is termed as a
logical expression.                                           ||                           OR
                                                              !                            NOT

Logical Table:
                    A           B          A AND B                 A OR B     NOT A
                    T           T          T                       T          F
                    T           F          F                       T          F
                    F           T          F                       T          T
                    F           F          F                       F          T
4. Assignment Operator (=): Assignment operators are used to assign the result of an
expression to a variable.
Syntax:                                variable=expression
Where, expression is whose value is to be assigned to the variable.
Examples:                a=10          b=20              sum= a+b




                                                   13
Programming in ‘C’


5. Increment and decrement Operators: The operators ++ adds 1 to the operand and the
operator – subtracts 1 from operand. We use the increment and decrement statements are use
in for and while loops extensively.
Example:
       A prefix operator first adds 1 to the operand and then the result is assigned to the
       variable on left.
                                       m=5;            Y=++m;
       In this case the value of y and m would be 6.
       A postfix operator first assigns the value to the variable on the left and the increment
       the operand.
                                       m=5;            Y=m++;
       In value of y would be 5 and m would be 6.


6. Conditional Operator: A ternary operator pair ‘?:’ is available in C to construct
conditional expressions of the form.
                                       Var1=condition? exp2: exp3;
The operator ‘?:’ works as fallows condition is evaluated first. If it is nonzero (true) then the
expression exp2 is evaluated and becomes the value of the var1. If condition is false, exp3 is
evaluated and its value becomes to the value of the var1.


Example:                       a=10;                   if(a>b)
                               b=15;                             x=a;
                               X=(a>b)?a:b;            else
                                                                 x=b;


7.Bitwise Operators: C has a distinction of
                                                     Operator           Meaning
supporting special operators for manipulation of
                                                     &                  Bitwise AND
data at bit level.These operators are used for
                                                     |                  Bitwise OR
testing the bits, or shifting them right or left.
                                                     ^                  Bitwise Exclusive OR
These operators are not applicable to the float or
                                                     <<                 Bitwise Left
double data types.
                                                     >>                 Bitwise Right
                                                     ~                  Bitwise NOT




                                               14
Programming in ‘C’



   1. Bit wise AND: The bit wise AND operator is represented by the symbol &. When this
   operator is      used, it compare the corresponding bits in the two operands and when they
   both are 1 then the corresponding bit in the result is 1, in all the other cases it is 0.
                   Example: a=0 0 0 0 0 1 0 1
                                b=0 1 0 1 0 1 1 1
                             a&b=0 0 0 0 0 1 0 1
   2. Bit wise OR: The bit wise OR operator is represented by the symbol |. When this
   operator is use d, it compare the corresponding bits in the 2 operands and when they both
   are 0 then the corresponding bit in the result is 0, in all the other cases it is 1.
                   Example: a=0 0 0 0 0 1 0 1
                                b=0 1 0 1 0 1 1 1
                             a | b=0 1 0 1 0 1 1 1


   3. Bit wise Exclusive OR: The bit wise OR operator is represented by the symbol ^.
   When this operator is used, it compare the corresponding bits in the 2 operands and when
   they both are either 0 or 1 then the corresponding bit in the result is 0, in all the other cases
   it is 1.
                   Example: a=0 0 0 0 0 1 0 1
                                b=0 1 0 1 0 1 1 1
                             a^b=0 1 0 1 0 0 1 0


  4. Bit wise NOT: The bit wise NOT operator is represented by the symbol ~. When this
  operator is used, in inverts each bit in the operand. In other words, each 0 in the operand is
  changed to 1 and vice-versa.
                 Example:       a=0 0 0 0 0 1 0 1
                              ~a=1 1 1 1 1 0 1 0


5. Right Shift: It has the purpose to transfer the bits of data to the right side. It is a binary
   operator that is it has two operands. The left operand is the data and the right operand is
   the number of times the shift operation to be done.
        Example:        a= 0 0 0 0 0 1 0 1
                        a>>2= 0 0 0 0 0 0 0 1



                                                 15
Programming in ‘C’


  Hence, the least significant bit will be discarded and the most significant bit will come out
to be 0.


6. Left Shift: It has the purpose to transfer the bits of data to the left side. It is a binary
operator i.e. it has two operands. The left operand is the data and the right operand is the
number of times the shift operation to be done.
              Example: a= 0 0 0 0 0 1 0 1                 a<<2=0 0 0 1 0 1 0 0
   Hence, the most significant bit will be discarded and the least significant bit will come out
to be 0.


8. Special Operator: These are used for special purpose in C language. These operations are
used in pointers, structures and unions etc.
                  1. Unary operator
                  2. Comma operator
                  3. Sizeof() Operator
                  4. Type operator
                  5. Pointer operator
                  6. Member selection operator


1. Unary Operator:
           These are used for identification of about where it is signed or unsigned. These are +
and -. Also increment or decrement operators ++, -- are in the unary operator category as
special operator.
Example:                  x=-3;           y=++x-7*3


2. Comma operator:
           The comma operator can be used to link the related expression together. A comma
linked list of expression is evaluated left to right and the values of right most expression is
the value of the combined expression.
Example:                  z=(x=10,y=5,x+y);
           First assigns the value 10 to x, then assign 5 to y and finally 15 to z.




                                                   16
Programming in ‘C’


3. Size of ()operator:
        The sizeof() is a compile time operator and, when used with an operand, it returns the
number of byte the operand occupies. The operand may be a variable, a constant or a data
type qualifier.
Syntax: Variable=sizeof(v or e)
Example:          int a;
                  K=sizeof(a) the value of k is 2 (because a occupies two bytes of memory)


4. Type operator:
        Type operator is used for conversion purpose or casting purpose. So it is called
convert operator. This operator converts float type data into integer form and vice-versa. It is
used for casting a value and process to convert from 1 form to another is called casting.
Syntax:                      (Type)v or e;            where v is variable e is an expression
Example:          int a=10, b=3;
                  float c;
                  C=a/b;
        If we divide a by b, then result stored in the c variable be 3.000000. But by using the
type operator, we can get the float value as
                  C=(float) a/b;
        Now c value is 3.333333
5. Pointer operator:
        There are two types of pointer operators used in C language. These are & and *.


6. Member selection operator:
        There operators are used in structure and union. These are used to create a relation
between owner and member within a structure or union data. These are “.” and .




                                                17
Programming in ‘C’


DATA TYPES:
         C language is rich in its data types. ‘C’ language supports the following data types.


                                             DATA TYPES



 Scalar                   Derived                  User                      Void                Pointer
                                                   Defined
 Char                     array or string          enum
 Integer                  structure
 Float                    union                    typedef
 Double


1. Scalar/ standard/ primary/ fundamental data types:
         A scalar data type is used for representing a single value only. It is only called simple
or fundamental data type.
Size and range of basic data types:
         Data type                Size             Range of value
         char                     1 byte           -128 to 127
         int                      2 bytes          -32,768 to 32,767
         float                    4 bytes          3.4e-38 to 3.4+38
         double                   8 bytes          1.7e-308 to 1.7e+308


2. Derived data types:
         Derived data types are derived from the scalar data type by adding some additional
relationship with the various elements of the primary or scalar data types. Note that derived
data type may be used for representing a single value or multiple values. These are further
sub divided into three categories.
         1. Array and strings               2. Structures        3. Unions
(a). Arrays: An Array is nothing but a collection of sequence of homogeneous(similar) data
type elements.
Declaration of an array:
         Data type variable-name [size];
Where datatype can be any primary or secondary datatypes. Size is any integer.
Example:          int a[50];


                                                    18
Programming in ‘C’


(b). Structure: A Structure is nothing but a collection of heterogeneous (different) datatypes
of elements.
Declaration of structure:
       Struct tage_name
       {
           datatype field1;
           datatype field2;
           ………………
           datatype field n;
       };
Where tagename is the name of the structure / datatype can be any primary or secondary
datatype.
Example:         struct student
                 {
                      int sno;
                      char name[10];
                      float m1,m2,m3;
                 };
       Once the structure data type is defined, the variable of that datatype can be declared
of follows.
Syntax:          struct tagname variablelist;
Example: struct student s;


3. User defined type:
       This is also used for definition, i.e. it allows the users to define a variable or an
identifier, which is used for representation of existing data types.
a) enum: Another user defined data type is enumerated data type provided by ANSI
standard.
       Syntax:              enum identified {value1, value2…..} variable;
                 The identifier is a user- defined enumerated data type, which can be used to
declare variables that can have one of the values enclosed within the braces known as
enumeration constant.
Example:         enum day{Monday, Tuesday, Wednesday,..} d;



                                                  19
Programming in ‘C’


b). type def: Supports a feature know “type definition” that allows user to define an identifier
that would represent an exiting data type. The user-defined data type identifier can later to
declare variable.
        Syntax:      typedef data_type identifier;
        Where type represents the data type of the identifier refers to the ‘new’ name giving
to the date type.
        Ex:              typdef int marks;
        Here marks symbolize int. they can be later used to declare variable as follows.
                         marks m1,m2;
        m1,m2 are declared as int variable. The main advantage of typedef is that we can
create meaningful data type names for increasing the readability of the program.


4. Void:
        Void or empty data type is used in user defined function or user defined sub
programs. These are used when the function sub-program returns nothing to the calling
location. Also it is used when a function or a sub-program have not any argument in it.


5. Pointer data type:
        Pointer data type is used to handle the data at their memory address.
Input / output functions
        In ‘C’ language I/O functions are categorized into following two types.

                                      Input/output functions



                    UnFormatted I/O                            Formatted I/O statements
                      statements


        getchar();             putchar();             scanf();                            printf();
          gets();               puts();
         getch();
        getche();


1. Formatted I/O statements:
        All input/output operations are carried out through function calls such as printf and
scanf there exist several functions that have more or less become standard for input and
output operations in C. There functions are collection known as the standard i/o library.


                                                 20
Programming in ‘C’


                        #include<stdio.h>
       The instruction <stdio.h> tells the compiler to search for a file stdio.h and place it’s
contents at this point in the program. The content of the header file become part of the source
code when it is compiled.


                        Conversion character            Meaning
                        %d                              Integer
                        %f                              Float
                        %c                              Character
                        %s                              String
                        %lf                             Double

a). scanf():
       The scanf() function is an input function. It used to read the mixed type of data from
the keyboard. You can read integer, float and character data by using its control codes or
format codes.
       Syntax:          scanf(“control string”,&v1,&v2…);
       The control string contains the format of data being received. The ampersand symbol
‘&’ before each variable name is an operator that specifies the address of variable v1.
                 Example:      scanf(“%d”,&n);
       The control string %d specifies that an integer value is to be read from the terminal
(keyboard).


b). printf():
       printf() fiunction for printing captions and numerical results the general form of
printf statement is….
                 printf(“controle string”,arg1,arg2…);
control string consists of three types of items:
    Characters that will be printed on the screen as they appear.
    Format specifications that define the output format for display of each item.
    Escape sequence character such as n,t….. the control string indicates how many
       arguments follow and what their types are the argument arg1,arg2… are the variable
       whose values are formatted and printed according to the specification of control
       string.




                                                   21
Programming in ‘C’


2. Unformatted I/O statements:
        These functions are used to read or print the data in unformatted way. These are also
called as character I/O functions. The following are the character I/O functions.
                       Input functions                     output functions
                       getchar();                          putchar();
                       getche();                           putc()
                       getch();
                       gets();
a). getchar():
        This is an input function. It is used for reading a single character from the keyboard. It
is buffered function. Bu8ffered functions get the input from the keyboard and store it in the
memory temporarily until you press the enter key. After you pressed the enter key then input
move to a relevant variable.
                 Syntax:         v=getchar();
                 Example:        char a;        a=getchar();
b). gets():
        This is an input function. It is used for read a string from the keyboard. It is a buffered
function it will read a string, when you type the string from the keyboard and press the enter
key from the keyboard. It will mark null character (‘0’) in the memory at the end of the
string, when you press the enter key.
                 Syntax:         gets(v);
                 Example:        char s[20];    gets(s);
c) getch():
        This is also an input function. This is used to read a single character from the
keyboard like getchar() function. But getchar() function is a buffered function; getch()
function is a non buffered function. When type the character data from the keyboard it does
not visible on the screen.
                 Syntax:         v=getch();
d). getche():
        All are same as getch() function except that when you type the character data from the
keyboard it will be visible on the screen.
                 Syntax:         v=getche();
e). putchar():



                                                22
Programming in ‘C’


          This function is an output function. It is used to display a single character on the
screen.
                 Syntax:         putchar(v);
                 Example:        char a;          getchar(a);
f). puts():
          This function is an output function . It is used to display a string inputted by gets()
function, which you will read in the next on the screen.
          Syntax:         puts(v);         or     puts(“text);
          Example:        char a[10];      gets(a);



Control statements:
          Normally C-compiler executes all the statements in the program sequentially in top
down process. In C-language some times we have to control the execution of program, Some
times the program executes some group of statements in the program, some other time
another group of statements in the program comes for execution. When ever the program
needs this type of situation, place some condition statements in the program. Those
conditions are made with the help of relational operators. The condition will execute and
returns the value 1 (TRUE) or 0 (FALSE) to specified location, where the condition place in
the program. C-language provides several types of decision making or control statements.
They are:
    1. If
    2. Switch
    3. looping statements.

IF conditional statement:
          ‘ If ’ it is one of the keyword in the C-language, by using this we make some controls
on the execution of program. The general syntax of the ‘if’ is:
          if(condition)
          {
                 Executable Statements;
          }




                                                      23
Programming in ‘C’


          In the above syntax ‘if ‘ is a key word. The condition is following by the keyword if.
When ever the condition comes to execution, if the given condition true, it will return 1 to if
statement. If the given condition is false, it will return 0 to if statement. We have several form
of if statements in C-language. They are:
      1. Simple if.
      2. if else.
      3. else if or else if ladder.
      4. Nested if.

1. Simple if:
          In simple if, the given condition is true, then some statements in program will come
for execution other wise normal statements will execute. The general syntax of the simple if
is:
          ---------------
          if(condition)                                      Texst       No
                                                              exp
          {
                                                               Yes
                    Stament1;
                                                         Statements
          }
          In the above syntax the condition following by the keyword ‘ if ‘. The executable
statements are enclosing with opening and closing curling braces ({). The compiler identifies,
those statements are comes under if block.
          When ever the condition in the ‘if’ statement is true it will return 1 to for if statement,
other wise it returns 0 for ‘if’ statement. The given condition is true, then the given
statements (statement1) in the ‘if’ part will come for execution other statement1 absence in
the execution, the compiles goes to execution of normal statements in the program.


Example program on simple if condition:
#include<stdio.h>
main()
{
          int num;
          clrscr();


                                                  24
Programming in ‘C’


       printf(“Enter your number”);
       scanf(“%d”,&num);
       if(num>0)
       {
                printf(“ given number is +ve :”);
       }
       printf(“Given number is : %d”, num);
       getch();
}

2. if else conditional statement:
       It is also one of the conditional statements in the C-language. If else is the extension
of the simple if. The general syntax of the ‘if else’ conditional statement is:
       ---------------
       if(condition)                                      Texst        No
                                                           exp
       {
                                                             Yes
                Stament1;
                                                       Statement1                 Statement2
        }
       else
       {
                Statement2;
       }
       ----------------
       In the above syntax, if else statement having condition following the keyword if. The
‘if’ else statement is divided in to two parts, one is if (TRUE) part and another one is else
(FALSE) part. If the given condition is true, then if part statements (Statement1) will comes
for execution. If the given condition is false, then else part statements (Statement2) will
comes for execution.
       When ever the first if statement succeeds, the second must fail, and vice versa. In this
if else conditional statement either if part statements or else part statements only comes for
execution another one absence in the execution time. When ever the C-program having two



                                                25
Programming in ‘C’


options for execution we use this is else statement. If the ‘if’ part or else part having single
statement, opening and closing curling braces are optional.
Example program for if else if:
#include<stdio.h>
main()
{
         int num;
         clrscr();
         printf(“Enter your number”);
         scanf(“%d”,&num);
         if(num%2= =0)
         {
                 printf(“ %d is even number”, num);
         }
         else
         {
                 printf(“%d is odd number”, num);
         }
         getch();
}

3. else if or else if ladder:
         When ever the C-program needs to check or build the conditions in different levels
else if ladder type is used. In this else if type, the main if having condition, if the if part
condition is fail, the else part having another condition, if the else if part condition fail then
else part having another condition… then the conditions are arranger in the ladder or chain
format. The else if conditional statement having common else for the all the else if
statements, if all conditions in the else if are fail then else part will executes, this else part is
optional. The general syntax of the else if conditional statement is:




                                                 26
Programming in ‘C’



         ---------------
         if(condition1)                   Texst        No
                                           exp
         {
                                            Yes
                  Stament1;                                 Texst        No
                                                             exp
                                       Statement1
         }
                                                                Yes
         else if(condition2)                             Statement2              Statement3
         {
                  Statement2;
         }




         else                           This else part is optional
         {
                  Statements3;
         }
         ----------------
         The above syntax represents the else if conditional statement arrangement. The
condition1 following main if, if the condition1 is true then if part statements (Statement1)
will come for execution. If the if part condition is false then the compiler will check the next
else if part condition, if it is true then the compiler will executes statements2 in the else if
part, if it will also false then compiler check the next condition. In this way the compiler will
check all the sequence of else if conditions in the program, all the conditions are false then
default else part statements (Statements3) will comes for execution.


Example program for else if statement:
#include<stdio.h>
main()
{
         int n1,n2,n3;



                                                  27
Programming in ‘C’


       clrscr();
       printf(“Enter 3 number”);
       scanf(“%d%d%d”,&n1,&n2,&n3);
       if((n1>n2)&&(n1>n2))
       {
                printf(“ %d is big number”,n1);
       }
       else if(n2>n3)
       {
                printf(“ %d is big number”,n2);
       }
       else
       {
                printf(“ %d is big number”,n3);
       }
       getch();
}


4. Nested if conditional statement:
       When ever the C-program need to check the conditions, condition with in the
conditions, use this nested if conditional statement. In this nested if conditional statement all
the conditions or some conditions are arrange in nested form. May be the main if or else part
body having another if of if else statement. The general syntax of the nested if is:
       ----------------
       if(condition1)
       {
           if(condition1)
           {
                Statement1;




                                               28
Programming in ‘C’



           }
           else                             This else part is optional
           {
               Statement2;
           }
       }
       ---------------
       The syntax represents the nested if conditional statement. The main if body having
another if condition, in this we place number of if conditions as condition with in the
condition. If all the given conditions in the ‘if’ part will true then only the statement1 will
come for execution, other wise it will execute the normal program. If the main if is false then
only the else part will come for execution, if inner most condition of the main if is false, then
the compiler goes to after the else part statements execution.


Example program for nested if conditional statement:
#include<stdio.h>
main()
{
       int n1,n2,n3;
       clrscr();
       printf(“Enter 3 number”);
       scanf(“%d%d%d”,&n1,&n2,&n3);
       if((n1>n2))
       {
               if(n1>n3)
               {
                      printf(“ %d is big number”,n1);
               }
               else
               {
                      printf(“ %d is big number”,n3);
               }
       }
       else
       {


                                               29
Programming in ‘C’


               if(n2>n3)
               {
                      printf(“ %d is big number”,n2);
               }
               else
               {
                      printf(“ %d is big number”,n3);
               }
       }
       getch();
}




Compound relation test:
       A compound relation test is a simple way to combine more then one conditions or
relations, with the help of logical operators. Those logical operators are; and (&&), or( || ).
       Syntactical representation of the compound relations are.
               ((condition1)&&(condition2)…..)
               ((condition1)||(condition2)…..)
       These compound relations are used with the “if” conditional statement.
       Example:        if((a>b)&&(a>c))                if((a>b)||(a>c))
                       {                               {
                               Statement1;                     Statement2;
                       }                               }
       The above example shows the compound relation of the condition. The a>b and a>c
are two individual conditions we can combine these two conditions with help of logical and,
or operators, it form a single condition statement.



2. Switch conditional statement:
       The switch statement is used to execute single statement or choices form many
statements or many choices. In this switch each choice can be represented with case of the
switch statement. The switch, case, default these three key words are arranged correctly, then
if will form a control statement.



                                                30
Programming in ‘C’


The general form of the switch conditional statement is:
       switch( variable or integer expressions)
       {
               case constant1:
                       statement1;
                       break;
               case constant2:
                       statement2;
                       break;




               default:
                       statement n;
       }
       The switch is a keyword. The switch statement requires single variable or integer
expression as arguments. The keyword case is followed by an integer or character constant
(1,2,3…., ‘a’,’b’,…’A’,’B’…). The keyword default represents the default case of the switch.
All the cases of the switch is enclosed with opening and closing curling braces ( { } ), and it
is having an other case is called default case. When ever the value in the variable is equals to
the constant value of the specified case in the switch is executed. The value in the variable is
not match with the constant values of all the cases in the switch, and then the default case is
executed. The value in the variable is equal to the constant in the case 1, and then statement 1
is executed, if the value is not mach with the value in the case 1, then the compile check with
next case constant. In this way the compiler will check with each and every constant value of
the cases in the switch.


Example program for switch conditional statement:
#include<stdio.h>
main()
{



                                              31
Programming in ‘C’


       int n1;
       clrscr();
       printf(“Enter number between 1 to 5”);
       scanf(“%d”,&n1);
       switch(n1)
       {
               case 1:
                       printf(“n I am in case 1”);
                       break;
               case 2:
                       printf(“n I am in case 2”);
                       break;
               case 3:
                       printf(“n I am in case 3”);
                       break;
               case 4:
                       printf(“n I am in case 4”);
                       break;
               case 5:
                       printf(“n I am in case 5”);
                       break;
               default:
                       printf(“ I am in default case”);
       }
       getch();
}


Looping statements:
       Loops are used for, when ever the C-program needs to execute the steps repeatedly. In
will repeatedly execute some sequence of steps or some portion of the program specified
number of times. The loop execution is controlled with the help of the loop control
instruction or loop condition. The statements in the loop will execute until the given
condition is false. In C-language we have three types of looping statements. They are:
           1. While statement.
           2. For statement.
           3. Do while statement.




                                               32
Programming in ‘C’


       The looping statements are divided in to two types based on condition checking
location. They are entry level condition checking, exit level condition checking. The for and
while looping statements are comes under entry level condition checking. The do while
looping statement is comes under exit level condition checking.


1. While looping statement:
       The while is a keyword C-language; use this keyword as looping statement. The while
is an entry controlled loop statement. The general syntax of the while looping statement is.
       Variable Initialization;
       while( test condition )
       {
               Body of the loop;
               Increment or decrement operations;
       }

                                       Start


                                   Initialization


                                                         No
                                     Test exp

                                          Yes
                                                              Stop
                                 Body of the loop


                                    Increment or
                                     Decrement
                                     operations




       It is often execute some sequence of steps or some part of a program, use this while
loop. In the while loop first initialize the starting value to the variable for counting purpose of
the loop iterations. Iteration is the process of loop execution. The while is a keyword
followed by the test condition. The body of the loop and the increment or decrement
statements are enclosed by the opening and closing curling braces ({}). The test condition is
true then the body of the loop will come for execution and perform increment or decrement
operations. After performing increment or decrement operations the test condition is once


                                                    33
Programming in ‘C’


again evaluated, if it is true the body of the loop is again executed. The process of repeated
execution of the body continues until the condition false the control is transfer to out of the
loop. The braces are need only if the body of the loop contains two or more statements.


Example program for while looping statement:
#include<stdio.h>
main()
{
         int i,num;
         printf(“Enter number”);
         scanf(“%d’,&num);
         i=1;
         while(i<=num);
         {
             printf(‘%dt”,i);
             i=i+1;
         }
         getch();
}

         The above program is used to display the numbers from 1 to given number. The i
values is initializes with one, and check the while loop condition and executes the body of the
loop. Then perform increment operation. The body of the loop executes continually until I
value greater then value in the variable num.


2. For looping statement:
         The ‘for’ loop is another Entry controlled looping statement. For is a keyword, by
using this we can build a looping statement.




                                                34
Programming in ‘C’


The general syntax of for looping statement is:
         for(intilization;condition;increment or decrimrnt)
         {
                Body of the loop;
         }
         Handling of for loop is easy to compare remaining looping statement. In while
looping statement, the initialization, conditions and increment and decrement statements are
placed in different locations. In for looping statement this initialization, condition and
increment and decrement statements are place in one location these are separated by
semicolon (;). Those three statements are enclosed with parentheses. The initialization part is
used for initialize counter variable for loop execution. The body of the loop will execute until
the given condition is false. The body of the loop is enclosed with closing and opening
curling braces ({ }), if the body of the loop has single statement need not to write braces. But
it is good practice to open the braces even it has single statement.
Execution process of for loop:
         Fires the initialization of control variable of loop will execute, after the execution of
initialization statement the control will follow up the next condition checking statement in for
loop. If the given condition is true, then the body of the loop will come for execution. Next
the control will transfer to increment or decrement statement and execute the step, then the
control goes to condition checking, if the condition is true, again the body of loop will
execute this process is continue until the given condition false.


Example program for ‘for’ looping statement:
#include<stdio.h>
main()
{
     int i,num;
     printf(“enter number”);
     scanf(“%d”,&num);
     for(i=1;i<=num;i++)
     {



                                                35
Programming in ‘C’


              printf(“%4d”,i);
      }
      getch();
}
          In the above, variable ‘i’ is used for counter of the loop. It will initialize to value 1 the
first time execution of for loop. The execution of loop terminates when the ‘i’ reaches to,
value in the variable ‘num’. In this process the ‘i’ value increment once each and every time
execution of loop.


3. Do while looping statement:
          The do while is the exit controlled looping statement. The while loop construct as the
test condition is made at the beginning of the loop and also condition will comes for
execution beginning of the loop. There fore the body of the loop may not executes, all the
conditions of while loop is not satisfied at the entry first time. Some times it might be
necessary to execute the body of the loop before the test is performed. In such a situation can
be handling with the help of the do statement.
The general form of the do-while statement is:
Initialization;
do
{
          Body of the loop;
          Increment or decrement operations;
}while(condition);
          The working of while and do while loops are same but only difference is, in while test
condition will be executed before executes the body of the loop. In ‘do while’ fist the body of
the loop will executes, at the end of the loop test condition is executed. This means in ‘do
while’ the body of the loop executes at least once, if the condition is fail. Remaining
initialization and increment decrement statements are located in same location in ‘while’ and
‘do while’ loops.




                                                   36
Programming in ‘C’


Example program for the ‘do-while’ looping statement:
#include<stdio.h>
main()
{
         int i,num;
         printf(“Enter number”);
         scanf(“%d’,&num);
         i=1;
         do
         {
              printf(‘%dt”,i);
              i=i+1;
         } while(i<=num);
         getch();
}
         In the above program the initialization is made at the beginning of the loop, next the
body of the loop is executed. After the execution of the increment statement of the ‘i’, the test
condition of the while is executes.


Difference between while and do-while loop:

While loop                                       Do-while loop

1. While loop can also called as an entry 1. Do-while loop can also be called as an exit
controlled loop.                                 controlled loop.
2. In the While loop the condition is placed at 2. In the Do-While loop the condition is
the beginning of the loop.                       placed at the end of the loop.
3. In the case of While loop after executing 3. In the case of Do-While loop, after
the initialization section, the condition will executing the initialization section, the body
be tested if it is true, the body of the loop is of the loop will be executed and then the
executed.                                        condition will be tested for the continuation
                                                 of the next iteration.




                                               37
Programming in ‘C’


4. In the case of While loop, if the condition 4. In the case of Do-While loop, the body of
is found to be false for the first time, the will be executed at least once without
body will never be executed and the loop will depending on the vale of the condition.
be terminated.
5. In most applications the while loop is user 5. In the body is to be executes at least once,
friendly.                                      the Do-While loop is much more suitable.
6. It is possible to have nested while loop 6. It is also possible to have nested Do-While
while loop can also contain a Do-While loop. loops. Do-While loop can also contain a
                                                while loop.
7. The general syntax of the While is:          7. The general syntax of the Do-While is:
Variable Initialization;                        Initialization;
while( test condition )                         do
{                                               {
         Body of the loop;                                Body of the loop;
         Increment or decrement operations;               Increment or decrement operations;
}                                               }while(condition);




Nested loops:
         The nested loops are used where the program needs loop with in the loop. Which
procedure used for nesting of ‘if’, that can be used for nesting loops. The nesting loops are
made by using while, do-while and for looping statements. Writing nested loops in while, for
is easier to compare do-while. The general form of the nested loops is:

Initialization;                                 for(intilization;condition;increment or decrimrnt)
while( test condition )
                                                {
{
     Initialization;                                for(intilization;condition;increment or decrimrnt)
     while( test condition )
                                                    {
     {
          Body of the loop;                               Body of the loop;
          Increment or decrement operations;
                                                     }
      }
          Body of the loop;                               Body of the loop;
          Increment or decrement operations;
}
                                                }

                                               38
Programming in ‘C’


Working of nested loops:
       First the outer loop initialization statement is executed, after test condition statement
is executed if it is true, then the body of the loop is executed. The outer loop body having
another looping statement, we can call it is an inner loop. Then the inner loop initialization
statement is executed, next the inner loop test condition will be processed, if it is true then the
inner loop body is executed. Next increment process is done. After that the control goes for
test condition, if it is true again the body of the loop is executed this process is continue until
the inner loop condition become false. When ever inner loop test condition is false the loop
will be terminated control will execute remaining statements in the out loop. After that the
control goes to increment or decrement operation, next the control goes to check the
condition of the loop if again it is true, again the inner loop is executed. This process is done
until the outer loop condition becomes false.


Unconditional statements:
       In the conditional statements the control will go to specified location when ever the
given condition either TRUE (1) or FALSE. (0). In the unconditional statements, when ever
the compiler reads the unconditional statement the control will goes to specified location with
out testing any condition. Here the control will jumps to specified location automatically so
this statements also called jumping statements. C-language provides three jumping statements
they are:
   1. goto.
   2. break.
   3. continue.

1. goto:
       The goto unconditional statement is used to transfer the control from one location to
another location in the program. Here goto is keyword in C-language. This statement is used
with the help of crating labels in the program; ‘goto’ keyword is followed by the specified
label in the program.
       Syntax:          goto <label name>;
       Example:         goto a;

Example program for goto statement:
#include<stdio.h>


                                                39
Programming in ‘C’


main()
{
         int a,b,c;
         ptintf(“Enter 2 numbers”);
         scanf(“%d%d”,&a,&b);
         c=a+b;
         printf(“Sum : %d”,c);
         goto a;
         c=a-b;
         printf(“Sub : %d”,c);
         a:
         getch();
}
         In above program after the execution of ‘goto a;’ statement control will goes to label
‘a:’, statements after the program will never participate in the execution.


2. break:
         In C language ‘break’ statement is used for stop the execution of statements or
program unconditionally. When ever use the break statement in program, the control will
never executes the statements available, after the ‘break’ statement. When the compiler reads
the break statement the compiler terminates from the execution of the program.
         Syntax:       break;
         Example:      break;

Example program for ‘break’ statement:
#include<stdio.h>
main()
{
         int n,i,sum=0,num;
         printf(“Enter number:”);
         scanf(“%d”,&n);
         printf(“Enter %d numbers”,n);


                                               40
Programming in ‘C’


         for(i=1;i<=n;i++)
         {
                scanf(“%d”,&num);
                if(num<0)
                {
                         break;
                }
                sum=sum+num;
         }
}
         The above program we can calculate the sum of ‘n’ numbers. When ever user give –
ve value to the variable ‘num’ then the loop execution is terminated. Break is used for stop
the normal execution of for loop at that specified time.


3. continue:
         The ‘continue’ is a keyword in C-language. This ‘continue’ statement is mainly used
in looping statements. Some times the program needs to transfer the control to the starting of
the loop. When ever the control reads the continue statement in the loops, the control never
executes the statements after the ‘continue’ in the loop. The control will transfer to the
beginning of the loop.
         Syntax:         continue;
         Example:        continue;


Example program for ‘continue’ statement:
#include<stdio.h>
main()
{
         int n,i,sum=0,num;
         printf(“Enter number:”);
         scanf(“%d”,&n);
         printf(“Enter %d numbers”,n);
         for(i=1;i<=n;i++)
         {


                                               41
Programming in ‘C’


               scanf(“%d”,&num);
               if(num<0)
               {
                      continue;
               }
               sum=sum+num;
       }
}
       The above program is used to calculate the sum of ‘n’ +ve numbers. When ever the
user gives –ve number to the variable num the compile never add that value to the previous
some. This process is done by using continue statement with in for loop. The compiler
decides the given number is –ve, automatically the control will goes to beginning of the loop.




                                              42
Programming in ‘C’


                                               Arrays
       When ever the program need to tack group of similar data elements, it is highly
impossible to create individual variables, and also accessing values, C-language provide a
feature called ‘Array’. An array is a group of related data items that are share common name.
Array is a set of homogeneous elements. Values in the array can be accessed by the special
number or integer is index of an array. Array indexing is starts every time with ‘0’.
Arrays are two types:
       1. Single dimensional arrays.
       2. Multi dimensional arrays.
Single dimensional arrays:
       A list of items can be given one variable name using only one subscript such a
variable is called single dimensional array.
Declaration of array:
       Array variable can be create like normal variable, but only difference is normal
variable take only single value, array variable can accept ‘n’ number of variables, ‘n’
represents the size of an array. General declaration of an array variable is:
               Data type variablename[size]…;
       In the above syntax, data type represents which type of values accepts into an array
variable. Variable name represents the identifier of an array; size represents how many
elements array can accept. Each and every value in the array can be accessed with the help of
an integer or number is called ‘index’ of an array, it can be place with in the brackets after the
array name.
               int rollno[10];
       It represents the ten students roll numbers. Variable ‘rollno’ can share all the ten roll
numbers of the ten students. rollno[0] is the roll number of the single student, rollno[1] is the
roll number on another student etc… the array indexing starts with 0 and ends with n-1. 0 is
the lower bound or limit of an array; n-1 is the upper bound or limit of an array.

Internal storage of array:
       If the array variable is declared like this:
               int a[5];




                                                 43
Programming in ‘C’




        Address               2000       2002         2004    2006        2008

       Elements                 50         34          65        5          12
    Locations or
                               a[0]       a[1]        a[2]     a[3]        a[4]
     subscripts




Initializing values into an array:
       Values initialization process is done like initialization of values to the normal
variable. The values are assigned to each and every location, with the help of index value of
an array.
       Values assigned at the time of declaration.
                   int a[5]={12,54,23,1,654};
       Values assign to individual array variable:
                   a[0]=20;   a[4]=43;
       Read values from the keyboard for array variable:
                   scanf(“%d”,a[0]);
       Read group of values into an array at a time we need loops. When ever we need to
read group of values for an array, we can write scanf statement for each and every variable.
This is highly impossible to write scanf statements for number of values, C-language
minimize this process with the help of loops. The below example represents read values into
an array from keyboard.
       for(i=0;i<n;i++)
       {
               scanf(“%d”,&a[i]);
       }

Access values in the array variable:
       Like normal variables, we can get the values in the array with the help of variable
name. But we can distinguish each and every variable with the logical address of the array
variable. Suppose you want to access 2nd logical location value in the array we can represent
like this ‘a[2]’. We can access group of values at a time with the help of loops.




                                                 44
Programming in ‘C’


       for(i=0;i<n;i++)
       {
               printf(“%d”,a[i]);
       }

Multi dimensional array:
Two dimensional arrays:
       In two dimensional arrays comes under multi dimensional type. In this type the array
variable name having two subscripts such a variable is called two dimensional arrays. When
ever program need to organize the data in rows and columns, use this two dimensional array.
The first subscript represents row size and second subscript represents column size. By using
this 2d array we can organize or store data in the form of tables. It is similar to the matrix
form to define the table of items the two dimensional are convenient.

Declaration of two dimensional arrays:
       The general declaration of 2d arrays:
               datatype varablename[row size][column size]…;
       The data type represents, which type of values can be accepted by the array. The
variable name represents the identification label of the array. The first subscript represents,
how many rows of data can be accepted by the array. The second subscript represents, how
many columns of data can be accepted by the array.
               int m1[2][2];
       The above 2d array variable can accept two rows and two columns of data. The array
variable ‘m1’ can accept integer values only. In single dimensional array we can access the
array values, by using single index value. In 2d array, values can be accessed with the help of
two indexing values. First one represents row index second one represents column index
value. For example m1[0][1] represents the value in the ‘0’th row ‘1’ st column.

Initializing values to 2d array:
        Initializing values to 2d array with the help of indexing values, this indexing values
are represented with combination row and column indexing vales.
       Values assigned at time of declaration:
               int a[2][2]={{12,32},{23,54}};
       Values assigned to individual variable:
               a[1][0]=34;


                                               45
Programming in ‘C’


Initial storage of 2d array:
          The array variable can be stored like this:
                 int a[2][2];




                        Address             2000         2002

                       Elements               50          34             1st row
                     Locations or
                                            a[0][0]     a[0][1]
                      subscripts

                        Address             2004         2006

                       Elements               50          34         2nd row
                     Locations or
                      subscripts            a[1][0]     a[1][1]



                                         1st column     2nd column




Reading values into 2d arrays:
          When ever we need to read or get values from the output screen. We can get those
values with the help of nested looping statements. The general format to read values to 2d
arrays:
                 for(i=0;i<row size;i++)
                 {
                         for(j=1;j<size of column;j++)
                         {
                                 scanf(“ “);
                         }
                 }




                                                   46
Programming in ‘C’


                                                Strings
String:
          In arrays we can store group of numerical values, string can also store group of values
those values comes under character type. String is a collection of character values, when we
declare the array variable under char data type the variable is called as string variable.
Normal char variable can accept only single character value, it can’t accept group of character
like persons names etc… C-language minimizes this problem by creating character array.
          General format to create string variable:
                 Syntax:         char variable name[size];
          The data type of the string is always char, size can represents the maximum number of
characters are store into a string.
                 Example:        char na[20];
Strlen( ):
           It is used to find the length of the string, length means how many characters will be
stored in a given string variable. This function accepts one string variable as the passing
variable from the calling location. In the calling area we can store the return value into an
integer variable.
                 Syntax:-
                            int var = strlen(string var);
                 Ex:-
                            char na[20] = “abc”;
                            int length ;
                            length = strlen(na);
Strcpy:-
       This is used to copy the string from one string variable to another string variable. This
function can accept two string variables as the passing arguments or one is string variable,
second one is string value. It can copy string value in the second variable in to first variable.
                 Syntax:-
                            strcpy(string var1,string var2);
                 Ex:-
                             strcpy(s1,s2);
                              strcpy(s1,”abc”);
Strcmp( ):
             This function performs compression operations between two strings and find out
whether two strings are same or different. It can accept two strings variables as the passing
arguments. If two strings are same strcmp( ) returns zero to the calling location other wise it




                                                   47
Programming in ‘C’


can returns numeric difference between the ascii values of the first non-matching pairs of the
character.
                 Syntax:-
                            int var = strcmp(string var1,string var2):
                 ex:-
                            strcmp(s1,s2);
Strcat( ):
             This function performs concatenation (combining) operation between 2-strings. It
can accept 2-string variables as the passing arguments. It can concatenate 2-strings in a given
string variables, resultant string will be stored into string variable1.
                  Syntax :-
                            strcat(string var1, string var2);
                 Ex:-
                            strcat(s1,s2);
Strrev( ):
         This function is used to reversing the string in a given string variable. It can accept
single string variable as the passing argument. It can reverse string in a given string variable
and the resultant string will be stored into the same string variable.
                 Syntax :
                            strrev(string var);
                 Ex:-
                            strrev(s1):
Strlwr( ):
         This function used to convert the string into lower case (small) letters. It can accept
string variable as the passing argument .The resultant string can store into same variable.
                 Syntax:
                            strlwr(string var);
                 Ex:-
                            strlwr(s1);
Strupr( ):
         This function used to convert the string into upper case (capital) letters. It can accept
single string variable as the passing argument. The resultant string will be stored into the
same variable.
                 Syntax:
                       strupr(string var);
                 Ex:-
                       strupr(s1);




                                                   48
Programming in ‘C’


                                          Functions
Function:
       It is a set of statements or part of a program, which are executed repeatedly and
randomly in our program. Functions are also called as sub programs. The set of statements
are written for accomplish a particular task or solve a problem. These set of statements are
identified by an identifier called function name. When we need to execute those set of
statements in our program, we can write the function name in the program. This procedure is
called function calling. Functions are classified into two types:

       1. Library functions or Predefined functions.
      2. User defined functions.
Library functions:
       Library functions are also called as predefined functions. Like keywords, task of the
function is defined or written by the C-language developers. These function definition are
written in library files. When we to done a particular task in our program simply we can call
those functions with the function names. These functions are use in any C-program.
       Examples: gets(), putchar(), printf(), scanf() etc……..

User defined functions:
       User defined functions are own functions. These functions are written or developed
by the programmer. These functions are developing with in the user programs, we can call
those functions with in the program, we can not call the user defined functions from another
program. Programmer can define number of user defined functions with in one program, each
function having individual task. Each one will be separated by the function names.
       Examples: add(), subtraction(), etc………

Advantages of the functions:

       1. The complicated problem can be divided into number of smaller tasks and can be
          solved separately.
       2. It is easy to understanding each sub program as it performs only a specified task.
       3. We can test the program are sub programs easily.
       4. More general functions can be kept in the library files for the later uses.
       5. We can reduce the complexity of the program.
       6. We can solve the complicated problems easily by using functions.
       7. Reduce the length of the programs.




                                               49
Programming in ‘C’


Each function has the following working procedures:
       1. Function declaration (or) Function prototype.
       2. Function definition.
       3. Passing arguments.
       4. Return statements.
      5. Function call.
Function declaration (or) prototype:
       It can tells to compiler, name of the function, which type of values can taken as the
passing arguments from the calling location and which type of value can be return to the
calling location. Function declaration is made at the beginning of the main function in our
program. The general format for the declaration of the function:
                       Return type function name(arguments list(optional));
       Example:        void addition(int x, int y);

Function definition:
       Here the program can specify the task of the function. The task of the function is
called as the definition of the function. The definition of the function can be written after the
completion of the main function or at the time of the declaration. We can maintain equal
prototype of the function at the time of declaration, at the time of the writing definition.
                       Return type function name(arguments list(optional))
                       {
                              --------- (Executable statements)
                       }
       Example:        void addition(int x, int y)
                       {
                              printf(“sum = %d”, x+y);
                       }
Passing arguments:
       Each function is design for executing a task in this way the function needs a some
values for the execution of further steps in function. Some times those values are given to the
function from the calling location, then those values are pass to the function as the passing
arguments.




                                                50
Programming in ‘C’


Return statements:
       The return statement tells to compiler which type of value return by the function to
the calling location. The return type is specifying before the function name. The return type
of the functions is mention as void, scalar or derived type.
Function call:
       After defining the function, we can call the function from main function or another
used defined function. The calling of the function is nothing but the execution of the function
code. Where you want to execute the code of the function in our program, just write the
function name in that location.
                 Function calling:     addition();
       When we declare the user defined functions in our program above steps should be
following. User defined functions are classified into 4 types based on the prototype of the
function. Those are:

       1. Functions have No return value and No passing arguments.
       2. Functions have No return value and Passing arguments.
       3. Functions have Return value and No passing arguments.
       4. Functions have Return value and Passing arguments.

1. Functions have No return value and No passing arguments:
       In this type function doesn’t take any values as the passing arguments from the calling
location. Function doesn’t return any value to the calling location. This type of functions,
declaration of variables, and logic of the task and results of the task should be placed in the
definition of the function. General format of this type is:
                        void function name( );
       Example:         void addition( )
                        {
                               Executable statements;
                        }
                        {
                               --------------
                               addition( ); (calling environment)
                        }




                                                 51
Programming in ‘C’


       In the above format the data type void represents the function doesn’t return any
value. The empty parenthesis represents the function doesn’t require any values as the
passing arguments from the calling location.


2. Functions have No return value and Passing arguments:
       In this type the function doesn’t return any value to the calling location but it can take
some values as the passing arguments from the calling location. The execution of the function
logic is depends on another values, those values are require from the calling location. Then
the values are sending to the function as the passing arguments. General format of this type
is:
                       void function name( arguments list);
       example:        void addition(int x,int y)
                       {
                              printf(“Sum = %d”,x+y);
                       }
                       {
                              int a=5,b=10;
                              addition (a,b); (calling environment)
                              ----------------
                       }

       In the above type void represents, function doesn’t return any value to the calling
location. Function requires two integer values as the passing arguments from the calling
location.


3. Functions have Return type and No passing arguments:
       In this type the function return one value to the calling location, the function doesn’t
take any values as the passing arguments from the calling location. The return value type is
specified in front of the function name. The return value type must be scalar or derived data
type. Then the function returns a value to the calling location with the help of keyword
‘return’ this keyword is placed in the body of the function. When the compiler read this
return keyword the control goes to the calling location. General format of this type is:




                                               52
Programming in ‘C’


                       data type funvtion name( )
                       {
                               -----------
                               return variable;
                       }
       Example:        int addition( );
                       {
                               int c; ---------
                               return c;
                       }
                       {
                               int c=addition( );        (calling environment)
                       }

       In the above function the return value of the function is ‘int’ type. The function
returns a ‘int’ value in the variable ‘c’. Specified return type of the function should be same
as the return value data type of the function. In the calling location, the return value will be
stored into a variable. These types of functions are involved into an expression in the calling
location.


4. Functions have Return value and Passing values:
       In this type functions return one value to the calling location and the functions
required some values as the passing arguments. This type is the combination of 2nd and 3rd
type of the functions. General format of this type is:
                       Data type function name( arguments list)
                       {
                               ----------
                               return variable;
                       }
       Example:        int addition(intx,int y)
                       {
                               return x+y;
                       }
                       {
                               int c=addition(5,6); (calling environment)
                       }




                                               53
Programming in ‘C’


       In the above type the function return an ‘int’ type value, the function requires two
‘int’ values as the passing arguments from the calling location. The return value of the
function is stored into ‘int’ variable c. These types of functions are involved into an
expression in the calling location.
       The following conditions must be satisfy when the function require values from the
calling location.

   1. Numbers of arguments specified in the calling location is must be same as the number
       of variables declared in the function definition.

   2. Data type’s of the variables in the calling location is must be same as the data types of
       the variables declared in the function definition.


Parameter passing mechanism in functions:
       The arguments passing to the functions are classified into tow types, they are formal
arguments and actual arguments. The variables declared in function definition are called
formal arguments. The variables given to the function in the calling location is called actual
arguments.
       In functions, some times the function requires values in the variables as the passing
arguments; some times it requires address of the variables as the passing arguments. Based on
these, C-language provides two types of mechanisms for passing arguments:

       1. Call y value (or) passing arguments by values.

       2. Call by references (or) passing arguments by references.


1. Call by value (or) passing arguments by values.
       In this type the values in the variables as the passing arguments to the function
definition. Here we can write the names of the variables or values in function calling, the
compiler transfer the values in the variables to the function definition. When ever we modify
the values in formal arguments the actual arguments are not affected. Changes are made only
on formal arguments because we can pass the values in the variable.




                                               54
Programming in ‘C’


General format of the call by value method:
                       main( )
                       {
                                 --------
                                 Function name( variable names); (calling location)
                                 ----------
                       }
                       return type function name(formal variables declaration)
                       {
                               -------
                               -------
                       }
       Example:
                       main()
                       {
                                 int a=10,b=20;
                                 swap(a,b);
                                 printf(“%d%4d”,a,b);
                                 getch();
                     }
                     void swap(int x,int y)
                     {
                            int c;
                            c=x;
                            x=y;
                            y=c;
                     }
       Observe the above function; it can get two integer values as the passing arguments
from the calling location. Those two values will be stored into the formal arguments of the
function. The function definition can interchange the values in the formal arguments but the
value in the actual arguments doesn’t change. Why because, formal arguments are local
variables to that function, the scope of the local variables is with in the declared function.
Example program for call by value mechanism:
               void add(int x,int y)
               main()
               {
                      int a,b,c=0;
                      clrscr();
                      printf(“Enter 2 numbers:”);


                                                55
Programming in ‘C’


                        scanf(“%d%d”,&a,&b);
                        add(a,b,c);
                        printf(“nSum of %d, %d is %d”,a,b,c);
                        getch();
               }
               void add(int x,int y,int z)
               {
                      z=x+y;
               }
       In the above program add function can perform addition operation on two numbers.
This function can take three integer numbers as the passing arguments from the calling
location. Two values are used for addition operation, third variable is for storing result. In the
function definition adds value in the ‘x’ with value in the ‘y’ and store result in to variable
‘z’, but the value in the actual variable doesn’t change. This is the main disadvantage in call
by value mechanism.


Call by reference (or) passing arguments by reference:
       In call by reference mechanism we can pass address of the variables as the passing
arguments to the function definition. In this type we can write address of the variables in the
calling location (when ever & symbol place before the variable it can represents the address
of the variable), the control sends the address of the variables to the function definition. The
function definition can get that variable address, by declaring pointer variables. In this type
function can perform different operations on the formal arguments the effect will be place on
the actual arguments.
General format of the call by reference method;
                        main( )
                        {
                                  --------
                                  Function name(address of the varables); (calling location)
                                  ----------
                        }
                        return type function name(pointer variables)
                        {
                                -------
                                -------
                        }



                                                 56
Programming in c
Programming in c
Programming in c
Programming in c
Programming in c
Programming in c
Programming in c
Programming in c
Programming in c

More Related Content

What's hot

What's hot (20)

C++ presentation
C++ presentationC++ presentation
C++ presentation
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
Introduction to c language | History of C language
Introduction to c language | History of C languageIntroduction to c language | History of C language
Introduction to c language | History of C language
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
C notes
C notesC notes
C notes
 
Storage classes in c language
Storage classes in c languageStorage classes in c language
Storage classes in c language
 
C++ programming
C++ programmingC++ programming
C++ programming
 
C# programming language
C# programming languageC# programming language
C# programming language
 
C presentation book
C presentation bookC presentation book
C presentation book
 
Chapter 4 5
Chapter 4 5Chapter 4 5
Chapter 4 5
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
How to execute a C program
How to execute a C  program How to execute a C  program
How to execute a C program
 
C LANGUAGE NOTES
C LANGUAGE NOTESC LANGUAGE NOTES
C LANGUAGE NOTES
 
Literals,variables,datatype in C#
Literals,variables,datatype in C#Literals,variables,datatype in C#
Literals,variables,datatype in C#
 
pdf c programming language.pdf
pdf c programming language.pdfpdf c programming language.pdf
pdf c programming language.pdf
 
Lecture 1- History of C Programming
Lecture 1- History of C Programming Lecture 1- History of C Programming
Lecture 1- History of C Programming
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
C language industrial training report
C language industrial training reportC language industrial training report
C language industrial training report
 
Introduction to c++ ppt
Introduction to c++ pptIntroduction to c++ ppt
Introduction to c++ ppt
 

Viewers also liked

gopal Ramesh Lekhak Resume - Final-gopal Ramesh Lekhak Resume - Final-gopal R...
gopal Ramesh Lekhak Resume - Final-gopal Ramesh Lekhak Resume - Final-gopal R...gopal Ramesh Lekhak Resume - Final-gopal Ramesh Lekhak Resume - Final-gopal R...
gopal Ramesh Lekhak Resume - Final-gopal Ramesh Lekhak Resume - Final-gopal R...Gopal Lekhak
 
Senior low level C developer
Senior low level C developerSenior low level C developer
Senior low level C developerNitin Cunha
 
Mohammed Nissar C S(Mobile Application Developer)
Mohammed Nissar C S(Mobile Application Developer)Mohammed Nissar C S(Mobile Application Developer)
Mohammed Nissar C S(Mobile Application Developer)Mohammed Nissar C S
 
C programming language Reference Note
C programming language Reference NoteC programming language Reference Note
C programming language Reference NoteChetan Thapa Magar
 
Erica C. Sutherlin Resumes
Erica C. Sutherlin ResumesErica C. Sutherlin Resumes
Erica C. Sutherlin ResumesErica Sutherlin
 
MikeHallMarch2016
MikeHallMarch2016MikeHallMarch2016
MikeHallMarch2016Mike Hall
 
Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)Saket Pathak
 
C programming project by navin thapa
C programming project by navin thapaC programming project by navin thapa
C programming project by navin thapaNavinthp
 
C++ project on police station software
C++ project on police station softwareC++ project on police station software
C++ project on police station softwaredharmenderlodhi021
 
Ryan jarrell resume
Ryan jarrell resumeRyan jarrell resume
Ryan jarrell resumeRyan Jarrell
 
Compilation of previous board examination questions
Compilation of previous board examination questionsCompilation of previous board examination questions
Compilation of previous board examination questionsRhem Rick Corpuz
 

Viewers also liked (15)

C Unix Developer
C Unix DeveloperC Unix Developer
C Unix Developer
 
gopal Ramesh Lekhak Resume - Final-gopal Ramesh Lekhak Resume - Final-gopal R...
gopal Ramesh Lekhak Resume - Final-gopal Ramesh Lekhak Resume - Final-gopal R...gopal Ramesh Lekhak Resume - Final-gopal Ramesh Lekhak Resume - Final-gopal R...
gopal Ramesh Lekhak Resume - Final-gopal Ramesh Lekhak Resume - Final-gopal R...
 
Senior low level C developer
Senior low level C developerSenior low level C developer
Senior low level C developer
 
Mohammed Nissar C S(Mobile Application Developer)
Mohammed Nissar C S(Mobile Application Developer)Mohammed Nissar C S(Mobile Application Developer)
Mohammed Nissar C S(Mobile Application Developer)
 
C programming language Reference Note
C programming language Reference NoteC programming language Reference Note
C programming language Reference Note
 
Erica C. Sutherlin Resumes
Erica C. Sutherlin ResumesErica C. Sutherlin Resumes
Erica C. Sutherlin Resumes
 
MikeHallMarch2016
MikeHallMarch2016MikeHallMarch2016
MikeHallMarch2016
 
CV Juhani Polvi
CV Juhani PolviCV Juhani Polvi
CV Juhani Polvi
 
Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)
 
C Programming
C ProgrammingC Programming
C Programming
 
Latest Resume C#,C++ Developer
Latest Resume C#,C++ DeveloperLatest Resume C#,C++ Developer
Latest Resume C#,C++ Developer
 
C programming project by navin thapa
C programming project by navin thapaC programming project by navin thapa
C programming project by navin thapa
 
C++ project on police station software
C++ project on police station softwareC++ project on police station software
C++ project on police station software
 
Ryan jarrell resume
Ryan jarrell resumeRyan jarrell resume
Ryan jarrell resume
 
Compilation of previous board examination questions
Compilation of previous board examination questionsCompilation of previous board examination questions
Compilation of previous board examination questions
 

Similar to Programming in c

Std 10 computer chapter 10 introduction to c language (part1)
Std 10 computer chapter 10 introduction to c language (part1)Std 10 computer chapter 10 introduction to c language (part1)
Std 10 computer chapter 10 introduction to c language (part1)Nuzhat Memon
 
INTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdfINTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdfSubramanyambharathis
 
Intoduction to c language
Intoduction to c languageIntoduction to c language
Intoduction to c languageStudent
 
C programming slide day 01 uploadd by md abdullah al shakil
C programming slide day 01 uploadd by md abdullah al shakilC programming slide day 01 uploadd by md abdullah al shakil
C programming slide day 01 uploadd by md abdullah al shakilZenith SVG
 
Introduction to C Programming Language.pptx
Introduction to C Programming Language.pptxIntroduction to C Programming Language.pptx
Introduction to C Programming Language.pptxAnithaTAssistantProf
 
Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 7Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 7Shipra Swati
 
Unit-2_Getting Started With ‘C’ Language (3).pptx
Unit-2_Getting Started With ‘C’ Language (3).pptxUnit-2_Getting Started With ‘C’ Language (3).pptx
Unit-2_Getting Started With ‘C’ Language (3).pptxSanketShah544615
 
C Unit 1 notes PREPARED BY MVB REDDY
C Unit 1 notes PREPARED BY MVB REDDYC Unit 1 notes PREPARED BY MVB REDDY
C Unit 1 notes PREPARED BY MVB REDDYRajeshkumar Reddy
 
C Programming UNIT 1.pptx
C Programming  UNIT 1.pptxC Programming  UNIT 1.pptx
C Programming UNIT 1.pptxMugilvannan11
 

Similar to Programming in c (20)

C lecture notes new
C lecture notes newC lecture notes new
C lecture notes new
 
Std 10 computer chapter 10 introduction to c language (part1)
Std 10 computer chapter 10 introduction to c language (part1)Std 10 computer chapter 10 introduction to c language (part1)
Std 10 computer chapter 10 introduction to c language (part1)
 
Introduction to c language
Introduction to c language Introduction to c language
Introduction to c language
 
CS3251-_PIC
CS3251-_PICCS3251-_PIC
CS3251-_PIC
 
INTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdfINTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdf
 
Intoduction to c language
Intoduction to c languageIntoduction to c language
Intoduction to c language
 
C programming slide day 01 uploadd by md abdullah al shakil
C programming slide day 01 uploadd by md abdullah al shakilC programming slide day 01 uploadd by md abdullah al shakil
C programming slide day 01 uploadd by md abdullah al shakil
 
Introduction to C Programming Language.pptx
Introduction to C Programming Language.pptxIntroduction to C Programming Language.pptx
Introduction to C Programming Language.pptx
 
Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 7Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 7
 
Programming in c
Programming in cProgramming in c
Programming in c
 
Programming in C
Programming in CProgramming in C
Programming in C
 
C.pdf
C.pdfC.pdf
C.pdf
 
Unit-2_Getting Started With ‘C’ Language (3).pptx
Unit-2_Getting Started With ‘C’ Language (3).pptxUnit-2_Getting Started With ‘C’ Language (3).pptx
Unit-2_Getting Started With ‘C’ Language (3).pptx
 
C programming
C programming C programming
C programming
 
C programme presentation
C programme presentationC programme presentation
C programme presentation
 
C language
C languageC language
C language
 
C Unit 1 notes PREPARED BY MVB REDDY
C Unit 1 notes PREPARED BY MVB REDDYC Unit 1 notes PREPARED BY MVB REDDY
C Unit 1 notes PREPARED BY MVB REDDY
 
Unit 1
Unit 1Unit 1
Unit 1
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
C Programming UNIT 1.pptx
C Programming  UNIT 1.pptxC Programming  UNIT 1.pptx
C Programming UNIT 1.pptx
 

Recently uploaded

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 

Recently uploaded (20)

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 

Programming in c

  • 1. Programming in ‘C’ Programming in C Introduction C is a programming language. It was developed by Dennis Ritchie at AT&T bell laboratories in the early 1970’s. C was an offspring of the Basic Combined Programming Language (BCPL) called B language. C language was designed from B language by adding some modifications to the B language. But C language compilers were not readily available for commercial use out side of the bell laboratories. So many programmers preferred C to older languages like FORTRAN or PL/I of the newer ones like PASCAL and APL. Why c seems so popular is because it is reliable, simple, easy to use and easy to learn. First time C language compilers are available for UNIX operating system. The first C programming text is written by Brian Kernighan and Dennis Ritchie but this book not provides complete information about C. In 1983’s American National Standards Institute (ANSI) is the organization forms a committee for development of C language. ANSI C committee releases standardized definition of C in 1990. International Standard Organization (ISO) is also involved soon for development of C, because most of the world uses c language. C is a general purpose, structured programming language. C combines elements of high level language with functionalism of assembly level languages (low level languages) so we say C language is a middle language. Features of C language:  Programs written in ‘C’ are efficient and fast. This is due to its variety of data types and power full operators.  There are only 32 keywords and its strength lies in its built-in-functions.  Several standard functions are available witch can be used for developing programs.  C language is well suited for structured programming, thus requiring the user to think of problem in terms of `functions’ of ` modules’. A proper collection of these modules of function would make a complete program. This modular structure makes program debugging, testing and maintenance easier.  A c program is basically collection of functions that are supported by the C library. With the availability of a large numbers of functions, the programming task becomes simple. 1
  • 2. Programming in ‘C’  C programs are highly portable. Portable means a C program written in one environment(O S) can run or executed in another environment with less or with out modifications.  C language is also called middle level language. Because it has both features of high level as well as low level language.  C is applied in system programming like operating systems, assemblers, language compilers, text editors and network devices.  Using c we can solve scientific, business, mathematical, research applications.  C language has an important facility called extendibility. It means you can write your own file and include in other programs. C fundamentals: Programming: Programming is a process to solve a particular problem by using the computer. When ever we need to computerize a particular, we have to solve those problems and write these solutions in the computer understandable code with the help of programming languages. Program: A program is a group of instructions which is used to perform particular task. The task’s like big number out of two numbers, billing process of a hotels or etc… Instruction: It is command given to the computer to perform any operation. These instructions may be addition, subtraction, relation between two numbers etc… Algorithm: A step by step procedure use to perform any task is called algorithm. Step by step represent of a program in general format is called algorithm. Flow chart: A pictorial representation of an algorithm is called flow chart. It can also show the flow of the program. Here we can use several symbols for several works in a program. These instructions and programs can be written in different languages like C, C++, java etc… these languages are called program languages. 2
  • 3. Programming in ‘C’ Example of an algorithm: To find a number is an even or odd. Step1. Start. Step2. Take a number ‘N’. Step3. Divide the number by 2 => N/2. Step4. If the reminder is ‘0’ then goto Step5 other wise goto Step6. Step5. Print the number is even. goto Step7. Step6. Print the number is odd. Step7. Stop. High level languages: Initially (olden days) the computer programs were written in machine level languages like binary language. Write a program in binary language and learning binary language is very difficult. Later assembly languages were developed, with which a programmer can work with the machine slightly higher level. Assembly language: It is one of the programming languages. This is an advanced programming language than binary language. Write a program in assembly language is nothing; arrange the instructions in a sequence order to complete the task. In this language we can write instructions instead of sequence of binary numbers in binary language. Here instructions are represented in the form of symbolic names like ‘add’,’sub’, etc…. Assembler: An assembler is used to convert the assembly language program into binary language or specified machine instructions. By using assembly languages we can write different programs for different machines. A program write for one machine can not be run on another machine, so these languages are called machine dependent languages. Later these assembly languages are replaced by high level languages. The first high level language is FORTRAN (FORmula TRANsulator). One FORTRAN instruction or statement can be executed in different machines unlike assembly language instruction. Then high level languages ate called machine independent languages. 3
  • 4. Programming in ‘C’ Basic structure of a C-program: Documentation section Linking section Definition section Global value declaration main() { Local variable declaration part Executable statements } Sub program section function1() { Local variable declaration part Executable statements } . . function2() { Local variable declaration part Executable statements }………. Documentation Section: The documentation section consists of a set of comments. Here we mention the name of the program and also write the comments for our program. The comment text can be bounded with astricks (*) and enclose with in back slash (/). By using these characters we can write comments for specified statements in our program. /* The program for addition of two numbers */ Link Section: The link section provides instructions to the compiler to link function from the C-language library. In this section, we can write which header files are use in our program. #include<stdio.h> Definition Section: The definition section defines all symbolic constants. We can use these constants are use many times in our program. Which value is define in the definition section, we can not modify or redefine those values any where in the program. #difine pi 3.14 4
  • 5. Programming in ‘C’ Global Declaration Section: There are some variables that are used in more than one function. Such variable are called global variables and declared in the global declaration section that is outside of all the function. I int a,b; Main function section: Every C program must have one main() function. This section contains two parts, declaration part and execution part. The declaration part declares all the variables used in the executable part. There is at least one statement in the executable part. These two parts must appear between the opening and the closing braces. The program execution begins at the opening brace and ends at the closing brace. All statements in the declaration and executable parts end with a semicolon. main() Subprogram Section: The subprogram section contains all the user-defined functions that are called by the main function. User defined function are generally declare, after, end of the main function. A Function is a subroutine that may include one or more statements designed to perform a specific task Example program for structure of C-program: /* Example program */ /* Documentation section */ #include<stdio.h> /* Linking section*/ #define a 10 /* Definition section */ int b; /* Global variable declaration */ main() /* Main function */ { int c; b=10; c=a+b; printf(“Sum : %d”,c); sub(b); } void sub(int y) /* (Sub program or function) */ { int z; / * Local variable declaration for function */ z=a-y; printf(“Subt : %d”,z); } 5
  • 6. Programming in ‘C’ Compiling program: Compiling of c- program is nothing, to generate binary code file for our program to execute the program, with the help of compiler. Compiler: The compiler is a software program, used to convert the program into machine understandable code (binary code). The compiler analyzes a program, and then translates it into a form that is suitable to the running computer. The steps involved to create a program in C-language are entering program, compiling program and running program. The program is typed in the computer with the help of editor. Editor: Editors provide space to write our program in computer. We can also open the existed programs in the computer. The text editors are usually used to write C- programs in to file. Source program: The program that is entered into the file is known as the source program. Start Editor Source program Name.C Compiler Yes Errors? Object program No Name.obj Linker Library and other obj files Exicutable code Name.exe Execute No Result ok? Yes Start 6
  • 7. Programming in ‘C’ We have to follow several steps to write, compile and a program in C-programming language. They are:  Open the C-programming language editor.  Write your program or open an existing program in the system.  When you create a new program, you have to save the program with a specific name. We have to follow the naming conventions (rules) to give name for C-program.  Give the file name with the extension ‘.C’. This extension represents a file as a C- Program file.  After saving the program, compile the program. The compilation process depends on the editor or running machines operating system.  For example, if we want to run our program in dos operating system, we have to follow several steps to compile the program. o Go to compile menu in editor. o Then chose ‘compile to obj’ command or press ALT+F9 key combination from the key board. o The compiler will compile the program  The compiler will give the syntax errors in our program. If we have any errors or warnings we have to rectify the errors, then open our source program, correct the errors then do the compile process again.  When ever we have an error free program then the compiler can create a .OBJ(object) file for machine. It is also called binary code file.  After creating the .OBJ file then run the program, go to run menu and choose run command or press CTRL+F9 key combination from the keyboard.  When ever run a program the linker links the .OBJ file and library files then create .EXE (executable) file, execute the program by using this .EXE file. Linker: It also a software program. By using this compiler links the OBJ file and library files the produce executable file this process is called building.  When ever execute our program, the steps in the program is executed sequentially this process is called top down approach. If our program get any data from the user is called input, then process the input and displays result on the output screen. If the output is 7
  • 8. Programming in ‘C’ correct then completed our task other wise open the program change the logic according to our requirement. Integrated development environment (IDE): The process of editing, compiling, running and debugging program is often managed by a single integrated application is known as Integrated Development Environment (IDE). The IDE’s are differing from form one operating system to n other. Some windows based IDE’s are Turbo ‘C’, Turbo C++, Microsoft Visual Basics, Microsoft .NET, etc…. Debugging: In the program does not produce desired results, it is necessary to go back and reanalyze the programs logic this process is called debugging. By using this process we can remove bugs (problems) in the program. Language interpreters: Interpreters are another type used for analyzing and executing programs developed in high-level languages. Interpreters are analyzed and execution of statements in a program is same time. The method usually allows programs to be more easily debugging. Basic and java programming languages are use these interpreters for analyze and execution of programs. Character set: Character set means that the characters and symbols that a C program can accept. These are grouped to form the commands, expressions, words, C statements and other tokens for C language character set is the combination of alphabet or character, digit, special characters and white spaces. 1. Letters (A…….Z and a………z) 52 2. Digits (……9) 10 3. Special characters (. , ; : ? / < >….) 29 4. White spaces Blank, Horizontal tab, 5 Carriage return, new line, Form feeds 96 8
  • 9. Programming in ‘C’ C Tokens: In a passage of text, individual words and punctuation marks are called token. Similarly in a C program the smallest individual units are known as c tokens. C TOKENS Keywords Identifiers Constants Strings Operators Special symbols Float main 50.00 “computer” +-*/ { < [ ? …. Int a -21.43 “a” While cost 1. KEYWORDS: Every C word is classified as either a keyword or an identifier. All keywords have fixed meaning and these meanings cannot be changed. Keywords serve as basic building blocks for program statements. All keywords must be written in lower case. auto double int struct break else long switch case enum register typedef char exturn return union const float short unsigned continue for signed void default goto sizeof vollatile do if static while 2. IDENTIFIERS: Identifiers refer to the names of variables, function and arrays. These are user-defined names and consist of a sequence of letters and digits with as a first character. Identifier should not be a keyword. 9
  • 10. Programming in ‘C’ Variable: A variable is a data name that may be used to store a data value. A variable may take different values at different times during execution. The programmer can choose a variable name in a meaningful way. Rules for a variable:  The first character of the variable name should be a letter (alphabet).  A variable should not be a keyword.  A variable name can be of any length in recent compilers but some implementations of C recognize the first eight characters as the valid variable name.  No special characters are allowed in the variable name except underscore.  The blank space characters are also not allowed while constructing variable names.  Upped and lower case letters are different in variable names. Because C is case sensitive language.  It is always useful to give the meaningful names to the variables. Some valid variable names are. ROLLNO, Area, arc, n1, n_1, n1_n2…… 3. CONSTANTS: Constants in C refer to fixed values that do not change during the execution of a program. Constants Numbered constants Character constants Integer Float Single String Black slash Decimal Octal Hexa- decimal 10
  • 11. Programming in ‘C’ 1. Numeric constants: These have numeric value having combination of sequence of digits i.e from 0-9 as alone digits or combination of 0-9 ,with or without decimal Point having positive or negative sighn. These are further sub—divided into two categories as: a) Integer Numeric constant b) Float Numeric constant a) Integer numeric constant: Integer numeric constant have integer data combination of 0-9 without any decimal point and with any + or – sign. These are further sub-divided into three parts. Decimal integer consists of a set of digits 0-9, preceded by an optional – or + sign. Examples: q23 -321 +7546 Embedded spaces, commas and no-digit characters are not permitted . An octal integer constant consists of any combination of digits from 0 to 7, with a leading 0. A sequence of digits proceeding by OX or ox is considered as hexadecimal integer. They may also include alphabets ‘A’ through ‘F’ or ‘a’ through ‘f’. The letter ‘A’ through ‘F’ represents the numbers 10 through 15. Examples: OX2 Ox9F Oxbcd Note: We rarely use octal and hexadecimal numbers in programming. b) Float Numeric constant Some constants which have a decimal point or a precision value with in having any positive or negative sign is called floating point constant . Float constants has two parts. One is mantissa and the other is exponent pat. These two parts in a real number are represented as: Mantissa E exponent 11
  • 12. Programming in ‘C’ The mantissa is either a real number expressed in decimal notation or an integer. The exponent is an integer umber with an optional + or – sign. The letter E separating the mantissa and the exponent can be written in either lowercase or uppercase. Example: 3.5x102 can be written as 3.5E2 2). Character constant: a) Single character constant: It contains a single character enclosed within a pair of single quote marks. Example: “Hellow” “2007” “X” “9+22+17” b) String character constant: String constant is a sequence of characters enclosed in double quotes. The characters may be letters, umbers special characters and blank space. Example: “hallow” “2007” “x” “9+22+65” c) Backslash characters: C supports some backslash character constants that are used in output functions. These character combinations are known as escape sequence. Constant Meaning ‘a’ Audible alert (bell) ‘b’ Back space ‘n’ New line ‘t’ Horizontal ‘0’ Null 4. OPERATORS: An operator is a symbol that tells the computer to perform certain mathematical manipulations. Types of Operators: 1. Arithmetic 2. Relational 3. Logical 4. Assignment 5. Increment and decrement 6. Conditional 7. Bitwise 8. Special 12
  • 13. Programming in ‘C’ 1. Arithmetic Operators: Arithmetic operators are Operator Meaning used for arithmetic operations like Addition, + Addition Subtraction, Multiplication, Division etc. - Subtraction If all operands are integers, the result is an * Multiplication integer. / Division If an operand is a floating point or double % Modulo Division (Remainder precision value, the result is a double. after division) 2. Relational Operators: We often compare two Operator Meaning quantities, and depending on their relation, take < Is less than certain decisions. These comparisions can be done <= Is less than or equal to with the help of relational operators. Containing a > Is greater than relation operator is termed as a relational expression >= Is greater than or equal to is either 1(true) or (false). == Is equal to != Is not equal to Operator Meaning 3.LogicalOperators:Anexpression,which combines && AND two or more relational expression, is termed as a logical expression. || OR ! NOT Logical Table: A B A AND B A OR B NOT A T T T T F T F F T F F T F T T F F F F T 4. Assignment Operator (=): Assignment operators are used to assign the result of an expression to a variable. Syntax: variable=expression Where, expression is whose value is to be assigned to the variable. Examples: a=10 b=20 sum= a+b 13
  • 14. Programming in ‘C’ 5. Increment and decrement Operators: The operators ++ adds 1 to the operand and the operator – subtracts 1 from operand. We use the increment and decrement statements are use in for and while loops extensively. Example: A prefix operator first adds 1 to the operand and then the result is assigned to the variable on left. m=5; Y=++m; In this case the value of y and m would be 6. A postfix operator first assigns the value to the variable on the left and the increment the operand. m=5; Y=m++; In value of y would be 5 and m would be 6. 6. Conditional Operator: A ternary operator pair ‘?:’ is available in C to construct conditional expressions of the form. Var1=condition? exp2: exp3; The operator ‘?:’ works as fallows condition is evaluated first. If it is nonzero (true) then the expression exp2 is evaluated and becomes the value of the var1. If condition is false, exp3 is evaluated and its value becomes to the value of the var1. Example: a=10; if(a>b) b=15; x=a; X=(a>b)?a:b; else x=b; 7.Bitwise Operators: C has a distinction of Operator Meaning supporting special operators for manipulation of & Bitwise AND data at bit level.These operators are used for | Bitwise OR testing the bits, or shifting them right or left. ^ Bitwise Exclusive OR These operators are not applicable to the float or << Bitwise Left double data types. >> Bitwise Right ~ Bitwise NOT 14
  • 15. Programming in ‘C’ 1. Bit wise AND: The bit wise AND operator is represented by the symbol &. When this operator is used, it compare the corresponding bits in the two operands and when they both are 1 then the corresponding bit in the result is 1, in all the other cases it is 0. Example: a=0 0 0 0 0 1 0 1 b=0 1 0 1 0 1 1 1 a&b=0 0 0 0 0 1 0 1 2. Bit wise OR: The bit wise OR operator is represented by the symbol |. When this operator is use d, it compare the corresponding bits in the 2 operands and when they both are 0 then the corresponding bit in the result is 0, in all the other cases it is 1. Example: a=0 0 0 0 0 1 0 1 b=0 1 0 1 0 1 1 1 a | b=0 1 0 1 0 1 1 1 3. Bit wise Exclusive OR: The bit wise OR operator is represented by the symbol ^. When this operator is used, it compare the corresponding bits in the 2 operands and when they both are either 0 or 1 then the corresponding bit in the result is 0, in all the other cases it is 1. Example: a=0 0 0 0 0 1 0 1 b=0 1 0 1 0 1 1 1 a^b=0 1 0 1 0 0 1 0 4. Bit wise NOT: The bit wise NOT operator is represented by the symbol ~. When this operator is used, in inverts each bit in the operand. In other words, each 0 in the operand is changed to 1 and vice-versa. Example: a=0 0 0 0 0 1 0 1 ~a=1 1 1 1 1 0 1 0 5. Right Shift: It has the purpose to transfer the bits of data to the right side. It is a binary operator that is it has two operands. The left operand is the data and the right operand is the number of times the shift operation to be done. Example: a= 0 0 0 0 0 1 0 1 a>>2= 0 0 0 0 0 0 0 1 15
  • 16. Programming in ‘C’ Hence, the least significant bit will be discarded and the most significant bit will come out to be 0. 6. Left Shift: It has the purpose to transfer the bits of data to the left side. It is a binary operator i.e. it has two operands. The left operand is the data and the right operand is the number of times the shift operation to be done. Example: a= 0 0 0 0 0 1 0 1 a<<2=0 0 0 1 0 1 0 0 Hence, the most significant bit will be discarded and the least significant bit will come out to be 0. 8. Special Operator: These are used for special purpose in C language. These operations are used in pointers, structures and unions etc. 1. Unary operator 2. Comma operator 3. Sizeof() Operator 4. Type operator 5. Pointer operator 6. Member selection operator 1. Unary Operator: These are used for identification of about where it is signed or unsigned. These are + and -. Also increment or decrement operators ++, -- are in the unary operator category as special operator. Example: x=-3; y=++x-7*3 2. Comma operator: The comma operator can be used to link the related expression together. A comma linked list of expression is evaluated left to right and the values of right most expression is the value of the combined expression. Example: z=(x=10,y=5,x+y); First assigns the value 10 to x, then assign 5 to y and finally 15 to z. 16
  • 17. Programming in ‘C’ 3. Size of ()operator: The sizeof() is a compile time operator and, when used with an operand, it returns the number of byte the operand occupies. The operand may be a variable, a constant or a data type qualifier. Syntax: Variable=sizeof(v or e) Example: int a; K=sizeof(a) the value of k is 2 (because a occupies two bytes of memory) 4. Type operator: Type operator is used for conversion purpose or casting purpose. So it is called convert operator. This operator converts float type data into integer form and vice-versa. It is used for casting a value and process to convert from 1 form to another is called casting. Syntax: (Type)v or e; where v is variable e is an expression Example: int a=10, b=3; float c; C=a/b; If we divide a by b, then result stored in the c variable be 3.000000. But by using the type operator, we can get the float value as C=(float) a/b; Now c value is 3.333333 5. Pointer operator: There are two types of pointer operators used in C language. These are & and *. 6. Member selection operator: There operators are used in structure and union. These are used to create a relation between owner and member within a structure or union data. These are “.” and . 17
  • 18. Programming in ‘C’ DATA TYPES: C language is rich in its data types. ‘C’ language supports the following data types. DATA TYPES Scalar Derived User Void Pointer Defined Char array or string enum Integer structure Float union typedef Double 1. Scalar/ standard/ primary/ fundamental data types: A scalar data type is used for representing a single value only. It is only called simple or fundamental data type. Size and range of basic data types: Data type Size Range of value char 1 byte -128 to 127 int 2 bytes -32,768 to 32,767 float 4 bytes 3.4e-38 to 3.4+38 double 8 bytes 1.7e-308 to 1.7e+308 2. Derived data types: Derived data types are derived from the scalar data type by adding some additional relationship with the various elements of the primary or scalar data types. Note that derived data type may be used for representing a single value or multiple values. These are further sub divided into three categories. 1. Array and strings 2. Structures 3. Unions (a). Arrays: An Array is nothing but a collection of sequence of homogeneous(similar) data type elements. Declaration of an array: Data type variable-name [size]; Where datatype can be any primary or secondary datatypes. Size is any integer. Example: int a[50]; 18
  • 19. Programming in ‘C’ (b). Structure: A Structure is nothing but a collection of heterogeneous (different) datatypes of elements. Declaration of structure: Struct tage_name { datatype field1; datatype field2; ……………… datatype field n; }; Where tagename is the name of the structure / datatype can be any primary or secondary datatype. Example: struct student { int sno; char name[10]; float m1,m2,m3; }; Once the structure data type is defined, the variable of that datatype can be declared of follows. Syntax: struct tagname variablelist; Example: struct student s; 3. User defined type: This is also used for definition, i.e. it allows the users to define a variable or an identifier, which is used for representation of existing data types. a) enum: Another user defined data type is enumerated data type provided by ANSI standard. Syntax: enum identified {value1, value2…..} variable; The identifier is a user- defined enumerated data type, which can be used to declare variables that can have one of the values enclosed within the braces known as enumeration constant. Example: enum day{Monday, Tuesday, Wednesday,..} d; 19
  • 20. Programming in ‘C’ b). type def: Supports a feature know “type definition” that allows user to define an identifier that would represent an exiting data type. The user-defined data type identifier can later to declare variable. Syntax: typedef data_type identifier; Where type represents the data type of the identifier refers to the ‘new’ name giving to the date type. Ex: typdef int marks; Here marks symbolize int. they can be later used to declare variable as follows. marks m1,m2; m1,m2 are declared as int variable. The main advantage of typedef is that we can create meaningful data type names for increasing the readability of the program. 4. Void: Void or empty data type is used in user defined function or user defined sub programs. These are used when the function sub-program returns nothing to the calling location. Also it is used when a function or a sub-program have not any argument in it. 5. Pointer data type: Pointer data type is used to handle the data at their memory address. Input / output functions In ‘C’ language I/O functions are categorized into following two types. Input/output functions UnFormatted I/O Formatted I/O statements statements getchar(); putchar(); scanf(); printf(); gets(); puts(); getch(); getche(); 1. Formatted I/O statements: All input/output operations are carried out through function calls such as printf and scanf there exist several functions that have more or less become standard for input and output operations in C. There functions are collection known as the standard i/o library. 20
  • 21. Programming in ‘C’ #include<stdio.h> The instruction <stdio.h> tells the compiler to search for a file stdio.h and place it’s contents at this point in the program. The content of the header file become part of the source code when it is compiled. Conversion character Meaning %d Integer %f Float %c Character %s String %lf Double a). scanf(): The scanf() function is an input function. It used to read the mixed type of data from the keyboard. You can read integer, float and character data by using its control codes or format codes. Syntax: scanf(“control string”,&v1,&v2…); The control string contains the format of data being received. The ampersand symbol ‘&’ before each variable name is an operator that specifies the address of variable v1. Example: scanf(“%d”,&n); The control string %d specifies that an integer value is to be read from the terminal (keyboard). b). printf(): printf() fiunction for printing captions and numerical results the general form of printf statement is…. printf(“controle string”,arg1,arg2…); control string consists of three types of items:  Characters that will be printed on the screen as they appear.  Format specifications that define the output format for display of each item.  Escape sequence character such as n,t….. the control string indicates how many arguments follow and what their types are the argument arg1,arg2… are the variable whose values are formatted and printed according to the specification of control string. 21
  • 22. Programming in ‘C’ 2. Unformatted I/O statements: These functions are used to read or print the data in unformatted way. These are also called as character I/O functions. The following are the character I/O functions. Input functions output functions getchar(); putchar(); getche(); putc() getch(); gets(); a). getchar(): This is an input function. It is used for reading a single character from the keyboard. It is buffered function. Bu8ffered functions get the input from the keyboard and store it in the memory temporarily until you press the enter key. After you pressed the enter key then input move to a relevant variable. Syntax: v=getchar(); Example: char a; a=getchar(); b). gets(): This is an input function. It is used for read a string from the keyboard. It is a buffered function it will read a string, when you type the string from the keyboard and press the enter key from the keyboard. It will mark null character (‘0’) in the memory at the end of the string, when you press the enter key. Syntax: gets(v); Example: char s[20]; gets(s); c) getch(): This is also an input function. This is used to read a single character from the keyboard like getchar() function. But getchar() function is a buffered function; getch() function is a non buffered function. When type the character data from the keyboard it does not visible on the screen. Syntax: v=getch(); d). getche(): All are same as getch() function except that when you type the character data from the keyboard it will be visible on the screen. Syntax: v=getche(); e). putchar(): 22
  • 23. Programming in ‘C’ This function is an output function. It is used to display a single character on the screen. Syntax: putchar(v); Example: char a; getchar(a); f). puts(): This function is an output function . It is used to display a string inputted by gets() function, which you will read in the next on the screen. Syntax: puts(v); or puts(“text); Example: char a[10]; gets(a); Control statements: Normally C-compiler executes all the statements in the program sequentially in top down process. In C-language some times we have to control the execution of program, Some times the program executes some group of statements in the program, some other time another group of statements in the program comes for execution. When ever the program needs this type of situation, place some condition statements in the program. Those conditions are made with the help of relational operators. The condition will execute and returns the value 1 (TRUE) or 0 (FALSE) to specified location, where the condition place in the program. C-language provides several types of decision making or control statements. They are: 1. If 2. Switch 3. looping statements. IF conditional statement: ‘ If ’ it is one of the keyword in the C-language, by using this we make some controls on the execution of program. The general syntax of the ‘if’ is: if(condition) { Executable Statements; } 23
  • 24. Programming in ‘C’ In the above syntax ‘if ‘ is a key word. The condition is following by the keyword if. When ever the condition comes to execution, if the given condition true, it will return 1 to if statement. If the given condition is false, it will return 0 to if statement. We have several form of if statements in C-language. They are: 1. Simple if. 2. if else. 3. else if or else if ladder. 4. Nested if. 1. Simple if: In simple if, the given condition is true, then some statements in program will come for execution other wise normal statements will execute. The general syntax of the simple if is: --------------- if(condition) Texst No exp { Yes Stament1; Statements } In the above syntax the condition following by the keyword ‘ if ‘. The executable statements are enclosing with opening and closing curling braces ({). The compiler identifies, those statements are comes under if block. When ever the condition in the ‘if’ statement is true it will return 1 to for if statement, other wise it returns 0 for ‘if’ statement. The given condition is true, then the given statements (statement1) in the ‘if’ part will come for execution other statement1 absence in the execution, the compiles goes to execution of normal statements in the program. Example program on simple if condition: #include<stdio.h> main() { int num; clrscr(); 24
  • 25. Programming in ‘C’ printf(“Enter your number”); scanf(“%d”,&num); if(num>0) { printf(“ given number is +ve :”); } printf(“Given number is : %d”, num); getch(); } 2. if else conditional statement: It is also one of the conditional statements in the C-language. If else is the extension of the simple if. The general syntax of the ‘if else’ conditional statement is: --------------- if(condition) Texst No exp { Yes Stament1; Statement1 Statement2 } else { Statement2; } ---------------- In the above syntax, if else statement having condition following the keyword if. The ‘if’ else statement is divided in to two parts, one is if (TRUE) part and another one is else (FALSE) part. If the given condition is true, then if part statements (Statement1) will comes for execution. If the given condition is false, then else part statements (Statement2) will comes for execution. When ever the first if statement succeeds, the second must fail, and vice versa. In this if else conditional statement either if part statements or else part statements only comes for execution another one absence in the execution time. When ever the C-program having two 25
  • 26. Programming in ‘C’ options for execution we use this is else statement. If the ‘if’ part or else part having single statement, opening and closing curling braces are optional. Example program for if else if: #include<stdio.h> main() { int num; clrscr(); printf(“Enter your number”); scanf(“%d”,&num); if(num%2= =0) { printf(“ %d is even number”, num); } else { printf(“%d is odd number”, num); } getch(); } 3. else if or else if ladder: When ever the C-program needs to check or build the conditions in different levels else if ladder type is used. In this else if type, the main if having condition, if the if part condition is fail, the else part having another condition, if the else if part condition fail then else part having another condition… then the conditions are arranger in the ladder or chain format. The else if conditional statement having common else for the all the else if statements, if all conditions in the else if are fail then else part will executes, this else part is optional. The general syntax of the else if conditional statement is: 26
  • 27. Programming in ‘C’ --------------- if(condition1) Texst No exp { Yes Stament1; Texst No exp Statement1 } Yes else if(condition2) Statement2 Statement3 { Statement2; } else This else part is optional { Statements3; } ---------------- The above syntax represents the else if conditional statement arrangement. The condition1 following main if, if the condition1 is true then if part statements (Statement1) will come for execution. If the if part condition is false then the compiler will check the next else if part condition, if it is true then the compiler will executes statements2 in the else if part, if it will also false then compiler check the next condition. In this way the compiler will check all the sequence of else if conditions in the program, all the conditions are false then default else part statements (Statements3) will comes for execution. Example program for else if statement: #include<stdio.h> main() { int n1,n2,n3; 27
  • 28. Programming in ‘C’ clrscr(); printf(“Enter 3 number”); scanf(“%d%d%d”,&n1,&n2,&n3); if((n1>n2)&&(n1>n2)) { printf(“ %d is big number”,n1); } else if(n2>n3) { printf(“ %d is big number”,n2); } else { printf(“ %d is big number”,n3); } getch(); } 4. Nested if conditional statement: When ever the C-program need to check the conditions, condition with in the conditions, use this nested if conditional statement. In this nested if conditional statement all the conditions or some conditions are arrange in nested form. May be the main if or else part body having another if of if else statement. The general syntax of the nested if is: ---------------- if(condition1) { if(condition1) { Statement1; 28
  • 29. Programming in ‘C’ } else This else part is optional { Statement2; } } --------------- The syntax represents the nested if conditional statement. The main if body having another if condition, in this we place number of if conditions as condition with in the condition. If all the given conditions in the ‘if’ part will true then only the statement1 will come for execution, other wise it will execute the normal program. If the main if is false then only the else part will come for execution, if inner most condition of the main if is false, then the compiler goes to after the else part statements execution. Example program for nested if conditional statement: #include<stdio.h> main() { int n1,n2,n3; clrscr(); printf(“Enter 3 number”); scanf(“%d%d%d”,&n1,&n2,&n3); if((n1>n2)) { if(n1>n3) { printf(“ %d is big number”,n1); } else { printf(“ %d is big number”,n3); } } else { 29
  • 30. Programming in ‘C’ if(n2>n3) { printf(“ %d is big number”,n2); } else { printf(“ %d is big number”,n3); } } getch(); } Compound relation test: A compound relation test is a simple way to combine more then one conditions or relations, with the help of logical operators. Those logical operators are; and (&&), or( || ). Syntactical representation of the compound relations are. ((condition1)&&(condition2)…..) ((condition1)||(condition2)…..) These compound relations are used with the “if” conditional statement. Example: if((a>b)&&(a>c)) if((a>b)||(a>c)) { { Statement1; Statement2; } } The above example shows the compound relation of the condition. The a>b and a>c are two individual conditions we can combine these two conditions with help of logical and, or operators, it form a single condition statement. 2. Switch conditional statement: The switch statement is used to execute single statement or choices form many statements or many choices. In this switch each choice can be represented with case of the switch statement. The switch, case, default these three key words are arranged correctly, then if will form a control statement. 30
  • 31. Programming in ‘C’ The general form of the switch conditional statement is: switch( variable or integer expressions) { case constant1: statement1; break; case constant2: statement2; break; default: statement n; } The switch is a keyword. The switch statement requires single variable or integer expression as arguments. The keyword case is followed by an integer or character constant (1,2,3…., ‘a’,’b’,…’A’,’B’…). The keyword default represents the default case of the switch. All the cases of the switch is enclosed with opening and closing curling braces ( { } ), and it is having an other case is called default case. When ever the value in the variable is equals to the constant value of the specified case in the switch is executed. The value in the variable is not match with the constant values of all the cases in the switch, and then the default case is executed. The value in the variable is equal to the constant in the case 1, and then statement 1 is executed, if the value is not mach with the value in the case 1, then the compile check with next case constant. In this way the compiler will check with each and every constant value of the cases in the switch. Example program for switch conditional statement: #include<stdio.h> main() { 31
  • 32. Programming in ‘C’ int n1; clrscr(); printf(“Enter number between 1 to 5”); scanf(“%d”,&n1); switch(n1) { case 1: printf(“n I am in case 1”); break; case 2: printf(“n I am in case 2”); break; case 3: printf(“n I am in case 3”); break; case 4: printf(“n I am in case 4”); break; case 5: printf(“n I am in case 5”); break; default: printf(“ I am in default case”); } getch(); } Looping statements: Loops are used for, when ever the C-program needs to execute the steps repeatedly. In will repeatedly execute some sequence of steps or some portion of the program specified number of times. The loop execution is controlled with the help of the loop control instruction or loop condition. The statements in the loop will execute until the given condition is false. In C-language we have three types of looping statements. They are: 1. While statement. 2. For statement. 3. Do while statement. 32
  • 33. Programming in ‘C’ The looping statements are divided in to two types based on condition checking location. They are entry level condition checking, exit level condition checking. The for and while looping statements are comes under entry level condition checking. The do while looping statement is comes under exit level condition checking. 1. While looping statement: The while is a keyword C-language; use this keyword as looping statement. The while is an entry controlled loop statement. The general syntax of the while looping statement is. Variable Initialization; while( test condition ) { Body of the loop; Increment or decrement operations; } Start Initialization No Test exp Yes Stop Body of the loop Increment or Decrement operations It is often execute some sequence of steps or some part of a program, use this while loop. In the while loop first initialize the starting value to the variable for counting purpose of the loop iterations. Iteration is the process of loop execution. The while is a keyword followed by the test condition. The body of the loop and the increment or decrement statements are enclosed by the opening and closing curling braces ({}). The test condition is true then the body of the loop will come for execution and perform increment or decrement operations. After performing increment or decrement operations the test condition is once 33
  • 34. Programming in ‘C’ again evaluated, if it is true the body of the loop is again executed. The process of repeated execution of the body continues until the condition false the control is transfer to out of the loop. The braces are need only if the body of the loop contains two or more statements. Example program for while looping statement: #include<stdio.h> main() { int i,num; printf(“Enter number”); scanf(“%d’,&num); i=1; while(i<=num); { printf(‘%dt”,i); i=i+1; } getch(); } The above program is used to display the numbers from 1 to given number. The i values is initializes with one, and check the while loop condition and executes the body of the loop. Then perform increment operation. The body of the loop executes continually until I value greater then value in the variable num. 2. For looping statement: The ‘for’ loop is another Entry controlled looping statement. For is a keyword, by using this we can build a looping statement. 34
  • 35. Programming in ‘C’ The general syntax of for looping statement is: for(intilization;condition;increment or decrimrnt) { Body of the loop; } Handling of for loop is easy to compare remaining looping statement. In while looping statement, the initialization, conditions and increment and decrement statements are placed in different locations. In for looping statement this initialization, condition and increment and decrement statements are place in one location these are separated by semicolon (;). Those three statements are enclosed with parentheses. The initialization part is used for initialize counter variable for loop execution. The body of the loop will execute until the given condition is false. The body of the loop is enclosed with closing and opening curling braces ({ }), if the body of the loop has single statement need not to write braces. But it is good practice to open the braces even it has single statement. Execution process of for loop: Fires the initialization of control variable of loop will execute, after the execution of initialization statement the control will follow up the next condition checking statement in for loop. If the given condition is true, then the body of the loop will come for execution. Next the control will transfer to increment or decrement statement and execute the step, then the control goes to condition checking, if the condition is true, again the body of loop will execute this process is continue until the given condition false. Example program for ‘for’ looping statement: #include<stdio.h> main() { int i,num; printf(“enter number”); scanf(“%d”,&num); for(i=1;i<=num;i++) { 35
  • 36. Programming in ‘C’ printf(“%4d”,i); } getch(); } In the above, variable ‘i’ is used for counter of the loop. It will initialize to value 1 the first time execution of for loop. The execution of loop terminates when the ‘i’ reaches to, value in the variable ‘num’. In this process the ‘i’ value increment once each and every time execution of loop. 3. Do while looping statement: The do while is the exit controlled looping statement. The while loop construct as the test condition is made at the beginning of the loop and also condition will comes for execution beginning of the loop. There fore the body of the loop may not executes, all the conditions of while loop is not satisfied at the entry first time. Some times it might be necessary to execute the body of the loop before the test is performed. In such a situation can be handling with the help of the do statement. The general form of the do-while statement is: Initialization; do { Body of the loop; Increment or decrement operations; }while(condition); The working of while and do while loops are same but only difference is, in while test condition will be executed before executes the body of the loop. In ‘do while’ fist the body of the loop will executes, at the end of the loop test condition is executed. This means in ‘do while’ the body of the loop executes at least once, if the condition is fail. Remaining initialization and increment decrement statements are located in same location in ‘while’ and ‘do while’ loops. 36
  • 37. Programming in ‘C’ Example program for the ‘do-while’ looping statement: #include<stdio.h> main() { int i,num; printf(“Enter number”); scanf(“%d’,&num); i=1; do { printf(‘%dt”,i); i=i+1; } while(i<=num); getch(); } In the above program the initialization is made at the beginning of the loop, next the body of the loop is executed. After the execution of the increment statement of the ‘i’, the test condition of the while is executes. Difference between while and do-while loop: While loop Do-while loop 1. While loop can also called as an entry 1. Do-while loop can also be called as an exit controlled loop. controlled loop. 2. In the While loop the condition is placed at 2. In the Do-While loop the condition is the beginning of the loop. placed at the end of the loop. 3. In the case of While loop after executing 3. In the case of Do-While loop, after the initialization section, the condition will executing the initialization section, the body be tested if it is true, the body of the loop is of the loop will be executed and then the executed. condition will be tested for the continuation of the next iteration. 37
  • 38. Programming in ‘C’ 4. In the case of While loop, if the condition 4. In the case of Do-While loop, the body of is found to be false for the first time, the will be executed at least once without body will never be executed and the loop will depending on the vale of the condition. be terminated. 5. In most applications the while loop is user 5. In the body is to be executes at least once, friendly. the Do-While loop is much more suitable. 6. It is possible to have nested while loop 6. It is also possible to have nested Do-While while loop can also contain a Do-While loop. loops. Do-While loop can also contain a while loop. 7. The general syntax of the While is: 7. The general syntax of the Do-While is: Variable Initialization; Initialization; while( test condition ) do { { Body of the loop; Body of the loop; Increment or decrement operations; Increment or decrement operations; } }while(condition); Nested loops: The nested loops are used where the program needs loop with in the loop. Which procedure used for nesting of ‘if’, that can be used for nesting loops. The nesting loops are made by using while, do-while and for looping statements. Writing nested loops in while, for is easier to compare do-while. The general form of the nested loops is: Initialization; for(intilization;condition;increment or decrimrnt) while( test condition ) { { Initialization; for(intilization;condition;increment or decrimrnt) while( test condition ) { { Body of the loop; Body of the loop; Increment or decrement operations; } } Body of the loop; Body of the loop; Increment or decrement operations; } } 38
  • 39. Programming in ‘C’ Working of nested loops: First the outer loop initialization statement is executed, after test condition statement is executed if it is true, then the body of the loop is executed. The outer loop body having another looping statement, we can call it is an inner loop. Then the inner loop initialization statement is executed, next the inner loop test condition will be processed, if it is true then the inner loop body is executed. Next increment process is done. After that the control goes for test condition, if it is true again the body of the loop is executed this process is continue until the inner loop condition become false. When ever inner loop test condition is false the loop will be terminated control will execute remaining statements in the out loop. After that the control goes to increment or decrement operation, next the control goes to check the condition of the loop if again it is true, again the inner loop is executed. This process is done until the outer loop condition becomes false. Unconditional statements: In the conditional statements the control will go to specified location when ever the given condition either TRUE (1) or FALSE. (0). In the unconditional statements, when ever the compiler reads the unconditional statement the control will goes to specified location with out testing any condition. Here the control will jumps to specified location automatically so this statements also called jumping statements. C-language provides three jumping statements they are: 1. goto. 2. break. 3. continue. 1. goto: The goto unconditional statement is used to transfer the control from one location to another location in the program. Here goto is keyword in C-language. This statement is used with the help of crating labels in the program; ‘goto’ keyword is followed by the specified label in the program. Syntax: goto <label name>; Example: goto a; Example program for goto statement: #include<stdio.h> 39
  • 40. Programming in ‘C’ main() { int a,b,c; ptintf(“Enter 2 numbers”); scanf(“%d%d”,&a,&b); c=a+b; printf(“Sum : %d”,c); goto a; c=a-b; printf(“Sub : %d”,c); a: getch(); } In above program after the execution of ‘goto a;’ statement control will goes to label ‘a:’, statements after the program will never participate in the execution. 2. break: In C language ‘break’ statement is used for stop the execution of statements or program unconditionally. When ever use the break statement in program, the control will never executes the statements available, after the ‘break’ statement. When the compiler reads the break statement the compiler terminates from the execution of the program. Syntax: break; Example: break; Example program for ‘break’ statement: #include<stdio.h> main() { int n,i,sum=0,num; printf(“Enter number:”); scanf(“%d”,&n); printf(“Enter %d numbers”,n); 40
  • 41. Programming in ‘C’ for(i=1;i<=n;i++) { scanf(“%d”,&num); if(num<0) { break; } sum=sum+num; } } The above program we can calculate the sum of ‘n’ numbers. When ever user give – ve value to the variable ‘num’ then the loop execution is terminated. Break is used for stop the normal execution of for loop at that specified time. 3. continue: The ‘continue’ is a keyword in C-language. This ‘continue’ statement is mainly used in looping statements. Some times the program needs to transfer the control to the starting of the loop. When ever the control reads the continue statement in the loops, the control never executes the statements after the ‘continue’ in the loop. The control will transfer to the beginning of the loop. Syntax: continue; Example: continue; Example program for ‘continue’ statement: #include<stdio.h> main() { int n,i,sum=0,num; printf(“Enter number:”); scanf(“%d”,&n); printf(“Enter %d numbers”,n); for(i=1;i<=n;i++) { 41
  • 42. Programming in ‘C’ scanf(“%d”,&num); if(num<0) { continue; } sum=sum+num; } } The above program is used to calculate the sum of ‘n’ +ve numbers. When ever the user gives –ve number to the variable num the compile never add that value to the previous some. This process is done by using continue statement with in for loop. The compiler decides the given number is –ve, automatically the control will goes to beginning of the loop. 42
  • 43. Programming in ‘C’ Arrays When ever the program need to tack group of similar data elements, it is highly impossible to create individual variables, and also accessing values, C-language provide a feature called ‘Array’. An array is a group of related data items that are share common name. Array is a set of homogeneous elements. Values in the array can be accessed by the special number or integer is index of an array. Array indexing is starts every time with ‘0’. Arrays are two types: 1. Single dimensional arrays. 2. Multi dimensional arrays. Single dimensional arrays: A list of items can be given one variable name using only one subscript such a variable is called single dimensional array. Declaration of array: Array variable can be create like normal variable, but only difference is normal variable take only single value, array variable can accept ‘n’ number of variables, ‘n’ represents the size of an array. General declaration of an array variable is: Data type variablename[size]…; In the above syntax, data type represents which type of values accepts into an array variable. Variable name represents the identifier of an array; size represents how many elements array can accept. Each and every value in the array can be accessed with the help of an integer or number is called ‘index’ of an array, it can be place with in the brackets after the array name. int rollno[10]; It represents the ten students roll numbers. Variable ‘rollno’ can share all the ten roll numbers of the ten students. rollno[0] is the roll number of the single student, rollno[1] is the roll number on another student etc… the array indexing starts with 0 and ends with n-1. 0 is the lower bound or limit of an array; n-1 is the upper bound or limit of an array. Internal storage of array: If the array variable is declared like this: int a[5]; 43
  • 44. Programming in ‘C’ Address 2000 2002 2004 2006 2008 Elements 50 34 65 5 12 Locations or a[0] a[1] a[2] a[3] a[4] subscripts Initializing values into an array: Values initialization process is done like initialization of values to the normal variable. The values are assigned to each and every location, with the help of index value of an array. Values assigned at the time of declaration. int a[5]={12,54,23,1,654}; Values assign to individual array variable: a[0]=20; a[4]=43; Read values from the keyboard for array variable: scanf(“%d”,a[0]); Read group of values into an array at a time we need loops. When ever we need to read group of values for an array, we can write scanf statement for each and every variable. This is highly impossible to write scanf statements for number of values, C-language minimize this process with the help of loops. The below example represents read values into an array from keyboard. for(i=0;i<n;i++) { scanf(“%d”,&a[i]); } Access values in the array variable: Like normal variables, we can get the values in the array with the help of variable name. But we can distinguish each and every variable with the logical address of the array variable. Suppose you want to access 2nd logical location value in the array we can represent like this ‘a[2]’. We can access group of values at a time with the help of loops. 44
  • 45. Programming in ‘C’ for(i=0;i<n;i++) { printf(“%d”,a[i]); } Multi dimensional array: Two dimensional arrays: In two dimensional arrays comes under multi dimensional type. In this type the array variable name having two subscripts such a variable is called two dimensional arrays. When ever program need to organize the data in rows and columns, use this two dimensional array. The first subscript represents row size and second subscript represents column size. By using this 2d array we can organize or store data in the form of tables. It is similar to the matrix form to define the table of items the two dimensional are convenient. Declaration of two dimensional arrays: The general declaration of 2d arrays: datatype varablename[row size][column size]…; The data type represents, which type of values can be accepted by the array. The variable name represents the identification label of the array. The first subscript represents, how many rows of data can be accepted by the array. The second subscript represents, how many columns of data can be accepted by the array. int m1[2][2]; The above 2d array variable can accept two rows and two columns of data. The array variable ‘m1’ can accept integer values only. In single dimensional array we can access the array values, by using single index value. In 2d array, values can be accessed with the help of two indexing values. First one represents row index second one represents column index value. For example m1[0][1] represents the value in the ‘0’th row ‘1’ st column. Initializing values to 2d array: Initializing values to 2d array with the help of indexing values, this indexing values are represented with combination row and column indexing vales. Values assigned at time of declaration: int a[2][2]={{12,32},{23,54}}; Values assigned to individual variable: a[1][0]=34; 45
  • 46. Programming in ‘C’ Initial storage of 2d array: The array variable can be stored like this: int a[2][2]; Address 2000 2002 Elements 50 34 1st row Locations or a[0][0] a[0][1] subscripts Address 2004 2006 Elements 50 34 2nd row Locations or subscripts a[1][0] a[1][1] 1st column 2nd column Reading values into 2d arrays: When ever we need to read or get values from the output screen. We can get those values with the help of nested looping statements. The general format to read values to 2d arrays: for(i=0;i<row size;i++) { for(j=1;j<size of column;j++) { scanf(“ “); } } 46
  • 47. Programming in ‘C’ Strings String: In arrays we can store group of numerical values, string can also store group of values those values comes under character type. String is a collection of character values, when we declare the array variable under char data type the variable is called as string variable. Normal char variable can accept only single character value, it can’t accept group of character like persons names etc… C-language minimizes this problem by creating character array. General format to create string variable: Syntax: char variable name[size]; The data type of the string is always char, size can represents the maximum number of characters are store into a string. Example: char na[20]; Strlen( ): It is used to find the length of the string, length means how many characters will be stored in a given string variable. This function accepts one string variable as the passing variable from the calling location. In the calling area we can store the return value into an integer variable. Syntax:- int var = strlen(string var); Ex:- char na[20] = “abc”; int length ; length = strlen(na); Strcpy:- This is used to copy the string from one string variable to another string variable. This function can accept two string variables as the passing arguments or one is string variable, second one is string value. It can copy string value in the second variable in to first variable. Syntax:- strcpy(string var1,string var2); Ex:- strcpy(s1,s2); strcpy(s1,”abc”); Strcmp( ): This function performs compression operations between two strings and find out whether two strings are same or different. It can accept two strings variables as the passing arguments. If two strings are same strcmp( ) returns zero to the calling location other wise it 47
  • 48. Programming in ‘C’ can returns numeric difference between the ascii values of the first non-matching pairs of the character. Syntax:- int var = strcmp(string var1,string var2): ex:- strcmp(s1,s2); Strcat( ): This function performs concatenation (combining) operation between 2-strings. It can accept 2-string variables as the passing arguments. It can concatenate 2-strings in a given string variables, resultant string will be stored into string variable1. Syntax :- strcat(string var1, string var2); Ex:- strcat(s1,s2); Strrev( ): This function is used to reversing the string in a given string variable. It can accept single string variable as the passing argument. It can reverse string in a given string variable and the resultant string will be stored into the same string variable. Syntax : strrev(string var); Ex:- strrev(s1): Strlwr( ): This function used to convert the string into lower case (small) letters. It can accept string variable as the passing argument .The resultant string can store into same variable. Syntax: strlwr(string var); Ex:- strlwr(s1); Strupr( ): This function used to convert the string into upper case (capital) letters. It can accept single string variable as the passing argument. The resultant string will be stored into the same variable. Syntax: strupr(string var); Ex:- strupr(s1); 48
  • 49. Programming in ‘C’ Functions Function: It is a set of statements or part of a program, which are executed repeatedly and randomly in our program. Functions are also called as sub programs. The set of statements are written for accomplish a particular task or solve a problem. These set of statements are identified by an identifier called function name. When we need to execute those set of statements in our program, we can write the function name in the program. This procedure is called function calling. Functions are classified into two types: 1. Library functions or Predefined functions. 2. User defined functions. Library functions: Library functions are also called as predefined functions. Like keywords, task of the function is defined or written by the C-language developers. These function definition are written in library files. When we to done a particular task in our program simply we can call those functions with the function names. These functions are use in any C-program. Examples: gets(), putchar(), printf(), scanf() etc…….. User defined functions: User defined functions are own functions. These functions are written or developed by the programmer. These functions are developing with in the user programs, we can call those functions with in the program, we can not call the user defined functions from another program. Programmer can define number of user defined functions with in one program, each function having individual task. Each one will be separated by the function names. Examples: add(), subtraction(), etc……… Advantages of the functions: 1. The complicated problem can be divided into number of smaller tasks and can be solved separately. 2. It is easy to understanding each sub program as it performs only a specified task. 3. We can test the program are sub programs easily. 4. More general functions can be kept in the library files for the later uses. 5. We can reduce the complexity of the program. 6. We can solve the complicated problems easily by using functions. 7. Reduce the length of the programs. 49
  • 50. Programming in ‘C’ Each function has the following working procedures: 1. Function declaration (or) Function prototype. 2. Function definition. 3. Passing arguments. 4. Return statements. 5. Function call. Function declaration (or) prototype: It can tells to compiler, name of the function, which type of values can taken as the passing arguments from the calling location and which type of value can be return to the calling location. Function declaration is made at the beginning of the main function in our program. The general format for the declaration of the function: Return type function name(arguments list(optional)); Example: void addition(int x, int y); Function definition: Here the program can specify the task of the function. The task of the function is called as the definition of the function. The definition of the function can be written after the completion of the main function or at the time of the declaration. We can maintain equal prototype of the function at the time of declaration, at the time of the writing definition. Return type function name(arguments list(optional)) { --------- (Executable statements) } Example: void addition(int x, int y) { printf(“sum = %d”, x+y); } Passing arguments: Each function is design for executing a task in this way the function needs a some values for the execution of further steps in function. Some times those values are given to the function from the calling location, then those values are pass to the function as the passing arguments. 50
  • 51. Programming in ‘C’ Return statements: The return statement tells to compiler which type of value return by the function to the calling location. The return type is specifying before the function name. The return type of the functions is mention as void, scalar or derived type. Function call: After defining the function, we can call the function from main function or another used defined function. The calling of the function is nothing but the execution of the function code. Where you want to execute the code of the function in our program, just write the function name in that location. Function calling: addition(); When we declare the user defined functions in our program above steps should be following. User defined functions are classified into 4 types based on the prototype of the function. Those are: 1. Functions have No return value and No passing arguments. 2. Functions have No return value and Passing arguments. 3. Functions have Return value and No passing arguments. 4. Functions have Return value and Passing arguments. 1. Functions have No return value and No passing arguments: In this type function doesn’t take any values as the passing arguments from the calling location. Function doesn’t return any value to the calling location. This type of functions, declaration of variables, and logic of the task and results of the task should be placed in the definition of the function. General format of this type is: void function name( ); Example: void addition( ) { Executable statements; } { -------------- addition( ); (calling environment) } 51
  • 52. Programming in ‘C’ In the above format the data type void represents the function doesn’t return any value. The empty parenthesis represents the function doesn’t require any values as the passing arguments from the calling location. 2. Functions have No return value and Passing arguments: In this type the function doesn’t return any value to the calling location but it can take some values as the passing arguments from the calling location. The execution of the function logic is depends on another values, those values are require from the calling location. Then the values are sending to the function as the passing arguments. General format of this type is: void function name( arguments list); example: void addition(int x,int y) { printf(“Sum = %d”,x+y); } { int a=5,b=10; addition (a,b); (calling environment) ---------------- } In the above type void represents, function doesn’t return any value to the calling location. Function requires two integer values as the passing arguments from the calling location. 3. Functions have Return type and No passing arguments: In this type the function return one value to the calling location, the function doesn’t take any values as the passing arguments from the calling location. The return value type is specified in front of the function name. The return value type must be scalar or derived data type. Then the function returns a value to the calling location with the help of keyword ‘return’ this keyword is placed in the body of the function. When the compiler read this return keyword the control goes to the calling location. General format of this type is: 52
  • 53. Programming in ‘C’ data type funvtion name( ) { ----------- return variable; } Example: int addition( ); { int c; --------- return c; } { int c=addition( ); (calling environment) } In the above function the return value of the function is ‘int’ type. The function returns a ‘int’ value in the variable ‘c’. Specified return type of the function should be same as the return value data type of the function. In the calling location, the return value will be stored into a variable. These types of functions are involved into an expression in the calling location. 4. Functions have Return value and Passing values: In this type functions return one value to the calling location and the functions required some values as the passing arguments. This type is the combination of 2nd and 3rd type of the functions. General format of this type is: Data type function name( arguments list) { ---------- return variable; } Example: int addition(intx,int y) { return x+y; } { int c=addition(5,6); (calling environment) } 53
  • 54. Programming in ‘C’ In the above type the function return an ‘int’ type value, the function requires two ‘int’ values as the passing arguments from the calling location. The return value of the function is stored into ‘int’ variable c. These types of functions are involved into an expression in the calling location. The following conditions must be satisfy when the function require values from the calling location. 1. Numbers of arguments specified in the calling location is must be same as the number of variables declared in the function definition. 2. Data type’s of the variables in the calling location is must be same as the data types of the variables declared in the function definition. Parameter passing mechanism in functions: The arguments passing to the functions are classified into tow types, they are formal arguments and actual arguments. The variables declared in function definition are called formal arguments. The variables given to the function in the calling location is called actual arguments. In functions, some times the function requires values in the variables as the passing arguments; some times it requires address of the variables as the passing arguments. Based on these, C-language provides two types of mechanisms for passing arguments: 1. Call y value (or) passing arguments by values. 2. Call by references (or) passing arguments by references. 1. Call by value (or) passing arguments by values. In this type the values in the variables as the passing arguments to the function definition. Here we can write the names of the variables or values in function calling, the compiler transfer the values in the variables to the function definition. When ever we modify the values in formal arguments the actual arguments are not affected. Changes are made only on formal arguments because we can pass the values in the variable. 54
  • 55. Programming in ‘C’ General format of the call by value method: main( ) { -------- Function name( variable names); (calling location) ---------- } return type function name(formal variables declaration) { ------- ------- } Example: main() { int a=10,b=20; swap(a,b); printf(“%d%4d”,a,b); getch(); } void swap(int x,int y) { int c; c=x; x=y; y=c; } Observe the above function; it can get two integer values as the passing arguments from the calling location. Those two values will be stored into the formal arguments of the function. The function definition can interchange the values in the formal arguments but the value in the actual arguments doesn’t change. Why because, formal arguments are local variables to that function, the scope of the local variables is with in the declared function. Example program for call by value mechanism: void add(int x,int y) main() { int a,b,c=0; clrscr(); printf(“Enter 2 numbers:”); 55
  • 56. Programming in ‘C’ scanf(“%d%d”,&a,&b); add(a,b,c); printf(“nSum of %d, %d is %d”,a,b,c); getch(); } void add(int x,int y,int z) { z=x+y; } In the above program add function can perform addition operation on two numbers. This function can take three integer numbers as the passing arguments from the calling location. Two values are used for addition operation, third variable is for storing result. In the function definition adds value in the ‘x’ with value in the ‘y’ and store result in to variable ‘z’, but the value in the actual variable doesn’t change. This is the main disadvantage in call by value mechanism. Call by reference (or) passing arguments by reference: In call by reference mechanism we can pass address of the variables as the passing arguments to the function definition. In this type we can write address of the variables in the calling location (when ever & symbol place before the variable it can represents the address of the variable), the control sends the address of the variables to the function definition. The function definition can get that variable address, by declaring pointer variables. In this type function can perform different operations on the formal arguments the effect will be place on the actual arguments. General format of the call by reference method; main( ) { -------- Function name(address of the varables); (calling location) ---------- } return type function name(pointer variables) { ------- ------- } 56