Saturday, 9 May 2015

Introduction


1.Intorduction
C programming is a popular computer programming language which is widely used for system and application software.
Despite being fairly old programming language, C programming is widely used because of its efficiency and control.

This tutorial is intended for beginners who does not have any prior knowledge or have very little knowledge of computer progrmming.

C programming  language was developed at AT &  T’s Bell Laboratories of USA in 1972. It was written and designed by Dennis Ritchie.

All the basic topics of C programming are included in detail with explanation and example which will give you better understanding of C programming language.

Friday, 8 May 2015

Union


                                                                  Union
Unions are quite similar to the structures in C. Union is also a derived type as structure. Union can be defined in same manner as structures just the keyword used in defining union in union where keyword used in defining structure was struct.

The major difference between structure and union is that structure provide separate memory space for each variable but union provided same memory space to variable particular datatype.
e.g.:
  union tag
 {
  Int a;
  Char b;
 Double c;
 }
Main()
{
 Union tag v;
 Printf(“%d\n”,sizeof(v));
 }
  

Structure


                                                               Structure
Structure is the collection of variables of different types under a single name for better handling.
Structure Definition in C
·         It is a user defined data type.
·         Collection of member of same/different type.
·         Member are accessed by name not by index
·         Member are stored in adjacent memory location.
·         Dereference operator “.” And -> are use to access member.
Its syntax
Struct  structure_name
  {
    Data_type member 1;
    Data_type member 1;
    .
    .
    .
  }
Lets see a program on structure
  Struct tag1
  {
    Int a;
    Float b;
    Double c;
  };
 Main()
 {
  Struct  tag1 v1;
 Printf(“%d\n”,sizeof(tag1));
}

Output:16;



Some important point regarding structure and structure member:
§  Members are not independently accessible
§  Members are accessible through structure variable
§  Structure member cannot be initialized.
§  Structure variable can only be initialized.
§  Structure variable name does not represent the base address of the variable but represent the whole structure.
Example to demonstrate the structure
#include<stdio.h>
Struct student
  {
    Int roll;
Char name[20];
Float mark;
  }v;
Void input (struct student *);
 Void  print(struct student);
Main()
 {
  Input(&v);
  Print(v);
 }
Void  input(struct student *p)
 {
   Printf(“enter roll:”);
   Scanf(“%d”,&p->roll);
   Printf(“enter name:”);
   Scanf(“%d”,p->name);
   Printf(“enter mark:”);
   Scanf(“%d”,&p->mark);
 }
Void  print(struct student v)
  {
  Printf(“%d %s%f”,v.roll,v.name,v.mark);
  }
…………………………………………………………………………………………………………………………
Input:
…………………………………………………………………………………………………………………………
Enter roll: 23
Enter name:deep
Enter mark:88
…………………………………………………………………………………………………………………………
Output
…………………………………………………………………………………………………………………………
23 deep 88



Self Referential structure:
A structure that contain pointer to structure of its own type is known as self referential structure.
For example:
Struct st
  {
   Data_type member 1;
    Data_type member 2;
 Struct st *ptr1;
 Struct st *ptr2;
};
Here *ptr1 & *ptr2 is a structure pointer which pointing to itself hence struct st is self structure pointer.

Pointer


                                                                                 Pointer
Pointers are the powerful feature of C and (C++) programming, which differs it from other popular programming language like: java and visual basic.

Pointers are used in C program to access the memory and manipulate the address.
Reference operator(&)
If x is a variable then, &x is the address in memory.
/* example to demonstrate use of reference operator in C programming.*/
#include<stdio.h>
Int main()
  {
   Int var=6;
  Printf(“Value:%d\n”,var);
  Printf(“address: %d”,&var);
 Return 0;
 }
Output:
Value:6
Address:2458712

In above source code , value 6 is stored in the memory location 2458712. Var is just the name given to that location.
You, have already used reference operator in C program while using scanf() function.
Scanf(“%d”,&var);

Reference operator (*) and pointer variables:
Pointer variables are used for taking addresses as values,l.e. , a variable that holds address value is called  a pointer variable or simply a pointer.
Declaration  operator(*) are used to identify an operator as a pointer.
Data_type * pointer_variable_name;
Int *p;
Above statement defines, p as pointer variable of type int.

