Friday, 5 July 2013

C Programming Language Tutorial pdf free download

C Programming Introduction | C Programming Tutorial pdf


The C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system.
C is the most widely used computer language.
This tutorial should be your starting point only.

C Language History | C Programming Tutorial pdf

                               C – Language History                                                                                                                             

  • C language is a structure oriented programming language, was developed at Bell Laboratories in 1972 by Dennis Ritchie
  • C features were derived from earlier language called “B” (BCPL language)
  • C was invented for implementing UNIX operating system
  • In 1978, Dennis Ritchie and Brian Kernighan published the first edition  “The C Programming Language” and commanly known as K&R C
  • In 1983, the American National Standards Institute (ANSI) established a committee to provide a modern, comprehensive definition of C. The resulting definition, the ANSI standard, or “ANSI C”, was completed late 1988.

C standards:

  • C89/C90 standard – First standardized specification for C language was developed by American National Standards Institute in 1989. C89 and C90 standards refer to the same programming language.
  • C99 standard – Next revision was published in 1999 that introduced new futures like advanced data types and other changes.
  • C11 and Embedded C
  • C11 standard adds new features to C and library like type generic macros, anonymous structures, improved Unicode support, atomic operations, multi-threading, and bounds-checked functions. It also makes some portions of the existing C99 library optional, and improves compatibility with C++.
  • Embedded C includes features not available in normal C like fixed-point arithmetic, named address spaces, and basic I/O hardware addressing
  • Operating systems, C compiler, all UNIX application programs are written in C
  • It is also called as procedure oriented programming language
  • C language is reliable, simple and easy to use.
  • C has been coded in assembly language

Features of C language:

  • Reliability
  • Portability
  • Flexibility
  • Interactivity
  • Modularity
  • Efficiency and Effectiveness

Uses of C language:

     C is used for developing system applications that forms portion of operating system. Below are some examples of C being used.
  • Database systems
  • Graphics packages
  • Word processors
  • Spread sheets
  • Operating system development
  • Compilers and Assemblers
  • Network drivers
  • Interpreters

C Basic Programming | C Programming Tutorial pdf

                      C – Basic Program

We are going to learn a simple “Hello World” program in this section. Functions, syntax and the basics of a C program are explained in below table.

Output:
Hello World!
Let us see the performance of above program line by line.

Compile and execute C program:
Compilation is the process of converting a C program which is user readable code into machine readable code which is 0′s and 1′s.
This compilation process is done by a compiler which is an inbuilt program in C.
As a result of compilation, we get another file called executable file. This is also called as binary file.
This binary file is executed to get the output of the program based on the logic written into it.
Steps to compile & execute a C program:
Step1 Type the above C basic program in a text editor and save as “sample.c”.
Step2 To compile this program, open the command prompt and goto the directory where you have saved this program and type “cc sample.c” or “gcc sample.c”.
Step3 If there is no error in above program, executable file will be generated in the name of “a.out”.
Step4 To run this executable file, type “./a.out” in command prompt.
Step5 You will see the output as shown in the above basic program.
C basic structure:

As already mentioned,c basic structure is defined by set of rules called protocol, to be followed by programmer while writing C program. Below is the C basic structure.

c basic structure in an example program:


Output:
This is main function
Total = 2
Let us see about each section of a C basic program in detail below. All below sections together are called as C basic structure.

Structure of C in real time application programs:
We have given simple real time application programs where the structure of a complete C program is shown. You can refer below C programs to know how to use C basics in real time programs.

Real time application C programs for your reference:

1.       C program example – Real time Calculator program

2.       C program example – Real time Bank Application program

Key points to remember:

  • Execution of every C program starts from main() function.
  • Protocol is set of rules to be followed by a programmer to write a program.                                                                                                            


C Printf and Scanf | C Programming Tutorial pdf

                             C – Printf and Scanf                                                                                                                  

C printf():

The printf() function can be used to print the character, string, float, integer, octal and hexadecimal values onto the output screen.

To display the value of an integer variable, we use printf  statement with the %d format specifier.
Similarly %c for character, %f for float variable,%s for string variable, %lf for double, %x for hexadecimal variable.
To generate a newline,we use /n in C printf statement.

Example program for C printf():

#include <stdio.h>

