Learning Center
Plans & pricing Sign in
Sign Out



									                     C Programming Language

What is Language?
“Language is a medium of share or bottle up our feeling with others” and we can
also say “Language is medium of Communication. Without any Language we can’t
express our feeling and thought.”

Why do we need Language in Computer Field?
Whenever we would like to share our feelings with computer and we want to use
computer than we’ll have to give commands and instructions and for giving
commands & instructions to computer we have to need a language.

What is Program?
Program is a group of systematically commands which we give to computer &
that must be understood by computer.

Why do we create a Program?
According to requirement and result we would like to get, we create a program.

Programming Language
For doing any special work through computer we give commands in systematically
order that’s called program and the process of making a program, is called
programming. In which language the commands are written that is called
Programming Language.

Types of Programming Language
      There are two types of programming language

      1. Low Level Language
      2. High Level Language
1. Low Level Language – When computer was developed during that time
some programming languages were also developed, that we call Low Level
Language. These Languages are depended only characters, they don’t provide
graphics utilities.

      There are two types of Low Level Language

      I)     Machine Language
      II)    Assembly Language

      i)     Machine Language – Such a programming language, which is
             understood by computer directly, without any use of translator. This
             Language is depended on binary digits (0, 1).
      ii)    Assembly Language - In Assembly language we can use numeric codes ,
             character and other symbols. In it we can use some characters for
             arithmetic symbol, that we call Mnemonics. Assembler changes
             assembly codes into machine codes.                      In this we
             use some symbol, that’s why it does know Symbol Language also.

2. High Level Language – In high level language both numeric digits and
character are used together with it provides some special shapes and graphics
that’s why it is called High Level Language.

      According our purpose there are four types of it.
      I) Scientific Purpose Language –

             Ex. - BASIC (Beginners All Purpose Symbolic Instruction Code)

      II) Commercial Purpose Language –
             Ex. - COBOL (Common Business Oriented Language)
      III) Special Purpose Language –
             Ex. - LOGO

      IV) Multi Purpose Language –
             Ex. - C++, VB, JAVA

Language Translator
Language translator is program that changes Source codes into Machine codes

There are three types of Translators

      I) Assembler –

             Assembly Codes                   Machine Codes

      II) Compiler –
             Source Codes                           Machine Codes

             It reads whole program and convert into machine code.

      III) Interpreter –
             Source Codes                           Machine Codes

             It reads line by line and changes them in machine code.

      An algorithm is a set of instruction which is step by step solution of a

Ex. Algorithm for adding two numbers

      Step 1 Start

      Step 2 Input two numbers a, b
       Step 3 Sum = a + b

       Step 4 Print Sum

       Step 5 Stop

Flow Chart
       Graphical Presentation of Algorithm is called Flow Chart.

There are some shapes for draw/create flow chart

1. Ellipse / Terminal box – Start, Stop

2. I/O Box – Input Value and Output Value

3. Process Box – Processing

4. Decision Box – Conditions

5. Arrow – Processing Direction
Ex. Flow Chart for find out sum of tow numbers


                 Input two number

                     Sum = a + b

                     Print Sum


                                    C Language
History of C Language
The root of all modern language is ALGOL (Algorithm Language), introduced in the
early 1960s. ALGOL was the first computer language to use a block structure.

In 1967, Martin Richards developed a language called BCPL (Basic Combined
Programming Language) primarily for writing System Software.

In 1970, Ken Thompson created a language using many features of BCPL and it
was called B.
And C was developed by Dennis Ritchie at AT & T’s Bell Laboratories (USA) in

Types of C Language
There are three types of C language.
   1. Borland ‘C’        -         Dos only

   2. ANSI ‘C’      -    Unix only

   3. Turbo ‘C’     -        Dos & Unix

Features of C Language
There are a number of features in C language so it is so popular. C language has
following features.

   1. Procedural Programming Language: Such a programming language in
      which we divide the program in modules, on the basis of logic and for every
      module we write coding, called Procedural Programming Language.

   2. Structured Programming Language: In which language we use
      sequence, branching and iteration called Structured Programming

   3. Portable Language: We can run our program on any other PC without
      any modification and some partly modification.

   4. Middle Level Language: In C language, low level and high level features
      are combined. That’s why it is called Middle Level Language.

   5. Case Sensitive Language: In C language lower case and upper case have
      different uses.
   6. Free Form Language: In C language we can write statements freely,
      because there are no limitations for writing.

   7. Top-Down Approach: In C language, Statements execute top to down.

