Vous êtes sur la page 1sur 24

ARRAYS

It is a collection of similar type of elements that can share a common name.


Syntax for declaration of an array :-

data type

array_name[ ]

[ ] represents the dimension of the array and here the array is a single
dimension array.
[ ] [ ] double dimension array.
[ ] [ ] [ ] triple dimension array.
Arrays are of two types.
1. Single dimension array
2. Multi dimension array.
1. Single dimension array : It ha only one dimension
2. Multi dimenision arrays: It contains more than one dimension
Working with single dimension arrays :syntax :- Data type array name [n];
Eg:- int a[5];
The above is the representation of a single dimension array where the array
consists o ffive elements.
memory allocation for arrays is in sequential manner (side by side)
Accessing of array elements :Here the name of the array is a .
How to assingn the values to an array :-a[0] =1;
a[1] =2;
a[2]=3;
a[3]=4;
a[4]=5;
Initialization of an array :Int a[5] = {1,2,3,4,5}; valid notation of an array.
int a[ ] = {1,2,3,4,5}; valid notation of an array.
inta[5] = {1,2,3,4}; this is also valid since the fifth value may be garbage
inta[5] = {1,2,3,4,5,6} invalid
30

Reading from keyboard or input buffer:for(i=0;i<n;i++)


{
scanf(%d,&a[i]);
}
Displaying the elements:for(i=0;i<n;i++)
{
printf(%d,a[i]);
}
Searching techniques:1. Linear search
2. Binary search
1.Linear search:- It searches the elements from the first element to the last
element.
2.Binary Search:-It is searching for elements in the half of total no of
elements.
Two dimensional array:
Syntax: - Data type arrayname[rows][columns];
Eg:- int a[3][3];
Memory allocation:Accessing the elements :Assignment:a[0][0]=1;
a[0][1]=2;
a[0][2]=3;

a[1][0]=4;
a[1][1]=5;
a[1][2]=6;

a[2][0]=7;
a[2]1]=8;
a[2][2]=9;

Initialization:Int a[3][3] = {1,2,3,4,5,6,7,8,9};


int a[3][3] = {1,2,3,4,5,6,7,8} ; valid. Here the last value may be taken as
garbage.
int a[3][3] = {1,2,3,4,5,6,7,8,9,10};invalid since there are more numbers
than the size of array.
Int a[3][ ] = {1,2,3,4,5,6,7,8,9}; Compilation error.
int a[ ][3] = { 1,2,3,4,5,6,7,8,9,10}; This is valid since the row size is
31

defined and the last two elements of the fourth row are garbage values.
int [ ][ ] = {1,2,3,} this is an invalid notation since the row
and column size must be defined but here the row and column size is not
defined.
To initialize two dimensional array at least no.of columns should specified.
Reading from the input buffer:for(i=0;i<rows;i++)
{
for(j=0;j<columns;j++)
{
scanf(%d,&a[i][j]);
}
}
Displaying in matrix format.
for(i=0;i<rows;i++)
{
printf(\n);
for(j=0;j<columns;j++)
{
printf(%d\t,a[i][j]);
}
}
STRINGS
It is a collection of characters that can common name.
character arrays are used to handle the strings
Declaration:Data type string [1+1];
1=length of string
Purpose of +1 :
While handling strings null character will be maintained at the end of the
string
\0 null character
To accommodate null character one extra byte required.
32

Ex:Char str[10] allows only 9 characters of data


H

Str[0]
str[7]

L
str[1]
str[8]

L
str[2]
str[9]

\0

str[3]

str[4]

str[5]

str[6]

String operations:Reading of a string


Displaying of a string
string
Copying a strings
Comparison of two strings
Concatenation of two strings
Reverse of string
Case conversion of string
Searching for a string
Sorting of two strings
a string

Length of

Arry of strings
Reading of

Assignment:Char str[10];
H

Str[0]
str[7]

L
str[1]
str[8]

L
str[2]
str[9]

\0

str[3]

str[4]

Str[0]=h
Str[1]=e
Str[2]=1
Str[3]=1
Str[4]=0
Str[5]=\0

Str=hello ; invalid
String does not work with operator
Strcpy(str,hello ) copies hello into the str
33

str[5]

str[6]

Initialization:Char str[10]=hello
H

Str[0]
str[7]

L
str[1]
str[8]

str[2]
str[9]

\0

str[3]

str[4]

str[5]

str[6]

str[4]

str[5]

Char str[ ]=hello;


Char str[6]=hello ;
H

Str[0]

L
str[1]

str[2]

\0
str[3]

Char str[5]=hello; compiles but fails at runs time. It raises memory


