SlideShare a Scribd company logo
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
Ad

More Related Content

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
Anoop Thomas Mathew
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
Emertxe Information Technologies Pvt Ltd
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
Megha V
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
Neeru Mittal
 
Template C++ OOP
Template C++ OOPTemplate C++ OOP
Template C++ OOP
Muhammad khan
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
malaybpramanik
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
Knoldus Inc.
 
Scala functions
Scala functionsScala functions
Scala functions
Knoldus Inc.
 
Loops and functions in r
Loops and functions in rLoops and functions in r
Loops and functions in r
manikanta361
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
UMA PARAMESWARI
 
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
Reuven Lerner
 
8 Pointers
8 Pointers8 Pointers
8 Pointers
Praveen M Jigajinni
 
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
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
Appili Vamsi Krishna
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
George Erfesoglou
 
Array strings
Array stringsArray strings
Array strings
Radhe Syam
 
Algorithm and Programming (Array)
Algorithm and Programming (Array)Algorithm and Programming (Array)
Algorithm and Programming (Array)
Adam Mukharil Bachtiar
 
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 language
Megha V
 
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
Anoop Thomas Mathew
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
Megha 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 presentation
malaybpramanik
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
Knoldus Inc.
 
Loops and functions in r
Loops and functions in rLoops and functions in r
Loops and functions in r
manikanta361
 
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
Reuven 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 language
Megha V
 

Similar to CSEG1001Unit 3 Arrays and Strings (20)

2 Arrays & Strings.pptx
2 Arrays & Strings.pptx2 Arrays & Strings.pptx
2 Arrays & Strings.pptx
aarockiaabinsAPIICSE
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
saneshgamerz
 
Arrays
ArraysArrays
Arrays
Aman Agarwal
 
Module_3_Arrays - Updated.pptx............
Module_3_Arrays - Updated.pptx............Module_3_Arrays - Updated.pptx............
Module_3_Arrays - Updated.pptx............
ChiragKankani
 
Arrays 06.ppt
Arrays 06.pptArrays 06.ppt
Arrays 06.ppt
ahtishamtariq511
 
Array i imp
Array  i impArray  i imp
Array i imp
Vivek Kumar
 
Arrays
ArraysArrays
Arrays
Dr. Sindhia Lingaswamy
 
Arrays.pptx
Arrays.pptxArrays.pptx
Arrays.pptx
Epsiba1
 
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
rohinitalekar1
 
Array definition and uses in computer.pptx
Array definition and uses in computer.pptxArray definition and uses in computer.pptx
Array definition and uses in computer.pptx
naushigrdcs
 
Array
ArrayArray
Array
Kathmandu University
 
Array&amp;string
Array&amp;stringArray&amp;string
Array&amp;string
chanchal ghosh
 
Arrays
ArraysArrays
Arrays
Neeru Mittal
 
Unit4pptx__2024_11_ 11_10_16_09.pptx
Unit4pptx__2024_11_      11_10_16_09.pptxUnit4pptx__2024_11_      11_10_16_09.pptx
Unit4pptx__2024_11_ 11_10_16_09.pptx
GImpact
 
Unit 2 dsa LINEAR DATA STRUCTURE
Unit 2 dsa LINEAR DATA STRUCTUREUnit 2 dsa LINEAR DATA STRUCTURE
Unit 2 dsa LINEAR DATA STRUCTURE
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
Arrays
ArraysArrays
Arrays
Manthan Dhavne
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
Janpreet Singh
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Abhilash Nair
 
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
Mohammad Imam Hossain
 
C Language Unit-3
C Language Unit-3C Language Unit-3
C Language Unit-3
kasaragadda srinivasrao
 
Ad

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
Dhiviya Rose
 
Programming for Problem Solving Unit 1
Programming for Problem Solving Unit 1Programming for Problem Solving Unit 1
Programming for Problem Solving Unit 1
Dhiviya Rose
 
Module 3 microsoft powerpoint
Module 3 microsoft powerpointModule 3 microsoft powerpoint
Module 3 microsoft powerpoint
Dhiviya Rose
 
Module 3 business computing.pdf
Module 3 business computing.pdfModule 3 business computing.pdf
Module 3 business computing.pdf
Dhiviya 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 Applications
Dhiviya Rose
 
Software
SoftwareSoftware
Software
Dhiviya Rose
 
Unit 1 Business Computing
Unit 1 Business ComputingUnit 1 Business Computing
Unit 1 Business Computing
Dhiviya 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 Application
Dhiviya Rose
 
CSEG1001Unit 2 C Programming Fundamentals
CSEG1001Unit 2 C Programming FundamentalsCSEG1001Unit 2 C Programming Fundamentals
CSEG1001Unit 2 C Programming Fundamentals
Dhiviya Rose
 
CSEG1001 Lecture 1 Introduction to Computers
CSEG1001 Lecture 1 Introduction to ComputersCSEG1001 Lecture 1 Introduction to Computers
CSEG1001 Lecture 1 Introduction to Computers
Dhiviya Rose
 
Lecture 3 internet and web
Lecture 3 internet and webLecture 3 internet and web
Lecture 3 internet and web
Dhiviya Rose
 
Strings
StringsStrings
Strings
Dhiviya Rose
 
Multidimentional array
Multidimentional arrayMultidimentional array
Multidimentional array
Dhiviya Rose
 
Searching in Arrays
Searching in ArraysSearching in Arrays
Searching in Arrays
Dhiviya Rose
 
Programming for Problem Solving Unit 2
Programming for Problem Solving Unit 2Programming for Problem Solving Unit 2
Programming for Problem Solving Unit 2
Dhiviya Rose
 
Programming for Problem Solving Unit 1
Programming for Problem Solving Unit 1Programming for Problem Solving Unit 1
Programming for Problem Solving Unit 1
Dhiviya Rose
 
Module 3 microsoft powerpoint
Module 3 microsoft powerpointModule 3 microsoft powerpoint
Module 3 microsoft powerpoint
Dhiviya Rose
 
Module 3 business computing.pdf
Module 3 business computing.pdfModule 3 business computing.pdf
Module 3 business computing.pdf
Dhiviya 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 Applications
Dhiviya Rose
 
Unit 1 Business Computing
Unit 1 Business ComputingUnit 1 Business Computing
Unit 1 Business Computing
Dhiviya 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 Application
Dhiviya Rose
 
CSEG1001Unit 2 C Programming Fundamentals
CSEG1001Unit 2 C Programming FundamentalsCSEG1001Unit 2 C Programming Fundamentals
CSEG1001Unit 2 C Programming Fundamentals
Dhiviya Rose
 
CSEG1001 Lecture 1 Introduction to Computers
CSEG1001 Lecture 1 Introduction to ComputersCSEG1001 Lecture 1 Introduction to Computers
CSEG1001 Lecture 1 Introduction to Computers
Dhiviya Rose
 
Lecture 3 internet and web
Lecture 3 internet and webLecture 3 internet and web
Lecture 3 internet and web
Dhiviya Rose
 
Multidimentional array
Multidimentional arrayMultidimentional array
Multidimentional array
Dhiviya Rose
 
Searching in Arrays
Searching in ArraysSearching in Arrays
Searching in Arrays
Dhiviya Rose
 
Ad

Recently uploaded (20)

How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 

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
  翻译: