SlideShare a Scribd company logo
MODULE 4:ARRAYS AND
STRINGS
CO4. Demonstrate
the use of arrays,
strings and
structures in C
language.
CONTENTS
● Introduction to Arrays
● Declaration and initialization of one dimensional and two-
dimensional arrays.
● Definition and initialization of String
● String functions
INTRODUCTION TO ARRAYS
An array is a group of elements (data items) that have common
characteristics (eg numerical data, character data etc.,) and share a common
name. The elements of an array are differentiated from one another by their
positions within an array.
Each array element(i.e., each individual data item) is referred to by specifying
the array name followed by its subscript enclosed in square brackets.
The subscript indicates the position of the particular element with respect to
the rest of the elements.
The subscript must be a non negative integer.
For example, in the n element array , x, the array elements are
x[1],x[2],x[3],x[4],..........x[n-1],x[n];
and
1,2,......n are the subscripts x[i] refers to the ith element in a list of n
elements.
INTRODUCTION TO ARRAYS
Types of arrays
Single dimensional array
Multidimensional array
SINGLE DIMENSIONAL ARRAY
Declaration Of An Array
An array is declared in the same manner as ordinary variables, except
that each array name must be accompanied by a size specification.
This is necessary because the complier will have to know how much
memory to reserve for this array.
A single dimensional array is declared as follows :
type array_name[n];
where array_name is the name of an array of n elements of the type
specified. The size of an array must be an integer constant.
The integer array declaration
int x[100];
creates an array that is 100 elements along with the first element
being 0 and the last being 99.
SINGLE DIMENSIONAL ARRAY
The subscript used to declare an array is sometimes called a
dimension and the declaration for the
array is often referred to as dimensioning. The dimension used to
declare an array must always be a
positive integer constant, or an expression that can be evaluated to a
constant when the program is
compiled. It is sometimes convinient to define an array size in terms
of the symbolic constant. For
example, i[20]=1234;
SINGLE DIMENSIONAL ARRAY
An individual element in an array can be referred to by means of the
subscript, the number in brackets following the array name. A
subscript is the number that specifies the element’s position in an
array.
In the C language, subscript begins with zero. Thus, the valid
subscript value can be from 0 to n-1, if n is the dimension of the
array. The subscript value used to access an array element could
result from a subscription variable, a unary expression, a binary
expression etc. Thus, i[2] is not the second element of the array i but
the third.
SINGLE DIMENSIONAL ARRAY
int a[4];
INITIALIZING ARRAYS
An array can be initialized when declared by specifying the values of
some or all of its elements.
Arrays can be intialized at the time of declaration when their intial
values are known in advance.
The values to intialize an array must be constants never variables or
function calls. The array can be initialized as follows :
int array[5]={4,6,5,7,2};
float x[6]={0,0.25,0,-0.50,0,0};
When an integer array is declared as, int array[5]={4,6,5,7,2}; the
compiler will reserve ten contiguous bytes in memory to hold the five
integer elements as shown in the diagram below :
INITIALIZING ARRAYS
The array size need not be specified explicitly when intial values are
included as a part of an array declaration.
With a numerical array, the array size will automatically be set equal
to the number of initial values included within the declaration.
int digits[]={1,2,3,4,5,6};
float x[]={0,0.25,0,-0.5};
So digits will be a six-element integer array, and x will be a four-
element floating-point array. The individual elements will be assigned
the following values.
The example given below illustrates this point.
digits [0]=1;digits[1]=2;digits[2]=3;
digits[3]=4;digits[4]=5 ;digits[5]=6;
INITIALIZING ARRAYS
An array may also be intialized as follows : int
xyz[10]={78,23,67,56,87,76};
In the above array initialization, although the array size is 10, values
were defined only for the first six elements.
INITIALIZING ARRAYS
Example
int a[4]={4, 3, 2, 1};
/*Intializing and printing the value*/
INITIALIZING ARRAYS
#include<stdio.h>
int main()
{
int i,a[4]={4,3,2,1};
for(i=0;i<4;i++)
{
printf("a[%d]=%dn",i,a[i]);
printf("Address of a[%d] is %un",i,&a[i]);
}
return 0;
}
ARRAY OVERFLOW
It is illegal to access a non-existent element of the array. C does not
check for array overflow.
It is the programmers responsibility to ensure that any subscription
performed does not crosses the upper as well as the lower bounds of
the array.
int array[5];
array[5]=105; /* illegal as valid subscripting ends at array[4] */
In the above code, an attempt is made to move the binary value of
105 onto the 2 bytes that immediately follow the end of the array.
So when executing the assignment array[5]=105, some other
variables that the program uses are being overwritten.
PROCESSING AN ARRAY
If a and b are two similar arrays of the same data type, same
dimensions and same size then assignment operations and
comparison operations etc, must be carried out on an element-by-
element basis.
This is done within a loop, where each pass through the loop is used
to process an element of the array.
The number of passes through the loop will there for equal to the
number of array elements to be processed; and the value of the index
(subscript) would be incremented from 0 to n-1.
MULTIDIMENSIONAL ARRAYS
C as a language provides for arrays of arbitrary dimensions. A two
dimensional array of size m rows by n columns is declared as follows :
type array_name[m][n];
A two dimensional array, of type int, with 3 rows and 4 columns is
declared as follows
The array can be declared by passing values of number of rows and
number of columns as subscript values.
Example
int a[3][4];
INITIALIZING ARRAYS
The values can also be initialized by forming group of initial values
enclosed within braces.
The values within an inner pair of braces will be assigned to the
element of a row or all the values can be given in single braces
sequentially.
Example
int array[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};
Or
int array[3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
PROCESSING AN ARRAY
The array processing is done as in the one dimensional array.
Since it is a two dimensional array we may need two variable to keep
track and to process the data in the array.
CHARACTER ARRAYS (STRINGS)
C Strings are nothing but array of characters ended with null character (‘0’).
This null character indicates the end of the string.
Strings are always enclosed by double quotes.
Whereas, character is enclosed by single quotes in C.
char string[20] = {‘f’, ’r’, ‘e’, ‘s’, ‘h’, ‘2’, ‘r’, ‘e’, ‘f’, ’r’, ‘e’, ‘s’, ‘h’, ‘0’};
(or)
char string[20] = “fresh2refresh”;
(or)
char string [] = “fresh2refresh”;
Difference between above declarations are, when we declare char as
“string[20]”, 20 bytes of memory space is allocated for holding the string
value.
When we declare char as “string[]”, memory space will be allocated as per the
requirement during execution of the program.
CHARACTER ARRAYS (STRINGS)
Declaration Of An Array
Array declaration is also done as same as normal array except for the
specification of character data type.
Example
char a[5];
INITIALIZATION OF CHARACTER
ARRAYS
Character array can be initialized in two different ways.
Firstly, they may initialize in the same way as the numeric array are
initialized.
char a[5] = {'H','a','r','i','0'};
(i.e.) by specifying character constants for each of the values. When
initializing character by character,
the null character ('0') should also be specified.
Secondly, character array can also be initialized as follows,
char a[5] ="Hari";
This type of initialization will include a provision for null character,
which is automatically added at the end of the string.
PROCESSING A CHARACTER
ARRAY
Character arrays are different from the numerical array. The entire
character string can be entered from the terminal and placed in a
character array. Whereas numeric arrays can be input element by
element only.
Same is the case with output also. The entire string can be output
using printf() function whereas an integer array can be output
element by element only.
PROCESSING A CHARACTER
ARRAY
#include<stdio.h>
#include<string.h>
int main ()
{
char a[6] ="Nikhat";
printf ("Name=%sn",a);
}
PASSING STRINGS TO FUNCTION
As strings are character arrays, so we can pass strings to function in a
same way we pass an array to a function.
PASSING STRINGS TO FUNCTION
// C program to illustrate how to
// pass string to functions
#include<stdio.h>
void printStr(char str[])
{
printf("String is : %s",str);
}
int main()
{
// declare and initialize string
char str[] = “nikhat";
// print string by passing string
// to a different function
printStr(str);
return 0;
}
STRING FUNCTIONS
Include string.h library to your program to use some of the inbuilt
string manipulation functions present in the library.there are about
20-22 inbuilt string manipulating functions present in this library.
The most common functions used from the library are:
1. strlen("name of string")
2. strcpy( dest, source)
3. strcmp( string1, string2 )
4. strstr( str1, str2 )
Commonly Used String Functions
strlen() - calculates the length of a string
strcpy() - copies a string to another
strcmp() - compares two strings
strcat() - concatenates two strings
STRING FUNCTIONS
STRING FUNCTIONS
STRING FUNCTIONS
The strlen() function takes a string as an argument and returns
its length. The returned value is of type size_t (the unsigned
integer type).
It is defined in the <string.h> header file.
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = “nikhat";
printf("Length of string str1: %d", strlen(str1));
return 0;
}
STRING FUNCTIONS
strcmp()
int strcmp(const char *str1, const char *str2)
It compares the two strings and returns an integer value. If both
the strings are same (equal) then this function would return 0
otherwise it may return a negative or positive value based on the
comparison.
If string1 < string2 OR string1 is a substring of string2 then it
would result in a negative value. If string1 > string2 then it
would return positive value.
If string1 == string2 then you would get 0(zero) when you use
this function for compare strings.
STRING FUNCTIONS
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = “nikhat";
char s2[20] = “shaikh";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
STRING FUNCTIONS
Return value
- if Return value if < 0 then it indicates str1 is less than str2
- if Return value if > 0 then it indicates str2 is less than str1
- if Return value if = 0 then it indicates str1 is equal to str2
STRING FUNCTIONS
strcat()
char *strcat(char *str1, char *str2)
It concatenates two strings and returns the concatenated string.
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}
STRING FUNCTIONS
strcpy()
char *strcpy( char *str1, char *str2)
It copies the string str2 into string str1, including the end character
(terminator char ‘0’).
#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}
STRING FUNCTIONS
strstr(str1, str2)
This library function finds the first occurrence of the substring str2 in
the string str1. The terminating '0' character is not compared.
strstr( str1, str2);
- str1: the main string to be scanned.
- str2: the small string to be searched in str1
This function is very useful in checking whether str2 is a substring of str1 or
not.
Return value
This function returns a pointer to the first occurrence in str1 of any of the
entire sequence of characters specified in str2, or a NULL pointer if the
sequence is not present in str1.
.
STRING FUNCTIONS
#include<stdio.h>
#include<string.h>
int main ()
{
char str1[55] ="This is a test string for testing";
char str2[20]="test";
char *p;
p = strstr (str1, str2);
if(p)
{
printf("string foundn" ); //i.e str2 is a substring of str1.
printf ("First occurrence of string "test" in "%s" is" " "%s"",str1, p);
}
else
printf("string not foundn" ); // str2 is not a substring of str1.
return 0;
}

