Sie sind auf Seite 1von 70

C_Review

AppsConnect Technologies Pvt Ltd

CONTENTS
Introduction to C Importance of C The C Compilation Model Basic structure of C program C Identifiers, Constants, Data Types C Operators Console input/output Functions

Decision Making and Branching


If statement The if-else statement Nesting of if-else statement The Switch statement The goto statement

Decision Making and Looping


The while statement The do statement The for statement

Functions
Introduction Elements of function
Function definition Function call Function declaration

Category of function of function


Function Function Function Function with with with with no arguments and no return values arguments and no returns arguments and one return value no arguments but return a value

Recursion

Passing array to the function Passing string to function The scope,visibility, and lifetime of variables
Automatic variable External variable Static variable Register variable

Arrays

Introduction Types of array One-Dimensional array Two-Dimensional array

Pointers
Introduction Accessing the address of a variable Declaring & initialization pointer variables Accessing a variable through its pointer Pointers and Arrays Array of pointers Pointers as a function arguments Functions returning pointers Pointer to functions Pointer and structures

Character Arrays & Strings


Introduction Declaring and initializing string variables Reading a line of text using getchar and gets function Writing strings to screen using puts and putchar String-Handling functions
Strcat(), strcmp(), strcpy(), strlen() etc..

Structure
Introduction Defining and declaring a structure variables Accessing structure members Structure initialization Array of structure Array within structure Structure within structure Structures and functions

File Management in C
Introduction Defining and opening a file Closing a file Input/output Operations on File Random access to file

The preprocessor
Introduction Macro substitution File Inclusion

Linked Data Structures


Dynamic Data structures Single linked list The operations that can be performed on singly linked lists Creation of a list Insertion of nodes Traversal of the list Search of a specific node Modification of a node Deletion of a node

Double linked list

Introduction:- C was developed by Dennis Ritchie at

Bell Laboratories in 1972. Most of its principles and ideas were taken from the earlier language B, BCPL and CPL. CPL was developed jointly between the Mathematical Laboratory at the University of Cambridge and the University of London computer unit in1960s. In 1972, a co-worker of Ken Thompson, Dennis Ritchie developed C Language by taking some of the generality found in BCPL to the B language. In 1973, C language had become powerful enough that most of the Unix kernel was rewritten in C. This was one of the first operating system kernels implemented in a language other than assembly. The committee approved a version of C in December 1989which is now known as ANSI C.

Year
1960

Language
ALGOL

Developed
International Committee Martin Richards Ken Thompson Dennis Ritchie ANSI Committee ISO Committee Standardization Committee

1967 1970 1972 1989 1990 1990

BCPL B Traditional C ANSI C ANSI/ISO C99 History of ANSI C

Introduction of C:-

It is a robust language whose rich set of built-in-functions and operators can be used to write any complex program. The C compiler combines the capabilities of an assembly language with the feature of high level language and therefore it is well suitable for writing both system software and business package. Programs written in C are efficient and fast. this is due to variety of data types and powerful operators. It is suited for structured programming. It offers portability. It is ability to extend itself.

C compiling process:-

The steps involved in C compilation process

Source code (editor) Preprocessor Compile (Compiler) Link (Linker)

Source File x.c

Object file x.o Other object modules

Execute (Loader)

Basic structure of C program:Documentation Section Link Section Definition Section Global Declaration Section Main() Function Section { }

Declaration part

Executable part

Subprogram section

Function1 Function2 (User defined function)

Function n

Filename : Author : Description :

hello.c Brian Kernighan & Dennis Ritchie This program prints the greeting Hello, World! */

#include <stdio.h> int main ( ) { printf (Hello, World!\n) ; return 0 ; }

Keyword:-

Keywords are the words whose meaning has already been explained to the C compiler. The keywords are also called as reserved words. There are 32 keywords available in C.

Identifiers:-