int main()
{
   char  ch = 'A';
   char  str[20] = "fresh2refresh.com";
   float flt = 10.234;
   int no = 150;

   double dbl = 20.123456;
   printf("Character is %c \n", ch);
   printf("String is %s \n" , str);
   printf("Float value is %f \n", flt);
   printf("Integer value is %d\n" , no);

   printf("Double value is %lf \n", dbl);
   printf("Octal value is %o \n", no);
   printf("Hexadecimal value is %x \n", no);

   return 0;

}

 Output:
Character is A
String is fresh2refresh.com
Float value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96
You can see the output with the same data which are placed within the double quotes of printf statement in the program except
%d got replaced by value of an integer variable(no),
%c got replaced by value of a character variable(ch),
%f got replaced by value of a float variable(flt),
%lf got replaced by value of a double variable(dbl),
%s got replaced by value of a string variable(str),
%o got replaced by a Octal value corresponding to integer variable(no),
%x got replaced by a hexadecimal value corresponding to integer variable(no),
\n got replaced by a newline.

C scanf :

scanf() function can be used to read a character, string,  numeric data from keyboard.
Consider the below example where the user enters a character and assign it to the variable ch and enters a string and assign it to the variable str.
Example program for C printf() and scanf():

#include <stdio.h>

int main()
{
    char ch;
    char str[100];

    printf("Enter any character \n");
    scanf("%c", &ch);
    printf("Entered character is %c \n", ch);

    printf("Enter any string ( upto 100 character ) \n");
    scanf("%s", &str);
    printf("Entered string is %s \n", str);
}

 Output:
Enter any character
a
Entered character is a
Enter any string ( upto 100 character )
hai
Entered string is hai

The format specifier %d is used in scanf statement so that the value entered is received as an integer and %s for string.
Ampersand is used before the variable name ch in scanf statement as &ch. It is just like in a pointer which is to point to the variable.For more information about how pointer works.

C Program Structure | C Programming Tutorial pdf

A C program basically has the following form:

  • Preprocessor Commands
  • Functions
  • Variables
  • Statements & Expressions
  • Comments

The following program is written in the C programming language. Open a text file hello.c using vi editor and put the following lines inside that file.

#include <stdio.h>

int main()
{
   /* My first program */
   printf("Hello, World! \n");
   
   return 0;
}
Preprocessor Commands: These commands tells the compiler to do preprocessing before doing actual compilation. Like #include <stdio.h> is a preprocessor command which tells a C compiler to include stdio.h file before going to actual compilation. You will learn more about C Preprocessors in C Preprocessors session.

Functions: are main building blocks of any C Program. Every C Program will have one or more functions and there is one mandatory function which is called main() function. This function is prefixed with keyword int which means this function returns an integer value when it exits. This integer value is retured using return statement.

The C Programming language provides a set of built-in functions. In the above example printf() is a C built-in function which is used to print anything on the screen. Check Builtin function section for more detail.

You will learn how to write your own functions and use them in Using Function session.

Variables: are used to hold numbers, strings and complex data for manipulation. You will learn in detail about variables in C Variable Types.

Statements & Expressions : Expressions combine variables and constants to create new values. Statements are expressions, assignments, function calls, or control flow statements which make up C programs.

Comments: are used to give additional useful information inside a C Program. All the comments will be put inside /*...*/ as given in the example above. A comment can span through multiple lines.

Note the followings

C is a case sensitive programming language. It means in C printf and Printf will have different meanings.

C has a free-form line structure. End of each C statement must be marked with a semicolon.

Multiple statements can be one the same line.

White Spaces (ie tab space and space bar ) are ignored.

Statements can continue over multiple lines.

C Program Compilation
To compile a C program you would have to Compiler name and program files name. Assuming your compiler's name is cc and program file name is hello.c, give following command at Unix prompt.

$cc hello.c
This will produce a binary file called a.out and an object file hello.o in your current directory. Here a.out is your first program which you will run at Unix prompt like any other system program. If you don't like the name a.out then you can produce a binary file with your own name by using -o option while compiling C program. See an example below

$cc -o hello hello.c
Now you will get a binary with name hello. Execute this program at Unix prompt but before executing / running this program make sure that it has execute permission set. If you don't know what is execute permission then just follow these two steps

$chmod 755 hello
$./hello

This will produce following result
Hello, World
Congratulations!! you have written your first program in "C". Now believe me its not difficult to learn "C".

