CSE109JUL2023 - LectureSlide - 05 (Array+String)
CSE109JUL2023 - LectureSlide - 05 (Array+String)
Computer Programming
Lecture 5:
Multi-Dimensional Arrays and
Strings
Khaled Mahmud Shahriar
Assistant Professor
Department of CSE, BUET
**Slightly modified by
Ishrat Jahan
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
#include<stdio.h>
int main() {
// two dimensional array with 4 rows and 4 columns
int twod[4][5];
int i, j;
for ( i = 0; i < 4; i++ ) {// iterate over rows
for ( j = 0; j < 5; j++ ) {// iterate over columns
twod[i][j] = i + j;
}
}
for ( i = 0; i < 4; i++ ) {// iterate over rows Output
for ( j = 0; j < 5; j++ ) {// iterate over columns 01234
printf("%d ", twod[i][j]);
}
12345
printf("\n"); 23456
} 34567
return 0;
}
Multidimensional array Matrix Transpose
#include<stdio.h> for ( i =0 ; i< r; i++ ) {
for ( j = 0; j < c; j++ ) {
int main() { b[j][i] = a[i][j];
int i, j, r, c; }
}
printf("Enter number of rows: ");
scanf("%d", &r); printf("The transformed matrix: \n");
printf("Enter number of columns: "); for ( i =0 ; i< c; i++ ) {
scanf("%d", &c); for ( j = 0; j < r; j++ ) {
int a[r][c], b[c][r]; printf("%d ", b[i][j]);
}
printf("Enter the matrix (separate by printf("\n");
space): "); }
for ( i =0 ; i< r; i++ ) {
for ( j = 0; j < c; j++ ) { return 0;
scanf("%d", &a[i][j]); }
}
}
Multidimensional array Matrix Addition
int main() { for ( i =0 ; i< r; i++ ) {
int i, j, r, c; for ( j = 0; j < c; j++ ) {
printf("Enter number of rows: "); // adding element by element
scanf("%d", &r); z[i][j] = x[i][j] + y[i][j];
printf("Enter number of columns: "); }
scanf("%d", &c); }
int x[r][c], y[r][c], z[r][c];
printf("The summation matrix: \n");
printf("Enter first matrix: "); for ( i =0 ; i< r; i++ ) {
for ( i =0 ; i< r; i++ ) { for ( j = 0; j < c; j++ ) {
for ( j = 0; j < c; j++ ) { printf("%d ", z[i][j]);
scanf("%d", &x[i][j]); }
} printf("\n");
} }
printf("Enter second matrix: "); return 0;
for ( i =0 ; i< r; i++ ) { }
for ( j = 0; j < c; j++ ) {
scanf("%d", &y[i][j]);
}
}
Multidimensional array Matrix Multiplication
int main() {
int i, j, k, r1, c1, r2, c2, sum;
printf("Enter number or rows and cols for for ( i =0 ; i< r1; i++ ) {
the first and second matrix: "); for ( j = 0; j < c2; j++ ) {
scanf("%d %d %d %d", &r1, &c1, &r2, &c2); sum = 0;
for ( k = 0; k < r2; k++ ) {
if ( c1 != r2) { sum += x[i][k] * y[k][j];
printf("Invalid Dimension\n"); }
return 0; z[i][j] = sum;
} }
int x[r1][c1], y[r2][c2], z[r1][c2]; }
1 2 3 4 5 6 7 8 9
5000 5004 5008 5012 5016 5020 5024 5028 5032
},{
{ {9,3}, {6,8}, {9,0} } {7,6},
} {5,1},
{3,4}
},{
{2,3},
{7,2},
{9,4}
},{
{9,3},
{6,8},
{9,0}
}
Multidimensional array
• A one dimensional array of two elements int arr[4][3][2]={ { {2,4}, {7,8}, {4,9} },
{ {7,6}, {5,1}, {3,4} },
• Three such arrays placed to create a two-
dimensional array of three rows { {2,3}, {7,2}, {9,4} },
{ {9,3}, {6,8}, {9,0} }
• 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
Multidimensional array
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
• Terminating null is important 'M' 'M' 'E' '2' '8' '7' '\0'
• Indicates where string ends String Size: 6, Array Size: 7
• A string constant is automatically null-terminated by
the compiler
String Initialization
Output:
C
S
E
1
0
9
Reading Strings: 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
Reading Strings: 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
Reading Strings
#include<stdio.h>
int main()
{
char s[80]; // declare an empty string with capacity 80
printf("Enter first string: ");
scanf("%s", s); // scan a single word, note there is no &
printf("You entered: %s\n", s);
return 0;
}
#include<stdio.h>
int main()
{
char s[80]; // declare an empty string with capacity 80
printf("Enter first string: ");
gets(s); // scan a single line
printf("You entered: %s\n", s);
return 0;
}
Writing strings
• Using %s in printf
• printf("%s", s);
• Using puts()
• puts("hello")
• puts(s)
Writing Strings
#include<stdio.h>
int main()
{
// string declaration
char t[] = "hello world";
// print character by character
int i = 0;
while(t[i] != '\0')
{
printf("%c", t[i]);
i++;
}
printf("\n");
// print using %s in printf
printf("%s\n", t);
// print using puts
puts(t);
return 0;
}
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 // strlen(u) - returns the length of u
#include<stdio.h>
#include<string.h> len = strlen(u);
printf("Length of your
int main() concatenated string: %d\n", len);
{ // strcmp(s,t) - compares s and t, if
char s[80], t[80]; // declare equal returns 0, otherwise returns the
two empty string with capacity 80 difference of first mismatch
char u[80] = "C string "; cmp = strcmp(s,t);
int len, cmp; printf("Comparing %s and %s : %d\
printf("Enter your string: "); n", s, t, cmp);
gets(s); cmp = strcmp(u,t);
// strcpy(t,s) - copies content printf("Comparing %s and %s : %d\
of s to t, overwrite t n", u, t, cmp);
strcpy(t,s); // you can also use fixed strings
printf("Your copied string: %s\ as second parameter
n", t); strcpy(u, "hello");
// strcat(u,t) - concats content strcat(u, " world");
of t to u, doesn't overwrite u len = strlen("hello world");
strcat(u,t); printf("New string = %s, length =
printf("Your concatenated %d\n", u, len);
string: %s\n", u); return 0;
String
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char a[10], b[10], c[10];
int x, y, result;
printf("Enter two numbers and operation (add/sub/mul/div): ");
scanf("%s %s %s", a, b, c);
// atoi(a) - converts string a into integer
x = atoi(a);
y = atoi(b);
if ( strcmp(c, "add") == 0 ) result = x + y; // if ( c == "add" ) doesn't
work
else if ( strcmp(c, "sub") == 0 ) result = x - y;
else if ( strcmp(c, "mul") == 0 ) result = x * y;
else if ( strcmp(c, "div") == 0 ) result = y == 0? 0 : x / y;
else result = 0;
printf("Result: %d\n", result);
return 0;
String Practice Problems
String length String copy
int main() int main()
{ {
char s[80]; char s[80], t[80];
int len; int i;
printf("Enter your string: "); printf("Enter your string: ");
gets(s); gets(s);
len=0; i=0;
while(s[len]) while(s[i])
{ {
len++; t[i] = s[i];
} i++;
printf("Length of s : %d\n", len); }
return 0; t[i] = ‘\0’;
} printf("Your copied string: %s\n", t);
return 0;
}
String Practice Problems
String concatenate String compare
int main() int main()
{ {
char s[80]; char s[80];
char t[80] = "C string "; char t[80] = "C string ";
int i, j; int i,cmp;
printf("Enter your string: "); printf("Enter your string: ");
gets(s); gets(s);
i = 0; i = 0;
j = strlen(t); while(s[i] && t[i] && s[i]==t[i] )
while(s[i]) {
{ i++;
t[j] = s[i]; }
i++; cmp = s[i]-t[i];
j++; printf("Comparing %s and %s : %d\
} n", s, t, cmp);
t[j] = ‘\0’; return 0;
printf(“After concatenate: %s\n", t); }
return 0;
}
String Practice Problems
• Anagram check
• Palindrome check
• To upper each word
• Count number of words
• Remove multiline comments from a code
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
1011 H i m e l \0
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
1 location)
String Tables
• Initialization:
char words[][2][40]={
"dog", "Hund",
"no", "nein",
"to", "zu",
"I", "Ich"
};
• Curly braces are needed
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
String Tables String Search in a List
#include<stdio.h>
#include<string.h>
int main() {
Input
int n,i,foundAt=-1; 3
char searchIn[20][20]; Programming Language
char searchFor[20]; Computer Networks
scanf("%d ",&n);//notice the space after %d Data Communication
for (i=0;i<n;i++) String to search for: Data Communication
gets(searchIn[i]);
printf("String to search for: ");
gets(searchFor);
for(i=0;i<n;i++){ Output
if(strcmp(searchFor,searchIn[i])==0){ Found at position 2
foundAt=i;
break;
}
}
if(foundAt>=0)
printf("Found at position %d",foundAt);
else printf("Not found");
return 0;
}
String Tables Sort a List of Strings
#include<stdio.h>
#include<string.h>
int main() { Input
int n=0,i,j; Programming Language
char list[20][20], temp[20]; Computer Networks
gets(temp); Data Communication
while(strcmp(temp,"end")){
strcpy(list[n++], temp);
end
gets(temp);
} Bubble Sort
for ( i=0; i < n-1; i++ ) {
for ( j =0; j < n-i-1; j++ ) {
if (strcmp(list[j],list[j+1])>0) {
Output
strcpy(temp,list[j]); List of string after sort:
strcpy(list[j],list[j+1]); Computer Networks
strcpy(list[j+1],temp); Data Communication
}
}
Programming Language
}
printf("List of string after sort: \n");
for ( i=0; i < n; i++ )
printf("%s\n",list[i]);
return 0;
}
Acknowledgement
All these slides of this course have been prepared by taking help from numerous
resources. The notable contributors are listed below.
1. Content and organization of many pages have been taken from the lecture slides and
codes of the course CSE110 offered to the Department of EEE that were -
i. primarily created by Johra Muhammad Moosa, Assistant Professor (on leave),
CSE, BUET and
ii. later modified by Madhusudan Basak, Assistant Professor, CSE, BUET
2. Most of the wonderful coding examples have been taken from the course CSE281
offered to the Department of BME instructed by Rifat Shahriyar, Professor, CSE,
BUET (course link).
3. search and all the sites that it made available in response to the course
related queries. Some of the sites are: https://geeksforgeeks.org/,
https://www.tutorialspoint.com, https://www.w3schools.com and the list goes on …
Thank You ☺