Identifiers refers to the names of variables, functions, and arrays. These are user-defined names and consists of a sequence of letters and digits, with a letter as a first character. Both uppercase and lowercase letters are permitted. The underscore character also permitted in identifiers. Rules for identifiers:First character must be a alphabet or underscore. Must consist of only letters, digits or underscore. Cannot use a keyword. Must not contain a white space.

Constants:-

A constant is a quantity that doesnt change this quantity can be stored at a location in the memory of the computer. There are mainly two types of constant. Numeric Constant 1. Integer Constant 2. Floating point Constants Character Constants. 1. Single Character Constant 2. String Constant

Variable:-

A variable is a data type that may be used to

store a data value.

Data Types:-

C language is rich in its data type. There are mainly three classes of data types.

1. Primary Data types 2. Derived Data types 3. User defined data types
I. II. III. IV. Primary data type:- There are mainly five primary data

types.
Int Char Float Void

Integer type: Data Type Range Byte Format

Signed char
Unsigned char Short signed int Short unsigned int Long signed int

-128 to +127
0 to 255 -32768 to +32767 0 to 65535 -2147483648 to +2147483647

1
1 2 2 4

%c
%c %d %u %ld

Long unsigned int

0 to +4294967295 4

%lu

Floating Point:- Floating point numbers are defined in

C by the keyword float. Depending upon the accuracy, it is divided into three types. 1. Float 2. Double 3. Long double.
Data Type Range Byte Format

Float Double

-3.4e38 to +3.4e38 -1.7e308 to +1.7e308

4 8

%f %lf

long double -1.7e4932 to +1.7e4932

10

%Lf

Character Types A single character can be defined as char type. Character are usually stored in 1 byte of internal storage. The qualifier signed or unsigned may be explicitly applied to char. Unsigned char Signed char 0-255, -128to 127.

Void types:- The void type has no value. The type of a function said to be void when it does not return any value to the calling function.

1. 2. 3. 4.

Derived data type:- There are four derived data types. Array Function Structure Pointer

User Defined data type:1. typedef type identifier 2. enum identifier{value1,value2,valuen}; Typedef:- C supports a feature known as type definition that allow to define a identifier that would represent an existing data type. its general form: typedef type identifier; example: typedef int units;

2. Enumerated data type:- It is defined as follows.


enum identifier {value1,value2,..valuen}; The enumerated variables v1,v2,vn can only have one of the values value1,value2,valuen. Example:- enum day {Monday,Tuesday, Sunday}; enum day week_st,week_end; week_st= Monday; week_end=Friday;

C Operators
Operator: A operator is a symbol that tells the computer to perform certain mathematical or logical manipulation. Operators are used in programs to manipulate data and variables. C operator are classified into number of categories. They are listed below. Arithmetic operators Relational operators Logical operators Assignment operators Increment and decrement operators Conditional operators Bitwise operators Special operators


1.
2. 3. 4. 5.

Arithmetic Operator:Operator
+ _ * / % Program:-

C provides all the basic operators. They are listed below.

Meaning
Addition or unary plus Subtraction or unary minus Multiplication Division Modulo Division

#include<stdio.h> main() { int months,days; Printf(enter the days:\n); Scanf(%d,&days); Month=days/30; Days=days%30; Printf(months=%d days=%d, month,days); }

Relational Operator:-

If we need any comparison or relation in an expression, then this can be achieved with the help of relational operator. They are listed below. Operator Meaning < is less then <= is less then or equal to > is greater then >= is greater then or equal to == is equal to != is not equal to. Its expression- ae-1< relational operator> ae-2.

Logical operator:-

C has three logical operators. They are given below.

&& meaning logical AND || meaning logical OR ! meaning logical NOT. Example:(a>b)&& x==10

Logical Operator:- Assignment Operators are used to

assign the result of an expression to a variable. The assignment operator is =. Its expression is:- v op= exp; where v= variable. exp=expression example:- x=x+3;

Increment & Decrement Operator:-

