You are on page 1of 42

CSE 109

Computer Programming
Arrays and Strings
Prepared by
Johra Muhammad Moosa
Assistant Professor
CSE, BUET

Modified by
Madhusudan Basak
Assistant Professor
CSE, BUET
Array
• List of variables of same type
• Accessed through a common name
• General form
– type var_name[size];
– int myarray[20];
– int m[10], a[5];
• Accessed by indexing
– Known as subscript
– Can be any valid expression
– Begin at 0
– myarray[1] : 2nd element
• Array elements are stored in contiguous memory location
Array (Initialization)
• int n[6]={48, 53, 26,71, 9, 12};
48 53 26 71 9 12

• float n[]={3.1, -5, 2.5, 17.4, 29};


3.1 -5 2.5 17.4 29
– Array dimension optional
Array
int a[5];
for(int i=0; i<5; i++) a[i]=i;
•After the declaration
– 20 bytes get reserved in memory
– Each integer 4 bytes long

a[0] a[1] a[2] a[3] a[4]


a 0 1 2 3 4
4002 4006 4010 4014 4018
Array
• Can be used anywhere a variable/constant can
int a[5];
for(int i=0; i<5; i++)
scanf("%d", &a[i]);
Array
• C does not perform any bound checking on array index
• Program may crash
int a[5];
for(int i=0; i<5; i++) a[i]=i;
printf("%d\n", a[10]);//a[5]
Array
• It is not possible to assign one entire array to other array

int a1[5], a2[5];


a1=a2; //not possible

• Need to copy explicitly

for(int i=0; i<5; i++)


