Tuesday, November 27, 2012

"C" Language :-


WHAT IS C ?

C language is a general purpose and structured pragramming langauge developed by 'Dennis Ritchie' at AT &T's Bell Laboratories in the 1972s in USA.
It is also called as 'Procedure oriented programming language.'
C is not specially designed for specific applications areas like COBOL (Common Business-Oriented Language) or FORTRAN (Formula Translation). It is well suited for business and scietific applications. It has some various features like control structures, looping statements, arrays, macros required for these applications.
The C language has following numorous features as:
  • Portability
  • Flexibility
  • Effectiveness and efficiency
  • Reliability
  • Interactivity

Execution of C Program :

C program executes in following 4 (four steps).
C program execution steps
  1. Creating a program :
  2. An editor like notepad or wordpad is used to create a C program. This file contains a source code which consists of executable code. The file should be saved as '*.c' extension only.
  3. Compiling the program :
  4. The next step is to compile the program. The code is compiled by using compiler. Compiler converts executable code to binary code i.e. object code.
  5. Linking a program to library :
  6. The object code of a program is linked with libraries that are needed for execution of a program. The linker is used to link the program with libraries. It creates a file with '*.exe' extension.
  7. Execution of program :
  8. The final executable file is then run by dos command prompt or by any other software.
    Structure Of "C" :-
Document Section
Links Section (File)
Definition Section
Global variable declaration Section
void main()
{
    Variable declaration section
    Function declaration section
    executable statements;
}
Function definition 1
---------------------
---------------------
Function definition n
where,
Document Section : It consists of set of comment lines which include name of a program, author name, creation date and other information.
Links Section (File) : It is used to link the required system libraries or header files to excute a program.
Definition Section : It is used to define or set values to variables.
Global variable declaration Section : It is used to declare global or public variable.
void main() : Used to start of actual C program. It includes two parts as declaration part and executable part.
Variable declaration section : Used to declare private variable.
Function declaration section : Used to declare functions of program from which we get required output.
Then, executable statements are placed for execution.
Function definition section : Used to define functions which are to be called from main()

Character Set :

A character refers to the digit, alphabet or special symbol used to data represetation.
  1. Alphabets :                 A-Z, a-z
  2. Digits :                       0-9
  3. Special Characters :    ~ ! @ # $ % ^ & * ( ) _ + { } [ ] - < > , . / ? \ | : ; " '
  4. White Spaces :            Horizontal tab, Carriage return, New line, form feed

Identifier :

Identifier is the name of a variable that is made up from combination of alphabets, digits and underscore.

Variable :

It is a data name which is used to store data and may change during program execution. It is opposite to constant. Variable name is a name given to memory cells location of a computer where data is stored.
* Rules for varibales:
  1. First character should be letter or alphabet.
  2. Keywords are not allowed to use as a variable name.
  3. White space is not allowed.
  4. C is case sensitive i.e. UPPER and lower case are significant.
  5. Only underscore, special symbol is allowed between two characters.
  6. The length of indentifier may be upto 31 characters but only only the first 8 characters are significant by compiler.
  7. (Note: Some compilers allow variable names whose length may be upto 247 characters. But, it is recommended to use maximum 31 characters in variable name. Large variable name leads to occur errors.)

Keywords :

Keywords are the system defined identifiers.
All keywords have fixed meanings that do not change.
White spaces are not allowed in keywords.
Keyword may not be used as an indentifier.
It is strongly recommended that keywords should be in lower case letters.
There are totally 32(Thirty Two) keywords used in a C programming.
intfloatdoublelong
shortsignedunsignedconst
ifelseswitchbreak
defaultdowhilefor
registerexternstaticstruct
typedefenumreturnsizeof
gotounionautocase
voidcharcontinuevolatile


Escape Sequence Characters (Backslash Character Constants) in C:

C supports some special escape sequence characters that are used to do special tasks.
These are also called as 'Backslash characters'.
Some of the escape sequence characters are as follow:
Character ConstantMeaning
\nNew line (Line break)
\bBackspace
\tHorizontal Tab
\fForm feed
\aAlert (alerts a bell)
\rCarriage Return
\vVertical Tab
\?Question Mark
\'Single Quote
\''Double Quote
\\Backslash
               \0          Null