Example to demonstrate working of pointer.
/* source code to demonstrate , handling of pointer in C program */
#include <stdio.h>
 Int main()
{
  Int *p,c;
 C=5;
 Printf(“Address of c:%d\n”,&c);
 Printf(“value of c:%d\n”,c);
P=&c;
 Printf(“Address of pointer p:%d\n”,p);
 Printf(“Value of pointer p:%d\n”,*p);
C=89;
Printf(“Address of pointer p:%d\n”,p);
 Printf(“Value of pointer p:%d\n”,*p);
*p=8;
Printf(“Address of c:%d\n”,&c);
 Printf(“value of c:%d\n”,c);
Return 0;
}
Output:
Address of c:2658972
value of c:5

Address of pointer p: 2658972
Value of pointer p:5

Address of pointer p: 2658972
Value of pointer p:89

Address of c:2658972
value of c:8


String


                                                                                  String
There is no separate data type for string in C , they are treated as array of characters. A character array is a string if it ends with a null character  (‘\0’). This  null character is an escape sequence with ASCII value 0  and is different from the ASCII  character ‘0’.
String are generally  used to store and manipulate data in text form like word or sentence.

String Constant
A string constant is a sequence of character enclosed in double quotes and is also called a literal . ”double quote are not a part of the string.e.g: “TAJ” “deep”.

String Liberary Function:
There are several library functions used to manipulate strings and the prototype for these functions are in header file string.h  most commonly used string function like: strlen(), strcpy(),strcmp(),strcat().

1.       Strlen()
Declaration: size_x strlen(char const *string);
This function returns the length of the string i.e the number of character in the string excluding the terminating null character.
Program to understand strlen():
#include<stdio.h>
#include<string.h>
Int main(void)
 {
  Char str[50];
  Printf(“enter the string:”);
  Gets(str);
  Printf(“Length of string:%d\n”,strlen(str));
 Return 0;
}

2.       Strcpy
Declaration: char * strcpy(char *s1 , const char *s2);
This function is used for copying one string to another string.
Program to understand strcpy():
#include<stdio.h>
#include<string.h>
Int main(void)
 {
  Char str[50],str1[50];
  Printf(“enter the string:”);
  Gets(str);
 Strcpy(str1,str);
  Printf(“first string:%s\n second string:%s\n”,str,str1);
 Return 0;
}

3.       Strcmp()
Declaration: int strcmp(char* s1,char *s2);

This function is used for lexicographic comparison of two strings. If the two string match,strcmp() returns a vlue 0 otherwise it returns a non-zero. It compares the string character by character and the comparison stops when either the end of string is reached or the corresponding characters in the two strings are not same.
Strcmp(s1,s2) return a value:
<0   when s1 <s2
=0    s1==s2
>0   s1>s2

/* program to understand the work of strcmp() function*/
#include<stdio.h>
#include<string.h>
Main(void)
 {
   Char str1[90],str2[90];
Printf(“enter two strings :”);
 Gets(str1);
 Gets(str2);
 If((strcmp(str1,str2))==0)
  Printf(“strings are same\n”);
 Else
  Printf(“strings are not same\n”);
 Return 0;
}

Output: Enter two strings: Deepak
                                                Kumar
Strings are not same.
  

4.       Strcat
Declaration : char* strcat(char*str1,const char*str2)
This function is used to append a copy  of a string at the end of other string.e.g if first string is “Cprogram” and second string is “stores “ then the output will come as Cprogramstores

/* Program to understand strcat() function*/
#include<stdio.h>
#include<string.h>
int main(void)
{
   char str1[20],str2[20];
   printf(“enter two string:”);
   gets(str1);
   gets(str2);
  strcat(str1,str2);
 printf(“%s\n”,str1);
 return 0;
}

Aarry


                                                                                 ARRAY
An array is a collection of similar type of data item and each data item is called an element of the array.
Declaration of Array:
Like other simple variable, array should be declared before they are used in the program. The syntax for declaration of an array is :
                                              Data_type    array_name[size];