More Related Content

What's hot (20)

PPTX
Operators in C Programming
Qazi Shahzad Ali
 
PPT
Constants in C Programming
programming9
 
PDF
Lecture02(constants, variable & data types)
Dhaka University of Engineering & Technology(DUET)
 
PPTX
Data Types and Variables In C Programming
Kamal Acharya
 
PPTX
Data types
Zahid Hussain
 
PPS
C programming session 04
Dushmanta Nath
 
PPTX
arrays and pointers
Samiksha Pun
 
PPT
constants, variables and datatypes in C
Sahithi Naraparaju
 
PDF
Arrays-Computer programming
nmahi96
 
PPTX
Introduction to C Programming - R.D.Sivakumar
Sivakumar R D .
 
PPT
Ch6 pointers (latest)
Hattori Sidek
 
PDF
Strings in c mrs.sowmya jyothi
Sowmya Jyothi
 
PPT
Ch7 structures
Hattori Sidek
 
PPTX
Constant, variables, data types
Pratik Devmurari
 
PPTX
What is identifier c programming
Rumman Ansari
 
PPT
pointer, structure ,union and intro to file handling
Rai University
 
PPSX
Getting started with c++.pptx
Akash Baruah
 
PPT
structure and union
student
 
PDF
Strings-Computer programming
nmahi96
 