Structure of C Language
There is structure of C language with a simple program.

Structure                                                 Example

Header File                                               #include<stdio.h>

Main Function                                                   main()

Opening Brace                                                   {

Coding                                                          printf(“HELLO C”);

Closing Brace                                                   }

#include<stdio.h> :- This line is called header line. It must be written starting in the
program. It means we are using stdio.h (standard input output) header file in our
program that has stored in our computer with C compiler. If we want to get input
or output by user then we use stdio.h header file. There are a number of header
files and every file’s use is specific and different.

main() :- It is a function. In a C program there can be more than one function but
one of them must be main(). When program is executed then it’s starting from
main() and it also control the program.

Opening Brace { :- It use for starting a block.

Coding :- In this block we write the coding for getting output. In this we use a
number of functions according to our program and printf() is one of them. printf()
is used for printing message.
Closing Brace } :- It use for ending a block.

Executing a ‘C’ Program
There are steps of executing a program.

   1. Creating a program / Source Code

   2. Compiling the program

   3. Linking the program with functions that are needed from the C library.

   4. Executing the program

     Source Code     .c

                          Compilation   .obj


                                                                      Executable File   .exe

Started with C
       There is a close analogy between learning any other language and learning
       C language.

       Here we discuss same steps for learning English and C language.

Steps in learning English Language:

         Alphabets              Words                     Sentences               Paragraphs
Steps in learning C Language:

         Alphabets                     Constants

         Digits                        Variables                 Instructions          Program
C’ Tokens Symbols
      Special                          Keywords
In a C program the smallest individual units are known as C Tokens.

C has five types of tokens.

                                              C Tokens

 Keywords               Identifiers           Constants          Separators             Operators

int                     total                      -4               [],()               +-       ex.
do                      per                        125              {}                  */

   1. Keywords – Keywords are the words whose meanings have already been
      explained to the C compiler. The keywords can’t be used as variable names
      because if we do so, we are trying to assign a new meaning to keyword,
      which is not allowed by the computer or compiler. The keywords are also
      called Reserved Words.

                  There are 32 keywords available in C language.

       auto                     double                    int                 struct

       break                    else                      long                switch
   case                 enum                    register        typedef

   char                 extern                  return          union

   const                float                   short           unsigned

   continue             for                     signed          void

   default              goto                    sizeof          volatile

   do                   if                      static          while

   Note: All keywords must be written in lowercase.

2. Identifiers – Identifiers refer to the name of variables, functions and arrays.

           Rules of declaring Identifiers

        a) First character must be an alphabet or underscore(_).

        b) It must consist of only letters, digits or underscore.

        c) Only first 31 characters are significant.

        d) It can’t be a keyword.

        e) It mustn’t contain white space.

3. Constants – Constants refer to fixed values that don’t change during the
   execution of a program.

          Numeric Constant                                 Character Constant

Integer                   Real / Float           Single Character      String   Back Slash

 Integer Constant: Integer constants refer to a sequence of digits.

            Ex. : Decimal                -   254, 19

                   Octal                 -   057, 673

                   Hexadecimal -             9F, 037B

 Real / Float Constant : Integer numbers are not allowed to represent
  quantities that vary continuously, such as distances, heights, temperatures,
  prices and so on. To represent these quantities, which number we use, are
  called Real or Float Constants.

            Ex. : 125.000000

 Single Character Constant: A single character constant is a single alphabet, a
  single digit or a single special symbol enclosed within single inverted
  commas (a pair of single quote marks).

            Ex. : ‘a’, ‘T’, ‘9’, ‘-‘

 String Constants: String constant is a sequence of characters enclosed in
  double quotes and characters may be letters, numbers, special characters
  and blank space.

            Ex. : “Hi……………….”, “1990”, “Good Morning” , “C”
 Backslash Character Constants: C supports some special backslash character
  constants that are used in output function. Like ‘\n’ in printf() for new line.

   These characters combinations are known as escape sequences.

   Constant                                      Meaning
          ‘\a’                                          Audible alert (Bell)

          ‘\b’                                          Back Space

          ‘\f’                                          Form Feed

          ‘\n’                                          New Line

          ‘\r’                                          Carriage Return

          ‘\t’                                          Horizontal Tab

          ‘\v’                                          Vertical Tab

          ‘\’’                                          Single Quote

          ‘\”’                                          Double Quote

          ‘\?’                                          Question Mark

          ‘\\’                                          Back Slash

          ‘\0’                                          Null

