0% found this document useful (0 votes)
520 views14 pages

Cs Unit1

An array is a collection of homogeneous elements, allowing for the storage of similar quantities such as integers or floats. In C, arrays are declared by specifying the data type and size, and they occupy contiguous memory locations. The document also discusses advantages and disadvantages of arrays, memory layouts for multi-dimensional arrays, and the concept of array bounds checking in C.

Uploaded by

raksharawat2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
520 views14 pages

Cs Unit1

An array is a collection of homogeneous elements, allowing for the storage of similar quantities such as integers or floats. In C, arrays are declared by specifying the data type and size, and they occupy contiguous memory locations. The document also discusses advantages and disadvantages of arrays, memory layouts for multi-dimensional arrays, and the concept of array bounds checking in C.

Uploaded by

raksharawat2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

UNIT 0- ARRAY

Dennllion of Array:
An array is a colleclion of homogeneous elements or n array is a coll«ti\•e name gi\'en 10 a group of
'similar quan1i1ics'. These similar quanlilics could be percentage marks of 100 students. or salaries of 300
employees. or ages of 50 rmployC'CS.. What is important is that the quantities must be 'similar'. Each
member in the group is rcfcmd to by its position in the group.
Similar elemen1s of array could be all ints. or all float.« all chars clC. Usually. the amy of chancters is
culled a 'string', whereas an ■my of ints or floats is calkd simply an array.
Where an Ordinary variables arc cap:1blc of holding only one value 111 time.
All umys consist of contiguous memory k>ca1ions. The lowesl addn:ss COfTCSfJOnd$ 10 the first ck.mcnt
and the higtk.-st addrn.1 10 the lasl ckmmt.
f1rst0...... U'II~

L L
I......." I~·· I.._..."' I...__. ,I
DcclanuKK'I of ID Arr.ay:
01 1 1

