SlideShare a Scribd company logo
1
ARRAYS
Definition
An array isa fixed-size sequencedcollectionof elementsof the same datatype.
Advantagesof arrays
 Huge amount of data can be storedundersingle variable name.
 Searchingof data itemisfaster.
 2 dimensionarraysare usedto representthe matrices.
 It ishelpful inimplementingotherdatastructure like linkedlist,queue,stack.
Types ofarrays
 One dimensional array.
 Two dimensional array.
 Multi dimensionalarray.
One dimensional array
A list of itemscan be givenone variable name usingonly one subscript is calledsingle subscripted
variable or a one dimensional array.
Declaration of one dimensional array
Syntax :
<data_type> <array_name> [size]
Data_type :It representsthe type of array(i.e)float,int,char,string.
Array_name:The name of array.
Size: Size of array representthe total numberof elementof array,datastoredinarray withindex,we
can retrieve databythere index.
Example:intx[7];
2
Initializationof one dimensionalarrays
Array can initializedateitherof the following:
 At run time .
 At compile time.
Run time initialization
An array can be explicitlyinitializedatruntime.
Syntax:
<data_type> <array_name> [size];
Example:intx[10];
Compile time initialization
The elementsof the arraycan be initialized asthe ordinaryvariables.
Example:int a[5]={1,2,3,4,5};
#include<stdio.h>
#include<conio.h>
voidmain()
{
intarr[50],i=0,b,c[5]={1,2,3,4,5};
3
clrscr();
printf("Howmanyelementyouwantto enter n");
scanf("%d",&b);
printf("Enter%dNoforarray n",b);
for(i=0;i<b ; i++)
{
scanf("%d", &arr[i]);
}
//output
printf("nElementof the arrayare :- n");
for(i=0;i<b ; i++)
{
printf("Elementof %dpositionis%d n",i,arr[i]);
printf(“Elementsof %d positionis%dn”,I,c[i]);
}
getch();
}
Output:
How manyelementyouwanttoenter 2
Enter 2 Nofor array
6
5
Elementof the array are :-
Elementof 0 positionis
6
4
Elementof 0 positionis
1
Elementof 1 positionis
5
Elementsof 1 positionis
2
Two dimensional array
A list of itemscan be givenone variable name usingtwo subscript is calledtwo dimensional
array. One subscriptfor row and another for column.
SYNTAX:
data-type array_name[row-size][column-size];
EXAMPLE:
inta[3][4];
Initializationof twodimensional arrays
Array can initializedateitherof the following:
 At run time .
 At compile time.
5
Run time initialization
An array can be explicitlyinitializedatruntime.
Syntax:
data-type array_name[row-size][column-size];
example:inta[2][2];
Compile time initialization
The elementsof the arraycan be initializedasthe ordinaryvariables.
Example:
 intodd[3][2]={1,3,5,7,9,11};
 Individual elementcanalsobe assignedas:
 Odd[0][0]=1;
 Odd[0][1]=3;
 Odd[1][0]=5;
 Odd[1][1]=7;
 Odd[2][0]=9;
 Odd[2][1]=11;
