Anda di halaman 1dari 16

/* Ranking of 60 students in a class */

int main() {
/*declaring 60 varialbes */
int score0, score1,score2,..,score59;
/* Reading scores for sixty times */
printf("Enter the score : ");
scanf("%d, &score0);
.. .. .. ..
printf("Enter the score : ");
scanf("%d, &score59);
/* comparing & swapping for 1770 times
* to arrange in descending order */
swap( score0, score1);
swap( score1, score2);
swap( score2, score3);
.. .. .. ..
swap( score0,score1);
swap( score1,score2);
swap( score0,score1);
/*printing 60 scores after sorting */
printf("%4d, score0);
printf("%4d, score1);
. . . .
}
void swap ( int a, int b) {
int temp;
if( a < b) {
temp = a ; a = b ; b = temp;
}
}
score0
score1
score2
score3

score39
scores0
scores1
scores2
scores3

scores39
#include<stdio.h>
int main() {
int scores[60] , i , j, temp;
for(i = 0; i < 60 ;i++) {
printf("Enter the score : ");
scanf("%d", &scores[i]);
}
for(i=0;i<(60-1);i++)
for( j=0; j <(60 -(i+1)); j++)
if(scores[ j ] < scores[ j +1]) {
temp = scores[ j ];
scores[ j ] = scores[ j +1];
scores[ j + 1] = temp;
}
for( i = 0; i < 60; i ++) printf("%4d", scores[i]);
}
SlxLy varlables are replaced by one Array
SlxLy lnpuL
sLaLemenLs are
called by one loop
sLaLemenL
1770 comparlng
sLaLemenLs are
lncluded ln one
loop sLaLemenL
Array |ts Advantage
scores[0] scores[1] scores[2] scores[3] scores[4]
scores Array
. . .
start here
022 023 02 023 026
027
028 029 030 031
( memory
addresses)
#lncludesLdloh
#lncludemaLhh
#deflne SlZL 10
lnL maln()
lnL scoresSlZLsum0l
floaL devlaLlon mean LoLal0
floaL varlance sLddev
for(l0 l SlZL l++)
prlnLf(LnLer score )
scanf(d scoresl )
sum sum + scoresl

mean (floaL)sum / SlZL


prlnLf(nMean 2fmean)
prlnLf(nuevlaLlons )
for(l0lSlZL l++)
devlaLlon scoresl mean
prlnLf(2fL devlaLlon)
LoLalLoLal + devlaLlon*devlaLlon

varlance LoLal / SlZL


prlnLf(nvarlance 2fn varlance)
sLddev sqrL(varlance)
prlnLf(SLandard uevlaLlon f sLddev)

Mean can be calculaLed only afLer readlng all scores Lach devlaLlon ls dlfference of lndlvldual score and
mean 1o calculaLe devlaLlons of all scores scores musL be sLored ln an AkkA
lnlLlallzaLlon of Array
ueclaraLlon of Array
rocesslng on Array
lnpuL Lo an elemenL
Accesslng
an elemenL
na|ar Var|ab|es
A varlable represenLs a daLa lLem and lL can be used Lo sLore a slngle aLomlc value aL a Llme
1hese are also called scalar varlables
lnLeger Lakes 2 byLes memory as a slngle unlL Lo sLore lLs value leLhe value of a scalar varlable
cannoL be subdlvlded lnLo a more slmpler daLa lLems
1he address of flrsL byLe ls Lhe address of a varlable
Ventor Var|ab|es (arrays)
ln conLrasL an array ls mulLlvarlable (an aggregaLe daLa Lype) whlch ls also referred Lo a daLa
sLrucLure lL represenLs a collecLlon of relaLed daLa lLems of same Lype
An lndlvldual daLa lLem of an array ls called as 'elemenL' Lvery elemenL ls accessed by lndex or
subscrlpL enclosed ln square brackeLs followed afLer Lhe array name
All lLs elemenLs are sLored ln consecuLlve memory locaLlons referred under a common array name
Lx lnL marks10 /* declaraLlon of array */
'0' ls flrsL number ln compuLer envlronmenL 1he flrsL elemenL of array marks ls marks0 and lasL
elemenL ls marks9 (Lhe address of flrsL elemenL ls Lhe address of Lhe array)
An array ls a derlved daLa Lype lL has addlLlonal operaLlons for reLrleve and updaLe Lhe lndlvldual
values
1he lowesL address corresponds Lo Lhe flrsL elemenL and Lhe hlghesL address Lo Lhe lasL elemenL
Arrays can have from one Lo several dlmenslons 1he mosL common array ls Lhe whlch ls
slmply an array of characLers LermlnaLed by a null
na|ar var|ab|e for s|ng|e data |tem Ventor var|ab|e for mu|t|p|e data |tems
Declaration of One Dimensional Arrays
Syntax :
arrayType arrayName | numberOIElements |;
Example :
int scores |60|;
Iloat salaries |20|;
Initialization oI Array while Declaration :
int numbers | | 9, 4, 2, 7, 3 };
char name| | R`,`a`,v`,i`, ,T`,e`,j`,`a`,`\0` };
char greeting| | 'Good Morning;
Declaration of Multi Dimensional Arrays
Syntax :
arrayType arrayName | Rows || Columns |;
arrayType arrayName | Planes|| Rows || Columns |;
Example :
/* Each student Ior seven subjects */
int marks|60||7|;
/* Matrix with 3 planes and 5 rows and 4 columns */
Iloat matrix|3||5||4|;
Initialization oI Array while Declaration :
int matrix | || | 4, 2, 7, 3 } ,
6, 1, 9, 5 } ,
8, 5, 0, 1 } };
00 01 02 03
10 11 12 13
20 21 22 23
LlemenLs of
Array 3 by
/*passlng an array Lo funcLlon */
#deflne SlZL 10
lnL maln()
floaL llsLSlZL avg