C Basic Datatypes | C Programming Tutorial pdf

C has a concept of 'data types' which are used to define a variable before its use. The definition of a variable will assign storage for the variable and define the type of data that will be held in the location.
The value of a variable can be changed any time.
C has the following basic built-in datatypes.
int
float
double
char
Please note that there is not a boolean data type. C does not have the traditional view about logical comparison, but thats another story.

int - data type:

int is used to define integer numbers.
    {
        int Count;
        Count = 5;
    }

float - data type:

float is used to define floating point numbers.
    {
        float Miles;
        Miles = 5.6;
    }

double - data type:

double is used to define BIG floating point numbers. It reserves twice the storage for the number. On PCs this is likely to be 8 bytes.
    {
        double Atoms;
        Atoms = 2500000;
    }

char - data type:

char defines characters.
    {
        char Letter;
        Letter = 'x';
    }

Modifiers:

The data types explained above have the following modifiers.
  • short
  • long
  • signed
  • unsigned
The modifiers define the amount of storage allocated to the variable. The amount of storage allocated is not cast in stone. ANSI has the following rules:
        short int <=    int <= long int
            float <= double <= long double

What this means is that a 'short int' should assign less than or the same amount of storage as an 'int' and the 'int' should be less or the same bytes than a 'long int'. What this means in the real world is:
                 Type Bytes             Range
---------------------------------------------------------------------
            short int  2             -32,768 -> +32,767          (32kb)
   unsigned short int  2         0 -> +65,535          (64Kb)
         unsigned int  4             0 -> +4,294,967,295   ( 4Gb)
                  int  4                  -2,147,483,648 -> +2,147,483,647   ( 2Gb)
             long int  4                -2,147,483,648 -> +2,147,483,647   ( 2Gb)
          signed char  1             -128 -> +127
        unsigned char  1              0 -> +255
                float  4
               double  8
          long double 12 

These figures only apply to todays generation of PCs. Mainframes and midrange machines could use different figures, but would still comply with the rule above.
You can find out how much storage is allocated to a data type by using the sizeof operator discussed in Operator Types Session.
Here is an example to check size of memory taken by various datatypes.
int
main()
{
  printf("sizeof(char) == %d\n", sizeof(char));
  printf("sizeof(short) == %d\n", sizeof(short));
  printf("sizeof(int) == %d\n", sizeof(int));
  printf("sizeof(long) == %d\n", sizeof(long));
  printf("sizeof(float) == %d\n", sizeof(float));
  printf("sizeof(double) == %d\n", sizeof(double));
  printf("sizeof(long double) == %d\n", sizeof(long double));
  printf("sizeof(long long) == %d\n", sizeof(long long));
  return 0;
}

Qualifiers:

A type qualifier is used to refine the declaration of a variable, a function, and parameters, by specifying whether:

The value of a variable can be changed.
The value of a variable must always be read from memory rather than from a register
Standard C language recognizes the following two qualifiers:
const
volatile
The const qualifier is used to tell C that the variable value can not change after initialisation.
const float pi=3.14159;
Now pi cannot be changed at a later time within the program.
Another way to define constants is with the #define preprocessor which has the advantage that it does not use any storage
The volatile qualifier declares a data type that can have its value changed in ways outside the control or detection of the compiler (such as a variable updated by the system clock or by another program). This prevents the compiler from optimizing code referring to the object by storing the object's value in a register and re-reading it from there, rather than from memory, where it may have changed. You will use this qualifier once you will become expert in "C". So for now just proceed.

What are Arrays:

We have seen all baisc data types. In C language it is possible to make arrays whose elements are basic types. Thus we can make an array of 10 integers with the declaration.
int x[10];
The square brackets mean subscripting; parentheses are used only for function references. Array indexes begin at zero, so the elements of x are:
Thus Array are special type of variables which can be used to store multiple values of same data type. Those values are stored and accessed using subscript or index.
Arrays occupy consecutive memory slots in the computer's memory.
x[0], x[1], x[2], ..., x[9]
If an array has n elements, the largest subscript is n-1.
Multiple-dimension arrays are provided. The declaration and use look like:
      int name[10] [20];
      n = name[i+j] [1] + name[k] [2];