Like int age[90];
Float salary [13];
Char grade[20];

Accessing 1-D array element
The element of an array can be accessed by specifying the array name followed by subscript in brackets.
Let us take an array  :  int arr[5];
The element of this array are: arr[0],arr[1],arr[2],arr[3],arr[4].
Here 0 is lower bound and 4 is  upper bound.
e.g:
 #include<stdio.h>
  int main()
{
  int a[5];
   printf(“size of array:%d\n”,sizeof(a));
   return 0;
}
OUTPUT:20
Note-worthy point regarding array:
·         If size of array is n l.e a[n] and we supply less than size of array then remaining data would be zero.
·         If array is initialized then to give size of array is optional.
Processing  1-D arrays:
1.       Reading values in arr
For(i=0;i<10;i++)
  Scanf(“%d”,&arr[i]);
2.       Displaying value of arr:
for(i=0;i<10;i++)
   printf(“%d”,arr[i]);
Lets see an example on this:
  #include<stdio.h>
   Int main(void)
    {
      Int arr[5],I;
      For(i=0;i<5;i++)
       {
         Printf(“enter the number:”);
         Scanf(“%d”,&arr[i]);
       }
 Printf(“You have entered:”);
  For(i=0;i<5;i++)
  {
   Printf(“%d\t”,arr[i]);
  }
}

Two dimentional array:
The syntax of 2-D array is :
  Data_type   array_name[row_size][column_size]
Here row_size specifies the number of row where as column_size specifies the number of column.
Lets see the example:
Add two matrix of order 3*3
#include<stdio.h>
Int main()
{
  Int a[3][3], I,j,b[3][3],c[3][3];
For(i=0;i<3;i++)
 {
   For(j=0;j<3;j++)
    {
     Scanf(“%d”,&a[i][j]);
    }
}
Printf(“enter second matrix\n:”);
  For(i=0;i<3;i++) 
  {
   For(j=0;j<3;j++)
    {
     Scanf(“%d”,&b[i][j]);
    }
}
///addition of two entered matrix is happening here
For(i=0;i<3;i++)
 {
   For(j=0;j<3;j++)
   {
   C[i][j]=a[i][j]+b[i][j];
   }
}
///displaying…
For(i=0;i<3;i++)
  {
   For(j=0;j<3;j++)
    {
      Printf(“%d\t”,c[i][j]);
    }
   Printf(“\n”);
  }
}//main close here

Storage Class


                                                                           STORAGE CLASSES
In addition to data type, each variable has one more attribute known as storage class. The proper use of storage classes makes our program efficient and fast.
The general syntax:
Storage_class   datatype   variable_name;
There are four types of storages classes:
1.       Automatic
2.       External
3.       Static
4.       Register
The keyword auto ,static,register,extern are used for these above storage classes.

A  storage class decides about these four aspects of a  variable:
1.       Life-time: Time between the creation and destruction of a variable.
2.       Scope: Location where the variable is available for use.
3.       Initial value:  Default value taken by an uninitialized variable.
4.       Place of storage: Place in memory where the storage is allocated for the variable.

Automatic:
All the variable declared inside a block/function without any storage class specified are automatic variables.
Lets see the examples:
  #include<stdio.h>
  Void func(void);
  Int main(void);
  {
     Func();
     Func();
     Func();
    Func();
 }
Void func(void)
 {
  Int x=2,y=9;
Printf(“x=%d,y=%d\n”,x,y);
 X++;
 Y++;
}

OUTPUT:
X=2,y=9
X=2,y=9;
X=2,y=9;
X=2,y=9;

Explanation:
Here when the function func() is called for first time , the variable x and y are created and initialized and when the control returns to main() , these variables are destroyed. when the function func() is called for second time again these variables are created and initialized and are destroyed after execution of the function.

Register:
 The scope ,lifetime and initial value of register variables are same as that of automatic variables. The only difference between the two is in the place where they are stored. Automatic variables are stored in memory while register variables are stored in CPU register. Registers are small storage units present in the processor. The variable stored in registers can be accessed much faster than the variables stored in memory so the variables that are frequently used can be assigned  register storage class for faster processing .
