3-Array and String
3-Array and String
3-Array and String
CHAPTER 3
ARRAY AND STRING
MAIN CONTENTS
Processing an array
Two-dimensional array
String
One dimensional array
• An array is a collection of the same type of data items,
which are stored in consecutive memory locations under
a common name.
• The size of an array signifies the number of elements of
the array. That number should be a positive integer
number.
• An one-dimensional array is one in which only one
subscript is needed to specify a particular element of
the array.
• Arrays in programming are similar to vectors or matrices
in mathematics
One dimensional array - Declaration
• Syntax:
data_type array_name [size];
• Example:
int a[10];
array_name [index]
One dimensional array
Array in Memory
int a[6];
• Size of One-
Dimensional Array:
sizeof(data_type)*size
or
sizeof(array_name)
One dimensional array - Initialization
Merge two
steps into
one?
Operations Perform on Arrays
Inserting an Element into a Linear Array (in a sorted Array)
Traversing: O(n).
Inserting:
- The best case is O (1),
- The worst case is O (n),
- The average case is O (n).
Deleting: The best case is O (1),
- The worst case is O (n),
- The average case is O (n).
Applications of Array
• Example:
Write the algorithms to solve these problems
- Input a string str1.
- Find the length of str1.
- Input another string str2.
- Check if two these strings are the same. Display the
result.
- Concatenate str2 to str1
Summary
An array is a collection of variables of the same data type
that are stored in consecutive memory location under a
common name.
An array can be an integer, character or floating-point data
type can be initialized only during declaration.
An array name is an address of the first element of the array.
A matrix is said to be Sparse Matrix if most of its elements
are having a relatively small number of non-zero elements.
The string is a sequence of characters.
Exercises
1. Complete the Exercises on pages 3.31, 3.32
2. Write the algorithms to solve following problems
2.1 Input an one dimensional integer array with N elements
(0<N<10) and an integer X. Find the position of X in given
array.
2.2. Input a string and check if this string is palindrome
3. Write the algorithms to use an array of strings (size
0<=N<=6) (you can use the library “string”)
- Input the data for each element in the array
- Show the shortest string in this array