4. Separators – Some special symbols we use in C language that are called
   Special Symbols and Separators.

   Ex.:   () Parenthesis
            {} Braces

  5. Operators – An operator is a symbol that tells the computer to perform
     mathematic or logical calculation.

     Ex.:   10 + 5 = 15

           Here 10, 5 and 15 are operands and + , = are operators. And whole
     statement is called Expression.

            Three types of operators are available.

      Binary Operators: At least two operands must in an expression.

        Ex.: 10/5            Here / is Binary Operator

      Unary Operators: Only one operand must be in an expression.

        Ex.: -8            Here – is Unary Operator

      Ternary Operators: Three operands are used that’s why it called Ternary

        Ex.: a>b ? a : b

Data Types
                    Such words that define the types of variables are called Data

        C language supports three classes of Data Types.

        1. Primary / Fundamental Data Type            -     int, char, float

        2. Derived Data Type                 -        array, pointer

        3. User-defined Data Type            -        struct, union, typedef
                                  Data Type

             Character                              Numeric

      Single Character       String           Integer         Float

                                                 singed         double

                                                 unsinged     long double



Data Type Classification in ‘C’
Data Type   Keyword           Size      Conversion Range of Vales
                              (Bytes)   Character

Integer     int               2         %d         -32,768 to 32,767

            signed int        2         %d         -32,768 to 32,767

            unsigned int      2         %u         0 to 65536

            short int         1         %u         -128 to 127

            unsigned short    1         %u         0 to 255
                              4         %ld        -2,147,483,648 to
            long int                               2,147,483,647
                              4         %lu
            signed long int                        -2,147,483,648 to
                              4         %lu
            unsigned long
            int                                    0 to 4,294,4967,295

Character   char              1         %c         -128 to 127

            signed char       1         %c         -128 to 127

            unsigned char     1         %c         0 to 255

Float       float             4         %f         3.4e-38 to 3.4e+38

            double            8         %if        1.7e-308 to 1.7e+308

            long double       10        %if        3.4e-4932 to 3.4e+4932
            A variable is a data name that may be used to store a data value and
value can be changed during the execution of program. In other words variable is
a memory location that represents value.

Rules of declaring Variables
              1. Use only alphabets, characters, digits and underscore.

              2. Mustn’t start from digit.

              3. Not allow comma, blank space.

              4. It can’t a Keyword.

              5. It can’t use special symbol.

      Ex. :    a, height , width, d_o_b , Total, area       Valid example

               123r, price$, char, (area), roll no          Invalid example

Declaration of Variables
              After designing suitable variable name, we must declare them to the

      Declaration does two things.

      1. It tells the compiler what the variable name is.

      2. It specifies what type of data the variable will hold.

Syntax -       Data_Type Variable_name;

Example - int count;

              int total, number;
                float per;

Note: The Declaration of variables must be done before they are used in the

       An operator is a symbol that tells the computer to perform certain
mathematical or logical calculations. Operators are used in programs to
manipulate data and variables. They usually form a part of the mathematical or
logical expressions.

Expression - Expression is a combination of variable, constants, operators, data
types etc.

       int a;

       float cot, delta, alpha, beta, gamma ;

       a = 3200;

       cot = 0.0056;

       delta = alpha * beta/gamma + 3.2 – 2;


   1. +, -, *, / are the Arithematic operators.

   2. = is Assignment operator.

   3. 2, 3200, 0.0056 are real/float constants.

   4. a is integer variable.

   5. cot, beta, gamma, alpha are float variables.
C operators can be classified into a number of categories.

   1. Arithmetic Operators

   2. Relational Operators

   3. Logical Operators

   4. Assignment Operator

   5. Increment and Decrement Operators

   6. Conditional Operator

   7. Bitwise Operators

   8. Special Operators

   1. Arithmetic Operators – C provides all the basic arithmetic operators for
      calculating numeric calculation.

            Operators                           Meaning

            +                                   Addition

            -                                   Subtraction

            *                                   Multiplication

            /                                   Division

            %                                   Modulo Division (Reminder)

   2. Relational Operators – We often compare two quantities and depending
      on their relation, take certain decisions. For example, we may compare the
      age of two persons, or the price of two items, and so on. These
      comparisons can be done with the help of relational operators.
          The value of a relational expression is either one or zero. It is one if
         the specified relation is true and zero if the relation is false. For

                 10 < 20 is true 1

                 10 > 20 is false 0

         Operators                             Meaning

         <                                     Is less than

         >                                     Is greater than

         <=                                    Is less than or equal to

         >=                                    Is greater than or equal to

         ==                                    Is equal to

         !=                                    Is not equal to