Readingdatafrom the user:
Nestedforloopisused.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int m, n, p, q, c, d, k, sum = 0;
6
int first[10][10], second[10][10], multiply[10][10];
printf("Enter the number of rows and columns of first matrixn");
scanf("%d%d", &m, &n);
printf("Enter the number of rows and columns of second matrixn");
scanf("%d%d", &p, &q);
if (n != p)
printf("Matrices with entered orders can't be multiplied with each
other.n");
else
{
printf("Enter the elements of first matrixn");
for (c = 0; c < m; c++)
{
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
}
printf("Enter the elements of second matrixn");
for (c = 0; c < p; c++)
{ for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
}
for (c = 0; c < m; c++)
{
for (d = 0; d < q; d++)
{
for (k = 0; k < p; k++)
{
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
printf("Product of entered matrices:-n");
for (c = 0; c < m; c++)
{
for (d = 0; d < q; d++)
{
printf("%dt", multiply[c][d]);
printf("n");
}
}
getch();
}
7
Multidimensional array
A list of itemscan be givenone variable name usingmore than two subscript is calledmulti
dimensional array. The exact limitis determinedbythe compiler.
SYNTAX:
data-type array_name[s1][s2][s3][s4][s5]……….[sm];
EXAMPLE:
inta[3][4][5];
Dynamicarrays
STATICARRAYS:
The processof allocatingmemoryatcompile time isknownasstaticmemoryallocation
and the arrays that receive staticmemoryallocationare calledstaticarrays.
Dynamicarrays:
The processof allocatingmemorytoarraysat runtime is knownasdynamicmemory
allocationandthe arrays createdat run time are calleddynamicarrays.
Dynamicarrays are createdusingpointervariablesandmemorymanagementfunctions
malloc,callocandrealloc.Thesefunctionsare includedinthe headerfile<stdlib.h>.Thedynamicarraysis
usedto create and manipulate datastructuressuchaslinkedlist,stackandqueues.
Character Arrays & Strings
Introduction
A string is a sequence of characters. Any sequence or set of characters defined within double
quotation symbols is a constant string. In c it is required to do some meaningful operations on strings
they are:
 Readingstringdisplayingstrings
 Combiningorconcatenatingstrings
 Copyingone stringtoanother.
 Comparingstring& checkingwhethertheyare equal
 Extractionof a portionof a string
8
Declaring & InitializingStringVariables
char month1[ ]={‘j’,’a’,’n’,’u’,’a’,’r’,’y’};
Thenthe string monthisinitializing to January. This is perfectly valid but C offers a special way
to initialize strings.
The above string can be initialized as
char month1[]=”January”;
The characters of the stringare enclosedwithinapartof double quotes.The compilertakescare
of stringenclosedwithina pair of double quotes. The compiler takes care of storing the ASCII codes of
characters of the string in the memory and also stores the null terminator in the end.
/*String.c string variable*/
#include < stdio.h >
#include<conio.h>
voidmain()
{
char month[15];
printf (“Enterthe string”);
gets(month);
printf (“The stringenteredis%s”,month);
}
0 specifies a single character whose ASCII value is zero.
J A N U A R Y 0 ? ? ? ? ? ? ?
Character string terminated by a null character ‘0’.
A string variable is any valid C variable name & is always declared as an array.
syntax
char string_name[size];
9
The size determines the number of characters in the string name.
Example:
char address[100];
The size of the array should be one byte more than the actual space occupied by the string since the
complier appends a null character at the end of the string.
Reading Strings from the terminal:
The function scanf with%s format specification is needed to read the character string from the
terminal.
Example:
char address[20];
scanf(“%s”,address);
->Scanf statement has a draw back it just terminates the statement as soon as it finds a blank space,
suppose if we type the string new york then only the string new will be read and since there is a blank
space after word “new” it will terminate the string.
->The function getchar can be used repeatedly to read a sequence of successive single characters and
store it in the array.
We cannotmanipulate stringssince Cdoesnotprovide anyoperatorsfor string. For instance we cannot
assign one string to another directly.
For example:
String=”xyz”;
String1=string;
are notvalid.To copythe chars inone string to another string we may do so on a character to character
basis.
10
Reading a Line of Text
To read a line of text with white spaces, we have a special format specifier %[..] called “Edit set
conversion code” that can be used to read a line containing a variety of characters.
Example: To terminate a string only when a ‘n’ (New Line) character is inserted, we need to give the
following statement:
scanf(“%[^n]”,str);
Here, str – string variable
^n – Describes terminate the reading when ‘n’ character is encountered
Using getchar and gets Function
getchar() function is used to read a single character from the terminal. By providing a loop to
read characters until we provide a newline character, we are facilitating the reading of a line of text.
Example:
int c;
char character;
….
c = 0;
do
{
character = getchar();
line[c++] = character;
}while(character != ‘n’);
11
We may also use the gets() function present in <stdio.h> header file to read a line of text. It is in the
form:
gets(str);
Example:
char line[80];
gets(line);
Writing Strings to Screen
Using printf() function
The format specifier %s can be used to display an array of characters that is terminated by null
(0) character.
Example:printf(“%s”, name);
We can also specify the precision. Example:
%10.4s
Indicatesthatfirstfourcharacters are to be printedin a field width of 10 columns. Including a –
(minus) sign immediately after the % symbol will print the content left-justified.
For variable specification of width and precision, we use the * symbol. Example:
printf(“%*.*s”,w,s,str);
Using putchar() and puts()
We can use the putchar() function repeatedly to print a string to the screen.
Example:
Void main()
{
char name[6] = “paris”;
for(i=0;i<5;i++)
12
putchar(name[i]);
putchar(‘n’);
getch();
}
Another convenient way of printing a string to screen is using puts() function present in <stdio.h>.
Example:
puts(line);
Arithmetic operations on characters:
We can alsomanipulate the charactersaswe manipulate numbersinclanguage.Whenever the system
encountersthe character data it is automatically converted into a integer value by the system. We can
represent a character as a interface by using the following method.
x=’a’;
Printf(“%dn”,x);
Will display 97 on the screen. Arithmetic operations can also be performed on characters for example
x=’z’-1; is a valid statement. The ASCII value of ‘z’ is 122 the statement the therefore will assign 121 to
variable x.
It is also possible to use character constants in relational expressions for example
ch>’a’ && ch < = ’z’ will check whether the character stored in variable ch is a lower case letter.
A character digit can also be converted into its equivalent integer value suppose un the expression
Void main()
{
char character=’8’;
int a;
a=character-‘1’;
13
printf(“%d”,a);
getch();
}
where a is defined as an integer variable & character contains value 8 then a= ASCII value of 8 ASCII
value ‘1’=56-49=7.
We can also get the support of the c library function to converts a string of digits into their equivalent
integer values the general format of the function in
x=atoi(string);
here x is an integervariable &stringis a character array containing string of digits. For example
string=“101”; it will be stored as numeral 101 to x.
Putting Strings Together
We cannot apply the arithmetic addition for joining of two or more strings in the manner
string1 = string2 + string3; or
string1 = string2 + "SACY";
For carrying out the above we need to write a program to copy the contents of the string2 &
string3 into string1 one after the other. This process is called concatenation of strings.
strcat() Function
strcat() joins two or more strings together. It takes the following form
strcat(string1, string2);
string1 and string2 are character arrays. When the above function is executed, string2 is
appendedtostring1. It does so by removing the null character at the end of string1 and placing string2
from there. The string at string2 remains unchanged.
strcat function may also append a string constant to a string variable. The following is valid
14
strcat(part1,"SACY");
C also permits nesting of strcat functions. For example
strcat(strcat((string1,string2),string3);
is allowed and concatenates all the three strings together. The resultant string is stored in
string1.
String Handling Functions
C language recognizesthatstringisa differentclassof array bylettingusinput and output the array as a
unitand are terminatedbynull character.Clibrarysupportsa large numberof string handling functions
that can be used to array out many o f the string manipulations such as:
 Length (number of characters in the string).
 Concatentation (adding two are more strings)
 Comparing two strings.
 Substring (Extract substring from a given string)
 Copy(copies one string over another)
To do all the operations described here it is essential to include<string.h> library header file in the
program.
strlen() function:
Thisfunctioncountsand returnsthe numberof charactersin a string.The lengthdoes not include a null
character.
Syntax: n=strlen(string);
Where n is integer variable. Which receives the value of length of the string.
15
Example
length=strlen(“Hollywood”);
The function will assign number of characters 9 in the string to a integer variable length.Result is
length=9.
strcat() function:
when you combine two strings, you add the characters of one string to the end of other string. This
processiscalledconcatenation. The strcat() functionjoins2stringstogether.Ittakesthe following form
strcat(string1,string2)
string1 & string2 are character arrays. When the function strcat is executed string2 is appended to
string1. the string at string2 remains unchanged.
Example
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
strcpy(string1,”sri”);
strcpy(string2,”Bhagavan”);
Printf(“%s”,strcat(string1,string2);
getch();
}
16
From the above program segment the value of string1 becomes sribhagavan. The string at str2
remains unchanged as bhagawan. Result string1= sribhagavan
strcmp function:
In c you cannot directly compare the value of 2 strings in a condition like:
if(string1==string2)
Most librarieshowevercontainthe strcmp() function,whichreturnsazeroif 2 strings are equal,
or a non zero number if the strings are not the same. The syntax of strcmp() is given below:
strcmp(string1,string2)
String1 & string2may be stringvariablesorstringconstants.String1,& string2may be stringvariablesor
stringconstants some computers return a negative if the string1 is alphabetically less than the second
and a positive number if the string is greater than the second.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
strcmp(“Newyork”,”Newyork”);//will return zero because 2 strings are equal.
strcmp(“their”,”therr”);//willreturna9 whichis the numeric difference between ASCII ‘i’ and ASCII ’r’.
strcmp(“The”, “the”)// will return 32 which is the numeric difference between ASCII “T” & ASCII “t”.
getch();
}
strcmpi() function
This function is same as strcmp() which compares 2 strings but not case sensitive.
17
Example :
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
strcmpi(“THE”,”the”);// will return 0.
getch();
}
strcpy() function:
C does not allow you to assign the characters to a string directly as in the statement name=”Robert”;
Insteaduse the strcpy(0functionfoundinmostcompilersthe syntax of the functionisillustratedbelow.
strcpy(string1,string2);
Strcpy function assigns the contents of string2 to string1. string2 may be a character array variable or a
string constant.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
strcpy(Name,”Robert”);
getch();
}
In the above example Robert is assigned to the string called name. Result:Name=Robert.
18
Other string functions
 strncpy//stringcopy
 strncmp//stringcompare
 strncat//stringconcatenation
 strstr//findingsubstring
strncpy//string copy
Thisis three parameterfunctionandisinvokedasfollows.
Syntax:strncpy(s1,s2,n);
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
char s2=”ammukutti”;
strncpy(s1,s2,5);
s1[6]=’0’;
printf(“%s”,s1);
getch();
}
Result:ammuk
strncmp//string compare
syntax:strncmp(s1,s2,n);
thiscomparesleftmostn charactersof s1 and s2 andreturns.
(a) 0 if theyare equal.
(b) Negative number,ifs1 sub-stringislessthans2.
(c) Positive numberotherwise negative number.
19
strncat//string concatenation
syntax:strncat(s1,s2,n);
Concatenate the leftmostncharacters of s2 to the endof s1.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
Char s1=”Bala”, s2=”ammukutti”;
strncat(s1,s2,5);
printf(“%s”,s1);
getch();
}
Result:Balaammuk.
strstr//finding sub string
It isa twoparameterfunctionthatcan be usedto locate a sub-stringina string.
Syntax:strstr(s1,s2);
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
20
Char s1=”Abacus”, s2=”cus”;
if(strstr(s1,s2)==NULL)
printf(“substringisnotfound”);
else
printf(“s2isa substringof s1);
getch();
}
Strchr//determine the existence ofa first occurrence of character in a string
Example:
s1=”Mohamed”;
strchr(s1,”M”);
strrchr//last occurrence of character ina string
Example:
s1=”Mohamed”;
strrchr(s1,”d”);
Ad