To d1.·darc on amay in C, a prognunmcr sp«if,cs the type of the clcmmts and the: number of clcmmts
n.-quirtd by an lllTD)' as follows:
dutatypc amyNumc ( IUTllySizc J;

Thii is called o singlc~imcnsionul amy. The arnySI« must be an in1cger cons1ant grc:uer than 1.ero
and 1ype cnn be any valid C duua type. Forexamp k:.10 di.-chn·t I l~li.,ncnt llnDY calll-d marks of type
int, use lhhJ ~1111cmcn1:
int mark,{ 10):
IEmlllll.:m!!lllil:i:illlllli:ll~llillli:llllllili:il:
lfnn in1c11cr takcs4 bytes (32 bil5} then size occupied by lft■rks ■rr.1y v.ill be 40 bylcs.
lalll■lb.allo■ or ID ■rny
• Complk thm lalll■llntio■
Fully initializatK>n:
int num[5J • 12.8.7.6.01;
This is also com:ct:
int num[I • 12.8.7.6.0);
int num[S) • (O~: // all ek:ments of
array will initialize with ttro
we can initialize an arTaY Partially:
inl num(S] • t2,8t; II remaining elements will be initialized with zero

• Ru ■ tlmt l■ltlaliutJoa
Using Kan function. we can stOfC ekmcnts of array at run time.
Ded■rado■ oflD Arny:
int abc(Sl(4J; C•""' I ~ t C..,,,... 2 COMM J
0(1111 ... . tJ O(IIZI .. ,. ,1
lnhlalb.allo■ oflD ■my:
... 111 0( t I tI a(t I ZI alt IJ J
int arr(31(4) • 111211 ) 0(2l t I •12 1 21 0(2ff l l
10.1.2.3.4..1.6.7.8,9.10.11 !;//Storage take
plac..-e in sequential order

int an12Jl4) • I
110. 11. 12. 131.
114. 15. 16. 171 I 0
I: 2 2
0 0
in11fl131(3J2 I I l,I ). 12.2.2).131);

int abc)2)12) • 11. 2, 3 .4 I /' Valid ' /


int abc[ 1(2 ) • (I. 2, 3 .4} r Valid, fir.a dimension can be empty•/
int abc[ ]l J • {I. 2. 3 ,4 I 1• Invalid declaration-you must specify second dimension• /
int abc(2)( ] • 11, 2, 3 ,4 J ) r
Invalid d...-claration - you m~ specify second dimension• /

Whll ore Advant1gn ind Diudvant1ges or 1rnys?


Adva■tace:
I. It iJ used to rq,ttSCnl multiple data items of same type by PJ.\ing only sin&lc name.
2. It can be used to impkmmt other data structures like linked lists. 5laeks.. queuc5., trees. gr.aphs e1c.
3. 20 amys arc used to rcprc-scnt mauiccs..
Diu dnnt•aa:
I. We must know in advance th.ill how many clanenu are lo be Slort'd in amiy.
2. Am.t.y 15 st:uic struc1urc. l1means that iuny is of fixed size. The memory which is alloca1ed 10 array
cannot be increased or reduced.
3. Since army is of fixed size. ifv.·c alloclle more memory than rtquircmcnl then the memory space will
be v.ucd. And ifwe allocate less memory than requirement. Ihm it will Crt';tte r,-oblem.
4. The ck-ntcnlJ of amay are stored in conseculi\·c memory locations. So inso,ions and deletions arc \'Cf)'
difficull and lime co,uumina.

Passi•& array 10 runtllon


Ju~t like variubk~. arrny can also be pa.~~-d to a functK>n as an alltumcnl. W~-n v.e pa..u the addres..~ o fan
array while calling a function !hen 1his is c:&lll-d function tall by reference

P■nlno ID arnv lo functloa Putin• 2D arnv to f•ttnio•


void mooify(int u[3)); 1,·oid prini(int m. inl n. inl anf)l(3)):
int muin() int main(}
I I
intorr(3) • 11.2.31; in11fl131)3J • ll l.2.31.14.5.61. 17.8.911;
modlfy(arr)~/ paullt1 add,..., or omoy intm • J, n • J:
for(i=O:l<J;i>-+) prial(m. a. arr): // paAa addrn1 of array
printl\-,'.d".arrfi)): n..--cumO:
)!<1th(); I
rctumO;
I ,·OM! print(int m. in1 n. int antJJIJJ)
(
void modily{int o(31) int i.j:
I for(i • O: i < m: i++l
inl i: for (j • O;j < n;j++)
for(i=O;i<J;i-t+) priDII\..,~ •. an1i]lil~
a(i) • a[iJ'o(i); I
I
Row-major ,,s. column-major
Hy far the two mosl common memory layouts for muhi-<limcnsional amy data arc row-
majr,r and ,:ol11mn-majt1r.
When working wi1h 20 arrays (ma1riccs), row-major vs. column-major arc easy 10 describe. The row-
major layout or a matrix puts the first row in coniiguous memory, then lhc second rm\' right ancr ii. then
the third. and so on. Colum...,.major layout puls the: first column in contiguous memory. then the second.
etc

Row-major order

[:Z:]
Column-major order

[t11]
Row-major order is used in CJC++/Objccth·c--C (for C-scylc an"Oys). Pl/I.rascal. Spcakcasy[ci1a1ion
needed). SAS, and Rasdaman.

Colum n-major order is used in Fonran. MATLAB. GNU Ocla\'C. S-Plus. R. Julia, and Scilab.

Fonnula or finding 1hc location (address) orpanicular element in 2D array using example

--
LOC (A fJ . .q) • 8--(A) • w(M(t(-t) • (J.t)I

LOC(A(J, KJ)

Bae (A) •lhllbae~olh~A

•lhllni..n-o.olbytn~lo--.,gt,e...._,.ollhll~A

M ---~nurrbefol~ ... - - ~
eslhero."ru-nbeirolete~

••
.. _ ·- -
A)ll."'"9"¥J7fA•abelo,,,"

~
( It) 1000

(2 t) 1002

(3 I) 100<

( 1 2) 1006

12.:n 1009
S - - _ _ _ .._ _ _ olA l3 , l1 n.,__,,...._
9-CAI
(1. 3)

(2,3 )

,.,_"""' __. . _g,..en~-~


&.OC CA 13, 21) • 1000•2131"2- 1) • P,.1 11
• 1000 • 2P 01 • 21

EJ (3... )

• 1000•2 151
• 1000• 2P •21

2. In case of RON Mo..- Order:

Tht formula is;


LOC (A (J . Kl) • 8-(A) + w(N (.J.1) + (K-1)1

LOC (A IJ. K)) is the loealion of h ....,_,,. WI .... Jth ro,,,, and Klh cdumn.

8-(A) islwbaN~ofh~A

a1ho.....-ol-r9qUAC110-.K,g1e- ol 1ho-A
N IS h ll>tal ~ o f ~ k-1 .... ~ .

tS the ro,,,, ....,...,_de. e6ement.

K is the coksm ~ of h ...,,,..,._

E.g.

A Jx •inlegar"an7tAia;abalow'

10

60
~

(1 . 1)

(1 .2 )
--
1000

1002

30 (1 .3) 1004

56 (1 .4) 1006
s

20 (2. 1) 1008

51,ppc,N - "'-9 lo find the location oA A (3. 2). The reqund .,.... - :
90 (2.2) 1010
Base (A) 1000

80 (2.3) 1012 w :> ci-:a- ;>'I inleger ta11N 2 i,y..;,. ......ary>


N 4
(2.4) 1014
65
J 3
(3. 1) 1016
50 K 2

(3.2) 1018 Now pul . _ . , . . . . in the giY8'I formula as below:


40
LOC (A (3. 2)) = 1000 + 2 (4 (3-1) + (2-1)1
(3,3) 1020
75 • 1000 + 2 (4 (2) + 1J

(3.41 1022 = 1000 + 2 (8 + 1)


79
= 1000 + 2 (9)

= 1000 + 18

= 1018

Array Bounds Checking in C


Mosl lunguagcs (Java, C#, Python, Javascrip1) preven1 the progrnmmer from going past the end of an
array. This process. performed al runtime by the language implementation, is frequently called Bounds
Checking.

What ifprogrammer accidentally occnsn ony inda of"""Y which is out ,ifbound?

Unrortunately in C there is no way for the prognmmer to determine the size of an arny at runtime
and so it becomes necessary for the programmer to keep track of the length of the array.

Array Bounds checking in not available in C language. C don't provide any specification which deal with
problem of accessing invalid index.

As per ISO C standard it is called Undefined Behavior.


An undefined behavior (UB) is a result of executing computer code whose behavior is not prescribed by
the language specification to which the code can adhere 10 , for the current state of the program (e.g.
memory). This generally happens when the translator of the source code makes certain assumptions, but
these assumptions are not satisfied during execution.

Examples of Undefined Behavior while accessing array out of bounds


I. Access non allocated locatlon or memory: The progr.im can access some piece of memory
which is owned by it.
// Program to demonsu-ate // accessing array out of bounds
#include <stdio. h>
int main()
TCS201: Programming and Problan Solving
UNIT-l(STRINGSJ

fil!:!Y!;
o String is an array of chllJ'llcler...
• II is 1crmina1cd by null characler '10' -
• h is usually s1orcd as one-dirncnsiooal character array.
• •10• characler is slorcd 10 signify lhe end of lhe chancier array. after lasl
charac1er.

For ex: red · idc he


"HELLO" is a siring wilh 6 characler.. including the null chancier sto ms I

compuler memory.

The above siring can be rcprcscnlcd in memory as:

Declaration oraString:
S1rings are declared in C using lhe char dalo lypc.
For ex:
c.bar .-(5):
//characters including 1he NULL charocler dcnoccd //as '10'
• The above declaration can be represented as:

namc[OI namc[l l namc[2 ) namc(JJ namc{4)

10

1+ Garbage valuces +1

lnUl•llzalil)D or. Strlg:


For ex:
char name[)z ('H','E','L ','L', ·o·. i 0' ):
char s[)="HELLO":

The above declaration can be rcpr=nlcd as:

name[0J name[!) namc[2) namc[JJ namc[4) namc(4)

'H' 'E' 'L' 'L' ·o· ·10·

Qt. Can w, dtdare slu of string grrater than no. ol •kmaits that art
Wlltlalized?

Ans. YES.
Char strf 10)=,raLO":

str[0) str[I I str[2) str)J) str{4j str(S) str(6J str[7] str(8] str(9)

'H' 'E' 'L' •L' ·o· ·10· ·10· ·10· ·10· ·10·

Example: Program lo demons1r111, inlliall2,u ion of I s iring.

#includc<S1d10.h>
rnt main()
I
chur namc[5J l ' L','J','O','N' ), or char ,(SJ ·"I.ION".

pn111f("Char-.ictcr tn lhc WTU) at Fil'\t position "lie n·. name)OIJ;


pnn1f("Charac1er m the llml) 01 Sc.:ond po'111on "lie n • name( I )J;
pnn1f("Charoc1er m the array al Tiurd post110n "lie In", namc)21J:
pnntf("Chnractcr m the llml) at Founh po,111O0 "lie •. rwne)3));
return 0;
I

Oulpul:
Character 1n the WTU) at F1r.1 pos111on L
Charnctcr 111 the urray Ill Second po-.11100: I
Char11<-icr in the urruy at Third po,11100: O
Chaructcr on the nmay 01 I ounh position N

Retdlng & Printing of Slrlnp:

The strings can be accep1cd from lhe ustr using thc following fomuoncd functions:

I. Using Scanf() and prinlf():


scanf() : to accept the string from the user
printf() : to print a stting to the screen

Example: Program to illustrate the use or scam0 and printf().


#include<stdio.h>
1nt main()
(
char str( 15(:
prin1fl l!ntcr a string: \n""):
00

scan[(·.. os·.s1r):
00
printfl••You typed the s1ring:•os str): •

return 0 :
I
Output I :
Enter a stnng: HELLO
Yo u typed the string: HELLO

Output 2:
Enter a string: HELLO WORLD
Yo u typed the string: HELLO

Problem with scant in ttadlng a string and Its solution:


Output 2 shows the drawback of using scanf(). scanf can read a string from the
input s tream until the fi rst occurrence of s pace. Hence. 10 enable scanf to read a
string until a newline character ic \n', the following modification can be done to
0

the scanf:

Aller modifying the scanl statement:


#incl udc<stdio.h>
int main()
I
c har sir) 15]:
pnntfl""Type a s tring: \n");
00
scan[(·...[ A\n ]s &str):

printf("·Yo u typed the s tring:•.s··. s tr):


ret urn 0:
I

Output:
Type a string: Graphic Era llill University

You typed the , tnng: Graphic Eru 11111 University

2. unrormatted Input/output String ruoctions: gets, puts

gets()••· to read a string from the user until the user enters a newline Character ie
·\n' (presses Enter key)
puts()--- 10 display a string to the screen

Example: Program 10 illustrate the use of gets() and puts().

#includc<, tdio.h>
int main()
(
char sirj 15 ]:
pnn1f(··Type a string: \n""):
gc1,(,1r): same as scan fl'.. o' (\n ]s', sir):
prmtfl'i nYou typed:"'):
pu1,(,1r): some as pnntfl',..s··. sir).
return 0:
I
Output:
Type a siring : Programming in C
Yo u typed: Prograrnrnlng In C

3. Input/output String functions: getcbar(), putcbar<)

getchar()•·· repeatedly string is read by getchar() to read sequence of single


characters unless tenninating character is entered.
putchar()··· to display a characters on the screen.

Example: Program lo illustrate the use o f gelchar() and putchar().


#includc<stdio.h>
int muin()
(
int i Oj.k=O:
char suf20):
char ch getch:uO:
-.h11c(ch 1 '• ')
(
s1rj1)=eh:
1++:
ch=gc1char():
I
, 1rj1J W':
pnn1f(''1 lic entered string"· n" ):
wh1lc(s1r)k)!=i O')
I
pu1char(s1r{ k I):
k++:
I
return 0:
I

STRING MANIPULATION FUNCTIONS


• Whenever strings needs 10 be manipulated in a program manually ii adds the
extra lines of program code and also makes ii a very lengthy and difficult 10
understand.
• To avoid this C suppons a large number of siring handling functions. There are
many functions defined in <slring.h> header file .

SI.No. Function Name & its meaning

I strlen(s I): ➔ Rerums the length of the sung s l

2 strcpy(s I .s2) ➔ Copies lhe siring s2 into s I

3 slrncpy(s J ,s2.n) ➔ Copies first n characters of siring s2 into s I

4 s1rca1(s J,s2) ➔ Concatenates/Joins the siring s2 10 the end of s I

5 stmca1(s I ,s2.n) ➔ Concatenates/Joins first n characters of

string s2 to the end of s I

6 strcmp(s I ,s2) ➔ compares siring s I with s2: if s I is equal 10 s2 lhe


return a value zero: if s l<s2 ii returns a value less than zero: otherwise
if sl>s2 it returns a value greater than zero.

7 strncrnp(s l ,s2,n) ➔ compares first n characters of siring s l with s2: ifsl


is equal 10 s2 the return a value zero: ifsl <s2 it returns a value less than

zero: otherwise if sl>s2 lhe it returns a value greater than zero.

8 strcmpi(s l ,s2) ➔ compares siring sl with s2 by ignoring the case


(uppercase or lowercase): if s l is equal 10 s2 the return a value zero: if
s I <s2 ii returns a value less than zero: otherwise if s I >s2 the ii returns a
value greater than zero.

9 strcMs I ,ch) ➔ Returns a pointer to the first occurrence of c haracter ch


in sl

10 strslr(s l ,s2)➔ Returns a pointer to the first occurrence of the siring s2 in


st

II strrev(s I )➔ Returns the reverse siring after reversing the characters of


lhe siring s t

12 s111ok(s I.delimiter): // splits sit into tokens separated by the delimiters.


It needs a loop 10 get all the tokens and ii return NULL when there are
no more tokens.

char •strtok(char str{ ), cons1char •delims):

.l1tlm!lll
• The function calculates & returns the length of a siring sit passed 10 ii as an
argument excluding the null.

Example: Program 10 illustrule the use of strlen().

#includc<s1ring.h>
#includc <sldio.h>
int main()
I
char s1rj 20):
1111 lcn:
pnnlf("Typc a stnng:"J:
scanf("9f. {A.nls ".s1r):
lcn >trlcn(str):
pn ntf("\nLcngth of the string "bs " 'lf.d ·. str.lcn):
return 0:
I
Ou1pu1:
Type a siring: HELLO
Length of the string HELLO is S

strcpyrst,sll
• This funclion copies the conlent of string s2 inlo another string s2.
Pu1ting text into a siring:
sucpy(S, "This is String I.");

Copying a whole string from S to 0 :


slrcpy(O, S);

Copying I.he !ail end of string S to 0:


sucpy(O, &S(S));

where O is destination and S is source.

• Example: Program lo illustrate the use of strcpy().

#include<slring.h>
#include<Ji1dio .h>
int main()
I
char s I (20),,2(20):
prin1f("En1er A siring: ");
scanf("%(A\n )s" .s2):
strcpy(s l.s2); ,Conten1of siring s2 is copied in10 siring s l
prin1f("Co pied siring :");
prin1f("%s",s I);
rclum 0:
I
Ou1pu1:
Enter string: PROGRAMMJNG JN C
Copied string: PROGRAMMING JN C

stmcpy{s I $2.p}

• This funclion copies first n characters ofs2 into another string s l .


where n is an integer

Assume thal the following s1a1emen1 has been execu1ed before each of I.he
remaining code fragmen1s.

Pulling texl inlo I.he source string:


sucpy(S, "This is String I.");

Copying four characters from the beginning of S to O and placing a null at the
end:
strncpy(D, S, 4 );
0 (4] = \ 0';

Copying two characters from the middle of string S 10 0 :


strncpy(D. &S[5). 2):
0(2) = \O':

Copying I.he tail end of string S 10 0 ;


stmcpy(O, &S(S], 15);
which produces lhe same resuh as strcpy(O. &S(S));

• Example: Program to illustrate I.he use of strncpy().

#include<slring.h>
#include<s1dio.h>
int main()
I
char s I (20J.s2120):
inl n:
prin1f("En1er a "nng: ");
,canf(".,, (A\n )s".,2);
printl{", nl low many characters 10 be copied:");
scanf{"o/od",& n):
Mmc py(s l.s2.n); 1/Con1en1 of slnng s2 is copied mlo s1nng s l
pnntf("Copied , iring: ,s· .s I J;
rc1urn0;
I
Output:
En1er a string; PROGRAMMING IN C
I low nuny c harac1ers 10 be copied: 7
Copied string; PROGRAM
strcatfsl.s2l

Joins two strings by copying the string s2 to the end of s 1. strcat() is used 10
concatenate a null-tenninated string to end of another string variable.

Example: Program to illustrate the use of ;.treat().

#include <stdio.h>
#include <string.h>
int main()
I
char s l I I0J. s2[ I0 J:
primf("Emer the First S tring:"):
get, (, I ):
printf("\n Enter the Second String:"):
gels(s2):
s1~ca1(~I .s2): //concatenates string s I and s2 stores the fi nal string in , 1
pnmf( \nConcatenatcd String: "):
puts(s 1): // final co ncmcnated string is stored in s 1
return 0 :
l
Output:
Enter the First String: Graphic
Enter the Second String: Era
Concate nated String: GraphicEra

stmcat(s1.s2.n)

Joins first n characters of s2 joins with string s I and stores it into s J.


Example: Program to illustrate the use of strcat().

#include <stdio.h>
#include <string.h>
int main()

I
c har s l I 10(. s2110 (:
inl n:
printf(" Enter the First String:"):
gets(s l ):
printf("\n Enter the Second S tring:"):
gcts(,2):
printf(''\nHo w ma ny characters needs to be appended:..):
scanf('"o/od" .&n):

strnc at(s l .s2.n): //concate nates n characters of string 2 10 string ; 1


and
//stores the final string in s l
printf("\nConcatenated String: "):
puts(s 1): // final concatenated string is stored in s J
return 0:
l
Output:
Ente r the First String: Tic
Ente r the Second String: Tac
Ho w many characters needs to be appended: 2
Concatenated String: TicTa

strcmp(sl,s2)

• This function compares two strings s l with s2 and


returns 0 if both the strings are equal i.e s I = s2.
returns a value< 0 if s I <s2
returns a value > 0 ifs l>s2

strcmp() is used to compare two strings. The strings are compared character by
character starting at the characters pointed at by the two pointers. If the strings are
identical, the integer value zero (0) is returned. As soon as a difference is found, the
comparison is halted and if the ASCH value at the point of difference in the first
string is less than that in the second (e.g. 'a' Ox61 vs. 'e' 0x65) a negative value is
returned; otherwise, a positive value is returned. Examine the following examples.

chars 1[25 I = "pat";


char s2[25] = "pct":
diff will have a negative value after the following statement is executed.
diff = strcmp(s 1. s2);

diff will have a positive value after the following statement is executed.
diff = strcmp(s2. s 1);

diff will have a value of zero (0) after the execution of the following statement,
which compares sl with itself.

diff = strcmp(s 1, s 1);

Exampl~ 1: Program usl.ng strcmp() function.


#include <string.h>
#include<stdio.h>
int main()
I
char s 11301.•21301:
prin1f("E111er the first siring: "):
geis(s I);
pri111f("E111er 1he second string: ");
gets(s2):
mt diff strcmp(s l.s2);
pnn1tt•,.od".dill);
return 0 .
I
Output 1:
Ente r the first .iring: Proi:ram
Ente r the second siring: program
0

Output 2:
Ente r the first string: Pal
Ente r the second string: Pet
•I

Exampl~2: Program using strcmp() runctlon.


#include <string.h>
#include<stdio.h>
int main()
I
char. 11301.s21301:

pn ntf("Enter the fi rst string: "");


gel\(> I );
printf("Enter the second string: "):
get.-,(s2):
if(,trc mp(s I .s2)=0)
pnntf("Both , iring, are equal"):
el...
if(m c mp(s 1.,2)>0)
printft"First string i; greater than second string"):
else
printft"First stnng is less thon second string"):
return 0:

I
Output:
Ente r the first string: program
Ente r the second string: Program
First string is greater than serond string

Ente r 1he fi rst string: RAINBOW


Ente r the second string: rainbow
First string is less than second string

strncmp(sl.s2.nl
• This function compares n characters of two strings s I with s2 and
returns O if both the strings are equal i.e s 1=s2 or
rerurns a value < 0 ifs 1<s2 or
returns a value > 0 ifs 1>s2

Examine the following examples.


char sl [25] = "pat";
char s2[25] = "pet";
diff will have a negative value after the following statement is executed.
diff = strncmp(sl, s2. 2);
diff will have a positive value after the following statement is executed.
diff = strncmp(s2, s 1, 3);
diff will have a value of zero (0) after the following statement.
diff = strncmp(s 1, s2, 1);

Example: Program using strncmp() function.


#include <string.h>
#includc<s1dio.h>
inl main()
I
char s l (30(.s2( 30J:
inl n:
prin1f("En1er 1he firs1 siring: "):
gc1,(s l ):
prin1f("En1cr 1he second siring: "):
ge1s(s2):
prinlf('i nHow many characlers to be compared:"):
scanf('"o/od'',&n):

if(stmcmp(s I .s2.n)==O)
printf(" Both strings are equal"):
else
printf("Strings are unequal"):
return 0:
)

Ou1put:
En1er 1he firs1 string: progRam
Enler the second string: program
How many characters 10 be compared: 4
Both s trings are equal

strempilsl,s2l

• This function compares iwo strings s I with s2 by ignoring the cases (uppercase or
lowercase) and
returns 0 if both the strings are equal i.e s I =s2.
returns a value < 0 ifs l<s2
returns a value > 0 ifs I>s2

Example: Program using slrcmpi() function.


#include <string.h>
#include<sidio.h>
inl main()
I
char , I (30(.s2(30):
prinlf("Enter 1he firs1 string: "):

ge1s(s l ):
printf("En1cr 1he second siring: "):
gets(s2):
if(sircmpi(s I .s2)==0)
printf("Both strings are equal"):
e lse
prin1f("S1rings are unequal"):
rciurn0:
)

Ou1put:
En1cr the firs1 string: program 14/22 ••
••
En1cr the second string: PROGRAM
Both s trings are equal
••
strlwr{strl;

This func1ion is used 10 conven uppercase leuers in10 lower case.


#include<.idio.h>
#include<string.h>
inl main()
I
char s1r{)=" Hel lo":
s1rlwr(s1r):
prin1f(·1he string is: ~os". sir):
rc1urn 0:
)

OUTPUT: 1he siring is: hello

stropr{strl:

This funclion is used 10 conven lowercase leuers into uppercase.

#include<sldio.h>
#include<string.h>
in1 main()
I
char str{)=" Hel lo":
strupr(str):
prinlf('1he string is: o/os". str):
return 0:
I
OUTPUT : the string is: HELLO

functio n is used to reverse the string.

#include<stdio.h>
#includc<string.h>
int main()
I
char strj )=" HELLO":
,trrev(str):
printf{'1hc string after reverse is: 0 os··. str):
return 0:
I
OUTPUT : the string is: OLLEH

Programs on strings without using inbuilt functions:

I. Program to copy one string into another without using the inbuilt function.

#include<stdio.h>
int main()
I
char s l [100], s2[100];
inti;
printf("Type a string:");
gets(sl);
i=0;
while (s l(i] != iO')
I
s2(i] = sl[i];
i++;
I
s2[i] = '\0';
printf("Copied String is: %s ". s2);
return 0;

Output:

Type a string : Blueberry


Copied String is: Blueberry

2. Program to compare 2 strings without using strcmp().


#include<stdio.h>
int main()
I
char s I [25],s2[25 ];
int i=O,fl ag=0 ;
printf("Enter the first string: ");
gets(s l );
printf("Enter the second string: ");
gets(s2);
while(s I [iJ !='\0' && s2[i] !='\0')
I
if(s I [i]!=s2[i]) 16/22
I nag= ! :
break;

i++:
I
if (flag==O)
printf("Bo th the strings arc equal"):
e lse
printf("Both the strings arc not equal"):
return 0:
I
Output:
Enter first string: Graphic
Ente r second string: Graphic
Both the strings are equal

3. Example: Program 10 concatenate two strings without using inbuilt function.


#include<stdio.h>
int main()
I
char s l(25 ].s2[25]:
int i=Oj =O:
printf(" Enter the First String:");
ge1s(s1r I):
printf("\n En1er the Second Siring:"):
ge1s(str2):

while(sl Li)!='\O')
i++:
s l [i++]= ' ';
while(s21J)!=\ 0')
(
s I (i )- ,2UJ:
j ++:
i++;
I
s l lil=\O':
prinrf('\n Concalenated String is %s",s l ):
re1um 0;
}
Ou1pu1:
En1er the Firsl Siring: Merry
En1er the Second String: goround
Conca1ena1ed String is Merry goround

POINTERS AND STRINGS:


Program 1:

#include<sldio.h>
inl main()
(
char str()="HELLO";
charstrl(I0]:
//str=strl; //error
char •p=str:
char •q:
q=p;
while(•q!=\0')
(
printf("%p\1%c\n",(void *)q,*q);
q++;

I
OUTPUT:
0x7ffe4c I 2674e H
0x7ffe4cl2674f E
0x7ffe4cl26750 L
0x7ffe4cl26751 L
0x7ffc4c126752 0

// Demo Code copy text using pointers

#include<stdio.h>
inl main()
(
char name I (100) = "GEHU": char name2( 100):
char •ptrl :
char •ptr2 :

ptrl = name I :
ptr2 = name2 :

while (*ptrl != \0')


(
•ptr2 = •ptrl :
ptrl++ :
ptr2++:
I
•ptr2 = '\0'; 18/22
prinlf("COPIED String is ...\n%s". name2);
}

OUTPUT:
COPIED String is...
GEHU

PASSING STRING IO FUNCTIONS USING POINTERS·


Program 1: User Deline Function 10 Copy a String:

#include<sldio.h>
void display(char*);
int main()
(
char str( I0):
gets(str):
display(str); //can be &sir, &str(O)
retumO;
}
void display(char *p)
(
while(*p!='\0')
(
prinlf("%c" .*p);
p++;
}
}

Program 2: User Define Func1ion to Compare 1wo Strings


II Case Sensitive Version
#include <stdio.h>

inl compare(char •.char•) ;

inc main()
(
char o rg[50[ = "Arjun":
char copy[50[

prin1f("En1er lhe second String 10 Compare\n");


scanf("%s", copy):

if (compare(org,copy) = OJ
printf("The two Strings are Equal \n");
else
printf("The Two Strings are Un-equal \n");

return O:

inl compare(char •org, char •copy)


(
inl i =0:

while ( (•org == •copy) && (*org != '\0' && •copy != '\O'))


(
org++ :
copy++;
}

if (*org = '\O' && •copy = '\O')


re1um0:
else
relum-1 :

II Sample Outpul
Enler lhe second String lo Compare
Arjun
The IWO Strings are Equal

En1er lhe second String 10 Compare


arjun
The Two Strings are Unequal

Two Dimensional Array or Characters:


#include <sldio.h>
inc main()
(
char monlhs [ 12)125) =
( "January","February","March". "April" ."'May". "June"."July"."Augus1".
"Sep1ember" ,"Oc1ober"."November". "December"} :

char •dow[) =
("Monday","Tuesday" .''Wednesday", "Thursday"."Friday","Sa1urday", "Su•~···" ' ·

prinlf("Monlhs ofa Year\n" );


for (inc i = 0; i < 12; i++)
20/22
prin1f("%s\n", monlhs(il);
prinlf("Days of lhe Week\n") ;
for (inc i = 0; i < 7; i++)
prinlf("%s\n", dow[il);
return 0;
The C library function char •strtok(char *sir. const char *delim) breaks string sir
into a series of tokens using the delimiter delim.

• Following is the declaration for strtok() function:

char *sb1ok(char •str, coost char *delim)


• Parameters:
sir - The contents of this string are modified and broken into smaller strings
(tokens).

delim - This is the C string containing the delimiters. These may vary from one call
to another.

• Return Value:
This function returns a pointer to the first token found in the string. A null pointer is
returned if there are no tokens left to retrieve.

The following example shows the usage of strtok() function:

#include <string.h>
#include <stdio.h>

int main() (
char str(80) = "Graphic-Era-Hill- University":
consl char s(2) = "· ":
char • token:

/* gel the first token*/


token = s1nok(s1r, s):

/* walk through other tokens */


while( token != NULL) (
prinlf(" %s\n". token):

token = strtok(NULL. s):


I

retum(O);
I
OUTPUT:
Graphic
Era
Hill
University

The C library function int atoi(consl char *sir) convens the string argument sir 10 an
integer (type int).

• aloi() convens a given string into its corresponding integer.


• This function returns that integer 10 the calling function.
• Therefor string should stan with a number.
• This function will stop reading from the string as it gets a non-numerical
c harac ter.

Syntax: Int atol(const char*str);

The following example shows the usage of ato i() function:


#include<stdio.h>
#include<stdlib.h>
int main()
I
char sir[ 10)=" 12345":
char slrl ( JO)=" 12345.57":
char su'l[ JO)=" 12345a678";
int i=atoi(" l 2"):
int a=atoi(slr);
int b=atoi(slr I);
int d=atoi(su'l):
printf("%d\t".i): //12
printf("%d\t".a); //12345
printf("%d\t".b+5); //12350
printf("%d\t".d): //12345

You might also like