Arrays and Strings
• Week 5 Lecture Notes
• Instructor: Isaac Muckson Sesay
• Contact Information:
isaacmsesay@central.edu.sl
Overview
• Declaring and using arrays
• Multidimensional arrays
• Basic string manipulation with <string.h>
Learning Objectives
• By the end of this week, students will:
• - Understand the declaration and use of
arrays.
• - Work with multidimensional arrays.
• - Perform basic string operations using the
<string.h> library.
Introduction to Arrays
• - Arrays are collections of elements of the
same data type.
• Syntax:
• ```c
• dataType arrayName[size];
• ```
• Example:
• ```c
• int numbers[5];
Multidimensional Arrays
• - Arrays with more than one dimension.
• Syntax:
• ```c
• dataType arrayName[size1][size2];
• ```
• Example:
• ```c
• int matrix[3][3];
• matrix[0][0] = 1;
String Manipulation in C
• - Strings are arrays of characters ending with a
null character (`\0`).
• Basic Operations:
• 1. Copying strings using `strcpy`.
• 2. Concatenating strings using `strcat`.
• 3. Comparing strings using `strcmp`.
• Example:
• ```c
• char str1[20], str2[20];
Program Example: Matrix Addition
• - Write a program to perform matrix addition:
• 1. Declare two 2D arrays.
• 2. Input their elements.
• 3. Add corresponding elements.
• 4. Display the resultant matrix.
• Example:
• ```c
• for (int i = 0; i < rows; i++) {
• for (int j = 0; j < cols; j++) {
Common Mistakes with Arrays and
Strings
• - Accessing out-of-bounds array indices.
• - Forgetting the null character in strings.
• - Using uninitialized arrays or string variables.
Hands-on Activity
• 1. Write a program to find the largest element
in a 1D array.
• 2. Create a program to reverse a string.
• 3. Implement matrix addition and test with
sample inputs.
Book Reference
• Primary Textbook:
• C Programming: A Modern Approach by K. N.
King
• - Chapter 8: Arrays and Strings, Pages 131-156
Quiz Questions
• 1. Write the syntax for declaring a 2D array
and provide an example.
• 2. Explain the difference between a character
array and a string.
• 3. Write a C program to concatenate two
strings using `strcat`.
Conclusion
• Recap of Week 5 topics
• Next Week: Pointers and Dynamic Memory
Allocation
• Contact information for questions