0% found this document useful (0 votes)
17 views34 pages

Unit-Iii Part-Ii

The document provides a comprehensive overview of arrays in the C programming language, detailing their definition, declaration, initialization, and properties. It explains the advantages of using arrays, such as code optimization and ease of traversal, and includes examples of one-dimensional and two-dimensional arrays. Additionally, it covers array access, updating elements, and sorting methods, along with specific syntax for declaring and initializing arrays.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views34 pages

Unit-Iii Part-Ii

The document provides a comprehensive overview of arrays in the C programming language, detailing their definition, declaration, initialization, and properties. It explains the advantages of using arrays, such as code optimization and ease of traversal, and includes examples of one-dimensional and two-dimensional arrays. Additionally, it covers array access, updating elements, and sorting methods, along with specific syntax for declaring and initializing arrays.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

UNIT-III

ARRAYS

Anarrayisdefinedasthecollectionofsimilartypeofdataitemsstoredatcontiguousmemory
locations. Arrays are the derived data type in C programming language which can store the
primitivetypeofdatasuch as int, char,double,float, etc. It also has thecapabilityto storethe
collection of derived data types, such as pointers, structure, etc. The array is the simplest data
structure where each data element can be randomly accessed by using its index number.

Carrayisbeneficialifyouhavetostoresimilarelements.Forexample,ifwewanttostorethe marks
ofastudent in 6subjects, thenwedon't need to definedifferent variables forthemarks in the
different subject. Instead of that, we can define an array which can store the marks in each
subject at the contiguous memory locations.

Byusingthearray,wecanaccesstheelementseasily.Onlyafewlinesofcodearerequiredto access the


elements of the array.

CArrayDeclaration

In C, we have to declare the array like any other variable before using it. We can declare an
arraybyspecifyingitsname,thetypeofits elements,andthesizeofitsdimensions.Whenwe
declareanarrayinC,thecompilerallocatesthememoryblockofthespecifiedsizetothearray name.

Syntaxof ArrayDeclaration

data_typearray_name[array_size];
or
data_typearray_name[size1][size2]...[sizeN];
TheC arraysarestaticin nature,i.e., theyare allocatedmemoryatthecompiletime.

Propertiesof Array

Thearraycontainsthefollowing properties.

 Each elementof an array isof same data type and carries the same size,i.e., int= 4bytes.
 Elementsofthearrayarestoredatcontiguousmemorylocationswherethefirstelement is
stored at the smallest memory location.
 Elements of the array can be randomly accessed since we can calculate the address of
each element of the arraywith thegiven baseaddress and thesizeof thedataelement.

AdvantageofCArray

1) CodeOptimization:Less codetotheaccessthedata.

2) Easeoftraversing: Byusingthefor loop, wecan retrievethe elements of an arrayeasily.

3) Easeof sorting: Tosorttheelementsofthearray,weneed afewlines ofcodeonly.

4) RandomAccess: Wecan accessanyelement randomlyusingthe array.


ExampleofArray Declaration:

//CProgramtoillustratethearraydeclaration

#include <stdio.h>

int main()
{
//declaringarrayofintegers
int arr_int[5];
//declaringarrayofcharacters
char arr_char[5];
return0;
}

CArrayInitialization

Initialization in C is the process to assign some initial value to the variable. When the arrayis
declared or allocated memory, the elements of the array contain some garbage value. So, we
needtoinitializethearraytosomemeaningfulvalue.Therearemultiplewaysinwhichwecan
initialize an array in C.

Thesimplestwaytoinitializeanarrayisbyusingtheindexofeachelement.Wecaninitialize each
element of the array by using the index. Consider the following example.

1. marks[0]=80;//initializationof array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;
Carrayexample:

1. #include<stdio.h>
2. intmain(){
3. inti=0;
4. intmarks[5];//declarationofarray
5. marks[0]=80;//initializationof array
6. marks[1]=60;
7. marks[2]=70;
8. marks[3]=85;
9. marks[4]=75;
10. //traversalofarray
11. for(i=0;i<5;i++){
12. printf("%d \n",marks[i]);
13. }//endofforloop
14. return 0;
15. }