C allows two very useful operators not generally found in other languages. These are increment(++) & decrement operator(--). Example:- m++ or ++m; m-- or ; --m; A ternary operator pair ? : is available in C to make the conditional expression of the form

Conditional Operator:-

exp1 ? Exp2 : exp3; Where exp1,exp2,exp3 are the expression. Example:- a=10; b=15; x=(a>b)?a:b;

Bitwise Operator:-

C has a distinction of supporting special operators known as bitwise operators for manipulation of data at bit level. These operators are used for testing the bits, or shifting them right or left. It may not be applied for float or double. The list of bitwise operator is given below. Operator Meaning & bitwise AND | bitwise OR ^ bitwise exclusive OR << shift left >> shift right
C supports some special operators. They are comma operator, size of operator, pointer operator and member selection operator.

Special Operator:-

Comma operator:- it is used to link the related


Example:expressions together. value=(x=10,y=5,x+y);

The size of operator:- The size of is the compile time


operator and when with an operand, it returns the number by bytes the operand. Example:m=sizeof (sum); n=sizeof (long int);

Arithmetic expression:- An arithmetic expression is the

combination of variables, constants, and operators arranged as per the syntax of the C language. Example:- variable=expression; x=a*b-c;

Console input and output function:-

The screen and keyword together are called a console. The console input and output function are classified into two types. 1. Formatted console I/O function. The list of console of i/o are given below. The formatted i/o are given below. Printf(), scanf(), escape sequences, sprintf(), sscanf(). 2. Unformatted console I/O function. The list of unformatted function are listed below. getch(), getche(), getchar(), fgetchar(), gets(), puts().

Decision Making and Branching:1. 2. 3. 4. if statement Switch statement Conditional Operator statement goto statement

The C offers such decision-making capabilities by supporting the following statements. They are

If statement:- The if statement is a powerful decision


making statement and is used to control the flow of execution of statements. Its takes the following form. If(test expression) { statement-block; } statement-x;

The if-else statement:-

the ifelse statement is an extension of the simple if statement. The general form is:
If(test expression) { true-block statement(s); } else { false-block statement(s); } statement-x

Nesting of ifelse statements:-

When a series of decision are involved, then we may use if-else statement in nested form. Its general form is:
If (test condition-1)
{ if (test condition-2); { statements-1; } else { stateement-2; } }

else
{ statement-3; } Statement-x;

Switch Statements:-

C has a built-in multiway decision statements known as a switch. The switch statement tests the variable of a given variable against a list of case value and when a match is found, a block of statements associated with that case is executed. General form is:
Switch (expression) {

case value-1:
block-1 break; case value-2: block-2 break; Default: default-block Break; } Statement-x;

The goto statement:-

A statement in a computer program that provides for the direct transfer of control to another statement with the identifier that is the argument of the GOTO statement. Its general form is:
goto label; ---------------------------------------label: statement;

Decision Making and Looping:-

1. 2. 3. 4.

A program loop consists of two segments, one known as the body of the loop and the other is known as the control statement. So a looping process, in general consists of four steps. Setting and initialization of a condition variable. Execution of the statements in the loop. Test for a specified value of the condition variable for execution of the loop. Incrementing or updating the condition variable.

C language provides three constructs for performing the loop operation. They are list below. The while statement. The do statement. The for statement.

While statement:-

The simplest of all the looping structure in c is the while statement. The basic format of while statements is: while (test condition) { body of loop } This is a entry controlled loop statement. the test-condition is evaluated and if the condition is true, then the body of the loop is executed. It will continue till condition becomes false. As we saw in the while statement if the condition is false it cant execute statements. But there might be necessary to execute the body of the loop before the test is performed.

Do statement:-

General form of do-while:do { body of the loop

} while (test-condition);

For statement:-

The for loop is another entrycontrolled loop that provides a more concise loop control structure. The general form of the loop is:for (initialization ; test-condition ; Increment) { body of loop }

Function:-

some kind. There are three elements that are related to the user defined function. Function definition Function Call Function declaration.