exceptions
Reading from the input buffer:Scanf(%,str);
& is not required here since the string name it self is the address
Input : hello world only upto space is considered there fore the value of str
is hello
Scan function will read the string upto space or tab or newline
character(enter key) only
Reading of a line :Gets() :- function to read a line
char str[30];
get(str);
gets() will read the input data upto enter key. It will read the data
including \n but \n will not store into string.
Puts():To display the string.
char str[30] = hello;
puts(hello);
34

or
puts(hello\nworld);
O/P formatting of a string :% w.d s this format tells that d no of characters of string to be printed with
a width of w.
char str[10] = helo;
printf(\n%10.2s,str);
The above string has 10 spaces i.e. 10 spaces are allocated on screen and
two characters are printed at the end.
%-w.ds for left alignment.
String Manipulation Functions:C library supports a large number of string handling functions that can
be used to perform various operations on strings the most commonly used
string handling functions that are defined in string.h header file are
1) Strcat ()
4)strlen()
5) strrev( )

2) Strcmp( )

3) strcpy()

6) strlwr( )

7) strupr( )

1) strcat():- It stands for string concatenation. This function used to add


two strings. General format strcat(string1,string2);
In the above format string1 and string2 are character arrays
when the function strcat( ) is executed. String2 is added at the end of the
string1.
2) Strcmp() :- It stands for string compare their function is used to
compare two strings. If two strings are equal, then this function returns
0. Otherwise this function returns the numeric difference between the
first non-matching characters in the strings.
General format :- strcmp(string1,string2);
3) Strcpy():- It stands for strings copy. This function is used to copy the
contents of string2 into string1. String2 may be a character array
variable or a string constant.
4) Strlen():- It stands for string length. This function is used to find the
length of the string i.e. it counts the number of characters in a string.
General format :- integer variable = strlen(string);
35

5) Strrev():- it stands for string reverse this function is used to reverse a


string.
General format :- strrev(string);
6) Strlwr():- It stands for string lower. This function is used to convert
string into lower case letters.
General format :- strlwr(string);
7) Strupr():- It stands for string upper. This function is used to convert a
string into upper case letters.
General format :- strupr(string);

FUNCTIONS
A function is a subprogram or a self contained block of code &
that performs a specific task, every c program can be made of
collection of one or more functions. Every program contains only one
main() function and many number of user defined functions.
Uses of functions :_
1. To understand large programs easily, we can use functions. Because
functions are much easier to understand, debug and test.
2. To increase modulate of a program, we can use functions.
3. To debug or correct errors easily in a program we can use functions.
4. The length of a program can be reduced by using functions.
5. The function is called and used whenever required. It save both
time and space.
6. The functions avoid repetition of code in a program.
7. The functions may be used by many other program
8. The program execution becomes faster when using functions.
9. The function facilitates top-down modular programming. That
means the main program is divided into several modules called
functions.
36

Disadvantages :1. While executing functions control jumping takes place between the
functions. So the time taken to execute and performance reduces.
2. If the programmer is not expert with the recursive functions then the
stack overflow takes place and leads to memory exceptions.
Types of user defined functions:1. Functions with no arguments and no return values.
2. Function with argument and no return value.
3. Function with arguments and return value.
4. Function with no arguments and return values.
Function with arguments and no return value:
Main()
{

..
function(par1, par2, par3.)
..
..

}
Functions (type arg1, type arg2, typ arg3..)
{

}
Parameters : inputs are parameters
Arguments : Receiving variables are arguments
Eg: main()
37

{
Function(a,b); here a and b are parameters.
}
f(int x, int y) here x and y arguments.
{
.

}
To call a function the number of parameters and type of parameters should
match with functions arguments.
Function with arguments and return value:Main()
{

..
.
Return value;

}
Function prototype:It declares the name of function, number of arguments, type of arguments
and return type of the function.
Prototype declaration of a function:Main()
{
.
..
Decl return_type function(type arg1, type arg2.); here name arg is an
optional

..
38

}
Def ( function definition)
Return_type function(type arg1, type arg2,..)
{

Return value;
}
Void :- It specifies no type
It is an empty datatype.
When function require return type:
1. If the function returning a value other than integer type of
data
2. If passing data other than integer also the return type.
Void display()
{
..
.
Return 0;
}
The above is invalid.
Void function does not return a value.
Void display()
{

return; valid
39

.
.

Purpose of return statement :


1. To return the value
2. To terminate the function
If the function contains multiple return statements then only one return
statement executes.
Storage classes
The compiler allows two types of locations. They are memory and CPU
registers, in which a value should be stored. That means a variables storage
class determines in which of these two locations (memory & CPU registers)
the value shuld be stored.
A variable storage class also tells us
a) Where the variable should be stored?
b) What will be the initial value of the variable
c) What is the scope of the variable i.e. in which function the value of the
variable is available?
d) What is the life of the variable, i.e. how long the variable exists?
There are four types of storage classes in C. they are
1. Automatic storage class(auto)
2. Register storage class(register)
3. Static storage class (static)
4. Extern storage class(extern)
Automatic storage class :- the keyword auto is used to define automatic
storae class. The features of a variable defined on automatic storage class
are
Storage
default intial value
scope