Output

80
60
70
85
75

CArray:Declaration withInitialization:

data_typearray_name[size] ={value1,value2,...valueN};
ArrayInitializationwithDeclarationwithoutSize:

If we initialize an array using an initializer list, we can skip declaring the size of the array as
thecompilercanautomaticallydeducethesizeofthearrayinthesecases.Thesizeofthearray in these
cases is equal to the number of elements present in the initializer list as the compiler can
automatically deduce the size of the array.

data_typearray_name[]= {1,2,3,4,5};

Thesizeoftheabovearraysis5whichis automaticallydeducedbythecompiler. Let's see

the C program to declare and initialize the array in C.

1. #include<stdio.h>
2. intmain(){
3. inti=0;
4. intmarks[5]={20,30,40,50,60};//declaration andinitializationof array
5. //traversalofarray
6. for(i=0;i<5;i++){
7. printf("%d \n",marks[i]);
8. }
9. return 0;
10. }

Output

20
30
40
50
60

ArrayInitializationafterDeclaration(UsingLoops):

We initialize the array after the declaration by assigning the initial value to each element
individually.Wecanuseforloop,whileloop,ordo-whilelooptoassignthevaluetoeach element of the
array.

for(inti=0;i<N;i++)
{
array_name[i]=valuei;
}
ExampleofArrayInitializationin C

//CProgramtodemonstratearrayinitialization
#include <stdio.h>

int main()
{

//arrayinitializationusinginitialierlist int
arr[5] = { 10, 20, 30, 40, 50 };

//arrayinitializationusinginitializerlist without
//specifying size
intarr1[]={ 1,2, 3, 4, 5 };

//arrayinitializationusingforloop float
arr2[5];
for (int i = 0; i < 5; i++)
{ arr2[i]=(float)i*2.1;
}
return0;
}

AccessArray Elements:

WecanaccessanyelementofanarrayinCusingthearraysubscriptoperator []andthe index value i


of the element.

array_name[index];

Onethingto noteis thattheindexingin thearrayalways startswith 0, i.e., thefirst element


isat index0and thelastelement is atN– 1whereNisthenumberof elements in the array.
ExampleofAccessingArrayElementsusingArraySubscriptOperator:

//CProgramtoillustrateelementaccessusingarray

// subscript

#include<stdio.h>

int main()

//arraydeclarationandinitialization int

arr[5] = { 15, 25, 35, 45, 55 };

//accessingelementatindex2i.e3rdelement

printf("Element at arr[2]: %d\n", arr[2]);

//accessingelementatindex4i.elastelement

printf("Element at arr[4]: %d\n", arr[4]);

//accessingelementatindex0i.efirstelement

printf("Element at arr[0]: %d", arr[0]);

return0;

Output

Elementatarr[2]:35

Elementatarr[4]:55

Elementatarr[0]:15

UpdateArrayElement

Wecanupdatethevalueofanelement atthegivenindexiinasimilarwaytoaccessingan element by


using the array subscript operator [ ] and assignment operator =.

array_name[i]=new_value;
CArrayTraversal

Traversalistheprocessinwhichwevisiteveryelementofthedatastructure.ForCarray traversal, we
use loops to iterate through each element of the array.

ArrayTraversalusingforLoop
for (int i = 0; i < N; i++)
{
array_name[i];
}
HowtouseArrayin C?

Thefollowingprogram demonstrates howto usean arrayin theC programminglanguage:

//CProgramtodemonstratetheuseofarray

#include <stdio.h>

int main()

//arraydeclarationandinitialization int

arr[5] = { 10, 20, 30, 40, 50 };

//modifyingelementatindex2

arr[2] = 100;

//traversingarrayusingforloop printf("Elements

in Array: ");

for (int i = 0; i < 5; i++)