3. Logical Operators – An expression, which combines two or more relational
   expressions, is termed as a logical expression or a compound relational

         The value of a relational expression is either one or zero.

         Operators                             Meaning

         &&                                    Logical AND

         ||                                    Logical OR

         !                                     Logical NOT

   Logical AND
              A           B        A && B

              1           0          0

              1           1          1

              0           0          0

              0           1          0

Logical OR

              A           B        A || B

              1           0          1

              1           1          1

              0           0          0

              0           1          1

Logical NOT

                  A           !A

                  1           0

                  0           1

Here          1 = true

              0 = false
   4. Assignment Operator – Assignment operators are used to assign the result
      of an expression to a variable. We have used the usual assignment
      operator,’=’. C has a set of ‘shorthand’ assignment operators of the

      Statement with simple assignment          Statement with shorthand operator

      a=a+1                                     a += 1

      a=a–1                                     a -= 1

      a = a *(n + 1)                            a *= n +1

      a = a / (n + 1)                           a /= n +1

      a=a%b                                     a %= b

   5. Increment and Decrement Operators - C allows two very useful operators
      not generally found in other languages. These are the increment and
      decrement operators are :

           Increment Operator        ++

          Decrement Operator         --

      The operator ++ adds 1 to the operand, while – subtracts. Both are unary
operators and takes the following form

             ++a; or a++;

             --a; or a--;

      Here     ++a; is equivalent to a = a+1; (or a +=1;)

               --a; is equivalent to a = a-1; (or a-=1;)

       While ++a and a++ mean the same thing when they form statements
independently they behave differently when they are used in expressions on the
right-hand side of an assignment statement.
             x = 5;

             y = x++;             here: y = 5

             y = ++y;             here: y =6

If ++ is used before a variable then it is called pre increment and if it is used after
a variable then it’s called post increment.

If -- is used before a variable then it is called pre decrement and if it is used after a
variable then it’s called post decrement.

   6. Conditional Operator – A ternary operator pair “? :” is available in C to
      construct conditional expression of the form

             exp1 ? exp2 : exp3;

      Where exp1, exp2, exp3 are expressions.

             a = 5;

             b = 15;

             c = (a>b) ? a : b;

      Then c = b =15

   7. Bitwise Operators – C has a distinction of supporting special operators
      known as bitwise operators for manipulation of data at bit level. These
      operators are used for testing the bits, or shifting them right or left.

             Bitwise operators may not be applied to float or double.

      Operators                                 Meaning
      &                                     Bitwise AND

      !                                     Bitwise OR

      ^                                     Bitwise XOR (Exclusive OR)

      ~                                     Bitwise One’s Complement

      <<                                    Left Shift

      >>                                    Right Shift

Bitwise AND (&)

Ex : (45)10 = (00101101)2 and (7)10 = (00000111 )2

      45 & 7

      (00101101) & (00000111) = (00000101) = 5

      45         0     0       1       0        1         1     0        1

      &          &     &       &       &        &         &    &         &

      7          0     0       0       0        0         1     1        1

      5          0     0       0       0        0         1     0        1

Bitwise OR (|)

Ex : 45 | 23

      (00101101) | (00010111) = (00111111) = 63

      45         0     0       1       0        1         1     0        1
       |        |         |   |      |       |    |   |   |

      23        0         0   0      1       0    1   1   1

      63        0         0   1      1       1    1   1   1

Bitwise XOR (^)

Ex : 45 ^ 23

      (00101101) ^ (00010111) = (00111111) = 58

      45        0         0   1      0       1    1   0   1

       ^        ^         ^   ^      ^       ^    ^   ^   ^

      23        0         0   0      1       0    1   1   1

      58        0         0   1      1       1    0   1   0

Bitwise Left Shift (<<)

Ex : 44 << 1

       00101100 << 1 = 88

      44        0         0   1      0       1    1   0   0

      88        0         1   0      1       1    0   0   0
Bitwise Right Shift (>>)

Ex : 44 >> 1

      00101100 >> 1 = 22

      44            0      0        1       0   1       1      0        0

      22            0      0        0       1   0       1      1        0

Bitwise One’s Compliment

      It converts bit value 1 to 0 or 0 to 1.

               2               0        0           1           0

               ~               ~        ~           ~           ~

               13              1        1           0           1

