0% found this document useful (0 votes)
60 views

Computer Program

1. The document discusses the structure of a C program, including preprocessor directives, global declarations, the main function, declarations, statements, and user-created subprograms. 2. It explains key elements like preprocessor directives that include header files, global declarations that declare variables outside main to be used in multiple functions, and the main function which identifies the start of the program. 3. The document also covers C data types including basic types like int and float, derived types like pointers and arrays, and the differences between structures and unions in how they allocate memory for members.

Uploaded by

Kushal Kushi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Computer Program

1. The document discusses the structure of a C program, including preprocessor directives, global declarations, the main function, declarations, statements, and user-created subprograms. 2. It explains key elements like preprocessor directives that include header files, global declarations that declare variables outside main to be used in multiple functions, and the main function which identifies the start of the program. 3. The document also covers C data types including basic types like int and float, derived types like pointers and arrays, and the differences between structures and unions in how they allocate memory for members.

Uploaded by

Kushal Kushi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Cbapter-2

Structure of C program Ex:


I. Preprocessor directives #include <stdio.h>
- 2. Global Declaration void main ( )
3. void main () {
4. { clrscr ( ) ; ,
5. Declarations; printf("\n welcome to c programmint-"'');
6. Statements; }
7.}
8. User created sub- program Output:
Welcome to c programming

statements begin with #(Hash) are called pre-processor


Line l: Pre-processor statements: The
· ·
dtrect1ves. They d'trect t he c preprocessor to include
. the header files and symbolic constants. The

information is stored in specific files called header files.


e.g. # iriclude <stdio.h> used for standard input output functions.
# include <math.h> used for mathematical functions.
# define pi 3.142 used for symbolic constants. I
Line 2: Global Declaration: The variables declared outside the main function and used in mote
than one functions are called global variables.
Line 3: void main O: Main is a special function used in to identify the beginning of the program,
every program should have only one main. It should be written in lower case and should not be
. terminated by a semicolon (;). The parenthesis after main. Tells the compiler that it refers to a
function.

Line 4 & 7: The start and end of the program is indicated by open braces ( {) and closing brace
(}).

Line 5: Declaration statements. It determines the type of the variable.


Line 6: Contains all executable statements, that must ends with a semicolon(;) . _ . . . . ,-,,:
Line 8: User defined functions· It · · I ·:- ·' ' ·,
· is opt1ona . User defines the task is not available m the C-
compiler under this sect-ion. ,
(..J
Variable Declaration·. · b
Th
e vana le declaration is made m art of the C-
program. It defining "the type of variabl b " . .
e eiore 1t ts used is called type
declaration".

'; p\ ,J_~Syntax: dataty e vari I ,-li.;:t•


l-1' lllll\ Liiv V dlU ~ orb IS %d\n", sizeof(b))·
printf("the value of c is %d\n", sizeof(c));

- printf("the value of c is %d\n", sizeof(d));


getchO;
}
OUTPUT:
Value of a is 2

Value of bis 4

Value of c is l

Value ofd is 8

Data types: Data type indicates the..,type of data a variable can have. A data type ~~ually defines
_a set o.f v alues. This can.,, be stored io ~ e variables along with the operators thaL may be
performed on those yalues:,c includes 3 tYpes of data,
✓ Built-in data types
✓ Derived data types
✓ User defined data types.
I
i tion
1. Basic Types: They are arithmetic types and are further classified into: (a)
inte er ~ · es and · - oint t es. · ·
2. Enumerated types: They are again arithmetic types and the;y are used to define
\@ri illll,es that can o □ l.¥ assign certain discrete integer v'3,lµes thi:oughgyt the
ro ram.
3. The --- e void: The t e · er void indicates that no value is avail ble.
4. Derived types: They include (a) Pointer types, (_b) Array types, (c):Stnicture
t e FunctiQ9J _ es

a. Simple or fundamental or Basic data type: These are the data type which i~_not ~~mposed
of other data types. In other words these are elementary data type or primitiv~ _clata type.

There a11: 4 fund~mental date types in C.

Char , int , float , double

char: This means that the variable is a character Type. Character objects are stored in..l byte. It
can hol ~ nly one character from the C - character set. Range is -128 to +127 ·
..::=:==
int: This means that the variables is an integer objects are stored in 2 bytes. It can hold whole
~umbers.
~-' ,:::>= Range is -32768 to +32767 ~ - ---.-=-- --
float: This means that the v ·abl fl .. . ·
h0 Id bo h h · . an es are. a oat.· . obJects. Float objects ~stored in 4 b}1es. It can
· t w o1e numbers and fract · • . • · . · ·· •- ---==.:=-->
to +3.4e3S · =---- ions. 11 givC$,b...J!l~ of decimal accuracy. Range as -J.4e38