Subscripts can be arbitrary integer expressions. Multi-dimension arrays are stored by row so the rightmost subscript varies fastest. In above example name has 10 rows and 20 columns.
Same way, arrays can be defined for any data type. Text is usually kept as an array of characters. By convention in C, the last character in a character array should be a `\0' because most programs that manipulate character arrays expect it. For example, printf uses the `\0' to detect the end of a character array when printing it out with a `%s'.
Here is a program which reads a line, stores it in a buffer, and prints its length (excluding the newline at the end).
       main( ) {
               int n, c;
               char line[100];
               n = 0;
               while( (c=getchar( )) != '\n' ) {
                       if( n < 100 )
                               line[n] = c;
                       n++;
               }
               printf("length = %d\n", n);
       }

Array Initialization:

As with other declarations, array declarations can include an optional initialization
Scalar variables are initialized with a single value
Arrays are initialized with a list of values
The list is enclosed in curly braces
int array [8] = {2, 4, 6, 8, 10, 12, 14, 16};
The number of initializers cannot be more than the number of elements in the array but it can be less in which case, the remaining elements are initialized to 0.if you like, the array size can be inferred from the number of initializers by leaving the square brackets empty so these are identical declarations:
int array1 [8] = {2, 4, 6, 8, 10, 12, 14, 16};
int array2 [] = {2, 4, 6, 8, 10, 12, 14, 16};

An array of characters ie string can be initialized as follows:
char string[10] = "Hello";

C Variable Types | C Programming Tutorial pdf

A variable is just a named area of storage that can hold a single value (numeric or character). The C language demands that you declare the name of each variable that you are going to use and its type, or class, before you actually try to do anything with it.

The Programming language C has two main variable types

  • Local Variables
  • Global Variables


Local Variables:

Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block.

When a local variable is defined - it is not initalised by the system, you must initalise it yourself.

When execution of the block starts the variable is available, and when the block ends the variable 'dies'.

Check following example's output

   main()
   {
      int i=4;
      int j=10;
   
      i++;
   
      if (j > 0)
      { 
         /* i defined in 'main' can be seen */
         printf("i is %d\n",i); 
      }
   
      if (j > 0)
      {
         /* 'i' is defined and so local to this block */
         int i=100; 
         printf("i is %d\n",i);      
      }/* 'i' (value 100) dies here */
   
      printf("i is %d\n",i); /* 'i' (value 5) is now visable.*/
   }
   
   This will generate following output
   i is 5
   i is 100
   i is 5
Here ++ is called incremental operator and it increase the value of any integer variable by 1. Thus i++ is equivalent to i = i + 1;

You will see -- operator also which is called decremental operator and it idecrease the value of any integer variable by 1. Thus i-- is equivalent to i = i - 1;

Global Variables:

Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it.

Global variables are initalised automatically by the system when you define them!

Data Type  Initialser
int                    0
char                  '\0'
float                    0
pointer          NULL
If same variable name is being used for global and local variable then local variable takes preference in its scope. But it is not a good practice to use global variables and local variables with the same name.

   int i=4;          /* Global definition   */
   
   main()
   {
       i++;          /* Global variable     */
       func();
       printf( "Value of i = %d -- main function\n", i );
   }

   func()
   {
       int i=10;     /* Local definition */
       i++;          /* Local variable    */
       printf( "Value of i = %d -- func() function\n", i );
   }

   This will produce following result
   Value of i = 11 -- func() function
   Value of i = 5 -- main function
i in main function is global and will be incremented to 5. i in func is internal and will be incremented to 11. When control returns to main the internal variable will die and and any reference to i will be to the global.

C Storage Classes | C Programming Tutorial pdf

A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program.

There are following storage classes which can be used in a C Program

  • auto
  • register
  • static
  • extern

auto - Storage Class

auto is the default storage class for all local variables.

{
            int Count;
            auto int Month;
}
The example above defines two variables with the same storage class. auto can only be used within functions, i.e. local variables.

register - Storage Class

register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and cant have the unary '&' operator applied to it (as it does not have a memory location).

{
            register int  Miles;
}
Register should only be used for variables that require quick access - such as counters. It should also be noted that defining 'register' goes not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register - depending on hardware and implimentation restrictions.

static - Storage Class

static is the default storage class for global variables. The two variables below (count and road) both have a static storage class.

static int Count;
        int Road;

        {
            printf("%d\n", Road);
        }
static variables can be 'seen' within all functions in this source file. At link time, the static variables defined here will not be seen by the object modules that are brought in.

static can also be defined within a function. If this is done the variable is initalised at run time but is not reinitalized when the function is called. This inside a function static variable retains its value during vairous calls.

   void func(void);
   
   static count=10; /* Global variable - static is the default */
   
   main()
   {
     while (count--) 
     {
         func();
     }
   
   }
   
   void func( void )
   {
     static i = 5;
     i++;
     printf("i is %d and count is %d\n", i, count);
   }
   
   This will produce following result
   
   i is 6 and count is 9
   i is 7 and count is 8
   i is 8 and count is 7
   i is 9 and count is 6
   i is 10 and count is 5
   i is 11 and count is 4
   i is 12 and count is 3
   i is 13 and count is 2
   i is 14 and count is 1
   i is 15 and count is 0

NOTE : Here keyword void means function does not return anything and it does not take any parameter. You can memoriese void as nothing. static variables are initialized to 0 automatically.

Definition vs Declaration : Before proceeding, let us understand the difference between defintion and declaration of a variable or function. Definition means where a variable or function is defined in realityand actual memory is allocated for variable or function. Declaration means just giving a reference of a variable and function. Through declaration we assure to the complier that this variable or function has been defined somewhere else in the program and will be provided at the time of linking. In the above examples char *func(void) has been put at the top which is a declaration of this function where as this function has been defined below to main() function.

There is one more very important use for 'static'. Consider this bit of code.

   char *func(void);

   main()
   {
      char *Text1;
      Text1 = func();
   }

   char *func(void)
   {
      char Text2[10]="martin";
      return(Text2);
   }
Now, 'func' returns a pointer to the memory location where 'text2' starts BUT text2 has a storage class of 'auto' and will disappear when we exit the function and could be overwritten but something else. The answer is to specify

    static char Text[10]="martin";
The storage assigned to 'text2' will remain reserved for the duration if the program.

extern - Storage Class

extern is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern' the variable cannot be initalized as all it does is point the variable name at a storage location that has been previously defined.

When you have multiple files and you define a global variable or function which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to decalre a global variable or function in another files.

File 1: main.c

   int count=5;

   main()
   {
     write_extern();
   }

File 2: write.c

   void write_extern(void);

   extern int count;

   void write_extern(void)
   {
     printf("count is %i\n", count);
   }
Here extern keyword is being used to declare count in another file.

Now compile these two files as follows

   gcc main.c write.c -o write
This fill produce write program which can be executed to produce result.

Count in 'main.c' will have a value of 5. If main.c changes the value of count - write.c will see the new value

C CONSTANTS AND LITERALS | C Programming Tutorial pdf

Constants:

The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after their definition.

Integer literals:

An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x
or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,
respectively. T he suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals:
212                    /* Legal */
215u                  /* Legal */
0xFeeL             /* Legal */
078                 /* Illegal: 8 is not an octal digit */
032UU          /* Illegal: cannot repeat a suffix */
Following are other examples of various type of Integer literals:
85                  /* decimal */
0213             /* octal */
0x4b            /* hexadecimal */
30               /* int */
30u            /* unsigned int */
30l            /* long */
30ul         /* unsigned long */

Floating-point literals:

A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can  represent floating point literals either in decimal form or exponential form.
While representing using decimal form, you must include the decimal point, the exponent, or both and while  representing using exponential form, you must include the integer part, the fractional part, or both.
The signed exponent is introduced by e or E.
Here are some examples of floating-point literals:
3.14159                           /* Legal */
314159E-5L                   /* Legal */
510E                              /* Illegal: incomplete exponent */
210f                              /* Illegal: no decimal or exponent */
.e55                             /* Illegal: missing integer or fraction */

Character constants:

Character literals are enclosed in single quotes e.g., 'x' and can be stored in a simple variable of char type. A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0').
T here are certain characters in C when they are proceeded by a back slash they will have special meaning and they are used to represent like newline (\n) or tab (\t). Here you have a list of some of such escape sequence codes

Following is the example to show few escape sequence characters:
#include <stdio.h>
int main()
{
printf("Hello\tWorld\n\n");
return 0;
}
When the above code is compiled and executed, it produces following result:
Hello   World

String literals:

