SlideShare a Scribd company logo
1 of 66
ARRAYS & STRING
OPERATIONS
1
Instructor
Dhiviya Rose J , AP-Sr. Scale | SoCSE
Recap
2
Variables Vs Array
3
int a,b;
a=10;
b=20;
c=30;
int marks[5];
marks[0]=51;
marks[1]=62;
marks[2]=43;
marks[3]=74;
marks[4]=55;
Index
Definition of Arrays.
Types of Arrays (1-D and 2-D)
1-D Arrays:
-Array Declaration.
-Accessing Elements of an array.
-Entering Data into an array.
-Reading data from an array.
-Array Initialization.
-Array Elements in Memory.
4
Introduction
• Arrays
• Structures of related data items
• Static entity – same size throughout program
• Derived data types
• Group of consecutive memory locations
• Same name and data type
5
• To refer to an element, specify
▫ Array name
▫ Position number/ Index
• Format:
arrayname[ position number ]
▫ First element at position 0
▫ n element array named c:
 c[ 0 ], c[ 1 ]...c[ n – 1 ]
6
Name of array
(All elements of
the array have
the same name, c)
Position number
or Index of the
element within
array c
c[6]
-45
6
0
72
1543
-89
0
62
-3
1
6453
78
c[0]
c[1]
c[2]
c[3]
c[11]
c[10]
c[9]
c[8]
c[7]
c[5]
c[4]
7
int marks[5];
marks[0]=51;
marks[1]=62;
marks[2]=43;
marks[3]=74;
marks[4]=55;
Array Name= ?
Array Size=?
Index Range=?
No of Elements in the Array=?
Characteristics of Array
8
• Array elements are like normal variables
c[0] = 3;
printf( "%d", c[0] );
▫ Perform operations in subscript.
c[0] = 10;
C[1] = 20;
C[2] = c[0] + c[1]
printf( “%d”, c[2] );
9
Types of Arrays
• One Dimensional Array (1D)
• Two Dimensional Array (2D)
• Multi Dimensional Array
10
Declaring Arrays – 1D
• When declaring arrays, specify
• Name
• Type of array
• Number of elements
arrayType arrayName[ numberOfElements ];
• Examples:
int c[10];
float myArray[20];
11
Initializing Arrays – 1D
• Initializers
int n[5] = { 1, 2, 3, 4, 5 };
▫ If not enough initializers, rightmost elements become 0
int n[ 5 ] = { 0 }
 All elements 0