PPTX
function, storage class and array and strings
Rai University
 
Operators in C Programming
Qazi Shahzad Ali
 
Constants in C Programming
programming9
 
Lecture02(constants, variable & data types)
Dhaka University of Engineering & Technology(DUET)
 
Data Types and Variables In C Programming
Kamal Acharya
 
Data types
Zahid Hussain
 
C programming session 04
Dushmanta Nath
 
arrays and pointers
Samiksha Pun
 
constants, variables and datatypes in C
Sahithi Naraparaju
 
Arrays-Computer programming
nmahi96
 
Introduction to C Programming - R.D.Sivakumar
Sivakumar R D .
 
Ch6 pointers (latest)
Hattori Sidek
 
Strings in c mrs.sowmya jyothi
Sowmya Jyothi
 
Ch7 structures
Hattori Sidek
 
Constant, variables, data types
Pratik Devmurari
 
What is identifier c programming
Rumman Ansari
 
pointer, structure ,union and intro to file handling
Rai University
 
Getting started with c++.pptx
Akash Baruah
 
structure and union
student
 
Strings-Computer programming
nmahi96
 
function, storage class and array and strings
Rai University
 

Similar to Module 4- Arrays and Strings (20)

DOC
Arrays and Strings
Dr.Subha Krishna
 