String literals or constants are enclosed in double quotes "". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.
Y ou can break a long lines into multiple lines using string literals and separating them using whitespaces. Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"

Defining Constants:

T here are two simple ways in C to define constants:
1. Using #define preprocessor.
2. Using const keyword.

1. The #define Preprocessor
Following is the form to use #define preprocessor to define a constant:
#define identifier value
Following example explains it in detail:
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces following result:
value of area : 50

The const Keyword:

Y ou can use const prefix to declare constants with a specific type as follows:
const type variable = value;
Following example explains it in detail:
#include <stdio.h>
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces following result:
value of area : 50

C Operator Types | C Programming Tutorial pdf

What is Operator?

Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. C language supports following type of operators.


  • Arithmetic Operators
  • Logical (or Relational) Operators
  • Bitwise Operators
  • Assignment Operators
  • Misc Operators


Lets have a look on all operators one by one.

Arithmetic Operators:

There are following arithmetic operators supported by C language:

Assume variable A holds 10 and variable B holds 20 then:

Show Examples

Logical (or Relational) Operators:

There are following logical operators supported by C language

Assume variable A holds 10 and variable B holds 20 then:

Show Examples

Bitwise operators:

Bitwise operator works on bits and perform bit by bit operation.

Assume if A = 60; and B = 13; Now in binary format they will be as follows:

A = 0011 1100

B = 0000 1101

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

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A  = 1100 0011

Show Examples

There are following Bitwise operators supported by C language

Assignment Operators:

There are following assignment operators supported by C language:

Show Examples

Short Notes on L-VALUE and R-VALUE:

x = 1; takes the value on the right (e.g. 1) and puts it in the memory referenced by x. Here x and 1 are known as L-VALUES and R-VALUES respectively L-values can be on either side of the assignment operator where as R-values only appear on the right.

So x is an L-value because it can appear on the left as we've just seen, or on the right like this: y = x; However, constants like 1 are R-values because 1 could appear on the right, but 1 = x; is invalid.

Misc Operators:

There are few other operators supported by C Language.

Show Examples

Operators Categories:

All the operators we have discussed above can be categorised into following categories:

Postfix operators, which follow a single operand.

Unary prefix operators, which precede a single operand.

Binary operators, which take two operands and perform a variety of arithmetic and logical operations.

The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression.

Assignment operators, which assign a value to a variable.

The comma operator, which guarantees left-to-right evaluation of comma-separated expressions.

Precedence of C Operators:

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedenace than + so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedenace operators will be evaluated first.


C Flow Control Statements | C Programming Tutorial pdf


C provides two sytles of flow control:

  • Branching
  • Looping

Branching is deciding what actions to take and looping is deciding how many times to take a certain action.

Branching:

Branching is so called because the program chooses to follow one branch or another.

if statement

This is the most simple form of the branching statements.

It takes an expression in parenthesis and an statement or block of statements. if the expression is true then the statement or block of statements gets executed otherwise these statements are skipped.

NOTE: Expression will be assumed to be true if its evaulated values is non-zero.

if statements take the following form:
Show Example

? : Operator:

The ? : operator is just like an if ... else statement except that because it is an operator you can use it within expressions.

? : is a ternary operator in that it takes three values, this is the only ternary operator C has.

? : takes the following form:

Show Example

if condition is true ? then X return value : otherwise Y value;

switch statement:

The switch statement is much like a nested if .. else statement. Its mostly a matter of preference which you use, switch statement can be slightly more efficient and easier to read.

Show Example

switch( expression )
     {
        case constant-expression1: statements1;
        [case constant-expression2: statements2;]    
        [case constant-expression3: statements3;]
        [default : statements4;]
     }
Using break keyword:

If a condition is met in switch case then execution continues on into the next case clause also if it is not explicitly specified that the execution should exit the switch statement. This is achieved by using break keyword.

Try out given example Show Example

What is default condition:

If none of the listed conditions is met then default condition executed.

Try out given example Show Example


Looping:

Loops provide a way to repeat commands and control how many times they are repeated. C provides a number of looping way.

while loop

The most basic loop in C is the while loop.A while statement is like a repeating if statement. Like an If statement, if the test condition is true: the statments get executed. The difference is that after the statements have been executed, the test condition is checked again. If it is still true the statements get executed again.This cycle repeats until the test condition evaluates to false.