▫ If too many a syntax error is produced syntax error
▫ C arrays have no bounds checking
• If size omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
▫ 5 initializers, therefore 5 element array
12
Initializing at Run time - scanf
void main()
{
int ans,myarr[2];
printf(“Enter the myarr[0]”);
scanf(“%d”,&myarr[0];
printf(“Enter the myarr[1]”);
scanf(“%d”,&myarr[1];
ans=myarr[0]+myarr[1];
printf(“The added answer is %d”,ans);
}
13
Accessing elements array using for– 1D
14
MULTI DIMENTIONALARRAY
15
Problem – Data Type???
• Class of 4 students
• Each student has 4 test scores
17
?????????????
Name varies……..
Instead of A[7]
given as A[2][0]
Solution( C Program representation)
• Represents this information in a two-dimensional array in
C program
• First dimension - student
• which student 0, 1, 2, 3
• Second dimension - marks
• which test score 0, 1, 2,3
18
19
Student 1
Student 2
Student 3
Student 4
M1 M2 M3 M3
Declaring a 2D Array
• Example:
int grades[4][4];
Creating a 2D Array
• Create array elements by telling how many ROWS and COLUMNS
• Example:
int grades[4][4];
• grades is a two-dimensional array,
• 4 rows and 4 columns
• One row for each student. One column for each test.
C arrays are row major, which means that we always refer to the row first.
Initializing Elements
// First student scores
grades[0][0] = 78;
grades[0][1] = 83;
grades[0][2] = 82;
Write assignment statements to fill-in the rest of the
array.
Declaration & Initialize 2D Arrays
• Example:
int grades[3][3] ={ { 78, 83, 82 },{ 90, 88, 94 },
{ 71, 73, 78 } };
• A Two-D Array is an array of arrays.
• Each row is itself a One-D array.
Multiple-Dimentional Arrays
• Initialization
• int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
• Initializers grouped by row in braces
• If not enough, unspecified elements set to zero
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
• Referencing elements
• Row Specific & Column Specific
• Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );
24
1 2
3 4
1 0
3 4
Row, Column Indices
78 83 82
90 88 94
71 73 78
97 96 95
89 93 90
Give both the ROW and COLUMN indices to pick out an individual element.
The fourth student’s third test score is at ROW 3, COLUMN 2
0
1
2
3
4
0 1 2
Exercise: Average Overall
• Find the average test score of all students’ test scores.
• Get the marks from the user
• Array name grades[4][4]
Exercise: Average Overall
int sum = 0;
int r,c;
for(r = 0; r < 4; r++)
for(c = 0; c < 4; c++)
sum = sum + grades[r][c];
Exercise:
Maximum Element in Matrix
Find maximum in a 2D array
max = matrix[0][0];
for(int i = 0; i < r; i++)
for(int j = 0; j < c; j++)
if ( matrix[i][j] > max)
max = matrix[i][j];
Searching Arrays: Linear Search and
Binary Search
• Search an array for a key value
• Linear search
• Simple
• Compare each element of array with key value
• Useful for small and unsorted arrays
30
Linear Search
• Step through array of records, one at a time.
• Look for record with matching key.
• Search stops when
• record with matching key is found
• or when search has examined all records without success.
How Linear Search works
32
33
Case 1: Target
found
34
Case 1: Target NOT
found
Program
#include<stdio.h>
void main()
{
int a[10],i,target;
printf("Enter array value n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Which value to be search ->");
scanf("%d",&target);
/* Linear Search logic */
for(i=0;i<n;i++)
if(target==a[i])
{
printf(“Value found at %d”,i);
}
}
35
Advantages of Linear Search
• Don't have to sort the data we search.
• Works well if only search operation is minimum
• Not optimal in case of large amount of data
36
Binary Search
• Assume that we are give an array of records that is
sorted. For instance:
• an array of records with integer keys sorted from smallest to largest
(e.g., ID numbers), or
• an array of records with string keys sorted in alphabetical order
(e.g., names).
Binary Search
[ 0 ] [ 1 ]
Example: sorted array of integer keys. Target=7.
3 6 7 11 32 33 53
[ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ]
39
Binary Search Pseudocode
…
if(size == 0)
found = false;
else {
middle = index of approximate midpoint of array segment;
if(target == a[middle])
target has been found!
else if(target < a[middle])
search for target in area before midpoint;
else
search for target in area after midpoint;
}
…
Program
int result=-1;
int low=0;
int high=length-1;
int mid;
while( result==-1 && low<=high )
{ mid= low + ((high - low) / 2);
if( list[mid] == target )
result = mid;
else if( list[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
41
Other Searching Algorithms
• Interpolation Search
• Indexed Searching
• Binary Search Trees
• Hash Table Searching
• Grover's Algorithm
• Best-first
• A*
42
Sorting Arrays
▫ Important computing application
▫ Arrange in some order
▫ Sorting done to make searching easier
Sorting: an operation that segregates items into groups
according to specified criterion.
A = { 3 1 6 2 1 3 4 5 9 0 }
A = { 0 1 1 2 3 3 4 5 6 9 }
• The "simple" sorting algorithms are
• bubble sort
• selection sort
43
Bubble Sort
• Several passes through the array
• Successive pairs of elements are compared
 If increasing order (or identical ), no change
 If decreasing order, elements exchanged
▫ Repeat
44
45
5 elements
….
4 pass
…..
5th pass all sorted
46
Program
/* Bubble sorting begins */
for (i = 0; i < num; i++)
{
for (j = 0; j < (num - i - 1); j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
} } }
47
SELECTION SORT
• improves on the bubble sort
• only one exchange for every pass through the array
Working Principle
• looks for the smallest value/largest value as it makes a
pass
• after each pass, the smallest item/largest item is in the
correct place.
48
How it works
49
Other Sorting Algorithms
● Bubble Sort
● Selection Sort
● Insertion Sort
● Merge Sort
● Shell Sort
● Heap Sort
● Quick Sort
● Radix Sort
● Swap Sort
51
STRING & ITS OPERATIONS
52
Definition
• A sequence of characters is often referred to
as a character “string”.
• No explicit type, instead strings are maintained
as arrays of characters
• Representing strings in C
• stored in arrays of characters
• array can be of any length
• end of string is indicated by a delimiter, the zero
character ‘0’
Character Vs Strings
Will be
considered as
string
Will be
considered as
character array
char myarr[]={‘h’,’e’,’l’,’l’,’o’,’0’}; char myarr[]={‘h’,’e’,’l’,’l’,’o’};
String Declaration & Initialization
• A string constant is a sequence of characters enclosed in
double quotes.
char a[10]=“Hello”;
Or
char *colorPtr = "blue";
pointer
String Input
• Use %s field specification in scanf to read string
• Example:
char myarr[11];
scanf(“%s”,myarr);
56
Only the
name of the
string
Example
#include <stdio.h>
void main()
{
char LName[10];
char FName[10];
printf("Enter your name : ");
scanf("%s %s",LName,FName);
printf("Nice to meet you %s %sn“,FName,LName);
}
57
String Functions
• string functions are used for performing different string
tasks
• Functions come from the utility library string.h
• #include <string.h>
• Examples
strlen(str) - calculate string length
strcpy(dst,src) - copy string at src to dst
strcmp(str1,str2) - compare str1 to str2
58
Standard Library
• String handling library has functions to
• Manipulate string data
• Search strings
• Tokenize strings
• Determine string length
59
String Length
Syntax: int strlen(char *str)
returns the length (integer) of the string argument
Example:
char str1 = “hello”;
int a;
a=strlen(str1);
61
Function prototype Function description
char *strcpy( char *s1,
const char *s2 )
Copies string s2 into array s1. The value of s1 is
returned.
char *strncpy( char *s1,
const char *s2, size_t n )
Copies at most n characters of string s2 into array s1.
The value of s1 is returned.
char *strcat( char *s1,
const char *s2 )
Appends string s2 to array s1. The first character of
s2 overwrites the terminating null character of s1.
The value of s1 is returned.
char *strncat( char *s1,
const char *s2, size_t n )
Appends at most n characters of string s2 to array s1.
The first character of s2 overwrites the terminating
null character of s1. The value of s1 is returned.
String Comparison
Syntax:
int strcmp(char *str1, char *str2)
compares str1 to str2, returns a value based on the first character
they differ at:
Answer < 0 if 2 string are less than or equal to
> 0 if 2 string are greater than
= 0 if the two strings are equal
String Comparison (cont)
strcmp examples:
strcmp(“hello”,”hello”) -- returns 0
strcmp(“yello”,”hello”) -- returns value > 0
strcmp(“Hello”,”hello”) -- returns value < 0
strcmp(“hello”,”hello there”) -- returns value < 0
strcmp(“some diff”,”some dift”) -- returns value < 0
expression for determining if two strings s1,s2 hold the
same string value:
!strcmp(s1,s2)
String Comparison (ignoring case)
Syntax:
int strcasecmp(char *str1, char *str2)
similar to strcmp except that upper and lower case characters
(e.g., ‘a’ and ‘A’) are considered to be equal
int strncasecmp(char *str1, char *str2, int n)
version of strncmp that ignores case
String Concatenation
Syntax:
char *strcat(char *dstS, char *addS)
appends the string at addS to the string dstS (after dstS’s
delimiter)
returns the string dstS
can cause problems if the resulting string is too long to fit in dstS
char *strncat(char *dstS, char *addS, int n)
appends the first n characters of addS to dstS
if less than n characters in addS only the characters in addS
appended
always appends a 0 character
Copying a String
WAP to create 3 string variable ,
String1 = Happy
String2=New Year
Op1: join s1+s2
Op2: Copy s1 to s3

More Related Content

What's hot

Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonAnoop Thomas Mathew
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsMegha V
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++Neeru Mittal
 
Templates presentation
Templates presentationTemplates presentation
Templates presentationmalaybpramanik
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheoryKnoldus Inc.
 
Loops and functions in r
Loops and functions in rLoops and functions in r
Loops and functions in rmanikanta361
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Reuven Lerner
 
Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++Anton Kolotaev
 
Advance python programming
Advance python programming Advance python programming
Advance python programming Jagdish Chavan
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++Nilesh Dalvi
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming languageMegha V
 

What's hot (20)

Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
Template C++ OOP
Template C++ OOPTemplate C++ OOP
Template C++ OOP
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Scala functions
Scala functionsScala functions
Scala functions
 
Loops and functions in r
Loops and functions in rLoops and functions in r
Loops and functions in r
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014
 
8 Pointers
8 Pointers8 Pointers
8 Pointers
 
Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++
 
Advance python programming
Advance python programming Advance python programming
Advance python programming
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
 
Array strings
Array stringsArray strings
Array strings
 
Algorithm and Programming (Array)
Algorithm and Programming (Array)Algorithm and Programming (Array)
Algorithm and Programming (Array)
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
 

Similar to CSEG1001Unit 3 Arrays and Strings (20)

2 Arrays & Strings.pptx
2 Arrays & Strings.pptx2 Arrays & Strings.pptx
2 Arrays & Strings.pptx
 
Arrays
ArraysArrays
Arrays
 
Arrays 06.ppt
Arrays 06.pptArrays 06.ppt
Arrays 06.ppt
 
Array i imp
Array  i impArray  i imp
Array i imp
 
Arrays
ArraysArrays
Arrays
 
Arrays.pptx
Arrays.pptxArrays.pptx
Arrays.pptx
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
Array
ArrayArray
Array
 
Array&amp;string
Array&amp;stringArray&amp;string
Array&amp;string
 
Arrays
ArraysArrays
Arrays
 
Unit 2 dsa LINEAR DATA STRUCTURE
Unit 2 dsa LINEAR DATA STRUCTUREUnit 2 dsa LINEAR DATA STRUCTURE
Unit 2 dsa LINEAR DATA STRUCTURE
 
Arrays
ArraysArrays
Arrays
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
SPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in CSPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in C
 
C Language Unit-3
C Language Unit-3C Language Unit-3
C Language Unit-3
 
Unit3 jwfiles
Unit3 jwfilesUnit3 jwfiles
Unit3 jwfiles
 
arrays
arraysarrays
arrays
 
COM1407: Arrays
COM1407: ArraysCOM1407: Arrays
COM1407: Arrays
 
DS Unit 1.pptx
DS Unit 1.pptxDS Unit 1.pptx
DS Unit 1.pptx
 

More from Dhiviya Rose

Programming for Problem Solving Unit 2
Programming for Problem Solving Unit 2Programming for Problem Solving Unit 2
Programming for Problem Solving Unit 2Dhiviya Rose
 
Programming for Problem Solving Unit 1
Programming for Problem Solving Unit 1Programming for Problem Solving Unit 1
Programming for Problem Solving Unit 1Dhiviya Rose
 
Module 3 microsoft powerpoint
Module 3 microsoft powerpointModule 3 microsoft powerpoint
Module 3 microsoft powerpointDhiviya Rose
 
Module 3 business computing.pdf
Module 3 business computing.pdfModule 3 business computing.pdf
Module 3 business computing.pdfDhiviya Rose
 
Module 2 Digital Devices and its Applications
Module 2 Digital Devices and its ApplicationsModule 2 Digital Devices and its Applications
Module 2 Digital Devices and its ApplicationsDhiviya Rose
 
Unit 1 Business Computing
Unit 1 Business ComputingUnit 1 Business Computing
Unit 1 Business ComputingDhiviya Rose
 
Module 1 - Digital Devices and its Application
Module 1 - Digital Devices and its ApplicationModule 1 - Digital Devices and its Application
Module 1 - Digital Devices and its ApplicationDhiviya Rose
 
CSEG1001Unit 2 C Programming Fundamentals
CSEG1001Unit 2 C Programming FundamentalsCSEG1001Unit 2 C Programming Fundamentals
CSEG1001Unit 2 C Programming FundamentalsDhiviya Rose
 
CSEG1001 Lecture 1 Introduction to Computers
CSEG1001 Lecture 1 Introduction to ComputersCSEG1001 Lecture 1 Introduction to Computers
CSEG1001 Lecture 1 Introduction to ComputersDhiviya Rose
 
Lecture 3 internet and web
Lecture 3 internet and webLecture 3 internet and web
Lecture 3 internet and webDhiviya Rose
 
Multidimentional array
Multidimentional arrayMultidimentional array
Multidimentional arrayDhiviya Rose
 
Searching in Arrays
Searching in ArraysSearching in Arrays
Searching in ArraysDhiviya Rose
 

More from Dhiviya Rose (14)

Programming for Problem Solving Unit 2
Programming for Problem Solving Unit 2Programming for Problem Solving Unit 2
Programming for Problem Solving Unit 2
 
Programming for Problem Solving Unit 1
Programming for Problem Solving Unit 1Programming for Problem Solving Unit 1
Programming for Problem Solving Unit 1
 
Module 3 microsoft powerpoint
Module 3 microsoft powerpointModule 3 microsoft powerpoint
Module 3 microsoft powerpoint
 
Module 3 business computing.pdf
Module 3 business computing.pdfModule 3 business computing.pdf
Module 3 business computing.pdf
 
Module 2 Digital Devices and its Applications
Module 2 Digital Devices and its ApplicationsModule 2 Digital Devices and its Applications
Module 2 Digital Devices and its Applications
 
Software
SoftwareSoftware
Software
 
Unit 1 Business Computing
Unit 1 Business ComputingUnit 1 Business Computing
Unit 1 Business Computing
 
Module 1 - Digital Devices and its Application
Module 1 - Digital Devices and its ApplicationModule 1 - Digital Devices and its Application
Module 1 - Digital Devices and its Application
 
CSEG1001Unit 2 C Programming Fundamentals
CSEG1001Unit 2 C Programming FundamentalsCSEG1001Unit 2 C Programming Fundamentals
CSEG1001Unit 2 C Programming Fundamentals
 
CSEG1001 Lecture 1 Introduction to Computers
CSEG1001 Lecture 1 Introduction to ComputersCSEG1001 Lecture 1 Introduction to Computers
CSEG1001 Lecture 1 Introduction to Computers
 
Lecture 3 internet and web
Lecture 3 internet and webLecture 3 internet and web
Lecture 3 internet and web
 
Strings
StringsStrings
Strings
 
Multidimentional array
Multidimentional arrayMultidimentional array
Multidimentional array
 
Searching in Arrays
Searching in ArraysSearching in Arrays
Searching in Arrays
 

Recently uploaded

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
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
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
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 

Recently uploaded (20)

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
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
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
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 

CSEG1001Unit 3 Arrays and Strings

  • 1. ARRAYS & STRING OPERATIONS 1 Instructor Dhiviya Rose J , AP-Sr. Scale | SoCSE
  • 3. Variables Vs Array 3 int a,b; a=10; b=20; c=30; int marks[5]; marks[0]=51; marks[1]=62; marks[2]=43; marks[3]=74; marks[4]=55;
  • 4. Index Definition of Arrays. Types of Arrays (1-D and 2-D) 1-D Arrays: -Array Declaration. -Accessing Elements of an array. -Entering Data into an array. -Reading data from an array. -Array Initialization. -Array Elements in Memory. 4
  • 5. Introduction • Arrays • Structures of related data items • Static entity – same size throughout program • Derived data types • Group of consecutive memory locations • Same name and data type 5
  • 6. • To refer to an element, specify ▫ Array name ▫ Position number/ Index • Format: arrayname[ position number ] ▫ First element at position 0 ▫ n element array named c:  c[ 0 ], c[ 1 ]...c[ n – 1 ] 6 Name of array (All elements of the array have the same name, c) Position number or Index of the element within array c c[6] -45 6 0 72 1543 -89 0 62 -3 1 6453 78 c[0] c[1] c[2] c[3] c[11] c[10] c[9] c[8] c[7] c[5] c[4]
  • 7. 7 int marks[5]; marks[0]=51; marks[1]=62; marks[2]=43; marks[3]=74; marks[4]=55; Array Name= ? Array Size=? Index Range=? No of Elements in the Array=?
  • 9. • Array elements are like normal variables c[0] = 3; printf( "%d", c[0] ); ▫ Perform operations in subscript. c[0] = 10; C[1] = 20; C[2] = c[0] + c[1] printf( “%d”, c[2] ); 9
  • 10. Types of Arrays • One Dimensional Array (1D) • Two Dimensional Array (2D) • Multi Dimensional Array 10
  • 11. Declaring Arrays – 1D • When declaring arrays, specify • Name • Type of array • Number of elements arrayType arrayName[ numberOfElements ]; • Examples: int c[10]; float myArray[20]; 11
  • 12. Initializing Arrays – 1D • Initializers int n[5] = { 1, 2, 3, 4, 5 }; ▫ If not enough initializers, rightmost elements become 0 int n[ 5 ] = { 0 }  All elements 0 ▫ If too many a syntax error is produced syntax error ▫ C arrays have no bounds checking • If size omitted, initializers determine it int n[ ] = { 1, 2, 3, 4, 5 }; ▫ 5 initializers, therefore 5 element array 12
  • 13. Initializing at Run time - scanf void main() { int ans,myarr[2]; printf(“Enter the myarr[0]”); scanf(“%d”,&myarr[0]; printf(“Enter the myarr[1]”); scanf(“%d”,&myarr[1]; ans=myarr[0]+myarr[1]; printf(“The added answer is %d”,ans); } 13
  • 14. Accessing elements array using for– 1D 14
  • 16. Problem – Data Type??? • Class of 4 students • Each student has 4 test scores
  • 18. Solution( C Program representation) • Represents this information in a two-dimensional array in C program • First dimension - student • which student 0, 1, 2, 3 • Second dimension - marks • which test score 0, 1, 2,3 18
  • 19. 19 Student 1 Student 2 Student 3 Student 4 M1 M2 M3 M3
  • 20. Declaring a 2D Array • Example: int grades[4][4];
  • 21. Creating a 2D Array • Create array elements by telling how many ROWS and COLUMNS • Example: int grades[4][4]; • grades is a two-dimensional array, • 4 rows and 4 columns • One row for each student. One column for each test. C arrays are row major, which means that we always refer to the row first.
  • 22. Initializing Elements // First student scores grades[0][0] = 78; grades[0][1] = 83; grades[0][2] = 82; Write assignment statements to fill-in the rest of the array.
  • 23. Declaration & Initialize 2D Arrays • Example: int grades[3][3] ={ { 78, 83, 82 },{ 90, 88, 94 }, { 71, 73, 78 } }; • A Two-D Array is an array of arrays. • Each row is itself a One-D array.
  • 24. Multiple-Dimentional Arrays • Initialization • int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; • Initializers grouped by row in braces • If not enough, unspecified elements set to zero int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; • Referencing elements • Row Specific & Column Specific • Specify row, then column printf( "%d", b[ 0 ][ 1 ] ); 24 1 2 3 4 1 0 3 4
  • 25. Row, Column Indices 78 83 82 90 88 94 71 73 78 97 96 95 89 93 90 Give both the ROW and COLUMN indices to pick out an individual element. The fourth student’s third test score is at ROW 3, COLUMN 2 0 1 2 3 4 0 1 2
  • 26. Exercise: Average Overall • Find the average test score of all students’ test scores. • Get the marks from the user • Array name grades[4][4]
  • 27. Exercise: Average Overall int sum = 0; int r,c; for(r = 0; r < 4; r++) for(c = 0; c < 4; c++) sum = sum + grades[r][c];
  • 29. Find maximum in a 2D array max = matrix[0][0]; for(int i = 0; i < r; i++) for(int j = 0; j < c; j++) if ( matrix[i][j] > max) max = matrix[i][j];
  • 30. Searching Arrays: Linear Search and Binary Search • Search an array for a key value • Linear search • Simple • Compare each element of array with key value • Useful for small and unsorted arrays 30
  • 31. Linear Search • Step through array of records, one at a time. • Look for record with matching key. • Search stops when • record with matching key is found • or when search has examined all records without success.
  • 32. How Linear Search works 32
  • 34. 34 Case 1: Target NOT found
  • 35. Program #include<stdio.h> void main() { int a[10],i,target; printf("Enter array value n"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Which value to be search ->"); scanf("%d",&target); /* Linear Search logic */ for(i=0;i<n;i++) if(target==a[i]) { printf(“Value found at %d”,i); } } 35
  • 36. Advantages of Linear Search • Don't have to sort the data we search. • Works well if only search operation is minimum • Not optimal in case of large amount of data 36
  • 37. Binary Search • Assume that we are give an array of records that is sorted. For instance: • an array of records with integer keys sorted from smallest to largest (e.g., ID numbers), or • an array of records with string keys sorted in alphabetical order (e.g., names).
  • 38. Binary Search [ 0 ] [ 1 ] Example: sorted array of integer keys. Target=7. 3 6 7 11 32 33 53 [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ]
  • 39. 39
  • 40. Binary Search Pseudocode … if(size == 0) found = false; else { middle = index of approximate midpoint of array segment; if(target == a[middle]) target has been found! else if(target < a[middle]) search for target in area before midpoint; else search for target in area after midpoint; } …
  • 41. Program int result=-1; int low=0; int high=length-1; int mid; while( result==-1 && low<=high ) { mid= low + ((high - low) / 2); if( list[mid] == target ) result = mid; else if( list[mid] < target) low = mid + 1; else high = mid - 1; } 41
  • 42. Other Searching Algorithms • Interpolation Search • Indexed Searching • Binary Search Trees • Hash Table Searching • Grover's Algorithm • Best-first • A* 42
  • 43. Sorting Arrays ▫ Important computing application ▫ Arrange in some order ▫ Sorting done to make searching easier Sorting: an operation that segregates items into groups according to specified criterion. A = { 3 1 6 2 1 3 4 5 9 0 } A = { 0 1 1 2 3 3 4 5 6 9 } • The "simple" sorting algorithms are • bubble sort • selection sort 43
  • 44. Bubble Sort • Several passes through the array • Successive pairs of elements are compared  If increasing order (or identical ), no change  If decreasing order, elements exchanged ▫ Repeat 44
  • 45. 45
  • 46. 5 elements …. 4 pass ….. 5th pass all sorted 46
  • 47. Program /* Bubble sorting begins */ for (i = 0; i < num; i++) { for (j = 0; j < (num - i - 1); j++) { if (array[j] > array[j + 1]) { temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } 47
  • 48. SELECTION SORT • improves on the bubble sort • only one exchange for every pass through the array Working Principle • looks for the smallest value/largest value as it makes a pass • after each pass, the smallest item/largest item is in the correct place. 48
  • 50. Other Sorting Algorithms ● Bubble Sort ● Selection Sort ● Insertion Sort ● Merge Sort ● Shell Sort ● Heap Sort ● Quick Sort ● Radix Sort ● Swap Sort
  • 51. 51
  • 52. STRING & ITS OPERATIONS 52
  • 53. Definition • A sequence of characters is often referred to as a character “string”. • No explicit type, instead strings are maintained as arrays of characters • Representing strings in C • stored in arrays of characters • array can be of any length • end of string is indicated by a delimiter, the zero character ‘0’
  • 54. Character Vs Strings Will be considered as string Will be considered as character array char myarr[]={‘h’,’e’,’l’,’l’,’o’,’0’}; char myarr[]={‘h’,’e’,’l’,’l’,’o’};
  • 55. String Declaration & Initialization • A string constant is a sequence of characters enclosed in double quotes. char a[10]=“Hello”; Or char *colorPtr = "blue"; pointer
  • 56. String Input • Use %s field specification in scanf to read string • Example: char myarr[11]; scanf(“%s”,myarr); 56 Only the name of the string
  • 57. Example #include <stdio.h> void main() { char LName[10]; char FName[10]; printf("Enter your name : "); scanf("%s %s",LName,FName); printf("Nice to meet you %s %sn“,FName,LName); } 57
  • 58. String Functions • string functions are used for performing different string tasks • Functions come from the utility library string.h • #include <string.h> • Examples strlen(str) - calculate string length strcpy(dst,src) - copy string at src to dst strcmp(str1,str2) - compare str1 to str2 58
  • 59. Standard Library • String handling library has functions to • Manipulate string data • Search strings • Tokenize strings • Determine string length 59
  • 60. String Length Syntax: int strlen(char *str) returns the length (integer) of the string argument Example: char str1 = “hello”; int a; a=strlen(str1);
  • 61. 61 Function prototype Function description char *strcpy( char *s1, const char *s2 ) Copies string s2 into array s1. The value of s1 is returned. char *strncpy( char *s1, const char *s2, size_t n ) Copies at most n characters of string s2 into array s1. The value of s1 is returned. char *strcat( char *s1, const char *s2 ) Appends string s2 to array s1. The first character of s2 overwrites the terminating null character of s1. The value of s1 is returned. char *strncat( char *s1, const char *s2, size_t n ) Appends at most n characters of string s2 to array s1. The first character of s2 overwrites the terminating null character of s1. The value of s1 is returned.
  • 62. String Comparison Syntax: int strcmp(char *str1, char *str2) compares str1 to str2, returns a value based on the first character they differ at: Answer < 0 if 2 string are less than or equal to > 0 if 2 string are greater than = 0 if the two strings are equal
  • 63. String Comparison (cont) strcmp examples: strcmp(“hello”,”hello”) -- returns 0 strcmp(“yello”,”hello”) -- returns value > 0 strcmp(“Hello”,”hello”) -- returns value < 0 strcmp(“hello”,”hello there”) -- returns value < 0 strcmp(“some diff”,”some dift”) -- returns value < 0 expression for determining if two strings s1,s2 hold the same string value: !strcmp(s1,s2)
  • 64. String Comparison (ignoring case) Syntax: int strcasecmp(char *str1, char *str2) similar to strcmp except that upper and lower case characters (e.g., ‘a’ and ‘A’) are considered to be equal int strncasecmp(char *str1, char *str2, int n) version of strncmp that ignores case
  • 65. String Concatenation Syntax: char *strcat(char *dstS, char *addS) appends the string at addS to the string dstS (after dstS’s delimiter) returns the string dstS can cause problems if the resulting string is too long to fit in dstS char *strncat(char *dstS, char *addS, int n) appends the first n characters of addS to dstS if less than n characters in addS only the characters in addS appended always appends a 0 character
  • 66. Copying a String WAP to create 3 string variable , String1 = Happy String2=New Year Op1: join s1+s2 Op2: Copy s1 to s3