Binary value of 2 = 0010

                   ~2 = 1101 = 13

For get 2’s complement of any value, we add 1 in one’s complement of that’s

Here – Binary value of 2 = 0010

       1’s complement of value 2 = 1101
       2’s complement of value 2 = 1’s complement of 2 + 1



             1110 = 14 ( 1 + 1 =0 or carry 1)

But in Output we get -3 it’s right because computer give value in 2’s complement.

   8. Special Operators - C supports some special operators of interest of such
      as comma operator, sizeof operator, pointer operators (& and *) and
      member selection operators (. And ->).

        Operator                      Meaning

        sizeof(…..)                   Sizeof Operator

        ,                             List Separator or Comma Operator

        .                             Member Operator

        ->                            Member Operator(For Pointer)

        []                            Array

      The Comma Operator: The comma operator can be used to link the related
expressions together. A comma-linked list of expressions is evaluated left to right
and the value of right-most expression is the value of the combined expression.

Ex. : a=1,b=2,c=6

      x = (a, b, c)

      Then value of x will be 6. It means right most expression will be returned.
      sizeof() Operator: The sizeof is a compile time operator and, when used
with and operand, it returns the number of bytes of the operand occupies.

                The operand may be a variable a constant or a data type qualifier.

Ex. : a = sizeof(float) = 4

        B = sizeof(long int) = 4

Precedence of Arithmetic Operators
       An arithmetic expression without parentheses will be evaluated from left to
right using the rules of precedence of operators. There are two distinct priority
levels of arithmetic operators in C:

                       High Priority         */%

                       Low Priority          +-

Priority                           Operators            Description

First                              *, /, %              Multiply, Division, Reminder

Second                             +,-                  Addition, Subtraction

Third                              =                    Assignment

Ex.      A = 15 – 4 + 8 * 2 – 3

         Step 1 : A = 15 – 4 + 16 – 3

         Step 2 : A = 11 + 16 – 3

         Step 3: A = 27 – 3

         Step 4: A = 24

Rules for Evaluation of Expression
          First, parenthesized sub expressions from left to right are evaluated.

          If parentheses are nested, the evaluation begins with the innermost sub-

Precedence of Operators Used in ‘C’
Operators          Description               Associativity        Rank

()                 Function call             Left to Right        1

[]                 Array element reference

+                  Unary plus                Right to Left        2

-                  Unary minus

++                 Increment

--                 Decrement

!                  Logical negation

~                  One’s complement

*                  Pointer reference

&                  Address

sizeof             Size of an object

*                  Multiplication            Left to Right        3

/                  Division

%                  Modulus (Reminder)

+                  Addition                  Left to Right        4

-                  Subtraction

<<                 Left shift                Left to Right        5

>>                 Right shift

<                  Less than                 Left to Right        6
<=               Less than or equal to

>                Greater than

>=               Greater than or equal to

==               Equality                   Left to Right      7

!=               Inequality

&                Bitwise AND                Left to Right      8

^                Bitwise XOR                Left to Right      9

|                Bitwise OR                 Left to Right      10

&&               Logical AND                Left to Right      11

||               Logical OR                 Left to Right      12

?:               Conditional expression     Right to Left      13

=                Assignment operators       Right to Left      14

*= /= %= += -=

,                Comma operator             Left to Right      15

Type Conversion in Expressions
       There are two types of conversion in C language, are following.

          o Implicit Conversion

          o Explicit Conversion

1. Implicit Conversion: C permits mixing of constants and variables of different
types in an expression. C automatically converts any intermediate values to the
proper type so that the expression can be evaluated without losing any
significance. This automatic conversion is known as implicit type conversion.
      During evaluation it adheres to very strict rules of type conversion. If the
operands are of different types, the ‘lower’ type is automatically converted to the
‘higher’ type before the operation proceeds. The result is of the higher type.

Ex. int k= 7;           float m = 5.5;          char c=’A’;

Expressions                      Result                       Data type of Result

k+m                              12.5                         Float

k+c                              72                           Integer

(k + c) – (2 * m / 5)            69.8                         Float

Here: Integer value of ‘A’ is 65

2.Explicit Conversion: If we want to force a type conversion in a way that is
different from the implicit conversion.

Syntax: (Data type to cast) operand

Ex. float a = 81.5;      a / 2 = 40.75000 and (int) a/2 = 40

Input Output Functions
1 .scanf() : For inputting data using standard input output device.

2. printf() : For printing data at standard input output device.