PPTX
MODUL new hlgjg thaybkhvnghgpv7E_02.pptx
lomic31750
 
PPTX
Arrays & Strings
Munazza-Mah-Jabeen
 
PPTX
C Programming Unit-3
Vikram Nandini
 
PPTX
c unit programming arrays in detail 3.pptx
anithaviyyapu237
 
PDF
Unit ii data structure-converted
Shri Shankaracharya College, Bhilai,Junwani
 
PDF
Unit 2
TPLatchoumi
 
PPS
C programming session 05
Vivek Singh
 
PPTX
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
AntareepMajumder
 
PPT
Basics of Data structure using C describing basics concepts
shanthidl1
 
PPTX
Chapter 13.pptx
AnisZahirahAzman
 
PPT
Lecture 15 Arrays with C++ programming.ppt
SamahAdel16
 
PPT
Array THE DATA STRUCTURE. ITS THE STRUCT
duttasoumyajit5
 
PDF
Array&amp;string
chanchal ghosh
 
PDF
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
PPTX
3.ArraysandPointers.pptx
FolkAdonis
 
DOCX
C UNIT-3 PREPARED BY M V B REDDY
Rajeshkumar Reddy
 
PPTX
Arrays in c
Jeeva Nanthini
 
PDF
Introduction to Arrays in C
Thesis Scientist Private Limited
 
Arrays and Strings
Dr.Subha Krishna
 
MODUL new hlgjg thaybkhvnghgpv7E_02.pptx
lomic31750
 
Arrays & Strings
Munazza-Mah-Jabeen
 
C Programming Unit-3
Vikram Nandini
 
c unit programming arrays in detail 3.pptx
anithaviyyapu237
 
Unit ii data structure-converted
Shri Shankaracharya College, Bhilai,Junwani
 
Unit 2
TPLatchoumi
 
C programming session 05
Vivek Singh
 
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
AntareepMajumder
 
Basics of Data structure using C describing basics concepts
shanthidl1
 
Chapter 13.pptx
AnisZahirahAzman
 
Lecture 15 Arrays with C++ programming.ppt
SamahAdel16
 
Array THE DATA STRUCTURE. ITS THE STRUCT
duttasoumyajit5
 
Array&amp;string
chanchal ghosh
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
3.ArraysandPointers.pptx
FolkAdonis
 
C UNIT-3 PREPARED BY M V B REDDY
Rajeshkumar Reddy
 
Arrays in c
Jeeva Nanthini
 
Introduction to Arrays in C
Thesis Scientist Private Limited
 
Ad

More from nikshaikh786 (20)

PPTX
Module 2_ Divide and Conquer Approach.pptx
nikshaikh786
 
PPTX
Module 1_ Introduction.pptx
nikshaikh786
 
PPTX
Module 1_ Introduction to Mobile Computing.pptx
nikshaikh786
 
PPTX
Module 2_ GSM Mobile services.pptx
nikshaikh786
 
PPTX
MODULE 4_ CLUSTERING.pptx
nikshaikh786
 
PPTX
MODULE 5 _ Mining frequent patterns and associations.pptx
nikshaikh786
 
PDF
DWM-MODULE 6.pdf
nikshaikh786
 
PDF
TCS MODULE 6.pdf
nikshaikh786
 
PPTX
Module 3_ Classification.pptx
nikshaikh786
 
PPTX
Module 2_ Introduction to Data Mining, Data Exploration and Data Pre-processi...
nikshaikh786
 
PPTX
Module 1_Data Warehousing Fundamentals.pptx
nikshaikh786
 
PPTX
Module 2_ Cyber offenses & Cybercrime.pptx
nikshaikh786
 
PPTX
Module 1- Introduction to Cybercrime.pptx
nikshaikh786
 
PPTX
MODULE 5- EDA.pptx
nikshaikh786
 
PPTX
MODULE 4-Text Analytics.pptx
nikshaikh786
 
PPTX
Module 3 - Time Series.pptx
nikshaikh786
 