{ printf("%d",arr[i])

return0;

Output

ElementsinArray:10 2010040 50
CArray Example:Sorting an array

Inthefollowingprogram,weareusingbubblesortmethodtosortthearrayinascendingorder.

1. #include<stdio.h>
2. void main ()
3. {
4. inti, j,temp;
5. int a[10]={ 10,9, 7, 101, 23,44, 12, 78, 34, 23};
6. for(i=0;i<10; i++)
7. {
8. for(j=i+1;j<10; j++)
9. {
10. if(a[j]>a[i])
11. {
12. temp=a[i];
13. a[i]=a[j];
14. a[j]=temp;
15. }
16. }
17. }
18. printf("PrintingSortedElementList...\n");
19. for(i=0;i<10; i++)
20. {
21. printf("%d\n",a[i]);
22. }
23.}

Programtoprintthelargestandsecondlargestelementofthe array.

1. #include<stdio.h>
2. void main ()
3. {
4. intarr[100],i,n,largest,sec_largest;
5. printf("Enterthe sizeofthearray?");
6. scanf("%d",&n);
7. printf("Entertheelements ofthearray?");
8. for(i=0;i<n; i++)
9. {
10. scanf("%d",&arr[i]);
11. }
12. largest= arr[0];
13. sec_largest= arr[1];
14. for(i=0;i<n;i++)
15. {
16. if(arr[i]>largest)
17. {
18. sec_largest= largest;
19. largest= arr[i];
20. }
21. elseif(arr[i]>sec_largest&&arr[i]!=largest)
22. {
23. sec_largest=arr[i];
24. }
25. }
26. printf("largest=%d,secondlargest=%d",largest,sec_largest); 27.
28.}

Typesof Arrayin C

Therearetwo typesof arraysbased onthenumberof dimensionsit has.Theyareas follows:

1. OneDimensionalArrays(1D Array)

2. MultidimensionalArrays

1. OneDimensional ArrayinC

TheOne-dimensionalarrays,alsoknownas1-DarraysinCarethosearraysthathaveonly one
dimension.

Syntaxof1DArrayinC array_name

[size];
Exampleof1DArrayinC

//CProgramtoillustratetheuseof1Darray

#include <stdio.h>

int main()

//1darraydeclaration int

arr[5];

//1darrayinitializationusingforloop for

(int i = 0; i < 5; i++) {

arr[i]=i * i-2 * i + 1;

printf("ElementsofArray:");

//printing1darraybytraversingusingforloop for

(int i = 0; i < 5; i++) {

printf("%d", arr[i]);

return0;

Output

ElementsofArray:10149

ArrayofCharacters(Strings)

In C, we store the words, i.e., a sequence of characters in the form of an array of


charactersterminated by a NULL character. These are called strings in C language.
//C Programto illustrate strings
#include<stdio.h>
int main()
{
// creatingarrayofcharacter
chararr[6]={'G', 'e', 'e','k', 's', '\0'};
//printingstring int
i = 0;
while(arr[i]){
printf("%c",arr[i++]);
}
return0;
}

Output
Geeks

2. MultidimensionalArrayinC

Multi-dimensional Arrays in C are those arrays that have more than one dimension. Some of
the popular multidimensional arrays are2D arrays and 3D arrays. We can declare arrays with
more dimensions than 3d arrays but they are avoided as they get very complex and occupy a
large amount of space.

A.Two-DimensionalArrayinC
The two-dimensional array can be defined as an arrayof arrays. The 2D arrayis organized as
matriceswhichcanberepresentedasthecollectionofrowsandcolumns.However,2Darrays are
created to implement a relational database lookalike data structure. It provides ease of
holding the bulk of data at once which can be passed to any number of functions wherever
required.
DeclarationoftwodimensionalArrayin C

Thesyntaxtodeclarethe 2Darrayisgiven below.

1. data_typearray_name[rows][columns];

Consider the following example.

2. inttwodimen[4][3];

Here,4 isthe number ofrows, and3 is thenumber of columns.

Initializationof 2DArrayin C

Inthe1Darray,wedon'tneedtospecifythesizeofthearrayifthedeclarationandinitialization are
being done simultaneously. However, this will not work with 2D arrays. We will have to
define at least the second dimension of the array. The two-dimensional array can be declared
and defined in the following way.

1. intarr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

Syntaxof 2DArrayinC
array_name[size1][size2];

Here,

 size1:Sizeofthefirst dimension.

 size2:Sizeof theseconddimension.

Exampleof2DArrayinC
//CProgramtoillustrate2darray
#include <stdio.h>
int main()
{
//declaringandinitializing2darray
intarr[2][3]={ 10,20, 30,40, 50,60 };
printf("2D Array:\n");
//printing2d array
for(int i =0;i <2; i++){
for (int j = 0; j < 3; j++)
{ printf("%d",arr[i][j]);
}
printf("\n");
}
return0;
}
Output
2DArray:
102030
405060

Two-dimensionalarrayexampleinC

1. #include<stdio.h>
2. intmain(){
3. inti=0,j=0;
4. intarr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing2Darray
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d]=%d\n",i,j,arr[i][j]);
9. }//endofj
10. }//endofi
11. return 0;
12. }
13. Output
14.arr[0][0] = 1
15.arr[0][1] = 2
16.arr[0][2] = 3
17.arr[1][0] = 2
18.arr[1][1] = 3
19.arr[1][2] = 4
20.arr[2][0] = 3
21.arr[2][1] = 4
22.arr[2][2] = 5
23.arr[3][0] = 4
24.arr[3][1] = 5
25.arr[3][2] = 6
C2Darrayexample:Storingelementsin amatrixandprintingit.

