Computer Program
Computer Program
Line 4 & 7: The start and end of the program is indicated by open braces ( {) and closing brace
(}).
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.
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 Double
These data types are used to modify the existing basic data types.
Short: it is used to reduce the size of an existing data type. To occupy fixed me!ftory
space the short keyword is used.
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
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.
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
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~+ · .
If a= 5, then a/ 2 results in 2.
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.
Similarly 7.6 ~ 2.9 results into 1.8 and -5 % -2 results into -1.
Operator + can also used to add two strings i.e, it concatenat~s two strings .
.-__;.;;;;--->
For e.g., 5 + 6 results into 11.
---·
.
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
10
!(5 > 12) results into true because the expression 5 > 12 is false .
statement.
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.=, <<=, >>=, >>>=
..
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 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
-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.
~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.
,.
Chapter-4
ARRAYS
Single dimensional array or scalar array: It is a list of data items represent by only one index
(Sub Script).
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
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:
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.
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.
. • -· - , '" ... I
b
STRC Cr LRLS
'' .-... .
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
t·
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.
'
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
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:
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.
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
/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.: #, <,>, [ ], .....,, +, -, *.
Tokens: ---.,p _. ,.
The smallest individual unit in a program is known as a token. C has 5 tokens.
!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:
" .
Break Else
-
long static
i- ·
2
Variables: A variable is ..~ .}dep tifier that denote~ a storage location used to store a data value.
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:
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;
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 ' .
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.
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 • •
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• ~ ;_, . : ·'! ·- :
_: 2 '
O-no.-~tions on characters [ctype.hl:
i ;