avg average(SlZL llsL )

floaL average( lnL n floaL x)


floaL sum0l
for( l 0 l n l++)
sum sum + xl
reLurn ( sum / n )

nar name2S
snanf("s" name) ]*read|ng a str|ng unt|| a w|te spane |s ennountered ( operator |s not requ|red )*]
pr|ntf("s" name) ]*pr|nt|ng a str|ng |n |nput w|ndow *]
gets(name) ]* read|ng a str|ng |nn|ud|ng w|te spanes unt|| 'n' |s ennountered *]
puts(name) ]* pr|nt|ng a str|ng and moves nursor to new ||ne *]
tr|ngs Cne D|mens|ona| Caranter Arrays
A tr|ng |s sequenne of naranters In 'C' str|ngs are |mp|emented by an array of naranters
term|nated w|t a nu|| naranter '0'(ban s|as fo||owed by zero )
nar name "kav| k|ran"
k a v | k | r a n 0
name
'name' |s an array of naranters as s|ze of e|even naranters |nn|ud|ng a nu||
naranter '0'(asn|| node |s zero)
tr|ng Man|pu|at|on Iunnt|ons |n str|ng
str|en(s1) returns te |engt of str|ng exn|ud|ng te |ast 'nu||' naranter
strnpy(s1s2) nop|es naranters |n s2 |nto s1
strnat(s1s2) nonnatenates s2 to s1
strnmp(s1s2) nompares s1 w|t s2 |ex|nograp|na||y and returns '0' |f two str|ngs are
same returns 1 |f s1 |s before s2 and returns +1 |f s1 |s after s2
strnmp|(s1s2) nompares s1 w|t s2 ||e strnmp() but nase of naranters |s |gnored
strnr(s1n) returns po|nter to f|rst onnurrenne of te naranter 'n' |n s1
strstr(s1s2) returns po|nter to f|rst onnurrenne s2 |n s1
strrev(s1) returns po|nter to te reversed str|ng
Memory Address 8lL ls a smallesL unlL of memory Lo sLore elLher '0' or '1' ln memory
8yLe ls unlL of memory of 8 blLs Memory ls a sequence of a large number of memory
locaLlons each of whlch has an address known as byLe Lvery byLe ln memory has a
sequenLlal address number Lo recognlzed by processor
8AM ls Lemporary sLorage place Lo run programs CLanguage runLlme also uLlllzes an
alloLLed memory block ln 8AM Lo run lLs programs
1ext ent|on Memoryarea LhaL conLalns Lhe machlne lnsLrucLlons(code)lL ls read
only and ls shared by mulLlple lnsLances of a runnlng program
Data ent|on Memory lmage of a runnlng program conLalns sLorage for lnlLlallzed
global varlables whlch ls separaLe for each runnlng lnsLance of a program
8 (8e|ow tan egment) Memory area conLalns sLorage for unlnlLlallzed global
varlables lL ls also separaLe for each runnlng lnsLance of a program
tan Area of memory lmage of a runnlng program conLalns sLorage for auLomaLlc
varlables of a funcLlon lL also sLores memory address of Lhe lnsLrucLlon
whlch ls Lhe funcLlon call Lo reLurn Lhe value of called funcLlon
eap 1hls memory reglon ls reserved for dynamlcally allocaLlng memory for
varlables aL run Llme Dynam|n Memory A||onat|on calculaLe Lhe requlred
memory slze whlle program ls belng execuLed
ared L|brar|es 1hls reglon conLalns Lhe execuLable lmage of shared llbrarles belng used by
a program
Memory ent|ons of Ckunt|me
1wo or more ermanent Man|pu|at|ons us|ng one Iunnt|on
]* program to swap two numbers *]
#|nn|udestd|o
vo|d swap(|nt x |nt y)