Basic syntax of while loop is as follows:

Show Example

while ( expression )
{
   Single statement 
   or
   Block of statements;
}
for loop:

for loop is similar to while, it's just written differently. for statements are often used to proccess lists such a range of numbers:

Basic syntax of for loop is as follows:

Show Example

for( expression1; expression2; expression3)
{
   Single statement
   or
   Block of statements;
}

In the above syntax:

expression1 - Initialisese variables.
expression2 - Condtional expression, as long as this condition is true, loop will keep executing.
expression3 - expression3 is the modifier which may be simple increment of a variable.
do...while loop

do ... while is just like a while loop except that the test condition is checked at the end of the loop rather than the start. This has the effect that the content of the loop are always executed at least once.

Basic syntax of do...while loop is as follows:

Show Example

do
{
   Single statement
   or
   Block of statements;
}while(expression);

break and continue statements:

C provides two commands to control how we loop:

  • break -- exit form loop or switch.
  • continue -- skip 1 iteration of loop.

You already have seen example of using break statement. Here is an example showing usage of continue statement.

This will produce following output:

C Input and Output | C Programming Tutorial pdf

Input : In any programming language input means to feed some data into program. This can be given in the form of file or from command line. C programming language provides a set of built-in functions to read given input and feed it to the program as per requirement.

Output : In any programming language output means to display some data on screen, printer or in any file. C programming language provides a set of built-in functions to output required data.

Here we will discuss only one input function and one putput function just to understand the meaning of input and output. Rest of the functions are given into C - Built-in Functions

printf() function

This is one of the most frequently used functions in C for output. ( we will discuss what is function in subsequent chapter. ).

Try following program to understand printf() function.

#include <stdio.h>

main()
{
  int dec = 5;
  char str[] = "abc";
  char ch = 's';
  float pi = 3.14;

  printf("%d %s %f %c\n", dec, str, pi,  ch);
}
The output of the above would be:

       5 abc 3.140000 c
Here %d is being used to print an integer, %s is being usedto print a string, %f is being used to print a float and %c is being used to print a character.

A complete syntax of printf() function is given in C - Built-in Functions

scanf() function

This is the function which can be used to to read an input from the command line.

Try following program to understand scanf() function.

#include <stdio.h>

main()
{
  int x;
  int args;

  printf("Enter an integer: ");
  if (( args = scanf("%d", &x)) == 0) {
      printf("Error: not an integer\n");
  } else {
      printf("Read in %d\n", x);
  }
}
Here %d is being used to read an integer value and we are passing &x to store the vale read input. Here &indicates the address of variavle x.

This program will prompt you to enter a value. Whatever value you will enter at command prompt that will be output at the screen using printf() function. If you eneter a non-integer value then it will display an error message.

Enter an integer: 20
Read in 20

C Pointing to Data | C Programming Tutorial pdf

A pointer is a special kind of variable. Pointers are designed for storing memory address i.e. the address of another variable. Declaring a pointer is the same as declaring a normal variable except you stick an asterisk '*' in front of the variables identifier.
  • There are two new operators you will need to know to work with pointers. The "address of" operator '&' and the "dereferencing" operator '*'. Both are prefix unary operators.
  • When you place an ampersand in front of a variable you will get it's address, this can be stored in a pointer vairable.
  • When you place an asterisk in front of a pointer you will get the value at the memory address pointed to.
Here is an example to understand what I have stated above.




This will produce following result.



Pointers and Arrays:
The most frequent use of pointers in C is for walking efficiently along arrays. In fact, in the implementation of an array, the array name represents the address of the zeroth element of the array, so you can't use it on the left side of an expression. For example:

   char *y;
   char x[100];
