Cs Unit1
Cs Unit1
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);
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)
•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 )
EJ (3... )
• 1000•2 151
• 1000• 2P •21
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 .... ~ .
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
= 1000 + 18
= 1018
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.
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.
compuler memory.
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:
10
1+ Garbage valuces +1
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·
#includc<S1d10.h>
rnt main()
I
chur namc[5J l ' L','J','O','N' ), or char ,(SJ ·"I.ION".
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
The strings can be accep1cd from lhe ustr using thc following fomuoncd functions:
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
the scanf:
Output:
Type a string: Graphic Era llill University
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
#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
.l1tlm!lll
• The function calculates & returns the length of a siring sit passed 10 ii as an
argument excluding the null.
#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.");
#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}
Assume thal the following s1a1emen1 has been execu1ed before each of I.he
remaining code fragmen1s.
Copying four characters from the beginning of S to O and placing a null at the
end:
strncpy(D, S, 4 );
0 (4] = \ 0';
#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.
#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)
#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):
strcmp(sl,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.
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.
Output 2:
Ente r the first string: Pal
Ente r the second string: Pet
•I
I
Output:
Ente r the first string: program
Ente r the second string: Program
First string is greater than serond 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
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
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;
stropr{strl:
#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
#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
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:
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
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
#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
#include<stdio.h>
inl main()
(
char name I (100) = "GEHU": char name2( 100):
char •ptrl :
char •ptr2 :
ptrl = name I :
ptr2 = name2 :
OUTPUT:
COPIED String is...
GEHU
#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++;
}
}
inc main()
(
char o rg[50[ = "Arjun":
char copy[50[
if (compare(org,copy) = OJ
printf("The two Strings are Equal \n");
else
printf("The Two Strings are Un-equal \n");
return O:
II Sample Outpul
Enler lhe second String lo Compare
Arjun
The IWO Strings are Equal
char •dow[) =
("Monday","Tuesday" .''Wednesday", "Thursday"."Friday","Sa1urday", "Su•~···" ' ·
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.
#include <string.h>
#include <stdio.h>
int main() (
char str(80) = "Graphic-Era-Hill- University":
consl char s(2) = "· ":
char • token:
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).