a1[i]=a2[i];
Array
• Average calculation
Array Bubble Sort
Array Bubble Sort
• One traversal = move the maximum element at the end
• Links to bubble sort simulation
• If you understand bubble sort in the class, then you need not study the
following resources.
• http://www.cc.gatech.edu/~bleahy/cs1311/cs1311lecture16wdl.ppt
• http://max.cs.kzoo.edu/~abrady/DSAlgs/Sorting/BubbleSort.Alyce.ppt
• http://en.wikipedia.org/wiki/Bubble_sort#Step-by-step_example
Array Homework
• Find nth maximum of an array. [Hint: sort the array in decreasing order. Return (n-1)th element of the
array]
• Some digits are given (in character format. Print the corresponding number. For example, 123 are given as
digits, convert the digits to number 123. [Hint: Take digits until an enter (‘\n’) character is pressed. Then
convert it to number.]
• A number is given. Output the digits of that number.
• Histogram/frequency of an array elements
• Maximum subarray sum
• Index sort
• Standard deviation
• Merge two sorted arrays into another sorted array
• Given an array. Insert a number n is the ith position of the array. n and i will be given by the user.
• Reverse an array
• Change case of an character array
• Remove all occurrences of a particular elements from an array
• Sort an array from xth position to yth position. An array and the value of x and y are given.
Array Homework
• More exercises
• See the First 22 problems in the list. Some problems require recursion.
You should not use function and recursion at this stage. Just try to solve
the problems with using loop and array.
• https://codeforwin.org/2015/07/array-programming-exercises-and.html
String
• Most common use of one dimensional array is string
• C has no built in string datatype
• One dimensional character array terminated by a null ('\0')
• '\0' & '0' are not same
– Value of '\0' is 0 and considered false
– Value of '0' is 48
• Array size must be at least one byte larger than the string size to make
room for the null 'C' 'S' 'E' '1' '0' '9' '\0'
String Size: 6, Array Size: 7
• Terminating null is important
– Indicates where string ends
• A string constant is automatically null-terminated by the compiler
String
• char dept[]={'E', 'E', 'E', '\0'};

dept[0] dept[1] dept[2] dept[3]


dept 'E' 'E' 'E' '\0'
4001 4002 4003 4004
String
• char dept[]=''EEE'';
– Shortcut for initializing string
– '\0' is not necessary in this declaration

dept[0] dept[1] dept[2] dept[3]


dept 'E' 'E' 'E' '\0'
4001 4002 4003 4004
String

Output:
C
S
E
1
0
9
String Read using scanf()
• %s is used in scanf
• Reads characters untill ENTER pressed
• ENTER key is not stored, replaced with null character
• No bound checking
• Can not read multi word string
– "Department Name: EEE"
• scanf("%s", s);
– Just the array name is used

– No & (ampersand) is used


String Read using gets()
• gets()
– Library function
– Defined in stdio.h
– Call it using the name of the character array without using any index or
ampersand (&)
• gets(s)
– Reads characters untill ENTER pressed
– ENTER key is not stored, replaced with null character
– No bound checking
– Can receive multiword string
String Write
• Using %s in printf
– printf("%s", s);
• Using puts()
– puts("hello")
– puts(s)
String
• Each character occupies one byte of memory

dept[0] dept[1] dept[2] dept[3]


dept 'E' 'E' 'E' '\0'
4001 4002 4003 4004

• Number of possible values in a string of length 3 is 2553


String Library Functions
• strlen : Finds the length of the string
• strcat : Appends one string at the end of the other
• strcpy( to, from): Copies one string into another
• strncpy : Copies first n characters of one string into another
• strcmp (s1, s2): Compares two strings
– Returns 0 if same
– -ve if s1 less than s2
– +ve if s1 greater than s2
• strchr : Finds first occurrence of a given character in a string
String Library Functions
• strcpy
Homework
• Anagram check
• Palindrome check
• To upper each word
• Count number of words
• Remove multiline comments from a code
Multidimensional array
• Arrays of two or more dimension
• int count[10][12];
• 2-d array
– Array of one dimensional arrays
– Row, column format
– Accessed a row at a time from left to right
0 1 2 3 4
0 a[0][0] a[0][1] a[0][2] a[0][3] a[0][4]
Row subscript
1 a[1][0]
Column subscript
2
3 a[3][0] a[3][4]
Multidimensional array
• Example:
• float yeartemp[12][31];
Multidimensional array
Multidimensional array
Multidimensional array

• Initialization: • Initialization:
int sqr[3][3] ={ • Specify all but the leftmost dimension
1,2,3, int sqr[][3] ={
4,5,6, 1,2,3,
7,8,9 4,5,6,
}; 7,8,9
Col no. 0 Col no. 1 Col no. 2 };
Row no. 0 1 2 3

Row no. 1 4 5 6

Row no. 2 7 8 9
Multidimensional array
• Initialization:
int sqr[3][3] ={
{1,2,3},
{4,5,6},
{7,8,9}
};
int sqr[3][3] ={1,2,3,4,5,6,7,8,9};
int sqr[][3] ={1,2,3,4,5,6,7,8,9};
Multidimensional array
• Initialization:
int sqr[3][] ={1,2,3,4,5,6,7,8,9};
int sqr[][] ={1,2,3,4,5,6,7,8,9};
• This would never work
Multidimensional array
• Arrangement of 2-D array in memory
• Memory doesn't contain rows and columns
• Elements are stored in one continuous chain

S[0][0] S[0][1] S[0][2] S[1][0] S[1][1] S[1][2] S[2][0] S[2][1] S[2][2]

1 2 3 4 5 6 7 8 9
5000 5004 5008 5012 5016 5020 5024 5028 5032
Multidimensional array
int th[4][2][7]
Multidimensional array
Multidimensional array
int arr[4][3][2]={ {
{2,4},
{7,8},
{4,9}
},{
{7,6},
{5,1},
{3,4}
},{
{2,3},
{7,2},
{9,4}
},{
{9,3},
{6,8},
{9,0}
}

}
Multidimensional array
• An one dimensional array of two elements
• Three such arrays placed to create a two dimensional array of three rows
• Four such two dimensional arrays are placed to yield a three dimensional
array containing three two dimensional arrays.

0th 2-D Array 1st 2-D Array 2nd 2-D Array 3rd 2-D Array
2 4 7 8 4 9 7 6 5 1 3 4 2 3 7 2 9 4 9 3 6 8 9 0
String Tables
• Arrays of strings
• char names[10][40]
– 10 names (strings) each can hold 40 characters at most including null
• gets(names[2]);
• printf(names[1]);
• char student_profile[10][4][80];//name, address, father's name, mother's name
– Specify two leftmost indices
– student_profile[3][4]
String Tables
char names[][10]={"Anik", "Himel", "Fatema", "Parag", "Azad” }

100 A n i k \0
1
101 H i m e l \0
1
102 F a t e m a \0
1
103 P a r a g \0
1
104 A z a d \0 1050 (last location)
1
String Tables
• Initialization:
char words[][2][40]={
"dog", "Hund",
"no", "nein",
"to", "zu",
"I", "Ich"
};
• Curly braces are needed
• Example: 2 (5.5)
Multidimensional array
• 100-character one dimensional requires 100 bytes of memory
• 100×100 character two dimensional array requires 10,000 bytes of memory
• 100 ×100 ×100 character array requires 10,00,000 bytes
Home Works
• Cumulative skills check: 2
• Matrix addition, multiplication, sort
Reference
• TEACH YOURSELF C by Herbert Schildt (3rd Edition)
– Chapter 5 (Full)
Thank You 

You might also like