y is of type pointer to character (although it doesn't yet point anywhere). We can make y point to an element of x by either of

   y = &x[0];
   y = x;
Since x is the address of x[0] this is legal and consistent. Now `*y' gives x[0]. More importantly notice the following:

   *(y+1)  gives x[1]
   *(y+i)  gives x[i]

and the sequence

   y = &x[0];
   y++;

leaves y pointing at x[1].

Pointer Arithmetic:

C is one of the few languages that allows pointer arithmetic. In other words, you actually move the pointer reference by an arithmetic operation. For example:

  int x = 5, *ip = &x;
  ip++;
On a typical 32-bit machine, *ip would be pointing to 5 after initialization. But ip++; increments the pointer 32-bits or 4-bytes. So whatever was in the next 4-bytes, *ip would be pointing at it.

Pointer arithmetic is very useful when dealing with arrays, because arrays and pointers share a special relationship in C.
Using Pointer Arithmetic With Arrays:
Arrays occupy consecutive memory slots in the computer's memory. This is where pointer arithmetic comes in handy - if you create a pointer to the first element, incrementing it one step will make it point to the next element.



This will produce following result:



See more examples on Pointers and Array


Pointers and const Type Qualifier:

  • The const type qualifier can make things a little confusing when it is used with pointer declarations.
  • The below example
       
As you can see, you must be careful when specifying the const qualifier when using pointers.

Modifying Variables Using Pointers:

You know how to access the value pointed to using the dereference operator, but you can also modify the content of variables. To achieve this, put the dereferenced pointer on the left of the assignment operator, as shown in this example, which uses an array:



This will produce following result:



Generic Pointers: ( void Pointer )

When a variable is declared as being a pointer to type void it is known as a generic pointer. Since you cannot have a variable of type void, the pointer will not point to any data and therefore cannot be dereferenced. It is still a pointer though, to use it you just have to cast it to another kind of pointer first. Hence the term Generic pointer. This is very useful when you want a pointer to point to data of different types at different times.

Try the following code to understand Generic Pointers.

NOTE-1 : Here in first print statement, the_data is prefixed by *(int*). This is called type casting in C language.Type is used to caste a variable from one data type to another datatype to make it compatible to the lvalue.

NOTE-2 : lvalue is something which is used to left side of a statement and in which we can assign some value. A constant can't be an lvalue because we can not assign any value in contact. For example x = y, here x is lvalue and y is rvalue.

However, above example will produce following result:

the_data points to the integer value 6
the_data now points to the character a

C Using Functions | C Programming Tutorial pdf


A function is a module or block of program code which deals with a particular task. Making functions is a way of isolating one block of code from other independent blocks of code.

Functions serve two purposes.

They allow a programmer to say: `this piece of code does a specific job which stands by itself and should not be mixed up with anyting else',

Second they make a block of code reusable since a function can be reused in many different contexts without repeating parts of the program text.

A function can take a number of parameters, do required processing and then return a value. There may be a function which does not return any value.

You already have seen couple of built-in functions like printf(); Similar way you can define your own functions in C language.

Consider the following chunk of code


To turn it into a function you simply wrap the code in a pair of curly brackets to convert it into a single compound statement and write the name that you want to give it in front of the brackets:

curved brackets after the function's name are required. You can pass one or more paramenters to a function as follows:

By default function does not return anything. But you can make a function to return any value as follows:

A return keyword is used to return a value and datatype of the returned value is specified before the name of function. In this case function returns total which is int type. If a function does not return a value then void keyword can be used as return value.

Once you have defined your function you can use it within a program:

Functions and Variables:

Each function behaves the same way as C language standard function main(). So a function will have its own local variables defined. In the above example total variable is local to the function Demo.

A global variable can be accessed in any function in similar way it is accessed in main() function.

Declaration and Definition:

When a function is defined at any place in the program then it is called function definition. At the time of definition of a function actual logic is implemented with-in the function.

A function declaration does not have any body and they just have their interfaces.

A function declaration is usually declared at the top of a C source file, or in a separate header file.

A function declaration is sometime called function prototype or function signature. For the above Demo() function which returns an integer, and takes two parameters a function declaration will be as follows:

Passing Parameters to a Function:

There are two ways to pass parameters to a function:

  • Pass by Value: mechanism is used when you don't want to change the value of passed paramters. When parameters are passed by value then functions in C create copies of the passed in variables and do required processing on these copied variables.
  • Pass by Reference:mechanism is used when you want a function to do the changes in passed parameters and reflect those changes back to the calling function. In this case only addresses of the variables are passed to a function so that function can work directly over the addresses.

Here are two programs to understand the difference: First example is for Pass by value:

Here is the result produced by the above example. Here the values of a and b remain unchanged before calling swap function and after calling swap function.

Following is the example which demonstrate the concept of pass by reference

Here is the result produced by the above example. Here the values of a and b are changes after calling swap function.