3. getchar() : For inputting a character from user.

4. putchar() : For printing a character.

5. gets() : For inputting a string.

6. puts() : For printing a string.

Mathematical Functions
Functions                             Meaning

acos(x)           Arc cosine of x

asin(x)           Arc sine of x

atan(x)           Arc tangent of x

atan 2(x,y)       Arc tangent of x/y

cos(x)            Cosine of x

sin(x)            Sine of x

tan(x)            Tangent of x


cosh(x)           Hyperbolic cosine of x

sinh(x)           Hyperbolic sine of x

tanh(x)           Hyperbolic tangent of x

Other functions

ceil(x)           x rounded up to the nearest integer

exp(x)            e to the x power( ex)

fabs(x)           Absolute value of x

floor(x)          x rounded down to the nearest integer

fmod(x,y)         Remainder of x/y

log(x)            Natural log of x, x>0

log10(x)          Base 10 log of x, x>0

pow(x,y)          x to the power y ( xy)
sqrt(x)                        Square root of x, x>0

Note : If we want to use any mathematical function then we will have to use
#include<math.h> header file in the beginning of the program.

Character Functions
Functions                      Test

isalnum(x)                     Is x an alphanumeric character?

isalpha(x)                     Is x an alphabetic character?

isidigit(x)                    Is x a digit?

islower(x)                     Is x lower case letter?

isprint(x)                     Is x a printable characher?

ispunct(x)                     Is x a punctuation mark>

isspacer(x)                    Is x a white space character?

isupper(x)                     Is x an upper case letter?

Note : If we want to use any character function then we will have to use
#include<ctype.h> header file in the beginning of the program.

Control Statements / Decision Making Statements
      As we know a C program is a set of statements which are normally
executed sequentially in the order in which they appear. This happens when no
options or no repetitions of certain calculations are necessary. We have a number
of situations where we may have to change the order of execution of statements
based certain conditions, or repeat a group of statements until certain specified
conditions are met. This involves a kind of decision making to see whether a
particular condition has occurred or not and then direct the computer to execute
certain statements accordingly.
In C language there are three types of Control Statements.
      Branching Statements
           o if
           o switch
           o conditional operator
     Looping Statements
           o while
           o do…while
           o for
     Jumping Statements
           o break
           o continue
           o goto

1.if statement : The general form of a simple if statement is

Syntax - if(test expression)
           {                                                          true
           }                                                 false

ex. – if ( a == 0 )                                  Statement-x


                printf(“You entered Zero”);          Next statement


                                                     Flow chart of simple if
2.if …else statement :

Syntax – if( text expression)


                   True statements;




                   False statements;


Ex. if(per>=36)

        printf(“Pass”);                        True                    False
                                       True statement                     False Statement

    {                                                   Statement-x



3.Nested if…..else Statements :

Syntax – if(test expression)

            if(test expression)











            if(test expression)








                                 true                                           false

        true              Text          false                            true              Text       false
                       expression                                                       expression
                           2                                                                3

True statement                      False statement              True statement                      False statement

                                                Next statement

                                        Flow chart of nested if…else

     Ex. :         if(a>b)




                                 printf(“The largest number %d“,a);




                                 printf(“The largest number %d“,c);






                       printf(“The largest number %d“,b);




                       printf(“The largest number %d“,c);



4.if…..else ladder :

Syntax : if (condition 1)

              Statement 1;

      else if (condition 2)

             Statement 2;

      else if (condition 3)

             Statement 3;


             Default statement;

Statement 1

                          Statement 2

                                                     Statement 3               Default statement

Statement x

    Ex.:      if (per >= 60)


              else if (per >= 45)


              else if (per >=36)



      The switch statement tests the value of a given variable (or expression)
against a list of case values and when a match is found, a block of statements
associated with that case is executed.

Syntax :    switch(expression)


                   case value-1:

                                 block 1;


                   case value-2:

                                 block 2;


                   case value-3:

                                 block 3;




                                 default block;




                                   Expression= value-1        block 1

                                   Expression = value-2
                                                              block 1
                                   Expression = value-3       bl ock 1


                             (No match) default           default block 1   Statement -x

                       Flow chart of switch statement

Ex.   switch(a)


             case 1:



             case 2:



             case 3:



                       printf(“Not one,two,three”);


      This operator is combination of ? and ; and operands and it is also known as
      conditional operator.

              Conditional exp1 ? exp2 : exp3;

      Where exp1, exp2, exp3 are expressions.

              a = 5;

              b = 15;

              c = (a>b) ? a : b;

      Then c = b =15

   It could be nested also

   Y = (a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c);

while Loop
      The while is an entry-controlled loop statement. The test condition is
evaluated and if the condition is true, then the body of loop is executed. After
execution of the body, the test condition is once again evaluated and if true, the
body is executed once again. The process of repeated execution of the body
continues until the test-condition finally becomes false and the control is
transferred out of the loop.

Syntax        while(test condition)

                      Body of loop


                   Test          False

                       True                  Entry Controlled Loop

                 Body of loop

                  Statement -x

      Ex.:   n = 1;                          // Initialization

      while (n<=10)                          // Testing


             printf(“%d”,n ;);

             n++;                            // Incrementing


do while Loop
       There is a minor difference between the working of while and do_while
loops. This difference is the place where the condition is tested. The while tests
the condition before executing any of the statements within the wile loop. As
against this, the do_while tests the condition after having executed the
statements within the loop.

       It is an exit-controlled loop statement.


                    Body of loop

                                                     Exit Controlled Loop


                    Statement -x

Syntax :        do


                        Body of loop


                while (test condition);

Ex.:   n = 1;                                 // Initialization


                printf(“%d”,n ;);

                n++;                          // Incrementing

     while (n<=10);                          // Testing

for Loop
     The for allows us to specify three things about a loop in a single line:

  a) Setting a loop counter to an initial value.

  b) Testing the loop counter to determine whether its value has reached the
     number of repetitions desired.

  c) Increasing the value of loop counter each time the program segment within
     the loop has been executed.

     The general form of for loop statement is as under:


                 Test            False

                    True                     Entry Controlled Loop
              Body of loop


               Statement -x