1. #include<stdio.h>
2. void main ()
3. {
4. intarr[3][3],i,j;
5. for (i=0;i<3;i++)
6. {
7. for (j=0;j<3;j++)
8. {
9. printf("Entera[%d][%d]: ",i,j);
10. scanf("%d",&arr[i][j]);
11. }
12. }
13. printf("\nprintingtheelements........\n");
14. for(i=0;i<3;i++)
15. {
16. printf("\n");
17. for (j=0;j<3;j++)
18. {
19. printf("%d\t",arr[i][j]);
20. }
21. }
22.}

Output

Entera[0][0]:56
Entera[0][1]:10
Entera[0][2]:30
Entera[1][0]:34
Entera[1][1]:21
Entera[1][2]:34

Entera[2][0]:45
Entera[2][1]:56
Enter a[2][2]: 78

printingtheelements....

56 10 30
34 21 34
45 56 78
RelationshipbetweenArraysand Pointers

Arrays and Pointers are closelyrelated to each other such that we can use pointers to perform
allthepossibleoperationsofthearray.Thearraynameisaconstantpointertothefirstelement of the
array and the array decays to the pointers when passed to the function.

//CProgramtodemonstratetherelationbetween arraysand

// pointers

#include<stdio.h>

int main()

intarr[5]={ 10,20, 30, 40, 50 };

int* ptr =&arr[0];

//comparingaddressof firstelementandaddressstored

//insidearrayname

printf("AddressStoredinArrayname:%p\nAddressof""1st

Array Element: %p\n",

arr,&arr[0]);

// printing array elements using pointers

printf("Arrayelementsusingpointer:");

for (int i = 0; i < 5; i++) {

printf("%d", *ptr++);

return0;

}
Output

AddressStoredinArrayname:0x7ffce72c2660
Address of 1st ArrayElement: 0x7ffce72c2660
Array elements using pointer: 10 20 30 40 50

PassinganArraytoaFunctioninC
AnarrayisalwayspassedaspointerstoafunctioninC.Wheneverwetrytopassanarrayto a function,
it decays to the pointer and then passed as a pointer to the first element of an array.

Wecan verifythis usingthe followingCProgram:

//CProgramtopassanarraytoafunction #include
<stdio.h>