A function is a self contained block of statements that perform a coherent task of

FUNCTION DEFINITION:- The Function definition is an independent program module i.e, specially written to implement the requirements of the function. It is also known as function implementation shall include the following elements.

Function name; Function type; List of parameters; Local variable declaration; Function statements; A return statements. A general format of a function definition is given below:
function_type function_name(parameter list) { Local variable declaration; Executable statement1; Executable statement2; Return statement; }

The first line is known as function header. and the statements within the opening and closing braces is known as the function body.

Function header:-The function header consists of three

parts; the function types, the function name, the formal parameter list.

Name and type:- The function type specifies the type of


value that the function is expected to return to the program calling the function. By default it is integer type.
variables that will receive the data sent by the calling program.

Formal parameter list:- The parameter list declares the Function body:- The function body contains the

declaration and statements necessary for the performing the required task. It is enclosed with open and closed braces, contains three parts 1. local declaration 2. function statements 3. a return type statements

Function Call:- A function can be called by simply using the


function name followed by a list of actual parameters or arguments. example:main() { int y; y = mul(10,5); Printf(%d\n, y); }

When the compiler encounters a function call, the control is transferred to the function mull(). This function is then executed line by line as described and a value is returned when a return statement is encountered.

Function declaration:- All the function in C program must


be declared, before they are involved. A function declaration (function prototype) consists of four parts.

Function type. Function name. Parameter list Terminating semicolon. They are coded in the following format: Function-type function-name (parameter list);

There are five category of functions. They are listed below. Function with no arguments and no return values. Function with arguments and no return values. Function with arguments and return value. Function with no arguments but return a value. Function that return multiple values.

Recursion:- When a called function in turn calls another

function a process of chaining occurs. Recursion is a process where a function calls itself. example:- main() { printf(recursion type\n); main(); } The output of this program is like this: recursion type recursion type recursion type Example:- A best example of recursion is factorial of a given number.

/*example of recursion*/ #include<stdio.h> int rec ( int); int main() { int a, fact; printf(enter any number ); Scanf(%d,&a); fact=rec(a); printf(factorial value=%d\n,fact); Return 0; } Int rec( int x ) { int f; if(x==1) return(1); else f=x*rec(x-1); return (f); }

Passing array to function:- Like the other variable, it is

possible to pass the value of an array to the function. It may may be either singledimension array or multi-dimension array. For the single dimension array we can passed without any subscripts and the size of the array as arguments.
Example:-

largest(a,n) float largest(float array[], int size)

and the largest function header looks like:

The multi-dimensional array can be passed by using the following simple rules. Function must be called by passing the array name. In function definition, must indicate array has two dimensions by indicating two sets of brackets. The size of the second dimension must be specified. The prototype declaration should be similar to the function header.

Passing string to function:- The strings are treated as

character arrays in C. hence rules for the passing strings to the functions are very similar to the passing array to the function. Basic rules are The function prototype must show that the argument in a string. It is written as
void display(char str[]);

A call to the function must have a string array name without subscripts as its actual arguments.
Example:- display (name); The string to be passed must declared a formal argument of the function when it is defined.
example:void display(char item_name[]) { }

Scope,visibility and lifetime of variable:- In c not only do all all variables have a
1. 2. 3. 4.

data type, they also have a storage class. These variable storage classes are most relevant to functions. There are four types storage class in C. Automatic Variables. External variables. Static Variables. Register variables

AUTOMATIC VARIABLES:- Automatic variables are declared inside a function in which they are to be utilized. They are created when the function is called and destroyed automatically when the function is excited, hence the name automatic. Automatic variables are local to the function.

Example:-

A program to illustrate the automatic variables work.


#include<stdio.h> #include<conio.h> void function1(void); void function2(void); main() { int m=1000; Function2(); Printf(%d\n,m); } Void function(void) { Int m=10; Printf(%d\n,m); } Void function2(void) { Int m=100; Function1(void); Printf(%d\n,m); }