15
. Double objects are
bl recision flo~ o•!!t ty£~· h I 5 decimal
double: This means that the variable is ~~~~orev;ry b i ~ber. It gives more t an_ _ _--==-
t d ·n 8 bytes. It is used to store ~erye s~ ::.:....::=-:-:~- - -
s ore 1 • to+ t.7e308
places of accuracy. Range is -1. 7e308 .

Float v/s double:

Float Double

Holds a real constant with Holds a real constant with

lesser accuracy more accuracy

Real constants can be stored Real constants can be

upto an accuracy of 6 digits stored upto an accuracy of

after decimal point. 16 digits after decimal point.

4 bytes are allocated. 8 bytes are allocated.

Range is -3.4e38 to +3.4e38 Range is -1. 7e308 to + I. 7 e308

Derived or data modifier

These data types are used to modify the existing basic data types.

They are four modifier are supported in C-language

► Long: it is used to double the size of an existing data 1)lpe


e.g long int a; ➔ 4 bytes

Short: it is used to reduce the size of an existing data type. To occupy fixed me!ftory
space the short keyword is used.

e.g short int a; ➔ 2 bytes.

► Unsigned: it is used to store only positive data elements.

Unsigned int a=l00; ➔ valid

Unsigned int a=-100; ➔ invalid

Signed: it is a default data typ~


.__.,_ . .,, --- -
This keyword accepts ~th negative or positive xalue. -
Int a=IO; ➔ valid
-
- -
Difference - - and
hrtween structures -----------
unions-r--
-- ------------ Structures ____~_ __ ___ __ _J __ _ _ Union
The ke, -\vo rd "struct'· is used to clct!11c ~1 1 The keyword "union" is used to d efi ne 3
I •

s true tu re . _ _ ______ _ urn o n_. _ _____________ __ 1

-T h ~ -:01111~~-ler will allocate th e rne11~~)7)~- f'o r The size of n1emory is allocated by th e


each memb er separately. compiler is the size of the men1ber that ·
() L·cupi es largest space . 1

Each memb er with 111 a strul'turc \) :\ll rnernbers of union shared comm on
Jss i gn~d it s O\\ n unique storage aren. --r1 memory location
----''----- - - - - -- -- -- --
S in1 ul tan eo usl v access all the data : Only one 1ne1nber can be accessed zi t d
I .
1nen1 l)er. tllne. ________ _____ I_
- - -- - - - - - - - - - -
Se \. -cr~il m emb e rs of J stru c ture can b e i Only the first men1ber of a union -~;1 11- b~-
.J~1_i\_~_~i_~_ec_l_~l_t o n ce ______________ ___ _ : initial _ i ?_.e_c_
l.______________
; ~ tru ct u_ _rc_=-s_· _ __ _ _ _ _ __ : l n_i(_11_1_ _ __ __ J

Syn ta\: ! Svntax:


I -
s truct struct name union union n31ne
i
t
cLlta type li st-!: data_t ype li st-1:

i
d~l tc_1 _ t ~ pt'. I j St - l L clat a_type li st-n:
I . l.
f)

- ~··-~ -~---- -· ·--- _______ ,. . - :--"'--:-:.,,.,..:- " ...... - ., ....... -.-..-·- -----_.. . , . . .... .. ,.,____-····--·-·~· ---,: .,..... . ~ -····•-..·: -·-:---- - ····---~·-·--- --- ~~- - ....~: ---:: ..... , • - - ~ - 1.-,"::"-~.:~~ ~ ~ ~; - -----
a++;
printf("o/od'' ,a) ;
getch()
}
// output: 50
Similarly the following program illustrates pre decrement and post decrement.

Binary operators: Operators that act upon two operands are referred to as Binary Op~rators.

a) Arithn1etic operators [+,-,* ,%,/]