Constants in C :

A constant is an entity that doesn't change during the execution of a program.
Followings are the different types of constants :

1. REAL CONSTANT :

  1. It must have at least one digit.
  2. It must have a decimal point which may be positive or negative.
  3. Use of blank space and comma is not allowed between real constants.
  4. Example:

  5. +194.143, -416.41

2. INTEGER CONSTANT :

  1. It must have at least one digit.
  2. It should not contain a decimal place.
  3. It can be positive or negative.
  4. Use of blank space and comma is not allowed between real constants.
  5. Example:

  6. 1990, 194, -394

3. CHARACTER CONSTANT :

  1. It is a single alphabet or a digit or a special symbol enclosed in a single quote.
  2. Maximum length of a character constant is 1.
  3. Example:

  4. 'T', '9', '$'

4. STRING CONSTANT :

  1. It is collection of characters enclosed in double quotes.
  2. It may contain letters, digits, special characters and blank space.

Operators in C :

"Operator is a symbol that is used to perform mathematical operations."
When we use a variable in a program then we have to mention the type of data. This can be handled using data type in C.
Followings are the most commonly used data types in C.

Operator NameOperators
Assignment=
Arithmetic+, -, *, /, %
Logical&&, ||, !
Relational<, >, <=, >=, ==, !=
Shorthand+=, -=, *=, /=, %=
Unary++, --
Conditional()?:;
Bitwise&, |, ^, <<, >>, ~








Decision Making Statements / Conditional Statements :

C program executes program sequentially. Sometimes, a program requires checking of certain conditions in program execution. C provides various key condition statements to check condition and execute statements according conditional criteria.
These statements are called as 'Decision Making Statements' or 'Conditional Statements.'
Followings are the different conditional statements used in C.
  1. If Statement
  2. If-Else Statement
  3. Nested If-Else Statement
  4. Switch Case

Looping Statements / Iterative Statements :

'A loop' is a part of code of a program which is executed repeatedly.
A loop is used using condition. The repetition is done until condition becomes condition true.
A loop declaration and execution can be done in following ways.
  • Check condition to start a loop
  • Initialize loop with declaring a variable.
  • Executing statements inside loop.
  • Increment or decrement of value of a variable.

* TYPES OF LOOPING STATEMENTS :

Basically, the types of looping statements depends on the condition checking mode. Condition checking can be made in two ways as : Before loop and after loop. So, there are 2(two) types of looping statements.
  • Entry controlled loop
  • Exit controlled loop
1. Entry controlled loop :
In such type of loop, the test condition is checked first before the loop is executed.
Some common examples of this looping statements are :
2. Exit controlled loop :
In such type of loop, the loop is executed first. Then condition is checked after block of statements are executed. The loop executed atleat one time compulsarily.
Some common example of this looping statement is :

Break Statement :

Sometimes, it is necessary to exit immediately from a loop as soon as the condition is satisfied.
When break statement is used inside a loop, then it can cause to terminate from a loop. The statements after break statement are skipped.
Syntax :

 break;

Figure :
stucture of break statement

Program :