Extern variable:-

The variable that are both alive and active throughout the entire program are known as external variables. It is also known as the global variables. It can be accessed by any function in the program. It is declared outside the main function. Example:int number;
float length=7.5; main() { ----------} function1() { --------} function2() { ------------}

Static variables:-

The value of static variables persists until the end of the program. A variable can be declared static using keyword static. It may be either an internal type or external type.

example:- static int x;

Register variables:-

A register declaration advises the compiler that the variable in question will be heavily used. The idea is that register variables are to be placed in machine registers, which may result in smaller and faster programs.
register int x; register char c;

The register declaration looks like

The register declaration can only be applied to automatic variables and to the formal parameters of a function. In this later case, it looks like f(register unsigned m, register long n) { register int i; ... }

Array:-

Array is the collection of the similar data types. there are three types of array. One-dimension arrays Two dimension arrays Multi-dimension arrays One-dimension array:- A list items can be given one variable name using only one subscript and such a variable is called single dimension array.
example:- x[1],x[2],x[3] Declaration:- type variable-name [size]; initialization:- type array-name[size]={list of value}

Two-dimension arrays:- it has two subscript. example:- x[5][3] declaration:- type array_name[row_size][column_size]. initialization:- int table[2][3]={1,1,2,2,3,3} int table[2][3]={ {1,2,3}, {4,5,6}, }

Pointer:-

A pointer is a derived data type. It is built in from one of the fundamental data type available in c. Pointers contains memory addresses as there values. Pointers are used for the following benefits to the programmers. They are

Pointers are more efficient in handling arraya and data tables. Pointers can be used to return multiple values from a function via function arguments. Pointer reduce length and complexity of program. They increase the execution speed. Pointers allow C to support dynamic memory management. It is widely used in data structure. The use of pointer arrays to character strings results in saving of data storage space in memory.

Accessing the address of a variable:- The operator &

is used to access the address of the variable associated with it. p=&quantity; pointer variables takes the

Declaring pointer variable:- The declaration of the


following form: data_types *pt_name;
example:int*p;

Initialization of pointer variable:- A process of assigning


the address of a variable to the pointer variable is known as initialization.
Example:int quantity; Int *p; P=&quantity;

Accessing a variable through its pointer:int quantity, *p, n; quantity=175; P=&quantity; n=*p;

Pointer and arrays:- When an array is declared, the

compiler allocates a base address and sufficient amount of storage to contain all the elements of an array in continuous memory locations. Suppose we declare an array x as follows: int x[5]={ 1,2,3,4,5} value 1 2 3 4 5 Elements

Address

Pointer and the character string:-

as follows: char str[5]=good; The compilers automatically insearts null character \0 at the end of the string. It we can print the string using either printf or puts functions.

It is declared and initialized

Array of pointers:-

It is declared and initialized as follows: char *name[3]={ siwan, patna jamshedpur };

Pointers as function arguments:-

When we passed address to the function, the parameters receiving the addresses should be pointers.

The process of calling a function using pointers to pass the addresses of a variables is known as the call by reference. And the process of passing the actual value of a variables is known as call by value. WAP to exchange the values stored in two locations in memory using pointer:
#include<stdio.h> void exchange(int *,int *); main() { int x,y: x=100; y=200; printf(before exchange: x=%d y=%d\n,x,y); exchange(&x,&y); printf(after exchange : x=%d y=%d\n,x,y); } exchange (int *a,int *b) { int t; t=*a; *a=*b; *b=t; }

Function returning pointers:int *larger(int *,int *); main() { int a=10; int b=20; int =*p; p=larger(&a,&b); printf(%d,*p); } int *larger(int *x, int *y) { if(*x>*y) return(x); /*address of a*/ else return(y); /address of b/ }

Pointer to functions:- A function is like a variable, has