Lets see the example:
#include<stdio.h>
 Int main(void)
{
 Register int I;
  For(i=0;i<2000;i++)
  Printf(“%d\n”,i);
Return 0;
}
NOTE: Register variables don’t have memory addresses so we can’t apply address operator (&) to them.


External:
The variables that have to be used by many functions and in different files can be declared as external variables. The initial value of an uninitialized external variable is zero.

Before studying external variables. Lets us first understand the difference between their definition and declaration. The declaration of an external variable declares the type and name of the variable, while the definition reserves storages for the variable as well as behaves as a declaration.
Note: The keyword extern is specified in declaration but not in definition. For example   the definition of an external variable salary will be written as :float salary;
 Its declaration will be written as: extern float salary;
Definition of an external variable:
a)      Definition creates the variable , so memory is allocated at the time of definition.
b)      There can be only one definition
c)       The variable can be initialized with the definition and initializer should be constent
d)      The definition can be written only outside of function.

Declaration of an external variable:
a)      Declaration does not create a variable, it only refers to a variable that has already been created somewhere, so memory is not allocated at the time of declaration.
b)      The variable can not be initialized at the time of declaration
c)      The keyword extern is always specified in the declaration.

Static:
There are two types of static variables:-
1.       Local static variables.
2.       Global static variables.
1.Local static variables
The scope of a local variable is same as that of an automatic variable l.e it can be used only inside the function or block in which it is defined. The lifetime of static variable is more than that  of automatic variable. A static variable is created at the compilation time and it remain alive the end of a program.

A static variable can be initialized only by constant or constant expression if a static variable is not explicitly initialzed then by default it takes initial value zero(‘0’).

Program to understand the use of local static variable:
#include<stdio.h>
 void func(void);
 int main(void)
{
  func();
  func();
  func();
return 0;
} 
 Void func(void)
  {
    Static int x=2,y=5;
    Printf(x=%d,y=  %d\n”,x,y);
   X++;
   Y++;
}
Output:   x=2,y=5
                X=3,y=6
               X=4,y=7
2.Global static variable:
 If a local variable is declared as static then it remains alive throughout the program. In case of global variable, the static specified is not used to extend the lifetime since global variable already have a lifetime equal to the life of program.
If an external variable is defined as static then it can’t be used by other files of the program so we can make an external variable private to a file by making it static.

Recursion


Function


                                                           Function
What is function ?
A function is a self- contained block of statements that perform a coherent task of same kind.

Advantages of using functions:

§  A program can be divided into function each of which performs some specific task. Thus the use of functions modularizes and divides the work of a program
§  When some specific code is to be used more than once and at different places in the program, the use of function avoids repetition of that code
§  The program becomes easily understandable modifiable and easy to debug and test.
§  Function can be stored in a library and can be reused.

A function contain three main part:
1)      Function declaration/prototype
2)      Function call
3)      Function definition
Lets see with the example:
#include<stdio.h>
void drawline(void); //function declaration
 int main(void)
 {
     drawline();   //function call
      return;
  }
void   drawline(void)   //function definition
  {
     int i;
     for(i=0;i<=80;i++)
      printf(“---“);
  }

In function declaration it contain what I am passing to the function and what we get as return.
It could be integer, float  or  character pointer.
Int sum(int x, int y);
                                                       
Return      first     second
                  value   value  

Return statement
The return statement is used for immediate exit from the called function to the calling function and to return a value to the calling function.There are two ways in which it can be used.
return;
return(expression);
here return is a keyword.
/* program to understand return statement*/
#include<stdio.h>
 void  selection(int age,float int);
int main(void)
 {
    Int age;
    Float ht;
    Printf(“enter age and height:”);
   Scanf(“%d%f”,&age,&ht);
    Selection(age,ht);
     Return 0;
  }
 Void  selection(int age,float ht)
 {
   If(age>25>
   {
    Printf(“age should be less than 25\n”);
    Return;
  }
   If(ht<5)
   {
   Printf(“height should be more than 5 \n”);
   Return;
   }
 Printf(“selected\n”);

}


Contact Form

Name

Email *

Message *