More Related Content

What's hot (20)

handling input output and control statements
 handling input output and control statements handling input output and control statements
handling input output and control statements
Rai University
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
Tasnima Hamid
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
yndaravind
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
Dr.Subha Krishna
 
14 strings
14 strings14 strings
14 strings
Rohit Shrivastava
 
Strings part2
Strings part2Strings part2
Strings part2
yndaravind
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programming
nmahi96
 
Unitii string
Unitii stringUnitii string
Unitii string
Sowri Rajan
 
Strings in C
Strings in CStrings in C
Strings in C
Kamal Acharya
 
Strings in c
Strings in cStrings in c
Strings in c
vampugani
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++
Fahim Adil
 
The string class
The string classThe string class
The string class
Syed Zaid Irshad
 
05 c++-strings
05 c++-strings05 c++-strings
05 c++-strings
Kelly Swanson
 
Strings
StringsStrings
Strings
Imad Ali
 
String in c
String in cString in c
String in c
Suneel Dogra
 
Strinng Classes in c++
Strinng Classes in c++Strinng Classes in c++
Strinng Classes in c++
Vikash Dhal
 
Chapter 13.1.7
Chapter 13.1.7Chapter 13.1.7
Chapter 13.1.7
patcha535
 
Operation on string presentation
Operation on string presentationOperation on string presentation
Operation on string presentation
Aliul Kadir Akib
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
International Islamic University
 