|nt temp
temp x x y y temp
pr|ntf("nIn swap() d d "xy)

|nt ma|n()

|nt a 2Sb 37
pr|ntf("8efore swap() d d"ab)
swap (ab)
pr|ntf("nAfter swap() d d"ab)

ass|ng arameters 8y Va|ue


ass|ng arameters 8y keferenne
Cutput
8efore swap() 2S 37
In swap () 37 2S
After swap() 2S 37
]* program to swap two numbers *]
#|nn|udestd|o
vo|d swap(|nt *x |nt *y)

|nt temp
temp *x *x *y *y temp
pr|ntf("nIn swap() d d "*x*y)

|nt ma|n()

|nt a 2Sb 37
pr|ntf("8efore swap() d d"ab)
swap (a b)
pr|ntf("nAfter swap() d d"ab)

Cutput
8efore swap() 2S 37
In swap () 37 2S
After swap() 37 2S
o|nter var|ab|e A var|ab|e o|ds te address of anoter var|ab|e
nar opt|on ''
AIIots some memory Iocation
4042 (for exampIe)
with a name option and
stores vaIue 'Y' in it
''
option
02
value ln 'opLlon'
Memory Address of varlable 'opLlon'
nar *ptr NULL
Creates a po|nter var|ab|e
w|t a name 'ptr'
W|n nan o|d a
Memory address ptr
Memory address of
Var|ab|e 'opt|on'
Is nop|ed to te
o|nter 'ptr'
4042
ptr
ptr opt|on
''
option
02
*ptr 'N'
1e va|ue 'N' |s
stored |n te var|ab|e
w|n as te
memory address
4042
4042
ptr
'N'
option
02
!rogram with Using !ointers
int main() {
int n1, n2 ;
int *p = NULL, *q = NULL;
n1 = 6 ;
p = & n1;
printf ("%d %d", n1,*p );
printf ("%Id %Id",&n1, p );
q = & n2;
*q = 3 ;
printf (" %d %d ", *p , *q ) ;
p = q ;
printf (" %d %d ", *p , *q ) ;
*p = 7 ;
printf (" %d %d ", *p , *q ) ;
}
-DLL -DLL
n1 n2
p q
6 3 n1 n2
p q
pointer variabIes are decIared
!rints 6 3
6 3 n1 n2
p q
pointer 'q' assigned with pointer 'q'
!rints 3 3
6 7 n1 n2
p q
!rints 7 7
Wen two po|nters are referenn|ng w|t one var|ab|e bot po|nters nonta|ns address of te
same var|ab|e and te va|ue nanged troug w|t one po|nter w||| ref|ent to bot of tem
!rints 6 6
!rints address of n1
!ointer and Arrays
Even though pointers and arrays work aIike and strongIy reIated,
they are not synonymous. When an array is assigned with pointer,
the address of first eIement of the array is copied into the pointer.
#incIude<stdio.h>
int main()
{
int a[3] = { 12, 5 ,7}, b[3];
int *p ,*q;
p = a;
printf("%d %d\n", *p, *a);
q = p;
printf("%d %d",*p,*q);
b = a; /* error */
}
!rints 12 12
!rints 12 12
!ointer is an address variabIe, having no
initiaIized vaIue by defauIt. The address
stored in the pointer can be changed
time to time in the program.
Array name is an address constant,
initiaIized with the address of the first
eIement (base address )in the array. The
address stored in array name cannot be
changed in the program.
!ointer Arithmetic and Arrays
#incIude <stdio.h>
int main() {
int arr [5] = { 12, 31, 56, 19, 42 };
int *p;
p = arr + 1;
printf("%d \n", *p);
printf("%d %d %d\n", *(p-1), *(p), *(p + 1));
--p;
printf("%d", *p);
!rints 31
!rints 12 31 56
!rints 12
Subscript operator [ ] used to access an eIement of array
impIements address arithmetic, Iike pointer.
12
31
36
19
2
arr[0] or *( arr + 0 )
arr[1] or *( arr + 1 )
arr[2] or *( arr + 2 )
arr[3] or *( arr + 3 )
arr[4] or *( arr + 4 )
p - 1
p
p + 1
p + 2
p + 3
Array of !ointers
The advantage of pointer array is that the Iength of each row in the array may
be different. The important appIication of pointer array is to store character strings
of different Iength. ExampIe :
char *day[ ] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday" };
!ointer to !ointer ( DoubIe indirection )
ExampIe :
int a = 25;
int *pa = &a;
int **ppa ;
*ppa = &pa;
printf("%d", *pa); prints 25
printf("%d", **ppa); prints 25
2S
pa ppa
078
4024 40S6
036
02
a
Two DimensionaI Array -- !ointers
a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2] a[3][0] a[3][1] a[3][2]
base_address
Address of a[ i ] [ j ] = *( * ( base_address + i ) + j ) = * ( * ( a + i ) + j )
Array name contains base address
void !ointer
int main( ) {
void* p;
int x = 7;
fIoat y = 23.5;
p = &x;
printf("x contains : %d\n", *( ( int *)p) );
p = &y;
printf("y contains : %f\n", *( ( fIoat *)p) );
}
'void' type pointer is a generic
pointer, which can be assigned to any
data type without cast during
compiIation or runtime. 'void' pointer
cannot be dereferenced unIess it is
cast.
Output :
x contains 7
y contains 23.500000
Function !ointers
Function pointers are pointers, which
point to the address of a function.
DecIaration :
<return type> (* function_pointer)
(type1 arg1, type2 arg2, ... );
int add ( int a, int b ) { return (a + b) ; }
int sub ( int a, int b ) { return (a - b) ; }
int (*fp ) (int, int ) ; /* function pointer */
int main( ) {
fp = add;
printf("Sum = %d\n", fp( 4, 5 ) ) ;
fp = sub;
printf("Difference = %d\n", fp( 6 , 2 ) ) ;
}
Output :
Sum = 9
Difference = 4
Dynamic Memory AIIocation (DMA) of pointers
Static memory aIIocation means aIIocating memory by compiIer. When using address operator,
the address of a variabIe is assigned to a pointer. Ex : int a = 20 ; int *p = &a ;
Dynamic memory aIIocation means aIIocating memory using functions Iike maIIoc() and caIIoc().
The vaIues returned by these functions are assigned to pointer variabIes onIy after execution of
these functions. Memory is assigned at run time.
int main()
{
int *p, *q ;
p = (int *) maIIoc ( sizeof( int ) );
if( p == NULL )
{
printf("Out of memory\n");
exit(-1);
}
printf("Address in p : %d", p );
free ( p );
p = NULL;
}
AIIocates memory in bytes and returns the address of first
byte to the pointer variabIe
ReIeases previousIy aIIocated memory space.
caIIoc ( ) is used for aIIocating memory space
during the program execution for derived data types
such as arrays, structures etc.,
ExampIe :
struct book {
int no ; char name[20] ; fIoat price ;
};
struct book b1 ;
b1 *ptr ;
ptr = (book *) caIIoc ( 10, sizeof ( book ) );
ptr = (book * ) reaIIoc ( ptr , 35 * sizeof ( book ) );
Modifies the size of previousIy aIIocated memory to
new size.
Standard Character Functions
CIassification of Characters
conLrol
lscnLrl ( )
prlnLable
lsprlnL ( )
space
lsspace ( )
graphlcal
lsgraph ()
alphanumerlc
lsalnum( )
puncLuaLlon
lspuncL ( )
alphabeLlc
lsalpha( )
dlglL
lsdlglL ()
upper
lsupper ( )
lower
lslower ()
Other character functions in <ctype.h>
toupper( ) - converts to uppercase.
toIower ( ) - converts to Iowercase.
toascii ( ) - converts greater than 127 to
with in the range 0 - 127
int main( int argc , char* argv [ ])
{
int i ;
printf("Number of arguments : %d", argc );
printf("\nName of !rogram : %s", argv [0] );
for ( i = 1; i < argc ; i++ )
printf("\nUser vaIue %d : %s ",
i , argv [ i ] );
}
Command Line Arguments
CompiIe the program :
c:\>tcc cmdIine.c
c:\>cmdIine weIcome to c-programming
c:\>Number of arguments : 4
Name of !rogram : c:\cmdIine.exe
User vaIue 1 : weIcome
User vaIue 2 : to
User vaIue 3 : c-programming
llle -ame cmdllnec
ouLpuL
<stdIib.h>
int atoi(s) Converts string s to an integer
long atol(s) Converts string s to a long integer.
float atof(s) Converts string s to a double-precision quantity.
void* calloc(u1,u2) Allocate memory to an array u1, each of length u2 bytes.
void exit(u) Closes all files and buffers, and terminate the program.
void free (p) Free block of memory.
void* malloc (u) Allocate u bytes of memory.
int rand(void) Return a random positive integer.
void* realloc(p,u) Allocate u bytes of new memory to the pointer variable p.
void srand(u) nitialize the random number generator.
void systerm(s) Pass command string to the operating system.
<time.h>
clock_t clock() Returns clock ticks since program starts.
char *asctime(stuct tm)
ConverLs daLe and Llme lnLo ascll
int stime(time_t *tp)
SeLs Llme
time_t time(time_t *timer)
CeLs Llme of day
double difftime(t1,t2)
8eLurns dlfference Llme beLween Lwo Llmes L1 and L2
Standard C-Library Functions

Anda mungkin juga menyukai