memory
any unpredictable or garbage value.
local to the block in which the variable is defined.
40

life
defined

till the control remains within the block I which it is

Eg:Main()
{
auto int i;
Printf(%d,i);
}
the above program output is 221 (garbage value)
Eg:main()
{
auto int i=1;
{
{
{
printf(%d,i);
}
printf(%d,i);
}
printf(%d,i);
}
}
The above program output is 111
Eg:Main()
{
auto int i=1;
{
auto int i=2;
{
auto int i=3;
printf(%d,i);
}
printf(%d,i);
}
printf(%d,i);
41

}
the above program output is 321
Since C compiler treats the 3 are different because they are defined in
different blocks once the control comes out of inner most block the variable i
with value 3 is lost and so on.
Register storage class :- the features of a variable defined as register type
are
Storage
CPU registers
default initial value
any unpredictable or garbage value
scope
local to the block in which the variable is defined
life
till the control remains within the block which it is
defined.
A vaue stored in a CPU register can always be accessed faster than the
value stored in memory. Therefore if a variable is used at many places in a
program. It is better to declare its storage class as register.
Eg:main()
{
register int I;
for(i=1;i<10;i++)
printf(%d,i);
}
In the above example we have declared storage class i as register.
Even though we cannot say for sure that the value of i would be stored in a
CPU registers. Because the number other works the CPU registers cant hold
float, double values because they requires 4 and 8 bytes for storing a value.
Static storage class :- the features of a variable defined to have a static
storage class are
storage
memory
default
zero
scope
local to the block in which it is defined.
life
value of the variable consists between various function
calls.
Eg:main()
42

{
increment();
increment();
increment();
}
increment();
{
static int i=1;
printf(%d,i);
i=i+1;
}
The output of the above program is 123.
Eg:main()
{
increment();
increment();
increment();
}
increment();
{
auto int i=1;
printf()%d,i);
i=i+1;
}
The output of the above program is 111.
External storage class (extern):the features of a variable whose storage class has been defined as extern
are
storage
memory
default initial value
zero
scope
global
life
as ong as the programs life i.e. programs
execution does not
come to end.
external variables are declared out side of all functions.
Eg:int i;
43