/*  Program to demonstrate break statement.

Creation Date : 09 Nov 2010 05:32:33 PM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>
#include <conio.h>
void main()
{
 int i;
 clrscr();
 for(i=1;  ; i++)
 {
  if(i>5)
  break;
  printf("%d",i);  // 5 times only
 }
 getch();
}

Output :


12345_

Continue Statement :

Sometimes, it is required to skip a part of a body of loop under specific conditions. So, C supports 'continue' statement to overcome this anomaly.
The working structure of 'continue' is similar as that of that break statement but difference is that it cannot terminate the loop. It causes the loop to be continued with next iteration after skipping statements in between. Continue statement simply skipps statements and continues next iteration.
Syntax :

 continue;

Figure :
stucture of continue statement

Program :


/*  Program to demonstrate continue statement.

Creation Date : 09 Nov 2010 07:44:43 PM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>
#include <conio.h>
void main()
{
 int i;
 clrscr();
 for(i=1; i<=10; i++)
 {
  if(i==6)
  continue;
  printf("\n\t %d",i);  // 6 is omitted
 }
 getch();
}

Output :


 1
 2
 3
 4
 5
 7
 8
 9
 10_

Goto Statement :

It is a well known as 'jumping statement.' It is primarily used to transfer the control of execution to any place in a program. It is useful to provide branching within a loop.
When the loops are deeply nested at that if an error occurs then it is difficult to get exited from such loops. Simple break statement cannot work here properly. In this situations, goto statement is used.
Syntax :

 goto [expr];

Figure :
stucture of goto statement

Program :


/*  Program to demonstrate goto statement.

Creation Date : 09 Nov 2010 08:14:00 PM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>
#include <conio.h>
void main()
{
 int i=1, j;
 clrscr();
 while(i<=3)
 {
  for(j=1; j<=3; j++)
  {
   printf(" * ");
   if(j==2)
   goto stop;
  }
  i = i + 1;
 }
 stop:
  printf("\n\n Exited !");
 getch();
}

Output :


 *  *

 Exited_

Contents :

  1. Functions
  2. Types of Functions :
  3. Function Call By Passing Value
  4. Function Call By Returning Value
  5. Function Call By Passing and Returning Value
  6. Advantages
  7. Recursion (Recursive Function)

Functions in C :

The function is a self contained block of statements which performs a coherent task of a same kind.
C program does not execute the functions directly. It is required to invoke or call that functions. When a function is called in a program then program control goes to the function body. Then, it executes the statements which are involved in a function body. Therefore, it is possible to call fuction whenever we want to process that functions statements.

Types of functions :

There are 2(two) types of functions as:
1. Built in Functions
2. User Defined Functions


1. Built in Functions :
These functions are also called as 'library functions'. These functions are provided by system. These functions are stored in library files. e.g.
  • scanf()
  • printf()
  • strcpy
  • strlwr
  • strcmp
  • strlen
  • strcat
1. User Defined Functions :
The functions which are created by user for program are known as 'User defined functions'.
Syntax:

void main()
{
 // Function prototype
 <return_type><function_name>([<argu_list>]);
 
 // Function Call
 <function_name>([<arguments>]);
}
// Function definition
<return_type><function_name>([<argu_list>]);
{
 <function_body>;
}

Program :


/*  Program to demonstrate function.

Creation Date : 23 Nov 2010 11:31:20 AM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>
#include <conio.h>

void add()
{
 int a, b, c;
 clrscr();
 printf("\n Enter Any 2 Numbers : ");
 scanf("%d %d",&a,&b);
 c = a + b;
 printf("\n Addition is : %d",c);
}
void main()
{
 void add();
 add();
 getch();
}

Output :


 Enter Any 2 Numbers : 23 6
 Addition is : 29_

Storage Class :

'Storage' refers to the scope of a variable and memory allocated by compiler to store that variable. Scope of a variable is the boundary within which a varible can be used. Storage class defines the the scope and lifetime of a variable.
From the point view of C compiler, a variable name identifies physical location from a computer where varaible is stored. There are two memory locations in a computer system where variables are stored as : Memory and CPU Registers.
Functions of storage class :
To detemine the location of a variable where it is stored ?
Set initial value of a variable or if not specified then setting it to default value.
Defining scope of a variable.
To determine the life of a variable.

Types of Storage Classes :

Storage classes are categorised in 4 (four) types as,

Array :

Array is a collection of homogenous data stored under unique name. The values in an array is called as 'elements of an array.' These elements are accessed by numbers called as 'subscripts or index numbers.' Arrays may be of any variable type.
Array is also called as 'subscripted variable.'

Types of an Array :

  1. One / Single Dimensional Array
  2. Two Dimensional Array

Single / One Dimensional Array :

The array which is used to represent and store data in a linear form is called as 'single or one dimensional array.'
Syntax:

 <data-type> <array_name> [size];

Example:

 int a[3] = {2, 3, 5};
 char ch[20] = "TechnoExam" ;
 float stax[3] = {5003.23, 1940.32, 123.20} ;
 
Total Size (in Bytes):

 total size = length of array * size of data type
 
In above example, a is an array of type integer which has storage size of 3 elements. The total size would be 3 * 2 = 6 bytes.

* MEMORY ALLOCATION :

     Single dimensional array
    Fig : Memory allocation for one dimensional array

Program :


/*  Program to demonstrate one dimensional array.

Creation Date : 10 Nov 2010 11:07:49 PM

Author :www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>
#include <conio.h>
void main()
{
 int a[3], i;;
 clrscr();
 printf("\n\t Enter three numbers : ");
 for(i=0; i<3; i++)
 {
  scanf("%d", &a[i]);  // read array
 }
 printf("\n\n\t Numbers are : ");
 for(i=0; i<3; i++)
 {
  printf("\t %d", a[i]);  // print array
 }
 getch();
}

Output :


 Enter three numbers : 9 4 6
 
 Numbers are : 9 4 6_


Features :
  • Array size should be positive number only.
  • String array always terminates with null character ('\0').
  • Array elements are countered from 0 to n-1.
  • Useful for multiple reading of elements (numbers).

Contents :

  1. Structure
  2. Array in Structures
  3. Structure with Array
  4. Structures within Structures (Nested Structures)

Structure :

Structure is user defined data type which is used to store heterogeneous data under unique name. Keyword 'struct' is used to declare structure.
The variables which are declared inside the structure are called as 'members of structure'.
Syntax:

struct structure_nm
{
 <data-type> element 1;
 <data-type> element 2;
 - - - - - - - - - - -
 - - - - - - - - - - -
 <data-type> element n;
}struct_var;


Example :

struct emp_info
{
 char emp_id[10];
 char nm[100];
 float sal;
}emp;

Note :
1. Structure is always terminated with semicolon (;).
2. Structure name as emp_info can be later used to declare structure variables of its type in a program.

* INSTANCES OF STRUCTURE :

Instances of structure can be created in two ways as,
Instance 1:

struct emp_info
{
 char emp_id[10];
 char nm[100];
 float sal;
}emp;


Instance 2:

struct emp_info
{
 char emp_id[10];
 char nm[100];
 float sal;
};
struct emp_info emp;
In above example, emp_info is a simple structure which consists of stucture members as Employee ID(emp_id), Employee Name(nm), Employee Salary(sal).

* ACEESSING STRUCTURE MEMBERS :

Structure members can be accessed using member operator '.' . It is also called as 'dot operator' or 'period operator'.
structure_var.member;

Program :


/*  Program to demonstrate structure.

Creation Date : 23 Nov 2010 02:41:01 AM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>
#include <conio.h>

struct comp_info
{
 char nm[100];
 char addr[100];
}info;

void main()
{
 clrscr();
 printf("\n Enter Company Name : ");
 gets(info.nm);
 printf("\n Enter Address : ");
 gets(info.addr);
 printf("\n\n Company Name : %s",info.nm);
 printf("\n\n Address : %s",info.addr);
 getch();
}

Output :


 Enter Company Name : TechnoExam, Technowell Web Solutions
 Enter Address : Sangli, Maharashtra, INDIA
 
 Company Name : TechnoExam, Technowell Web Solutions
 Address : Sangli, Maharashtra, INDIA_


Disadvantages :
  • There is no easy method to initialize large number of array elements.
  • It is difficult to initialize selected elements.

Pointer :

Pointer is a variable which holds the memory address of another variable. Pointers are represented by '*'. It is a derive data type in C. Pointer returns the value of stored address.
Syntax:

 <data_type> *pointer_name;
 
In above syntax,
* = variable pointer_name is a pointer variable.
pointer_name requires memory location
pointer_name points to a variable of type data type.
How to Use ?
 
 int *tot;

Illustration :

 int tot = 95;
 
Figure :
  pointer representation
In above example, the statement instructs the system to find out a location for integer variable quantity and puts the values 95 in that memory location.
* Features of Pointer :

* Pointer variable should have prefix '*'.
* Combination of data types is not allowed.
* Pointers are more effective and useful in handling arrays.
* It can also be used to return multiple values from a funtion using function arguments.
* It supports dynamic memory management.
* It reduces complexity and length of a program.
* It helps to improve execution speed that results in reducing program execution time.

Program :


/*  Program to demonstrate pointer.

Creation Date : 10 Nov 2010 11:41:20 PM

Author :www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>
#include <conio.h>

void main()
{
 int a=10;
 int *ptr;
 clrscr();
 ptr = &a;
 printf("\n\t Value of a : %d", a);
 scanf("\n\n\t Value of pointer ptr : %d", *ptr);
 printf("\n\n\t Address of pointer ptr : %d", ptr);
 getch();
}

Output :


 Value of a : 10
 
 Value of pointer ptr : 10
 
 Address of pointer ptr : -12_

Union :

Union is user defined data type used to stored data under unique variable name at single memory location.
Union is similar to that of stucture. Syntax of union is similar to stucture. But the major difference between structure and union is 'storage.' In structures, each member has its own storage location, whereas all the members of union use the same location. Union contains many members of different types, it can handle only one member at a time.
To declare union data type, 'union' keyword is used.
Union holds value for one data type which requires larger storage among their members.
Syntax:

 union union_name
 {
  <data-type> element 1;
  <data-type> element 2;
  <data-type> element 3;
 }union_variable;

Example:

 union techno
 {
  int comp_id;
  char nm;
  float sal;
 }tch;
 
In above example, it declares tch variable of type union. The union contains three members as data type of int, char, float. We can use only one of them at a time.

* MEMORY ALLOCATION :

     C union
  Fig : Memory allocation for union
To access union members, we can use the following syntax.
 tch.comp_id
 tch.nm
 tch.sal

Program :


/*  Program to demonstrate union.

Creation Date : 10 Nov 2010 09:24:09 PM

Author :www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>
#include <conio.h>

union techno
{
 int id;
 char nm[50];
}tch;


void main()
{
 clrscr();
 printf("\n\t Enter developer id : ");
 scanf("%d", &tch.id);
 printf("\n\n\t Enter developer name : ");
 scanf("%s", tch.nm);
 printf("\n\n Developer ID : %d", tch.id);//Garbage 
 printf("\n\n Developed By : %s", tch.nm);
 getch();
}

Output :


 Enter developer id : 101
 
 Enter developer name : technowell
 
Developer ID : 25972

Developed By : technowell_

String Handling in C :

String :
A string is a collection of characters. Strings are always enlosed in double quotes as "string_constant".
Strings are used in string handling operations such as,
  • Counting the length of a string.
  • Comparing two strings.
  • Copying one string to another.
  • Converting lower case string to upper case.
  • Converting upper case string to lower case.
  • Joining two strings.
  • Reversing string.

Declaration :

The string can be declared as follow :
Syntax:

 char string_nm[size];

Example:

 char name[50];
 

String Structure :

When compiler assigns string to character array then it automatically suppliesnull character ('\0') at the end of string. Thus, size of string = original length of string + 1.
 char name[7];
 name = "TECHNO"
 
structure of string

Read Strings :

To read a string, we can use scanf() function with format specifier %s.
 char name[50];
 scanf("%s",name);
 
The above format allows to accept only string which does not have any blank space, tab, new line, form feed, carriage return.

Write Strings :

To write a string, we can use printf() function with format specifier %s.
 char name[50];
 scanf("%s",name);
 printf("%s",name);
 

Header File in C :
Header file contains different predefined functions, which are required to run the program. All header files should be included explicitly before main ( ) function.
It allows programmers to seperate functions of a program into reusable code or file. It contains declarations of variables, subroutines. If we want to declare identifiers in more than one source code file then we can declare such identifiers in header file. Header file has extension like '*.h'. The prototypes of library functions are gathered together into various categories and stored in header files.
E.g. All prototypes of standard input/output functions are stored in header file 'stdio.h' while console input/output functions are stored in 'conio.h'.
The header files can be defined or declared in two ways as
Method 1 : #include "header_file-name"
Method 2 : #include <header_file-name>
Method 1 is used to link header files in current directory as well as specified directories using specific path. The path must be upto 127 characters. This is limit of path declaration. Method 2 is used to link header files in specified directories only.

Standard Header Files :

Followings are the some commonly used header files which plays a vital role in C programming :

Assert.h

Ctype.h

Math.h

Process.h

Stdio.h

Stdlib.h

String.h

Time.h

Graphics.h



No comments:

Post a Comment

Blogger Widgets