a type and address location in the memory. Therefore we can declare a pointer to function. it is declared as follows:- type (*fptr) (); Here , this tells to the compiler that fptr is a pointer to function, which returns type value. Example:- double mul(int, int); double (*p1)(); P1=mul; here p1 as a pointer to function and mul is a punction. P1 is pointing to mul() function. To call the mul, we have to use the list like that (*p1)(x,y) /*function call*/

Pointers and structures:struct details { char name[20]; int number; float price; } product[2], *ptr;

it is declared as follows: suppose product is an array variable of struct type. The name product represents the address of its 0th elements.

Here, statement declares product as a array of two elements, each of type struct details and ptr as a pointer to data objects of the type struct details. ptr=product; here, it is assign the address of the 0th elements of product to ptr. The pointer ptr will point to product[0]. It is accessed like following notation.
ptr->name; ptr->number; Ptr->price;

WAP to to illustrate the use of structure pointers.


#include<stdio.h> struct invent { char *name[20]; int number; float price; }; main() { struct invent product[3],*ptr; printf(input\n\n); for(ptr=product;ptr<product+3;ptr++) scanf(%s %d %f, ptr->name, &ptr->number, &ptr->price); printf(\n output\n\n); ptr=product; while(ptr<product+3) { printf(%-20s %5d %10.2f\n, ptr->name, ptr->number, ptr->price); ptr++; } }

Character arrays and strings:-

string is a sequence of characters that is treated as a single data items. Declaration:- char string_name[size]; Example:char city[10];
char name[20];

For reading and writing the string, there are many function. there are many function to do this. They are printf();scanf();gets();puts();getchar();putchar(); etc. There is a C library supports a large number of stringhandling functions that can be used to manipulate the string. In C many string handling function to do some specific task. They are listed below.

strcat():- strcat(string1,string2); strcmp():- strcmp(string1,string2); strcpy():- strcpy(string1,string2); strlen():- strlen(string1,string2); These are some string handling function in C.

Structure:-

Structure is a user defined data types. It is a mechanism for packing together data of different types.
{ char title[20]; char auther[15]; int pages; float price; };

Defining a structure:- struct book_name

Declaration of a structure variables:-

A structure variable declaration is similar to the declaration of variables of any other data types. example:- struct book_bank
{ Char title[20]; Char auther[15]; Int pages; Float price; }; Struct book_bank book1, book2, book3;

Accessing structure members:-

To access the member of a structure. Make link between a member and a variable by using the member operator . which is also known as dot operator or period operator.

For example:-

book1.price
strcpy(book.title, basic); strcpy(book1.auther, ansi); book1.pages=250; book1.price=120.50;

Structure initialization:main() { Struct { Int weight; Float height; } Student={60,180.75}; }

Array of structure:a structure variable. example:- struct marks


{

The array of structure , each elements of an array representing

int subject1; int subject2; int subject3; }; main() { struct marks student[3]={{45,56,58},{65,58,98},{89,69,36}};

This declares the student as an array of three elements student[0],student[1],student[2] and initializes their members as follow:
student[0].subject=45;
student[0].subject2=56; Student[2].subject3=36;

Write a program to calculate the subject-wise and studentwise totals and store them as a part of the structure.
#include<stdio.h> #include<conio.h> struct marks { int sub1; int sub2; int sub3; int total; }; main() { int I; struct marks student[3]={{56,36,58,0},{47,58,96,0},{98,56,87,0}}; struct marks total; for(i=0;i<=2;i++) { student[i].total=student[i].sub1+student[i].sub2+student[i].sub3; total.sub1=total.sub1+student[i].sub1; total.sub2=total.sub2+student[i].sub2; total.sub3=total.sub3+student[i].sub3;

printf(student total\n\n); for(i=0;i<=2;i++) printf(student[%d] %d\n,i+1,student[i].total); printf(\n subject total\n\n); printf(%s %d\n%s %d\n%s %d\n,subject1 ,total.sub1,subject2 ,total.sub2,subject3 , total.sub3); printf(\n grand total = %d\n, total.total); }