PPTX
Module 2_ Regression Models..pptx
nikshaikh786
 
PPTX
MODULE 1_Introduction to Data analytics and life cycle..pptx
nikshaikh786
 
PPTX
IOE MODULE 6.pptx
nikshaikh786
 
PDF
MAD&PWA VIVA QUESTIONS.pdf
nikshaikh786
 
Module 2_ Divide and Conquer Approach.pptx
nikshaikh786
 
Module 1_ Introduction.pptx
nikshaikh786
 
Module 1_ Introduction to Mobile Computing.pptx
nikshaikh786
 
Module 2_ GSM Mobile services.pptx
nikshaikh786
 
MODULE 4_ CLUSTERING.pptx
nikshaikh786
 
MODULE 5 _ Mining frequent patterns and associations.pptx
nikshaikh786
 
DWM-MODULE 6.pdf
nikshaikh786
 
TCS MODULE 6.pdf
nikshaikh786
 
Module 3_ Classification.pptx
nikshaikh786
 
Module 2_ Introduction to Data Mining, Data Exploration and Data Pre-processi...
nikshaikh786
 
Module 1_Data Warehousing Fundamentals.pptx
nikshaikh786
 
Module 2_ Cyber offenses & Cybercrime.pptx
nikshaikh786
 
Module 1- Introduction to Cybercrime.pptx
nikshaikh786
 
MODULE 5- EDA.pptx
nikshaikh786
 
MODULE 4-Text Analytics.pptx
nikshaikh786
 
Module 3 - Time Series.pptx
nikshaikh786
 
Module 2_ Regression Models..pptx
nikshaikh786
 
MODULE 1_Introduction to Data analytics and life cycle..pptx
nikshaikh786
 
IOE MODULE 6.pptx
nikshaikh786
 
MAD&PWA VIVA QUESTIONS.pdf
nikshaikh786
 
Ad

Recently uploaded (20)

PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 