Syntax: for (initialization ; test-condition ; increment )


               Body of loop ;


Ex.:       for (a=0; a<5; a++)




It is also an entry controlled loop statement.

Nesting of for loop
       Nesting of loop is one for statement within another for statement.



       for (i=1; i<5; i++)



               for(j=1; j<5; j++)






       In such a situations where we want to jump of a loop instantly, the keyword
break allows us to do this. When a break statement is encountered inside any
loop, the loop is immediately exited and the program continues with the
statement immediately following the loop. When the loops are nested, the break
would only exit from the loop containing it.

        A break is usually associated with an if condition.

Syntax :

        while(……..)                                   do

        {                                             {

            -----------                                       -----------

                      if (condition)                                   if (condition)

                             break;                                             break;

                         ------------                                  -------------

        }                                             } while (---------);

        ---------                                     ----------

                   (A)                                        (B)

        for (-----------)                             for(---------)

        {                                             {

                ----------                                    ----------

                if (condition)                                for(----------)
                 break;                                   {

                  ----------                                      --------

       }                                                          if(condition)

               ------------                                                  break;






               (C)                                                (D)

      In some programming situations, we want to take the control to the
beginning of the loop, bypassing the statements inside the loop, which have not
yet been executed. When continue is encountered inside any loop, control
automatically passes to the beginning of the loop.

Syntax :

      while(……..)                                 do

      {                                           {

           -----------                                    -----------

                   if (condition)                                 if (condition)

                         continue;                                continue;

                         ------------                             ------------
}                                          } while (---------);

      ---------                                   ----------

               (A)                                         (B)

      for (-----------)



           if (condition)






      C supports the goto statement to branch unconditionally from one point to
another in the program. The goto requires a label in order to identify the place
where the branch is to be made. A label is any valid variable name, and must be
followed by a colon. The label is placed immediately before the statement where
the control is to be transferred.

      The general form of goto and label statements are shown below:

      goto label;                                 label:

      ------------                                statement;

      ------------                                ------------

      label:                                      ------------
      statement;                                   goto label;

The label: can be anywhere in the program either before or after the goto label;
statement. During running of a program when a statement like goto end; is met,
the flow of control will jump to the statement immediately following the label
end. This happens unconditionally.

If the label: is before the statement goto label; such a jump is known as a
backward jump. On the other hand, if he label: is placed after the goto label; jump
is known as a forward jump.

     An array is a fixed-size sequenced collection of elements of the
same data type. It is simply a grouping of like-type data. In its simplest
form, an array can be used to represent a list of numbers, or a list of

     An array is a sequenced collection of related data items that share
a common name. For instance, we can use an array name marks to
represent a set of marks of a student.

Syntax : int marks[6];

      Here the complete set of values is referred to as an array,
individual values are called elements.

There are two types of arrays.

      One-Dimensional Array

      Two-Dimensional Array / Multi-Dimensional Array
One-Dimensional Array
     A list of items can be given one variable name using only one
subscript and such a variable is called a single-subscripted variable or a
one-dimensional array.

Declaration of One-Dimensional Array

      Data-type variable-name[size/dimension];

Initialization of One-Dimensional Array

Ex.       int a[5];

          a[1] = 8;

          a[2] = 10;

          a[3] = 7;

          a[4] = 5;

          a[5] = 15;


          int a[5] = {8,10,7,5,15};


          int a[] = {8,10,7,5,15};

      a[1]     a[2]    a[3]     a[4]   a[5]      Index value of variable a

      8        10      7        5      15        Stored Data

      6815 6817 6819            6821 6823        Memory Location
Two-Dimensional Array / Multi-Dimensional Array
       As you know the array variables can store a list of values. But there could
be a situation where a table of values will have to be stored. In such a situation
we can use Two-Dimensional or Multi-Dimensional Array.

       Two-Dimensional Arrays are declared as follow:

             Data-type variable-name [row_size][column_size];
                        int a[3][2];



                   Column1        Column2

Row1              78             69

                   [1][1]          [1][1]

Row2              86             87

                   [2][1]          [2][2]

Row3              45             60

                   [3][1]          [3][2]
Initialization of One-Dimensional Array
      int table[2][3] = { 0,0,0,1,1,1};


      int table[2][3] = { {0,0,0}, {1,1,1} };


      int table[2][3] = {





      int table[ ][3] = {




Multi-Dimensional Array

      Data-type variable-name[d1][d2][d3];

Ex.   int a[2][2][2];
      A string is a sequence of characters that is treated as a single data
item. Any group of characters (except double quote sign) defined
between double quotations marks is a string constant. We can also say
one dimensional of character array is called a String.

Declaring and Initializing String variables

      C does not support strings as a data type. It allows us to represent
strings as character arrays. A string variable is any valid C variable name
and is always declared as an array of characters.

Syntax:    char string_name[size];

Example: char name[20];

            char address[30];

            char city[10+ = “Didwana”;

            char city*10+= ,‘D’,’i’,’d’,’w’,’a’,’n’,’a’,’\0’};

In string “Didwana” there are 8 characters. Because every string has a
character at the end of string that is called Null character. If there is no
null character then it’s so difficult to find out where is the string

Reading Strings from terminal

Using scanf function

Using scanf function we can input a string.

Ex. char city[10];

But the problem with the scanf function is that it terminates its input
on the first white space it finds. A white space includes blanks, tabs,
carriage returns, form feeds, and new lines.

We can also use %s in following type:



Ex: scanf(“%*abc+s”,name);         // Only a, b and c allowed.

   scanf(“%*^abc+s”,name);         // All allowed except a, b and c.

   scanf(“%*^\n+s”,name);          // All allowed except \n (Enter Key).

NOTE:- In the case of character arrays, the ampersand(&) is not
required before the variable name.

Using getchar and gets functions

      As we know using getchar function we can store a character in a
variable. If we use this function repeatedly to read successive single
characters from the input and place them into a character array. Thus,
as entire line of text can be read and stored in an array.

      There is also one another function (gets) that allows to input a
line with white space. It reads characters into a variable from keyboard
until a new-line character is encountered and then appends a null
character to the string.
Ex.   char line[80];



Using putchar and puts functions
      Using putchar function we can print a character that is stored in a variable.
We can use this function repeatedly to output a string of characters stored in an
array using a loop.

      char ch = ‘S’;

      putchar (ch);              // printf(“%c”,ch);

Output : S

      char city*20+ = “didwana”;

      for (i=0; i<20; i++)


Output: didwana

      There is also one another function (puts) that allows printing an array of
characters (string).

      char line[80];


Strings Functions
Functions                      Test

strlen(a)                      To find out length of string

strlwr(a)                      To convert Capital letter into Small letter

strupr(a)                      To convert Small letter into Capital letter

strcat(a,b)                    To add two strings (a+b)

strncat(a,b,number)            To add two strings (a+n character of string b)

strcpy(b,a)                    To copy string a in string b

strcmp(a,b)                    To compare between string a and string b(case

strcmpi(a,b)                   To compare between string a and string b(case

strrev(a)                      To get reverse of string a

      Note: If we want to use any string function then we will have to use
#include<string.h> header file in the beginning of the program.

To top