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";