Module 4- Arrays and Strings

  • 1. MODULE 4:ARRAYS AND STRINGS CO4. Demonstrate the use of arrays, strings and structures in C language.
  • 2. CONTENTS ● Introduction to Arrays ● Declaration and initialization of one dimensional and two- dimensional arrays. ● Definition and initialization of String ● String functions
  • 3. INTRODUCTION TO ARRAYS An array is a group of elements (data items) that have common characteristics (eg numerical data, character data etc.,) and share a common name. The elements of an array are differentiated from one another by their positions within an array. Each array element(i.e., each individual data item) is referred to by specifying the array name followed by its subscript enclosed in square brackets. The subscript indicates the position of the particular element with respect to the rest of the elements. The subscript must be a non negative integer. For example, in the n element array , x, the array elements are x[1],x[2],x[3],x[4],..........x[n-1],x[n]; and 1,2,......n are the subscripts x[i] refers to the ith element in a list of n elements.
  • 4. INTRODUCTION TO ARRAYS Types of arrays Single dimensional array Multidimensional array
  • 5. SINGLE DIMENSIONAL ARRAY Declaration Of An Array An array is declared in the same manner as ordinary variables, except that each array name must be accompanied by a size specification. This is necessary because the complier will have to know how much memory to reserve for this array. A single dimensional array is declared as follows : type array_name[n]; where array_name is the name of an array of n elements of the type specified. The size of an array must be an integer constant. The integer array declaration int x[100]; creates an array that is 100 elements along with the first element being 0 and the last being 99.
  • 6. SINGLE DIMENSIONAL ARRAY The subscript used to declare an array is sometimes called a dimension and the declaration for the array is often referred to as dimensioning. The dimension used to declare an array must always be a positive integer constant, or an expression that can be evaluated to a constant when the program is compiled. It is sometimes convinient to define an array size in terms of the symbolic constant. For example, i[20]=1234;
  • 7. SINGLE DIMENSIONAL ARRAY An individual element in an array can be referred to by means of the subscript, the number in brackets following the array name. A subscript is the number that specifies the element’s position in an array. In the C language, subscript begins with zero. Thus, the valid subscript value can be from 0 to n-1, if n is the dimension of the array. The subscript value used to access an array element could result from a subscription variable, a unary expression, a binary expression etc. Thus, i[2] is not the second element of the array i but the third.
  • 9. INITIALIZING ARRAYS An array can be initialized when declared by specifying the values of some or all of its elements. Arrays can be intialized at the time of declaration when their intial values are known in advance. The values to intialize an array must be constants never variables or function calls. The array can be initialized as follows : int array[5]={4,6,5,7,2}; float x[6]={0,0.25,0,-0.50,0,0}; When an integer array is declared as, int array[5]={4,6,5,7,2}; the compiler will reserve ten contiguous bytes in memory to hold the five integer elements as shown in the diagram below :
  • 10. INITIALIZING ARRAYS The array size need not be specified explicitly when intial values are included as a part of an array declaration. With a numerical array, the array size will automatically be set equal to the number of initial values included within the declaration. int digits[]={1,2,3,4,5,6}; float x[]={0,0.25,0,-0.5}; So digits will be a six-element integer array, and x will be a four- element floating-point array. The individual elements will be assigned the following values. The example given below illustrates this point. digits [0]=1;digits[1]=2;digits[2]=3; digits[3]=4;digits[4]=5 ;digits[5]=6;
  • 11. INITIALIZING ARRAYS An array may also be intialized as follows : int xyz[10]={78,23,67,56,87,76}; In the above array initialization, although the array size is 10, values were defined only for the first six elements.
  • 12. INITIALIZING ARRAYS Example int a[4]={4, 3, 2, 1}; /*Intializing and printing the value*/
  • 13. INITIALIZING ARRAYS #include<stdio.h> int main() { int i,a[4]={4,3,2,1}; for(i=0;i<4;i++) { printf("a[%d]=%dn",i,a[i]); printf("Address of a[%d] is %un",i,&a[i]); } return 0; }
  • 14. ARRAY OVERFLOW It is illegal to access a non-existent element of the array. C does not check for array overflow. It is the programmers responsibility to ensure that any subscription performed does not crosses the upper as well as the lower bounds of the array. int array[5]; array[5]=105; /* illegal as valid subscripting ends at array[4] */ In the above code, an attempt is made to move the binary value of 105 onto the 2 bytes that immediately follow the end of the array. So when executing the assignment array[5]=105, some other variables that the program uses are being overwritten.
  • 15. PROCESSING AN ARRAY If a and b are two similar arrays of the same data type, same dimensions and same size then assignment operations and comparison operations etc, must be carried out on an element-by- element basis. This is done within a loop, where each pass through the loop is used to process an element of the array. The number of passes through the loop will there for equal to the number of array elements to be processed; and the value of the index (subscript) would be incremented from 0 to n-1.
  • 16. MULTIDIMENSIONAL ARRAYS C as a language provides for arrays of arbitrary dimensions. A two dimensional array of size m rows by n columns is declared as follows : type array_name[m][n]; A two dimensional array, of type int, with 3 rows and 4 columns is declared as follows The array can be declared by passing values of number of rows and number of columns as subscript values. Example int a[3][4];
  • 17. INITIALIZING ARRAYS The values can also be initialized by forming group of initial values enclosed within braces. The values within an inner pair of braces will be assigned to the element of a row or all the values can be given in single braces sequentially. Example int array[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}}; Or int array[3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
  • 18. PROCESSING AN ARRAY The array processing is done as in the one dimensional array. Since it is a two dimensional array we may need two variable to keep track and to process the data in the array.
  • 19. CHARACTER ARRAYS (STRINGS) C Strings are nothing but array of characters ended with null character (‘0’). This null character indicates the end of the string. Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in C. char string[20] = {‘f’, ’r’, ‘e’, ‘s’, ‘h’, ‘2’, ‘r’, ‘e’, ‘f’, ’r’, ‘e’, ‘s’, ‘h’, ‘0’}; (or) char string[20] = “fresh2refresh”; (or) char string [] = “fresh2refresh”; Difference between above declarations are, when we declare char as “string[20]”, 20 bytes of memory space is allocated for holding the string value. When we declare char as “string[]”, memory space will be allocated as per the requirement during execution of the program.
  • 20. CHARACTER ARRAYS (STRINGS) Declaration Of An Array Array declaration is also done as same as normal array except for the specification of character data type. Example char a[5];
  • 21. INITIALIZATION OF CHARACTER ARRAYS Character array can be initialized in two different ways. Firstly, they may initialize in the same way as the numeric array are initialized. char a[5] = {'H','a','r','i','0'}; (i.e.) by specifying character constants for each of the values. When initializing character by character, the null character ('0') should also be specified. Secondly, character array can also be initialized as follows, char a[5] ="Hari"; This type of initialization will include a provision for null character, which is automatically added at the end of the string.
  • 22. PROCESSING A CHARACTER ARRAY Character arrays are different from the numerical array. The entire character string can be entered from the terminal and placed in a character array. Whereas numeric arrays can be input element by element only. Same is the case with output also. The entire string can be output using printf() function whereas an integer array can be output element by element only.
  • 23. PROCESSING A CHARACTER ARRAY #include<stdio.h> #include<string.h> int main () { char a[6] ="Nikhat"; printf ("Name=%sn",a); }
  • 24. PASSING STRINGS TO FUNCTION As strings are character arrays, so we can pass strings to function in a same way we pass an array to a function.
  • 25. PASSING STRINGS TO FUNCTION // C program to illustrate how to // pass string to functions #include<stdio.h> void printStr(char str[]) { printf("String is : %s",str); } int main() { // declare and initialize string char str[] = “nikhat"; // print string by passing string // to a different function printStr(str); return 0; }
  • 26. STRING FUNCTIONS Include string.h library to your program to use some of the inbuilt string manipulation functions present in the library.there are about 20-22 inbuilt string manipulating functions present in this library. The most common functions used from the library are: 1. strlen("name of string") 2. strcpy( dest, source) 3. strcmp( string1, string2 ) 4. strstr( str1, str2 ) Commonly Used String Functions strlen() - calculates the length of a string strcpy() - copies a string to another strcmp() - compares two strings strcat() - concatenates two strings
  • 29. STRING FUNCTIONS The strlen() function takes a string as an argument and returns its length. The returned value is of type size_t (the unsigned integer type). It is defined in the <string.h> header file. #include <stdio.h> #include <string.h> int main() { char str1[20] = “nikhat"; printf("Length of string str1: %d", strlen(str1)); return 0; }
  • 30. STRING FUNCTIONS strcmp() int strcmp(const char *str1, const char *str2) It compares the two strings and returns an integer value. If both the strings are same (equal) then this function would return 0 otherwise it may return a negative or positive value based on the comparison. If string1 < string2 OR string1 is a substring of string2 then it would result in a negative value. If string1 > string2 then it would return positive value. If string1 == string2 then you would get 0(zero) when you use this function for compare strings.
  • 31. STRING FUNCTIONS #include <stdio.h> #include <string.h> int main() { char s1[20] = “nikhat"; char s2[20] = “shaikh"; if (strcmp(s1, s2) ==0) { printf("string 1 and string 2 are equal"); }else { printf("string 1 and 2 are different"); } return 0; }
  • 32. STRING FUNCTIONS Return value - if Return value if < 0 then it indicates str1 is less than str2 - if Return value if > 0 then it indicates str2 is less than str1 - if Return value if = 0 then it indicates str1 is equal to str2
  • 33. STRING FUNCTIONS strcat() char *strcat(char *str1, char *str2) It concatenates two strings and returns the concatenated string. #include <stdio.h> #include <string.h> int main() { char s1[10] = "Hello"; char s2[10] = "World"; strcat(s1,s2); printf("Output string after concatenation: %s", s1); return 0; }
  • 34. STRING FUNCTIONS strcpy() char *strcpy( char *str1, char *str2) It copies the string str2 into string str1, including the end character (terminator char ‘0’). #include <stdio.h> #include <string.h> int main() { char s1[30] = "string 1"; char s2[30] = "string 2 : I’m gonna copied into s1"; /* this function has copied s2 into s1*/ strcpy(s1,s2); printf("String s1 is: %s", s1); return 0; }
  • 35. STRING FUNCTIONS strstr(str1, str2) This library function finds the first occurrence of the substring str2 in the string str1. The terminating '0' character is not compared. strstr( str1, str2); - str1: the main string to be scanned. - str2: the small string to be searched in str1 This function is very useful in checking whether str2 is a substring of str1 or not. Return value This function returns a pointer to the first occurrence in str1 of any of the entire sequence of characters specified in str2, or a NULL pointer if the sequence is not present in str1. .
  • 36. STRING FUNCTIONS #include<stdio.h> #include<string.h> int main () { char str1[55] ="This is a test string for testing"; char str2[20]="test"; char *p; p = strstr (str1, str2); if(p) { printf("string foundn" ); //i.e str2 is a substring of str1. printf ("First occurrence of string "test" in "%s" is" " "%s"",str1, p); } else printf("string not foundn" ); // str2 is not a substring of str1. return 0; }