voidprintArray(int arr[])
{
printf("SizeofArrayinFunctions:%d\n",sizeof(arr)); printf("Array
Elements: ");
for (int i = 0; i < 5; i++)
{ printf("%d",arr[i])
;
}
}
//drivercode
int main()
{
intarr[5]={ 10,20, 30, 40, 50 };
printf("SizeofArrayinmain():%d\n",sizeof(arr)); printArray(arr);
return0;
}

Output
Size of Array in main(): 20
Size of Array in Functions: 8
ArrayElements:1020304050
CSTRINGS:
A String in C programming is a sequence of characters terminated with a null character ‘\0’.
The C String is stored as an arrayof characters. The difference between a character arrayand a
C string is that the string in C is terminated with a unique character ‘\0’.

The string can be defined as the one-dimensional array of characters terminated by a


null('\0').Thecharacterarrayorthestringisusedtomanipulatetextsuchaswordorsentences. Each
character in the array occupies one byte of memory, and the last character must always
be0.Theterminationcharacter('\0')isimportantinastringsinceitis theonlywaytoidentify where the
string ends. When we define a string as char s[10], the character s[10] is implicitly initialized
with the null in the memory.

Therearetwo waysto declare astringinclanguage.

1. Bychararray
2. Bystring literal

CString Initialization

A string in C can be initialized in different ways. We will explain this with the help of an
example. Below are the examples to declare a string with the name str and initialize it with
“GeeksforGeeks”.
Wecan initializea C stringin4different wayswhichareas follows:

1. AssigningaStringLiteral without Size

String literals can be assigned without size. Here, the name of the string str acts as a pointer
because it is an array.

charstr[] ="GeeksforGeeks";
2. AssigningaStringLiteralwithaPredefinedSize

String literals can be assigned with a predefined size. But we should always account for one
extra space which will be assigned to the null character. If we want to store a string of size n
then we should always declare a string with a size equal to or greater than n+1.

charstr[50] ="GeeksforGeeks";
3. AssigningCharacterbyCharacterwith Size

We can also assign a string character by character. But we should remember to set the end
character as ‘\0’ which is a null character.

charstr[14]={ 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
4. AssigningCharacterbyCharacterwithout ize

We can assign character by character without size with the NULL character at the end. The
size of the string is determined by the compiler automatically.

charstr[]={ 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};

Note: When a Sequence of characters enclosed in the double quotation marks is encountered
by the compiler, a null character ‘\0’ is appended at the end of the string by default.
StringExampleinC

Let'sseeasimpleexamplewhereastringisdeclaredandbeingprinted.The'%s'isusedasa format
specifier for the string in c language.

1. #include<stdio.h>
2. #include<string.h>
3. intmain(){
4. charch[11]={'j', 'a','v','a','t','p','o','i','n','t','\0'};
5. charch2[11]="javatpoint";
6. printf("CharArrayValueis: %s\n",ch);
7. printf("StringLiteralValueis:%s\n",ch2);
8. return 0;
9. }

Output:

Char Array Value is: javatpoint

StringLiteralValueis:javatpoint

C StringExample
//Cprogramtoillustratestrings #include

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

intmain()
{
//declareandinitializestring
charstr[] = "Geeks";

// print string
printf("%s\n",str);

intlength = 0;
length=strlen(str);

// displaying the length of string


printf("Lengthofstringstris%d",length);

return0;
}
Output
Geeks
Lengthofstringstris5.
Wecanseeintheaboveprogramthatstringscanbeprintedusingnormalprintfstatementsjust like we
print any other variable. Unlike arrays, we do not need to print a string, character by
character.

Note: The C language does not provide an inbuilt data type for strings but it has an access
specifier “%s” which can be used to print and read strings directly.

Stringinput/outputfunction:

ReadaStringInputFrom theUser

Thefollowing exampledemonstrates howto take stringinputusingscanf() function in C.

//Cprogramtoreadstringfromuser
#include<stdio.h>

int main()
{
//declaringstring
char str[50];

//readingstring
scanf("%s",str);

// print string
printf("%s",str);

return0;
}

Input

GeeksforGeeks

Output
GeeksforGeeks

Youcanseeintheaboveprogramthatthestringcanalsobereadusingasinglescanfstatement. Also,
youmightbethinkingthatwhywehavenot usedthe‘&’sign withthestringname‘str’
inscanfstatement!Tounderstandthisyouwillhavetorecallyourknowledgeofscanf.
Weknowthatthe‘&’signisusedtoprovidetheaddressofthevariabletothescanf()function
to store the value read in memory. As str[] is a character array so using str without braces ‘[‘
and ‘]’ will give the base address of this string. That’s why we have not used ‘&’ in this case
as we are already providing the base address of the string to scanf.

Nowconsider onemore example,

//CProgramtotakeinputstringwhichisseparated by
// whitespaces
#include<stdio.h>

//drivercode
intmain()
{

charstr[20];
//takinginputstring
scanf("%s", str);

//printingthereadstring
printf("%s", str);

return0;
}

Input

GeeksforGeeks

Output

Geeks

Here,the stringis read onlytill the whitespaceisencountered.

Note:Afterdeclaration,ifwewanttoassignsomeothertextto thestring, wehavetoassignit


onebyoneorusethebuilt-instrcpy()functionbecausethedirectassignmentofthestringliteral to
character array is only possible in declaration.

Cgets()andputs()functions:

Thegets()andputs()aredeclaredin theheaderfilestdio.h.Boththefunctionsareinvolvedin the


input/output operations of the strings.

Cgets() function
Thegets()functionenablestheusertoentersomecharactersfollowedbytheenterkey.Allthe
charactersenteredbytheusergetstoredinacharacterarray.Thenullcharacterisaddedtothe array to
make it a string. The gets() allows the user to enter the space-separated strings. It returns the
string entered by the user.

Declaration

1. char[]gets(char[]);

Readingstringusing gets()

1. #include<stdio.h>
2. void main ()
3. {
4. chars[30];
5. printf("Enterthe string?");
6. gets(s);
7. printf("Youentered %s",s);
8.}

Output
Enter the string?
javatpointisthebest
Youenteredjavatpointisthebest

Thegets()function is riskyto usesinceit doesn't performanyarraybound checkingand keep


readingthecharactersuntilthenewline(enter)isencountered.Itsuffersfrombufferoverflow,
whichcanbeavoidedbyusingfgets().Thefgets()makessurethatnotmorethanthemaximum limit of
characters are read. Consider the following example.

1. #include<stdio.h>
2. void main()
3. {
4. charstr[20];
5. printf("Enterthe string?");
6. fgets(str,20,stdin);
7. printf("%s",str);
8.}

Output
Enterthestring?javatpointisthebestwebsite javatpoint is
the b

Cputs() function

Theputs()functionisverymuchsimilartoprintf()function.Theputs()functionisusedtoprint
thestringontheconsolewhichispreviouslyreadbyusinggets()orscanf()function.Theputs()
function returns an integer value representing the number of characters being printed on the
console.Since,itprintsanadditionalnewlinecharacterwiththestring,whichmovesthecursor to
thenewlineon theconsole, theintegervaluereturned byputs()will always beequal to the number
of characters present in the string plus 1.

Declaration

1. intputs(char[])

Let'sseeanexampletoreadastringusinggets() and printiton theconsoleusingputs().

1. #include<stdio.h>
2. #include<string.h>
3. intmain(){
4. charname[50];
5. printf("Enteryourname: ");
6. gets(name);//readsstringfromuser
7. printf("Yournameis:");
8. puts(name);//displaysstring
9. return 0;
10. }

Output:
Enteryourname:SonooJaiswal Your
name is: Sonoo Jaiswal
Example

FollowingistheCprogramforinputandoutputforstrings− #include<stdio.h>
main ( )
{ chara[30
];
printf("enteryourname");
scanf ( "%s",a);
printf("yournameis%s",a);
getch ( );
}

Output

Whentheaboveprogramisexecuted,itproducesthefollowingresult−

1.Enteryourname:Lucky2.Enteryourname:LuckyLol Your name


is Lucky Your name is Lucky

Note−

 ‘&’isnotusedforacceptingstringsbecausenameofthestringitselfspecifiesthebase address
of the string.
 Spaceisnotacceptedasacharacter byscanf().
 ‘\0’isplacedbythe compilerattheend.

Example

FollowingistheCprogramforusinggets()and puts()forreadingandwritingstrings −

#include<stdio.h>
main ( )
{ chara[30
];
printf("enteryourname"); gets
(a);
printf("Yournameis");
puts (a);
}

Output

Whentheaboveprogramisexecuted,itproducesthefollowingresult −

1.EnteryourName:Lucky2)Enteryourname:LuckyLol Your
name is Lucky Your name is Lucky Lol.

Array of Strings in C: In C programmingString is a 1-D arrayof characters and is defined


asanarrayofcharacters.Butanarrayofstringsin Cisatwo-dimensionalarrayofcharacter types.
Each String is terminated with a null character (\0). It is an application of a 2d array.

Syntax:charvariable_name[r]={listofstring};

Here,

 var_nameisthenameofthevariablein C.
 ris themaximum number ofstringvaluesthat canbestored in a stringarray.
 cis themaximum number ofcharacter values that can bestored in each stringarray.

Example:

//CProgramtoprintArray
// of strings
#include<stdio.h>

//Drivercode
intmain()
{
chararr[3][10]={"Geek",
"Geeks","Geekfor"};
printf("StringarrayElementsare:\n");

for(inti=0;i<3;i++)
{
printf("%s\n",arr[i]);
}
return0;
}

Output

StringarrayElementsare: Geek
Geeks
Geekfor
BelowistheRepresentationoftheaboveprogram

We have 3 rows and 10 columns specified in our Array of String but because of
prespecifying,thesizeofthearrayofstringsthespaceconsumptionishigh.So,toavoidhigh space
consumption in our program we can use an Array of Pointers in C.

The C string functions are built-in functions that can be used for various operations and
manipulations on strings. These string functions can be used to perform tasks such as
string copy, concatenation, comparison, length, etc. The <string.h> header file contains
these string functions.
In this article, we will discuss some of the most commonly used String functions in
the C programming language.
String Functions in C
Some of the commonly used string functions in C are as follows:
1. strcat() Function
The strcat() function in C is used for string concatenation. It will append a copy of the
source string to the end of the destination string.
Syntax
char* strcat(char* dest, const char* src);
The terminating character at the end of dest is replaced by the first character of src.
Parameters
 dest: Destination string
 src: Source string
Return value
 The strcat() function returns a pointer to the dest string.
// C Program to illustrate the strcat function
#include <stdio.h>
int main()
{
char dest[50] = "This is an";
char src[50] = " example";
printf("dest Before: %s\n", dest);
strcat(dest, src);
printf("dest After: %s", dest);
return 0;
}
Output
dest Before: This is an
dest After: This is an example
In C, there is a function strncat() similar to strcat().
strncat()
This function is used for string handling. This function appends not more than n
characters from the string pointed to by src to the end of the string pointed to
by dest plus a terminating Null-character.
Syntax of strncat()
char* strncat(char* dest, const char* src, size_t n);
where n represents the maximum number of characters to be appended. size_t is an
unsigned integral type.

2. strlen() Function
The strlen() function calculates the length of a given string. It doesn’t count the null
character ‘\0’.
Syntax
int strlen(const char *str);
Parameters
 str: It represents the string variable whose length we have to find.
Return Value
 strlen() function in C returns the length of the string.

// C program to demonstrate the strlen() function

#include <stdio.h>

#include <string.h>

int main()

char str[] = "GeeksforGeeks";

size_t length = strlen(str


printf("String: %s\n", str);
printf("Length: %zu\n", length);

return 0;

Output
String: GeeksforGeeks
Length: 13
3. strcmp() Function
The strcmp() is a built-in library function in C. This function takes two strings as
arguments and compares these two strings lexicographically.
Syntax
int strcmp(const char *str1, const char *str2);
Parameters
 str1: This is the first string to be compared.
 str2: This is the second string to be compared.
Return Value
 If str1 is less than str2, the return value is less than 0.
 If str1 is greater than str2, the return value is greater than 0.
 If str1 is equal to str2, the return value is 0.
Example
// C program to demonstrate the strcmp() function

#include <string.h>

int main()

{
char str1[] = "Geeks"
char str2[] = "For";
char str3[] = "Geeks";
int result1 = strcmp(str1, str2);
int result2 = strcmp(str2, str3);
int result3 = strcmp(str1, str1);
printf("Comparison of str1 and str2: %d\n", result1);
printf("Comparison of str2 and str3: %d\n", result2);
printf("Comparison of str1 and str1: %d\n", result3);

return 0;

Output
Comparison of str1 and str2: 1
Comparison of str2 and str3: -1
Comparison of str1 and str1: 0
There is a function strncmp() similar to strcmp().
strncmp()
This function lexicographically compares the first n characters from the two null-
terminated strings and returns an integer based on the outcome.
Syntax
int strncmp(const char* str1, const char* str2, size_t num);
Where num is the number of characters to compare.
4. strcpy
The strcpy() is a standard library function in C and is used to copy one string to another.
In C, it is present in <string.h> header file.
Syntax
char* strcpy(char* dest, const char* src);
Parameters
 dest: Pointer to the destination array where the content is to be copied.
 src: string which will be copied.
Return Value
 strcpy() function returns a pointer pointing to the output string.

// C program to illustrate the use of strcpy()

#include <stdio.h>

#include <string.h>
int main()
{
char source[] = "GeeksforGeeks";

char dest[20];

strcpy(dest, source);

printf("Source: %s\n", source);

printf("Destination: %s\n", dest);


return 0;

Output
Source: GeeksforGeeks
Destination: GeeksforGeeks
strncpy()
The function strncpy() is similar to strcpy() function, except that at most n bytes of src
are copied.
If there is no NULL character among the first n character of src, the string placed in dest
will not be NULL-terminated. If the length of src is less than n, strncpy() writes an
additional NULL character to dest to ensure that a total of n characters are written.
Syntax
char* strncpy( char* dest, const char* src, size_t n );
Where n is the first n characters to be copied from src to dest.
5. strchr()
The strchr() function in C is a predefined function used for string handling. This function is
used to find the first occurrence of a character in a string.
Syntax
char *strchr(const char *str, int c);
Parameters
 str: specifies the pointer to the null-terminated string to be searched in.
 ch: specifies the character to be searched for.
Here, str is the string and ch is the character to be located. It is passed as its int
promotion, but it is internally converted back to char.
Return Value
 It returns a pointer to the first occurrence of the character in the string.
Example
C++

1
#include <stdio.h>
2
#include <string.h>
3

4
int main()
5
{
6
char str[] = "GeeksforGeeks";
7
char ch = 'e';
8

9
12
char* result = strchr(str, ch);

if (result != NULL) {

printf("The character '%c' is found at index %ld\n", ch, result - str);

else {

printf("The character '%c' is not found in the " "string\n", ch);

return 0;

Output
The character 'e' is found at index 1
strrchr() Function
In C, strrchr() function is similar to strchr() function. This function is used to find the last
occurrence of a character in a string.
Syntax
char* strchr(const char *str, int ch);
6. strstr()
The strstr() function in C is used to search the first occurrence of a substring in another
string.
Syntax
char *strstr (const char *s1, const char *s2);
Parameters
 s1: This is the main string to be examined.
 s2: This is the sub-string to be searched in the s1 string.
Return Value
 If the s2 is found in s1, this function returns a pointer to the first character of the s2 in
s1, otherwise, it returns a null pointer.
 It returns s1 if s2 points to an empty string.

// C program to demonstrate the strstr() function

#include <stdio.h>

#include <string.h>

int main()

char s1[] = "GeeksforGeeks";

char s2[] = "for";

char* result;
result = strstr(s1, s2);

if (result != NULL) {

printf("Substring found: %s\n", result);

else {
printf("Substring not found.\n");

return 0;

Output
Substring found: forGeeks
7. strtok()
The strtok() function is used to split the string into small tokens based on a set of delimiter
characters.
Syntax
char * strtok(char* str, const char *delims);
Parameters
 str: It is the string to be tokenized.
 delims: It is the set of delimiters
// C program to demonstrate the strtok() function

#include <stdio.h>

#include <string.h>

int main()

char str[] = "Geeks,for.Geeks";

const char delimiters[] = ",.";

char* token = strtok(str, delimiters);

while (token != NULL) {

printf("Token: %s\n", token);

token = strtok(NULL, delimiters);

return 0;

Output
Token: Geeks
Token: for
Token: Geeks

You might also like