main()
{
printf(%d,i);
increment();
increment();
decrement();
decrement();
}
increment();
{
i=i+1;
printf(\non incrementing i=%d,i);
}
decrement();
{
i=i-1;
printf(\n on decrementing i=%d,i);
The above program output is
i=0
on incrementing i=1
On incrementing i=2
on decrementing i=1
on decrementing i=0
Call by value and call by reference or pass by value & pass by
reference or information passing to a function
In C there are two ways of passing information from calling function to a
called function. They are
call by value or passed by value
call by reference or pass by reference
Call By value :- In this method, the formal arguments receives a copy of
values of actual arguments. Whenever changes is made to the formal
arguments. Whenever changes is made to the formal arguments. That will
not be affected or resulted in actual parameters.
Or
The formal parameters are the duplicates of the actual parameters. The
changes made on the formal parameters will not take any effect on the
actual parameters in the call by value method.
44

Note:- The values in the actual arguments (a&b) are not interchanged the
changes made to the formal arguments (x&y) will not result in actual
arguments.
Call by reference :- In this method , the formal arguments receive the
address of actual arguments. Because the formal arguments are the pointer
variables to pointers to the formal arguments. Whenever the changes is
made to the formal arguments then the changes will result in the actual
arguments in the function calling statement, the parameters should
represent the address of the variables.
Note: If any changes are made to the formal arguments then that changes
will effect in actual arguments.
Recursion:- Recursion is process by which a function calls itself until the
specified condition becomes fals. A function calls itself is known as recursion
or circular definition. The recursion process is used for respective
computations. When a recursive program is executed the recursion function
calls not executed immediately.
If a recursive function contains local variables a different set of the
local variables a different set of the local variables will be created during
each function call. The names of the local variables will always be is same as
declared in the function.
Passing an array to function :#include <stdio.h>
{
int a[5];
.
.
function(a);
..
.
}
function (int x[ ])
{

}
45

Passing string to function (character array)


main()
{
char str[10];
.

function(str);

..
}
function (char s[ ])
{

..
}
Global declaration of a function:If the function is declared globally then it can be called from any function.

STRUCTURES
It is a collection of different type of elements.
Structures are user defined data types
Declaration :syntax: struct tag name
{
data type member 1;
data type member 2; /* templates of structure*/
.
.
}; statement
Eg:struct emp
{
int eno;
char ename[15];
float sal;
46

char dept[15];
};
structure is a logical idea of something.
structure members do not acquire any memory with out declaring
variable.
Declaration of structure variable:struct emp e1, e2;
(here e1,e2 are the variables)
Memory map of structure members:Accessing structure members;e1.eno;
e2.eno;
e1.ename;
e2.ename;
e1.sal;
e2.sal;
e1.dept;
e2.dept;
Assignment:e1.eno=1001;
strcpy(e1.name, srilekha);
e1.sal=15000.0;
strcpy(e1,dept,edp);
Initialization:
struct emp e1 = {1001,srilekha, 15000.0,edp}
Reading from the input buffer :_
Scanf(%d%s%f%s, &e1.eno, &e1.ename, &e1.sal, &e1.dept);
Displaying :Printf(%d %s %f %s, e1.eno, e1.ename, e1.sal, e1.dpt);
Typedef key word with structure:typedef is to define the short cut name for the structure
Eg:1st method of declaration
Struct emp
{
int eno;
float sal;
47

char ename[15];
char dept[15];
};
typedef struct emp emp;
emp e1;

2nd method of declaration :typedef struct


{
Int eno;
char ename[15];
float sal;
char dpt[15];
}emp;
emp e1;
Size of structures :Struct emp
{
int eno;
char ename[15];
Float sal;
char dept[15];
};
Int n;
n= sizeof (struct emp);

Array of structures: It is a collection of similar type of structures.


declaration:

48

Struct sample
{
int a;
float b;
char ch;
};
Struct sample s[5];
Accessing:S[0].a;
s[0].b;
s[0].ch;

s[1].a;
s[1].b;
s[1].ch;

Nested structures
A structure contains variables of another structure as its member is
called as nested structure
A structure contains another structure as its member is called as
nested structure
Syntax:Struct inner
{

}
Struct outer
{
.
...
struct inner var1, var2;
};
Syntax 2:struct outer
{

..
49

struct inner
{

..
} var1, var2;
};
They are mainly used to access the date of joining of the employees.
Memory map of structure members.
1. Struct date
{
int day;
int month;
int year;
};
struct emp
{
int eno;
char ename[15];
float salary;
char dept[15];
date dob;
date doj;
};
2. Struct emp
{
Int eno;
char ename[15];
float salary;
char dept[15];
Struct date
{

50

Int day;
int month;
int year;
} dob, doj;
};

Accessing the inner structure members:e1.doj.d;


e1.doj.m;
e1.doj.y;

POINTERS
A pointer is a variable that can hold the address of another variable.
That means pointer variable stores the address of an ordinary variable.
Declaring and initializing pointers:Like all other variable pointers, variables must be declared before they
can be used in a c program.
Syntax :- datatype *ptr_var;
1) The asterisk tells that the variable ptrvar is a pointer variable.
2) Ptrvar needs a memory location.
3) Ptrvar points to a variable to type datatype
Eg:- int *p;
Eg:- float *x,*y;
Once a pointer variable has been declared it can be made to point to a
variable using as assignment statement.
Int *x;
Int quantity = 68;
51

P=&quantity;
The statement p=&quantity causes p to point to quantity that is p contains
the address of quantity. So it is known as pointer initialization.
Note:- pointer variable always point to the corresponding type of data. A
pointer variable can be initialized in its declaration itself.
Eg:- int x, *p=&x;
It declares x is an integer variable &p is a pointer variable and then initializes
p to the adderess of x.
Accessing the address of a variable using address operator (&):We can use the ampersand(&) operator to accuse the address of a
variable in c. So & operator is also called as address operator. The operator &
immediately preceding a variable returns the address of a variable
associated with it.
Eg:- p=&quantity;
In the above example the address of quantity i.e. 5000 is assigned to
the variable p. The & operator can be used only with a simple variable or an
array element.
Accessing a variable through its pointers or asterisk operator :To access the value of the variable using the pointer i.e. asterisk(*)
operator. The operator is also called as indirection operator.
Eg:- int quantity *p,n;
quantity = 100;
p= &quantity;
n=*p;
In this statement *p returns the value of the variable quantity. Because
p is the address of quantity. The operator * returns the value at the address.
So the value of n is 100.
Therefore in the above example, the last two statements
P=&quantity
52

N=*p;
N=*quantity;
Or n=quantity;

*****************************************************

53

Vous aimerez peut-être aussi