Arithn1~i~ Operator+: It is us~ to ~oi.it.§_operands and the result is the ~\UI) ·O{ tb
~alues of its two operands. Operands ,nay he ~ct@
ger ar flgat ·
For Ex: 4 + 20 results in 24.

If a= 2 , then a+ 10 results in 12.

If a= 3 , b= IO, then a+ b results in 13.

8
~II
Arithmetic Operator -: The - operator subtracts the second operand from the first. For Ex:
10-4resultsin6. - -

If a= 5, then a- 2 results in 3.

If a= l 0, b= 3, then a - b results in 7.
I

Arithmeti~ Operator*: The* operator_multipli~s the val~es of its operands.

For Ex: 3 * 4 results in 12.

If a= 5, then a * 2 results in 10.

If a= 3, b= 3, then a* b results in 9.
. "d • cfi
Arithmetic Operator / : The/ operato~_d_!.~~_1t~' -,t "PP.rand by the second.
-.l~+ · .

For Ex: l 00 / 5 results in 20. ··

If a= 5, then a/ 2 results in 2.

lf a= 10, b= 2, then a/ b results in 5.

Arithmetic Operator °/4,: The % operator finds the modulus of its first opera~d relative to
the second. i.e.; it produces the remainder of dividing the first by the second operand.

For Ex: IO % 2 results in 0. •

Similarly 7.6 ~ 2.9 results into 1.8 and -5 % -2 results into -1.

Operator + with Strings:

Operator + can also used to add two strings i.e, it concatenat~s two strings .
.-__;.;;;;--->
For e.g., 5 + 6 results into 11.

"5" + "6" results into "56".

--- 5 + "ABC" results into "5 ABC". (Internally converts 5 to "5")

b) Relational operators [<,> <= >= = '=]


' ' ' '.
It is used to deter!Iline the relation among different operands. C provides six relatio~al
.

---·
.

operators for comparing numbers and characters. They don't work wi.!!,i strinis. If the
. . . . . -
companson 1s true, 1t_results into t~e value l and to Oif comgarison _is false.
,.·

< (less than) <= (less than or equal to) == (equal to)
> (greater than)
>= (greater than or equal to) != (not equal to)
Q
p < ----- p === Q
--
p >Q
p;:;,-== Q P!=Q

p Q p <Q

I
0
--
0
~ l

I
0 I - i-- 1 1
1
0 0
l 0 0
0

3 3 0 I

l
l

0
0

0
1

0 1
-
1
2 6 I

I\
c) Logical operators [&&, II, !, &, I, ] d't' ns There are 3
d or complex con t to .
These operators are used to construct compoun . .
logical operators C.
&& Logical AND II Logical OR ! Lo_gical NOT
= fi
The Logical operators && and II are used when we want to orm
compound conditions by
. .. .
combi!Jing 2 ~!:. mQrcuelationl:
. . 1· ression
The logical AND(&&): It combines two expres~1ons mto one. The resu tmg exp
has the value true only if both of the original expressions (operands) are true.
✓ (6=3) && (4=4) results into false because first express~<:~ is false .
. . _ / ✓ ( 4=4) && (8=8) results into true because both expressions are true.
✓✓ 6 < 9 && 4 > 2 results into true because both expressions are true.
✓ 6 > 9 && 5 < 2 results into.fals~ because both expressions are false.
-=- .
-
The logical OR (II): It combines.two expr.essions.lnta one. The resulting expression has

the value true if either of its operands evaluate to true.

(6=3) 11(4=4) results into tr~e because second expression is true.


(4=4) II (8 8) results int~ because both expressions are true.
✓ 6<9 114 > 2 results into true because first expressions is true.
--.../
✓ 6> 9 i~ 5 < 2 results into false because both expressions are false.
/✓ 0118 results intq_ tru:,bec~~~;:md expression is true. .
The logical NOT operator(!): It w?rks on single expression or operand i.e., it is a unary
operator. It negates or reverses the value i.e., if the e~pression is true, then !expression ·is
faJse and vice versa
For Ex:
-,a.P Jf ~~ -l"D c..e__

!(5 != 0) results j nto false_because 5_i:~. non zero (i.e.• true)


- h1w;_ ·~ -f).
!{5 > 2) results i~to_plse because the expression 5 > 2 is true.

10
!(5 > 12) results into true because the expression 5 > 12 is false .

d) Assignment operators [=]


The assignment .operator '=' assigns the value on its right to_~ ~_!:rand on its left.
E.g. int x =10;
·float y = 20.5F;
int p = 10 + x;
This operator can also used on objects to assign object references

e) Compound or shorthand assignment operators [+=,-=, *=,/=,%=]


C offers ~pecial shorthand's that simplify the coding of a certain type of assignment

statement.

For Ex: a= a+ 10 can be written as a+= 10.

i.e., var= var operator expression is same as var operator = expression.

X -= 1O; equivalent to x = x - IO;

X *= 1; equivalent to x = x * I;

X /= 10; equivalent to x = x / 6;

X %= 1O; equivalent to x = x % 2;

And also we can us~ &=, 1=, 11.=, <<=, >>=, >>>=