Unit 2
Unit 2Unit 2
Unit 2
TPLatchoumi
 

Similar to Array &strings (20)

C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
Vikram Nandini
 
Lecture 05 2017
Lecture 05 2017Lecture 05 2017
Lecture 05 2017
Jesmin Akhter
 
function, storage class and array and strings
 function, storage class and array and strings function, storage class and array and strings
function, storage class and array and strings
Rai University
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
String notes
String notesString notes
String notes
Prasadu Peddi
 
Module 4- Arrays and Strings
Module 4- Arrays and StringsModule 4- Arrays and Strings
Module 4- Arrays and Strings
nikshaikh786
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
Appili Vamsi Krishna
 
Week6_P_String.pptx
Week6_P_String.pptxWeek6_P_String.pptx
Week6_P_String.pptx
OluwafolakeOjo
 
[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
Muhammad Hammad Waseem
 
unit-5 String Math Date Time AI presentation
unit-5 String Math Date Time AI presentationunit-5 String Math Date Time AI presentation
unit-5 String Math Date Time AI presentation
MukeshTheLioner
 
ARRAY's in C Programming Language PPTX.
ARRAY's in C  Programming Language PPTX.ARRAY's in C  Programming Language PPTX.
ARRAY's in C Programming Language PPTX.
MSridhar18
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothi
Sowmya Jyothi
 
Team 1
Team 1Team 1
Team 1
Sathasivam Rangasamy
 
string function with example...................
string function with example...................string function with example...................
string function with example...................
NishantsrivastavaV
 
Array,string structures. Best presentation pptx
Array,string structures. Best presentation pptxArray,string structures. Best presentation pptx
Array,string structures. Best presentation pptx
Kalkaye
 
Strings in programming tutorial.
Strings  in programming tutorial.Strings  in programming tutorial.
Strings in programming tutorial.
Samsil Arefin
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
GC University Faisalabad
 
Lesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsLesson in Strings for C Programming Lessons
Lesson in Strings for C Programming Lessons
JamesChristianGadian
 
6.array
6.array6.array
6.array
Shankar Gangaju
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
Thesis Scientist Private Limited
 
function, storage class and array and strings
 function, storage class and array and strings function, storage class and array and strings
function, storage class and array and strings
Rai University
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
Module 4- Arrays and Strings
Module 4- Arrays and StringsModule 4- Arrays and Strings
Module 4- Arrays and Strings
nikshaikh786
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
Appili Vamsi Krishna
 
unit-5 String Math Date Time AI presentation
unit-5 String Math Date Time AI presentationunit-5 String Math Date Time AI presentation
unit-5 String Math Date Time AI presentation
MukeshTheLioner
 
ARRAY's in C Programming Language PPTX.
ARRAY's in C  Programming Language PPTX.ARRAY's in C  Programming Language PPTX.
ARRAY's in C Programming Language PPTX.
MSridhar18
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothi
Sowmya Jyothi
 
string function with example...................
string function with example...................string function with example...................
string function with example...................
NishantsrivastavaV
 
Array,string structures. Best presentation pptx
Array,string structures. Best presentation pptxArray,string structures. Best presentation pptx
Array,string structures. Best presentation pptx
Kalkaye
 
Strings in programming tutorial.
Strings  in programming tutorial.Strings  in programming tutorial.
Strings in programming tutorial.
Samsil Arefin
 
Lesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsLesson in Strings for C Programming Lessons
Lesson in Strings for C Programming Lessons
JamesChristianGadian
 
Ad

Recently uploaded (20)

pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Ad

Array &strings

  • 1. 1 ARRAYS Definition An array isa fixed-size sequencedcollectionof elementsof the same datatype. Advantagesof arrays  Huge amount of data can be storedundersingle variable name.  Searchingof data itemisfaster.  2 dimensionarraysare usedto representthe matrices.  It ishelpful inimplementingotherdatastructure like linkedlist,queue,stack. Types ofarrays  One dimensional array.  Two dimensional array.  Multi dimensionalarray. One dimensional array A list of itemscan be givenone variable name usingonly one subscript is calledsingle subscripted variable or a one dimensional array. Declaration of one dimensional array Syntax : <data_type> <array_name> [size] Data_type :It representsthe type of array(i.e)float,int,char,string. Array_name:The name of array. Size: Size of array representthe total numberof elementof array,datastoredinarray withindex,we can retrieve databythere index. Example:intx[7];
  • 2. 2 Initializationof one dimensionalarrays Array can initializedateitherof the following:  At run time .  At compile time. Run time initialization An array can be explicitlyinitializedatruntime. Syntax: <data_type> <array_name> [size]; Example:intx[10]; Compile time initialization The elementsof the arraycan be initialized asthe ordinaryvariables. Example:int a[5]={1,2,3,4,5}; #include<stdio.h> #include<conio.h> voidmain() { intarr[50],i=0,b,c[5]={1,2,3,4,5};
  • 3. 3 clrscr(); printf("Howmanyelementyouwantto enter n"); scanf("%d",&b); printf("Enter%dNoforarray n",b); for(i=0;i<b ; i++) { scanf("%d", &arr[i]); } //output printf("nElementof the arrayare :- n"); for(i=0;i<b ; i++) { printf("Elementof %dpositionis%d n",i,arr[i]); printf(“Elementsof %d positionis%dn”,I,c[i]); } getch(); } Output: How manyelementyouwanttoenter 2 Enter 2 Nofor array 6 5 Elementof the array are :- Elementof 0 positionis 6
  • 4. 4 Elementof 0 positionis 1 Elementof 1 positionis 5 Elementsof 1 positionis 2 Two dimensional array A list of itemscan be givenone variable name usingtwo subscript is calledtwo dimensional array. One subscriptfor row and another for column. SYNTAX: data-type array_name[row-size][column-size]; EXAMPLE: inta[3][4]; Initializationof twodimensional arrays Array can initializedateitherof the following:  At run time .  At compile time.
  • 5. 5 Run time initialization An array can be explicitlyinitializedatruntime. Syntax: data-type array_name[row-size][column-size]; example:inta[2][2]; Compile time initialization The elementsof the arraycan be initializedasthe ordinaryvariables. Example:  intodd[3][2]={1,3,5,7,9,11};  Individual elementcanalsobe assignedas:  Odd[0][0]=1;  Odd[0][1]=3;  Odd[1][0]=5;  Odd[1][1]=7;  Odd[2][0]=9;  Odd[2][1]=11; Readingdatafrom the user: Nestedforloopisused. Example: #include<stdio.h> #include<conio.h> void main() { int m, n, p, q, c, d, k, sum = 0;
  • 6. 6 int first[10][10], second[10][10], multiply[10][10]; printf("Enter the number of rows and columns of first matrixn"); scanf("%d%d", &m, &n); printf("Enter the number of rows and columns of second matrixn"); scanf("%d%d", &p, &q); if (n != p) printf("Matrices with entered orders can't be multiplied with each other.n"); else { printf("Enter the elements of first matrixn"); for (c = 0; c < m; c++) { for (d = 0; d < n; d++) scanf("%d", &first[c][d]); } printf("Enter the elements of second matrixn"); for (c = 0; c < p; c++) { for (d = 0; d < q; d++) scanf("%d", &second[c][d]); } for (c = 0; c < m; c++) { for (d = 0; d < q; d++) { for (k = 0; k < p; k++) { sum = sum + first[c][k]*second[k][d]; } multiply[c][d] = sum; sum = 0; } } printf("Product of entered matrices:-n"); for (c = 0; c < m; c++) { for (d = 0; d < q; d++) { printf("%dt", multiply[c][d]); printf("n"); } } getch(); }
  • 7. 7 Multidimensional array A list of itemscan be givenone variable name usingmore than two subscript is calledmulti dimensional array. The exact limitis determinedbythe compiler. SYNTAX: data-type array_name[s1][s2][s3][s4][s5]……….[sm]; EXAMPLE: inta[3][4][5]; Dynamicarrays STATICARRAYS: The processof allocatingmemoryatcompile time isknownasstaticmemoryallocation and the arrays that receive staticmemoryallocationare calledstaticarrays. Dynamicarrays: The processof allocatingmemorytoarraysat runtime is knownasdynamicmemory allocationandthe arrays createdat run time are calleddynamicarrays. Dynamicarrays are createdusingpointervariablesandmemorymanagementfunctions malloc,callocandrealloc.Thesefunctionsare includedinthe headerfile<stdlib.h>.Thedynamicarraysis usedto create and manipulate datastructuressuchaslinkedlist,stackandqueues. Character Arrays & Strings Introduction A string is a sequence of characters. Any sequence or set of characters defined within double quotation symbols is a constant string. In c it is required to do some meaningful operations on strings they are:  Readingstringdisplayingstrings  Combiningorconcatenatingstrings  Copyingone stringtoanother.  Comparingstring& checkingwhethertheyare equal  Extractionof a portionof a string
  • 8. 8 Declaring & InitializingStringVariables char month1[ ]={‘j’,’a’,’n’,’u’,’a’,’r’,’y’}; Thenthe string monthisinitializing to January. This is perfectly valid but C offers a special way to initialize strings. The above string can be initialized as char month1[]=”January”; The characters of the stringare enclosedwithinapartof double quotes.The compilertakescare of stringenclosedwithina pair of double quotes. The compiler takes care of storing the ASCII codes of characters of the string in the memory and also stores the null terminator in the end. /*String.c string variable*/ #include < stdio.h > #include<conio.h> voidmain() { char month[15]; printf (“Enterthe string”); gets(month); printf (“The stringenteredis%s”,month); } 0 specifies a single character whose ASCII value is zero. J A N U A R Y 0 ? ? ? ? ? ? ? Character string terminated by a null character ‘0’. A string variable is any valid C variable name & is always declared as an array. syntax char string_name[size];
  • 9. 9 The size determines the number of characters in the string name. Example: char address[100]; The size of the array should be one byte more than the actual space occupied by the string since the complier appends a null character at the end of the string. Reading Strings from the terminal: The function scanf with%s format specification is needed to read the character string from the terminal. Example: char address[20]; scanf(“%s”,address); ->Scanf statement has a draw back it just terminates the statement as soon as it finds a blank space, suppose if we type the string new york then only the string new will be read and since there is a blank space after word “new” it will terminate the string. ->The function getchar can be used repeatedly to read a sequence of successive single characters and store it in the array. We cannotmanipulate stringssince Cdoesnotprovide anyoperatorsfor string. For instance we cannot assign one string to another directly. For example: String=”xyz”; String1=string; are notvalid.To copythe chars inone string to another string we may do so on a character to character basis.
  • 10. 10 Reading a Line of Text To read a line of text with white spaces, we have a special format specifier %[..] called “Edit set conversion code” that can be used to read a line containing a variety of characters. Example: To terminate a string only when a ‘n’ (New Line) character is inserted, we need to give the following statement: scanf(“%[^n]”,str); Here, str – string variable ^n – Describes terminate the reading when ‘n’ character is encountered Using getchar and gets Function getchar() function is used to read a single character from the terminal. By providing a loop to read characters until we provide a newline character, we are facilitating the reading of a line of text. Example: int c; char character; …. c = 0; do { character = getchar(); line[c++] = character; }while(character != ‘n’);
  • 11. 11 We may also use the gets() function present in <stdio.h> header file to read a line of text. It is in the form: gets(str); Example: char line[80]; gets(line); Writing Strings to Screen Using printf() function The format specifier %s can be used to display an array of characters that is terminated by null (0) character. Example:printf(“%s”, name); We can also specify the precision. Example: %10.4s Indicatesthatfirstfourcharacters are to be printedin a field width of 10 columns. Including a – (minus) sign immediately after the % symbol will print the content left-justified. For variable specification of width and precision, we use the * symbol. Example: printf(“%*.*s”,w,s,str); Using putchar() and puts() We can use the putchar() function repeatedly to print a string to the screen. Example: Void main() { char name[6] = “paris”; for(i=0;i<5;i++)
  • 12. 12 putchar(name[i]); putchar(‘n’); getch(); } Another convenient way of printing a string to screen is using puts() function present in <stdio.h>. Example: puts(line); Arithmetic operations on characters: We can alsomanipulate the charactersaswe manipulate numbersinclanguage.Whenever the system encountersthe character data it is automatically converted into a integer value by the system. We can represent a character as a interface by using the following method. x=’a’; Printf(“%dn”,x); Will display 97 on the screen. Arithmetic operations can also be performed on characters for example x=’z’-1; is a valid statement. The ASCII value of ‘z’ is 122 the statement the therefore will assign 121 to variable x. It is also possible to use character constants in relational expressions for example ch>’a’ && ch < = ’z’ will check whether the character stored in variable ch is a lower case letter. A character digit can also be converted into its equivalent integer value suppose un the expression Void main() { char character=’8’; int a; a=character-‘1’;
  • 13. 13 printf(“%d”,a); getch(); } where a is defined as an integer variable & character contains value 8 then a= ASCII value of 8 ASCII value ‘1’=56-49=7. We can also get the support of the c library function to converts a string of digits into their equivalent integer values the general format of the function in x=atoi(string); here x is an integervariable &stringis a character array containing string of digits. For example string=“101”; it will be stored as numeral 101 to x. Putting Strings Together We cannot apply the arithmetic addition for joining of two or more strings in the manner string1 = string2 + string3; or string1 = string2 + "SACY"; For carrying out the above we need to write a program to copy the contents of the string2 & string3 into string1 one after the other. This process is called concatenation of strings. strcat() Function strcat() joins two or more strings together. It takes the following form strcat(string1, string2); string1 and string2 are character arrays. When the above function is executed, string2 is appendedtostring1. It does so by removing the null character at the end of string1 and placing string2 from there. The string at string2 remains unchanged. strcat function may also append a string constant to a string variable. The following is valid
  • 14. 14 strcat(part1,"SACY"); C also permits nesting of strcat functions. For example strcat(strcat((string1,string2),string3); is allowed and concatenates all the three strings together. The resultant string is stored in string1. String Handling Functions C language recognizesthatstringisa differentclassof array bylettingusinput and output the array as a unitand are terminatedbynull character.Clibrarysupportsa large numberof string handling functions that can be used to array out many o f the string manipulations such as:  Length (number of characters in the string).  Concatentation (adding two are more strings)  Comparing two strings.  Substring (Extract substring from a given string)  Copy(copies one string over another) To do all the operations described here it is essential to include<string.h> library header file in the program. strlen() function: Thisfunctioncountsand returnsthe numberof charactersin a string.The lengthdoes not include a null character. Syntax: n=strlen(string); Where n is integer variable. Which receives the value of length of the string.
  • 15. 15 Example length=strlen(“Hollywood”); The function will assign number of characters 9 in the string to a integer variable length.Result is length=9. strcat() function: when you combine two strings, you add the characters of one string to the end of other string. This processiscalledconcatenation. The strcat() functionjoins2stringstogether.Ittakesthe following form strcat(string1,string2) string1 & string2 are character arrays. When the function strcat is executed string2 is appended to string1. the string at string2 remains unchanged. Example #include<stdio.h> #include<conio.h> #include<string.h> Void main() { strcpy(string1,”sri”); strcpy(string2,”Bhagavan”); Printf(“%s”,strcat(string1,string2); getch(); }
  • 16. 16 From the above program segment the value of string1 becomes sribhagavan. The string at str2 remains unchanged as bhagawan. Result string1= sribhagavan strcmp function: In c you cannot directly compare the value of 2 strings in a condition like: if(string1==string2) Most librarieshowevercontainthe strcmp() function,whichreturnsazeroif 2 strings are equal, or a non zero number if the strings are not the same. The syntax of strcmp() is given below: strcmp(string1,string2) String1 & string2may be stringvariablesorstringconstants.String1,& string2may be stringvariablesor stringconstants some computers return a negative if the string1 is alphabetically less than the second and a positive number if the string is greater than the second. Example: #include<stdio.h> #include<conio.h> #include<string.h> Void main() { strcmp(“Newyork”,”Newyork”);//will return zero because 2 strings are equal. strcmp(“their”,”therr”);//willreturna9 whichis the numeric difference between ASCII ‘i’ and ASCII ’r’. strcmp(“The”, “the”)// will return 32 which is the numeric difference between ASCII “T” & ASCII “t”. getch(); } strcmpi() function This function is same as strcmp() which compares 2 strings but not case sensitive.
  • 17. 17 Example : #include<stdio.h> #include<conio.h> #include<string.h> Void main() { strcmpi(“THE”,”the”);// will return 0. getch(); } strcpy() function: C does not allow you to assign the characters to a string directly as in the statement name=”Robert”; Insteaduse the strcpy(0functionfoundinmostcompilersthe syntax of the functionisillustratedbelow. strcpy(string1,string2); Strcpy function assigns the contents of string2 to string1. string2 may be a character array variable or a string constant. Example: #include<stdio.h> #include<conio.h> #include<string.h> Void main() { strcpy(Name,”Robert”); getch(); } In the above example Robert is assigned to the string called name. Result:Name=Robert.
  • 18. 18 Other string functions  strncpy//stringcopy  strncmp//stringcompare  strncat//stringconcatenation  strstr//findingsubstring strncpy//string copy Thisis three parameterfunctionandisinvokedasfollows. Syntax:strncpy(s1,s2,n); Example: #include<stdio.h> #include<conio.h> #include<string.h> Void main() { char s2=”ammukutti”; strncpy(s1,s2,5); s1[6]=’0’; printf(“%s”,s1); getch(); } Result:ammuk strncmp//string compare syntax:strncmp(s1,s2,n); thiscomparesleftmostn charactersof s1 and s2 andreturns. (a) 0 if theyare equal. (b) Negative number,ifs1 sub-stringislessthans2. (c) Positive numberotherwise negative number.
  • 19. 19 strncat//string concatenation syntax:strncat(s1,s2,n); Concatenate the leftmostncharacters of s2 to the endof s1. Example: #include<stdio.h> #include<conio.h> #include<string.h> Void main() { Char s1=”Bala”, s2=”ammukutti”; strncat(s1,s2,5); printf(“%s”,s1); getch(); } Result:Balaammuk. strstr//finding sub string It isa twoparameterfunctionthatcan be usedto locate a sub-stringina string. Syntax:strstr(s1,s2); Example: #include<stdio.h> #include<conio.h> #include<string.h> Void main() {
  • 20. 20 Char s1=”Abacus”, s2=”cus”; if(strstr(s1,s2)==NULL) printf(“substringisnotfound”); else printf(“s2isa substringof s1); getch(); } Strchr//determine the existence ofa first occurrence of character in a string Example: s1=”Mohamed”; strchr(s1,”M”); strrchr//last occurrence of character ina string Example: s1=”Mohamed”; strrchr(s1,”d”);