SlideShare a Scribd company logo
1 of 36
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

Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C ProgrammingQazi Shahzad Ali
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programmingprogramming9
 
Data Types and Variables In C Programming
Data Types and Variables In C ProgrammingData Types and Variables In C Programming
Data Types and Variables In C ProgrammingKamal Acharya
 
C programming session 04
C programming session 04C programming session 04
C programming session 04Dushmanta Nath
 
arrays and pointers
arrays and pointersarrays and pointers
arrays and pointersSamiksha Pun
 
constants, variables and datatypes in C
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in CSahithi Naraparaju
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programmingnmahi96
 
Introduction to C Programming - R.D.Sivakumar
Introduction to C Programming -  R.D.SivakumarIntroduction to C Programming -  R.D.Sivakumar
Introduction to C Programming - R.D.SivakumarSivakumar R D .
 
Ch6 pointers (latest)
Ch6 pointers (latest)Ch6 pointers (latest)
Ch6 pointers (latest)Hattori Sidek
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiSowmya Jyothi
 
Constant, variables, data types
Constant, variables, data typesConstant, variables, data types
Constant, variables, data typesPratik Devmurari
 
What is identifier c programming
What is identifier c programmingWhat is identifier c programming
What is identifier c programmingRumman Ansari
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingRai University
 
Getting started with c++.pptx
Getting started with c++.pptxGetting started with c++.pptx
Getting started with c++.pptxAkash Baruah
 
structure and union
structure and unionstructure and union
structure and unionstudent
 
Strings-Computer programming
Strings-Computer programmingStrings-Computer programming
Strings-Computer programmingnmahi96
 
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 stringsRai University
 

What's hot (20)

Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
 
Lecture02(constants, variable & data types)
Lecture02(constants, variable & data types)Lecture02(constants, variable & data types)
Lecture02(constants, variable & data types)
 
Data Types and Variables In C Programming
Data Types and Variables In C ProgrammingData Types and Variables In C Programming
Data Types and Variables In C Programming
 
Data types
Data typesData types
Data types
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
 
arrays and pointers
arrays and pointersarrays and pointers
arrays and pointers
 
constants, variables and datatypes in C
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in C
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programming
 
Introduction to C Programming - R.D.Sivakumar
Introduction to C Programming -  R.D.SivakumarIntroduction to C Programming -  R.D.Sivakumar
Introduction to C Programming - R.D.Sivakumar
 
Ch6 pointers (latest)
Ch6 pointers (latest)Ch6 pointers (latest)
Ch6 pointers (latest)
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothi
 
Ch7 structures
Ch7 structuresCh7 structures
Ch7 structures
 
Constant, variables, data types
Constant, variables, data typesConstant, variables, data types
Constant, variables, data types
 
What is identifier c programming
What is identifier c programmingWhat is identifier c programming
What is identifier c programming
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Getting started with c++.pptx
Getting started with c++.pptxGetting started with c++.pptx
Getting started with c++.pptx
 
structure and union
structure and unionstructure and union
structure and union
 
Strings-Computer programming
Strings-Computer programmingStrings-Computer programming
Strings-Computer programming
 
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
 

Similar to Module 4- Arrays and Strings (20)

C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
Array
ArrayArray
Array
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
3.ArraysandPointers.pptx
3.ArraysandPointers.pptx3.ArraysandPointers.pptx
3.ArraysandPointers.pptx
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
Arrays
ArraysArrays
Arrays
 
Chapter 13.1.7
Chapter 13.1.7Chapter 13.1.7
Chapter 13.1.7
 
Unit 2
Unit 2Unit 2
Unit 2
 
Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
 
2 arrays
2   arrays2   arrays
2 arrays
 
Array&amp;string
Array&amp;stringArray&amp;string
Array&amp;string
 
Array &strings
Array &stringsArray &strings
Array &strings
 
Arrays
ArraysArrays
Arrays
 
Arrays In C
Arrays In CArrays In C
Arrays In C
 
C UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDYC UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDY
 
ARRAYS
ARRAYSARRAYS
ARRAYS
 
Chapter-Five.pptx
Chapter-Five.pptxChapter-Five.pptx
Chapter-Five.pptx
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 

More from nikshaikh786

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

More from nikshaikh786 (20)

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

Recently uploaded

Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxabhijeetpadhi001
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 

Recently uploaded (20)

Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptx
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 

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; }