f) Bitwise Operators · [&,!,",~]


The bitwise operators work with integral_!Yee~ _i.e., byte, short, int and long types. The
bitwise·operators a~~.sbmetimes referred to as logical operators when they work with Boaiean
</~ '
values. -
Operator Use Operation ·C
;>l',

..

These operators allow


& Opl & Op2 Bitwise and
performing bit manipulation
on data. Bitwise operators are
not applied to float /or I Opl I Op2 Bitwise pr_ .
double, it performed only on
I\
integral type. Op! /\ Op2 Bitwise xor

~ ~Op2 Bitwise complement

The bitwise operations calculate each b Of h


the it t eir results by comparing the correspqptling biUfS>L
two <>peraoos ons~he basis of these three rules:

11
r Exclusive OR means that i f th .
. - ---~ two operands bits t 0 l
·i;
are different~the result is I ; other:~ise ~h~-res_ult 0.
1 0
t.

The complcm.ent Operator~:

The complement o perator inve,ts the value of each bit of th e Opl Result
th
operand. If the operand bit is l the result is O and if operand bit is O e ---Opt
result is I.
o·· l

1 0

. . t · ry operator available in C.
g) The Conditional Operator: The character. pair ?: 1s a~~er~n~a~~==:.:.....::...:...::=.::= = -
This operator is used to construct conditional expression of the fonn,
1 expression 1 ? _exRression2 : exp ression3 . ·\
·) -- · ·· h 2 1· s evaluated otherwise
Where exp I,_exp2 an~ exp3 are express10ns. I[s_xp I 1s true t en exp
exp3 is evaluated. ·
Example: I. result= marks >=50? ' P' : ' F' ; the identifief result will have value 'p' if the
test expression marks >=50 evaluates to true (1) otherwise result will have value 'F'.

2. IO> 4 ? IO : 4

h) Shift operator [<<,>>]


A shift operator p~rforms bit manipulation on data by shifting the bits of its first
operand right or left.

Right Shift Operator: It operators on a single varia~le. It is represented by _ >?-' a~u

-the
it spifts each bit in the operand to the right. The blank~ _t~at are created on -- left.. --will always__b£
__........
_filled wit~ zer.Q.s.

. :- . .
Example: num >> 3 would sh_ift all bits three places to the right.

If the variable num contains the bit pattern I I001111 o, then

Num >> I gives 011001 I 11

Num >> 3 gives 0001100 I I


bv ,.~ < ..and it
._, 5 ·ves 00000 I l O0 . It is represented . .,i , , , ~ . · - - -
. -

Num >- g1 single ~!:~~}e· teft~l!)~l~~x~ be J~kh...-


erators on a~ - --··· -- eated on th~----
Left Shift Operator: ft op blanks that are er
the left. The
shifts each bit in the operan d to

filled..with..ze.cos. the left.


laces to
ould shift all bits three P
3
Exa mpfe: num << w
. b·t
I
ttern I IO IO I I 1, then
If the variable num contarns the pa

Num << I gives IOIOI I 10

Num << 3 gives I 01 J IOOO

Num << 5 gives I I 100000 ·


. . h as comma operat o'
r sizeof
Special Operators: C supports some s2ec1al operators sue . re:
· · t rators (* and & ).
operator, member selection op~cato...rs ( . and -> )_~n~ pom er ope _ .
. h Th group of expressions
Comma Operator: It is used to link the related expressions toget er. e - .
t
sep,~ t~ _,by comma~_Q is evaluated left-to-right i.~ -s~qµ.fU£_e • The result i~ the right moS

~xpress!on '?.~co~es the valu_e o.f tli~ L COIJ!.J21_a2 ~parated e~£!:<:.~ ~~!:.
Ex: sum= ( a=IO, b=5, a+b ); the sum contains the value 15.

SizeofQ Operator: sizeof() r~tums the ~umber of bytes necessary to store an variable..w,ith. the
type of its operand.

Ex: if num is of type int, the expression sizeof(num) returns the value as 2.

if num is of type long, the expression sizeof(num) returns the value as 4.

if num is of type float, the expression sizeof(num) returns the value as 4.

if num is of type char, the expression sizeof(num) returns the value as 1.

Ex: the following program demonstrate the use of size of operator


#incJude<stdio.h>
#include<c.onio.h>
void main()
{
int a;
float b;
char c;
-doubled;
printf("the value of a is %d\n", sizeof(a));

,.
Chapter-4
ARRAYS

The fundameiilal data types can


h
::at:
be cases to handle large amount O .d
di limited amounts of data. In some cases th
in terms of reading. Processing ~nd print:e may
derived data type called 1'8-RAY. g.
To solve the above problem C provi es: ta elements or it is a continuous memo 1 .
Array· It is a collection of homogenous a ry ocat1on to
: . · d · ed data type.
store similar type of data. Ar~y is a eriv f I memory locations.
► Array allocates contiguous or sequen ia
► Individual values are called elements.

C allows two different types of arrays,


► Single dimensional Array or scalar Array
► Two dimensional or Multi dimensional or vector Array.

Single dimensional array or scalar array: It is a list of data items represent by only one index
(Sub Script).

Syntax: datatype Array-Name [Size]; .


Where datatyp~ is a any valid C-language data type, Array-~ame 1s the user defined name, Size
is the number of memory location in an array. · ·
e.g I int X[lO]; -> Declaring X to be an array containing 10 elements.
The declaration statement indicates the compiler about
1. Data type of the array
2. Name of the array
3. Size of the array . l
:.g 2 int a[5]; ➔compiler allocates 5 blocks each of 2 bytes in which integers can
be stored.

I I I I I 2 I
~ a[~] ~ ~ ~
rray initialization: A special feature of arrays is that array can be initialized when they are
clared I.e. it is the process of storing data into the array. This is done by a pair of braces.
lese braces contain a series of constant values separated by commas.
can be done using 2 methods
1. Direct initialization
2. Initialization using a for loop '

·ect initialization

int marks [5] = {70,65,45,34,22};


iis declaration, marks [OJ is initialized to 70
marks [I] is initialized to 65
marks[2] is initialized to 45
marks [3] is initialized to 34
. - ·- .
J
Two dimensional arrays:
A two dimensional array is used to represent elements in a table with rows and columns,
provided each element in the table is of the same type. A element in a two dimensional array is
as
~

associated by specifying the rows and columns indices of the item in an array. It is also called
table or rectangular array.
Eg: Matrix.
Syntax:

Data_type array_name [RSIZE] [CSIZE];


Where,
Data_type is the any basic or derived data type,
Array_mn,c is the user defined array name.
RSIZE is the row size.
ti

CSIZE is the column size.


Ex: int A[3] [2];

A is _L dimensional array which contain 3 rows and 2 columns, totally 6 elements are
stored in array A.

This statement tell~ the compiler to allocate 6 memory blocks to the variable A. In other
words a matrix contains 3 rows and 2 columns. By default 2D array elements are represented in
memory as row major access or row major order.
The conventional method of memory representation is as follows
(

A[O][O] - A[O][l]
A[l][O] A[l][l]
A[2][0] A[2][1]
Each data item in the array A is identifiable by specifying the_?ITay name A followed by
a pair of square brackets .enclosing row number, followed by a pair of square-brackets enclosing
column number.
A[O][O] refers to da~ item in the first row and first colwnn.
A[O][l] refers to·data item in the first row and second column.
A[l ][O] refers to data ite~ in the second row and first column.
A[l][l] refers to data item in the second row and second column.
A[2][0] refers to data item in the third row and first colwnn.
A[2][1] refers to data item in the third row and second column.
-
Initialization:
,Direct initialization
. A Two dimensional array either by initializing it in its declaration or by using
'='(assignment) statements.
Ex 1 : int A[3] [2] = {{2,5},{3,6},{43,5}} or int A [3][2]= {2,5,6,7,10,33};
Ex 2: int a0[3]={10,80,60,30,5,19,20,3,l6,is,1s,100};
Thus it is important to note that while initializing 2D array it is compulsory to mention the
second dimension(column) where as the first dimension(row) is optional.
Using a for loop to initialize array
Ex: int a[4][3]
Toe declaration int a[4][3] qeates 20
for(i=O;i<4;i++) array with 4 rows and 3 columns with
{ names a[O][O],a[0][1],a[0][2],a[l][O],
forG=0j<3j++) a[1][1]--,a[3][2]. The ~uter
{ loop would loop 4 times. Each times
printf("enter an integer\n"); ___
the control enters from the outer for
looo to the i nner for loop __.
--•u11,.u laSk. fl
reduces the complexity of the program.
There are two types of c functions
I • Built-in functions or library functions.

• User defined functions .

B}JI'Jt-in functions: These are the functions whose meaning is defined in some header files
e.g.: printfO~scanfQ,getchO,putchar(), etc defined in stdio.h. ·
sqrt(n),pow(r,n),abs(x) defined under math.h •
strcpy(),strlen0,strupr() etc under string.h
User defined functions: User can define the function within a program. A progr· .
. . am may contam one or
more functions. The execution always starts from the mam; all other functions are i kd
nvo e (called) from
the main.
The general fonn of function definition is as follows
R_type function name (parameter list)
{
R_Type ➔ the data type of the return value of the
Local variable declaration; function.
If nothing is returned the data type is void.
Statement 1; Parameter list ➔ list of variable that receives value from I
calling function.

Statement n;
• retum ➔ is a keyword used to re~rn a value from sub
function to calling function.

retum (value computed); ·


}

Actual parameters and Formal parameten:


Arguments or parameters are the variables used in a program. \:;,:/,·· . ~ ---.'. .. . .. '"'· '
Actual parameters: The variables used in the calling function are called Actu~I parameters since they a:
accepted in the main function (calling function).
Formal parameters: The variables used in the function definition are called Formal parameters since _th,
are not the accepted values. They'have a copy of ac~ parameters.
Note: There is a one to one correspon~ence between the actual parameters and the fonnal parameters i.e. 1
number of actu11/ p11rameters is equal to the no offorma/-~ar~meters~
-

. • -· - , '" ... I
b
STRC Cr LRLS

Stru(turc is a collection of related da ta items of cli ss imibr or he teroue ..


- .. . . I : : , neou s dat a t ,
related Jlcm s are grouped together_under a s111g e name. . . . YPes but logica lly
r or example. common attnbutes of an employee 111 an orga111zat1on such , ,
. · ds employe
r department and ~alary etc .. can be represented us mg a structure. e number, name
Syntax: '
struct stnrc.t name

data _ type list I;


I
I

data_ type list n;


I .
I •

st ru ct 1:-- th-: kc y,voro.


stTu cr_name is the any user defined structure nam e.
data_ type G ll1 be any of the data type in C . ·
listl...l is tu a re the set of variables called fields .
Tht. i :iri;ibk's.; defin ed in the structure are also called Structure i\ f.emb •..
I.:\'
. . \. .
. s.l. , .l"l i·•"-··1. t."l 11 1'
' •/ }
(:IS .

di;u 11 ;m 1c/ :2u J:


. . k : :k:11 / !< Jj:
j J'il ,J ;.
I
I.

'' .-... .
fJ ' I
: ' ' I·. \ ' l. 1 11
.: , !I\ \,_ " j-i L1 ,· d~iu, r>· ;c ~;r ttrnplate.

J lw r1,.· 1·., ·1 -_
r ·- .
1 c'll i 1
r- . -
I. _ _ _

(- ~ ➔ ~-
hytc <

J> .
. . ,1 ., ( i/' type L' lllfJ ··t - ·t
,111:1 blt._,
\ ', Ii L: 11 · l .l l . 11- 1..- 1\.. I•·r l . _ .·' 1 l h.. LI n_
i 1 1•· , :. "·"· · I,11 ' s. 1n \. 1, , . ; ., 1, , , •

O 1

L , :1nd bk P 'l h, , .. ... !'


Programming in C

CHAPTER-11

Pointers

A
.
pomter . ~-.powe1-t:..J
1s ., u .
construct of the C programming language.
.

,Definiti()n:
.,..
''A pointer is a variable wh~ch hoids ~e address of other variabfos such as arrays,
structures and functions that are used m program.

Advantages:
• Manipul~tion of data at different memory locatfons is easier. .
~-r- ~
• Jo ac1i1eve clarity and simplicity.
--
• More CQmpact and efficient coding.

• Dynamic memory allocation,

Operators used with pointers:

There are 2 basic operators used with pointers. They are

• The address operator{&): it gh'es tl:!e adress ofa·variable.


. -
• The indirection operator (*) : it gives the value of the variable that the pointer is pointing
. to.

'
Pointer/ dec1aration:
~ '

/ /__,. Like ordinary variab.es, pointer variables that appear in a C program must be declared.

Iaddress.
1000
I Data
100
dereferencing ·

1001
Referencin:1 1002
1003 640
...
... I
2001)
- -·
-ammingin C

Pointer Dereferencing
Vidyavahini First Grade College, Tumkur

.is aprocess of referencing the contents of the variables using_ .ooint~rs


. . : i'nd·1rec.tiy.
ps involved in dereferen~ing:

, Address of a variable, whose value is to be referenced is assigned to_a pointer.


, Then: this pninter points to the value,
f
I
I
1000 -- i
ptr to int -" .. 4 I

Ir/
J
I

1001
1002
1003 I
num 1004 ..
Ann
--
·•
II

2000
in the above figure, the variable mnn designates the memory location I 004 and the pointer
variable ptr-to-int designates the memory location 1000.

91iemions on pointers
,...
___

A pointer variable hQlds the address of the other variable. This address can be incremented or
,decremented. But the mulf. ,lication and division operations cannot be performed .on the
1

addresses. This means th~t thi: pointer variables cannot be multiplied or divided. Operations t11at
can be perfonned on pointers lS given below. .

Assignment:

• Apointer variable car.. be assiwied the address of the·other·variable.


Ex: int *ptr, var,

ptr= &var;

• if~ pointer variables Jre pointi~g to the object of the same data type, then they can be
assigned. · · ··
Ex: int *pttl, *ptr2;

ptrl = ptr2;
. . . ··· · - - ·· - JI Vta ay JJ l U V IU e~ L powertul f
- · - - v . ... . . ' - ' U t y . C
,._ . . _ _ . . Unctions tOr performinJ
fo rmatted rnput and output operations. They are printf ( ), scanf ( ). ·

These 2 functions c a n read and write data in various formats in specified by the user.
Format specifiers gives the forma t in which the values of variables are to be input - d d" . .d
. ... an 1sp1aye
accordingly to the type specifiers like int, float, char..,.double etc.,
a. Formatted Input function:

scanf ( ): 1✓

Is formatted input functions. It is used to accept data. It can be used to enter any combination
of numerical values, single character and strings.
Syntax: scanf (" format Control String" , & argument-list);
Where format control string has 2 components
l. a series of characters.
2. .Format specifiers.

And argument list is preceded by an ampersand symbol meaning that address is to be


passed.

Format control string specifies the field format in which data is to be entered and the
argument list specifies the address of location where value is to be stored. The name of the
variable preceded by the ampersand (&) symbol gives the address to the variable. The format
control string contains only fonnat specifies.
..
Format Specifiers Meaning --
%c Print a character format
%d Print a signed .decimal number
%i Print a signed integer
%e Print a float value in exponential form
%f Print a signed float value
%g Print using %e or %f which ever is smaller
%0 Print unsigned octal value
%s Print a string
%x Print a hexadecimal value
%u Print an unsigned integer
%p Print an pointer value
% Id , Print a signed Jong integer
•1' lu i Print double
4
L.--
. l,y.·
·
11/;_u,lh b;i, b
t, ' 'J1cs, 11-'ord. /JI
~ f({lJctur,-, , ., '
w~,, •o "•·e/J01n1
. c,
ce'f!, flo:,Jj
111!/JOif!t I

APoftr

Ex: scan{ ("%d:, & )·


' n'
scan{ ("%d%f', &k, &s);

b..Formatted Output function .


pr,ntf ( ): It is a fonnatted · ti _• . . . . .
· . output unction. It 1s used to prmt vanable content or stnngs. This
funct10n can take a b
ny num er of arguments. The print{ () function consists of 2 component,
control string and argument 11st.
·
The control string, which decides the format of the output. Th',g·
string will have 2 distinct classes of characters
► plains characters such as pure text , which is enclosed by pair of double quotes , and escape
sequences characters like new line, tab etc.,
► Convers1on
· or fonnat specifiers with the '%'symbol.All scan£ 0 ,unctwn
i'; •
°
fi nnat specifiers
are also valid.
► . If the control string
If the control string contains a_· plain text, no need of argument 11st.
contains format specifiers, need of argument list.
► The number of format specifiers is equal to number of arguments.

fSyntax: print{ ("Control String", argument-list);


· · h 3 components.
where contra1string as
1. a series of characters.
2_ Format specifiers.
3. Escape sequence.
And the argument list consists of a list of variable whose values to be printed.
E.g. printf ("Well Come to Computer Lab");
printf ("%d %d", m, n);
printf ("Sum of the series= %f', sum);

Field width specification in print(:


,.,.;
Field width can be used inside a printf() function. This specifies the width of the space al)otied :
for a variable on the screen. ·
e.g.
Ex: I
int a=27635;
printf("%5d",a); .
here 5 columns will be allocated and the integer a is printed on the screen.

/2/7/6/3/5/
Ex:2
int a=27635:
printf("%8d" . a);

5
Tokens
2. .-- -
...
-
I. The character set.
-
3. 'Yc!riable.s.
4. ~ ta types. I
The c~ -~!.!.t ~ -
. e The character in C is
Character set is set of valid charactei: that a lang~age can recog!).tZ ·
- - - - ---
grouped into....__
4 categories .
► !:ett~rs: upper case alphabets [A, B ...... Z], lower case alphabets [a, b... •· .z]
► Digits: 0, I, 2 ..... 9. ~
---------
► ~p~cial character.: #, <,>, [ ], .....,, +, -, *.

► W...!! ite ~p~ ces:._blank spaces i.e. \n, \t.

Tokens: ---.,p _. ,.
The smallest individual unit in a program is known as a token. C has 5 tokens.

I. Key word. 2. Identifiers. 3. C~nstants._ 4. Punctuators. 5. Operators.

!Sey words: Key words are words which have been assigned specific meanings in the context
of C- language program. These are also called as reserve words. All 'C' keywords. must be
written i~ ower cas_~~~!12hai:e!s. The C-language contains 32 keywords. They are:
" .

Auto Double int struct

Break Else
-
long static
i- ·

2
Variables: A variable is ..~ .}dep tifier that denote~ a storage location used to store a data value.

. . - . ~._. . ._ ·<____ . ---..·-----~--------


A variable may take different values at different times during the execution of the program.

Or

It is a program .ele~ ent, while execution of the e rogram, the value changes. Each variable in
~ reality represents the name of a memory location in which to values can be stored. Ex:?name,

..
sum, total.
_
Rules:

l. Variable name must not begin wi~h i} digit.


2. Variable names can be of any length.
3. It shou~ _not be a keyword
.. --·
4. ~ e r case and lo wer case are different.
5. White space is not allowed.
~ Syntax: dat:rt~e variable-list;

Where, datatype is a any valid C-language data type.

Variable-list is a user defined identifier name. The list consists fil mlre than one variables
separated by commas. -· . - ---==:::::::::::::::=
->- ~----~-.~ ~:,,--

E.g. int x;

float a, b;

long Val= 25L;

Initialization of variable: The process of assig_ning_ values to variables using assignment


operator (=) is called initialization of var(ables.:: · 1

Syntax: variable-name= value/ expression;

E.g. a= 10;
--P · . that can be used to carr y \)\_~
C proararnming . f string-handling ' \\ ""-\ , : - ~
" . . \:1rge nu1nbe1 o A ,.f ~
. orts ,1 ' -~/,, ✓ •
: . c -LibrarY :;upP r'""'<l ·//2,
. ~• open1trnns. · ) ,.,,
Stnn,,.. . . . , such ns. . · 1 a string ·
,~f lht' :-iring rnnn1pu\at10ns. . of d1aracte1s ll ' .. · ) ---- -
. Length [ ,nun bet . f the two stnngs .
i. - . [ Adding o
.. Concatennt1on
11 ·
.. Comparing two s1rin s
11
i:, • •
· string) .
fr 11 the main
i11. . . . [Extractin g substnng 01
iY. Substnng . , ' ~- another].
v. .· ¢9RY [Copies one st11ng to ' .

. tions· 11 terminated strings.


String ma~ipulatton func _ . . I re used to manipulate the nu . der file in the program.
These are the built in funct10ns w!11c 1 _a C ·ou must include string.It ltbrary hea . tring The length does
No te: To use all tlte string Ju11ct1011s m y . the number of characters m a s .
l. strlen Ofunction: This function counts and returns
not include the NULL character.
Syntax: n== strlen (string); . . fr m the strlen function
Where n is integer vaiiables which receive the va1ue o
E.g. n = strlen ("TUMKUR"); ➔6
• · t· tring.
2. strcpy Ofunction: This function is used to make the duplicate copy of exiS mg s
Syntax: strcpy {str2, strl);
It copies the content of strl to str2.
E.g. strcpy(str2, "TUMKUR") ; . . .
Note: c language does not allow you to assign the string to another string directly by assignment operator.
Strl = "Tumkur" ; This is invalid statement.

3.strcat O function : This function used to combine two strings into single string. In other words
add the content of second string to the end of the first string. It is also called as merge two strings.
Syntax: strcat(strl ,str2);
Str2 is appended to srrl and str2 unchanged.
E.g. strcpy (strl, "Tumkur");
strcpy(str2, "Kamataka");
strcat (strl, str2); The resultant of str 1 is "Tumkur Kamataka"
5. strcmp Ofunction : This function is used to compare two strings with case sensitive, which returns an
integer. If the integer value is equal to zero, indicate both the strings are equal. If value is +ve , first string is
greater than second string. If value is -ve, first string is smaller then second string.
Syntax: strcmp(strl, str2);
E.g. strcmp("Tumkur", "Tumkur"); will return Ovalue.
strcmp("tumkur", "Tumkur"); will return +ve value.
strcmp("Tumkur", "tumkur"); will return -ve value.
6. strcmpi Ofunction: This function is same as strcmp, which compares two strings but not case sensitive,
which returns an integer. If the integer value is equal to zero, indicate b'Jth the strings are equal. If value is
+ve , first string is greater than second string. If value is -ve, first string : ; smaller then second string.

Dept of BCA Page 2


..5 ra1n zn i ng VVFGC, :;Tu1nku r .

l _~
,11tax: strcn1pi(strl, str?); I •• • ;

i.
'
~
.
-E • l:;).
a strcmpi ("Tun1.la.1r" , "tumkur"); will return O value :! I .•. • •,

7,, strlwr Ofunction : This' function converts all alphabets in a string from uppercase to 1~wet'
i> :r..;}·9. a~e.
: .. · ..
. ,';
Syntax: strlwr(str); ·: ;;?1::~ . i\:- ,~ "j • •

; -~ :•,. • I • •

strlwr ("TUMKUR"); output is : "tumkur" ·1 ·. .

8. strupr Ofunction: This function converts all alphabets in a string from lower case .t(?,upp:e r-case:.i _-
Syntax: strupr(str); ' : ' .
} ·' '. ·
E.g. strupr ("tumkur"); output is : "TUMKUR" - :L · Ft• ~ ;_, . : ·'! ·- :

9. strrev Ofunction: This function reverser the characters in a string. · :· := ·. /:•·:


Syntax: strrev(str); , •:, : ;?. ;: .
E.g. sttTeV ("TUMKUR"); output is : "RUKMUT"
l
·,

_: 2 '
O-no.-~tions on characters [ctype.hl:
i ;

You might also like