Module 6: Arrays and Strings in C
Learning Objectives
By the end of this module, you will be able to:
- Understand what arrays are and why they are used.
- Work with one-dimensional, two-dimensional, and multidimensional arrays.
- Traverse arrays using loops.
- Understand strings and character arrays.
- Learn the difference between
gets()andfgets(). - Use common string functions such as
strlen(),strcpy(),strcat(), andstrcmp(). - Build practical programs using arrays and strings.
- Develop matrix and string manipulation applications.
Introduction
Imagine storing the marks of 100 students.
Without arrays, you would need to create 100 separate variables:
1int mark1; 2int mark2; 3int mark3; 4... 5int mark100;
Managing this many variables becomes difficult.
Arrays solve this problem by storing multiple values of the same data type under a single name.
Similarly, strings are simply arrays of characters that allow us to store and manipulate text.
Arrays and strings are among the most frequently used concepts in C programming and form the foundation for many advanced data structures.
Arrays
An array is a collection of elements of the same data type stored in contiguous memory locations.
Example:
1Marks = [85, 90, 78, 92, 88]
Instead of using five separate variables, we use one array.
Advantages of Arrays
- Store multiple values using one variable.
- Easy access using indexes.
- Efficient memory usage.
- Simplifies loops.
- Foundation for matrices, stacks, queues, and many data structures.
Array Indexing
Array indexing starts from 0.
Example
1Index : 0 1 2 3 4 2Value : 10 20 30 40 50
Declaring an Array
Syntax
1data_type array_name[size];
Example
1int numbers[5];
Initializing an Array
1int numbers[5] = {10,20,30,40,50};
Or
1int numbers[] = {10,20,30,40,50};
The compiler automatically determines the array size.
Accessing Array Elements
Example
1#include <stdio.h> 2 3int main() 4{ 5 int marks[] = {80,85,90}; 6 7 printf("%d", marks[1]); 8 9 return 0; 10}
Output
185
One-Dimensional (1D) Array
A one-dimensional array stores values in a single row.
Example
1Roll Numbers 2 310 420 530 640 750
Program
1#include <stdio.h> 2 3int main() 4{ 5 int numbers[5] = {10,20,30,40,50}; 6 7 for(int i=0;i<5;i++) 8 { 9 printf("%d ", numbers[i]); 10 } 11 12 return 0; 13}
Output
110 20 30 40 50
Input in Array
1#include <stdio.h> 2 3int main() 4{ 5 int marks[5]; 6 7 printf("Enter 5 marks:\n"); 8 9 for(int i=0;i<5;i++) 10 { 11 scanf("%d",&marks[i]); 12 } 13 14 printf("\nMarks:\n"); 15 16 for(int i=0;i<5;i++) 17 { 18 printf("%d ",marks[i]); 19 } 20 21 return 0; 22}
Two-Dimensional (2D) Array
A two-dimensional array stores data in rows and columns.
It is commonly used to represent matrices.
Example
11 2 3 24 5 6 37 8 9
Declaration
1int matrix[3][3];
Initialization
1int matrix[2][3] = 2{ 3 {1,2,3}, 4 {4,5,6} 5};
Accessing Elements
1printf("%d", matrix[1][2]);
Output
16
Input and Output of 2D Array
1#include <stdio.h> 2 3int main() 4{ 5 int matrix[2][2]; 6 7 for(int i=0;i<2;i++) 8 { 9 for(int j=0;j<2;j++) 10 { 11 scanf("%d",&matrix[i][j]); 12 } 13 } 14 15 printf("\nMatrix:\n"); 16 17 for(int i=0;i<2;i++) 18 { 19 for(int j=0;j<2;j++) 20 { 21 printf("%d ",matrix[i][j]); 22 } 23 24 printf("\n"); 25 } 26 27 return 0; 28}
Multidimensional Arrays
Arrays can have more than two dimensions.
Example
1int data[2][3][4];
Applications:
- Image Processing
- 3D Graphics
- Scientific Computing
- Machine Learning
Array Traversal
Traversal means visiting every element of an array.
Example
1#include <stdio.h> 2 3int main() 4{ 5 int numbers[]={5,10,15,20}; 6 7 for(int i=0;i<4;i++) 8 { 9 printf("%d\n",numbers[i]); 10 } 11 12 return 0; 13}
Strings
A string is a sequence of characters terminated by the null character ('\0').
Example
1Hello
Memory representation
1H e l l o \0
Character Arrays
Strings are stored using character arrays.
Example
1char name[20];
Initialization
1char name[]="Ankit";
Equivalent to
1A n k i t \0
Reading Strings
Using scanf()
1char name[20]; 2 3scanf("%19s",name);
This reads input only until the first whitespace.
gets() vs fgets()
gets()
1gets(name);
Problems:
- Unsafe
- No bounds checking
- Removed from the C standard
- Can cause buffer overflow
fgets()
1fgets(name,sizeof(name),stdin);
Advantages
- Safe
- Limits input length
- Prevents buffer overflow
Recommendation
Always prefer fgets() over gets() in modern C programs.
puts()
Displays a string followed by a newline.
Example
1#include <stdio.h> 2 3int main() 4{ 5 char name[]="Tech3Space"; 6 7 puts(name); 8 9 return 0; 10}
Output
1Tech3Space
Common String Functions
To use string functions include:
1#include <string.h>
strlen()
Returns the length of a string (excluding the null character).
Example
1#include <stdio.h> 2#include <string.h> 3 4int main() 5{ 6 char name[]="Programming"; 7 8 printf("%zu",strlen(name)); 9 10 return 0; 11}
Output
111
strcpy()
Copies one string into another.
Example
1char source[]="Hello"; 2char destination[20]; 3 4strcpy(destination,source); 5 6printf("%s",destination);
Output
1Hello
strcat()
Concatenates (joins) two strings.
Example
1char first[30]="Hello "; 2char second[]="World"; 3 4strcat(first,second); 5 6printf("%s",first);
Output
1Hello World
strcmp()
Compares two strings.
Example
1char first[]="Apple"; 2char second[]="Apple"; 3 4printf("%d",strcmp(first,second));
Output
10
Return values:
| Result | Meaning |
|---|---|
| 0 | Equal |
| < 0 | First string is smaller |
| > 0 | First string is greater |
Practice Project 1: Matrix Addition
1#include <stdio.h> 2 3int main() 4{ 5 int a[2][2],b[2][2],sum[2][2]; 6 7 printf("Enter first matrix:\n"); 8 9 for(int i=0;i<2;i++) 10 for(int j=0;j<2;j++) 11 scanf("%d",&a[i][j]); 12 13 printf("Enter second matrix:\n"); 14 15 for(int i=0;i<2;i++) 16 for(int j=0;j<2;j++) 17 scanf("%d",&b[i][j]); 18 19 printf("\nSum Matrix:\n"); 20 21 for(int i=0;i<2;i++) 22 { 23 for(int j=0;j<2;j++) 24 { 25 sum[i][j]=a[i][j]+b[i][j]; 26 printf("%d ",sum[i][j]); 27 } 28 29 printf("\n"); 30 } 31 32 return 0; 33}
Practice Project 2: Matrix Multiplication
Matrix multiplication is performed by multiplying rows of the first matrix with columns of the second matrix.
1Result[i][j] = Σ(A[i][k] × B[k][j])
1#include <stdio.h> 2 3int main() 4{ 5 int a[2][2], b[2][2], result[2][2] = {0}; 6 7 printf("Enter first 2x2 matrix:\n"); 8 for(int i=0;i<2;i++) 9 for(int j=0;j<2;j++) 10 scanf("%d",&a[i][j]); 11 12 printf("Enter second 2x2 matrix:\n"); 13 for(int i=0;i<2;i++) 14 for(int j=0;j<2;j++) 15 scanf("%d",&b[i][j]); 16 17 for(int i=0;i<2;i++) 18 { 19 for(int j=0;j<2;j++) 20 { 21 for(int k=0;k<2;k++) 22 { 23 result[i][j] += a[i][k] * b[k][j]; 24 } 25 } 26 } 27 28 printf("\nResult Matrix:\n"); 29 30 for(int i=0;i<2;i++) 31 { 32 for(int j=0;j<2;j++) 33 { 34 printf("%d ", result[i][j]); 35 } 36 printf("\n"); 37 } 38 39 return 0; 40}
Practice Project 3: String Reverse
1#include <stdio.h> 2#include <string.h> 3 4int main() 5{ 6 char str[100]; 7 8 printf("Enter a string: "); 9 fgets(str,sizeof(str),stdin); 10 11 int len=strlen(str); 12 13 if(str[len-1]=='\n') 14 { 15 str[--len]='\0'; 16 } 17 18 printf("Reversed String: "); 19 20 for(int i=len-1;i>=0;i--) 21 { 22 printf("%c",str[i]); 23 } 24 25 return 0; 26}
Practice Project 4: Palindrome Checker
1#include <stdio.h> 2#include <string.h> 3 4int main() 5{ 6 char str[100]; 7 int flag=1; 8 9 printf("Enter a string: "); 10 fgets(str,sizeof(str),stdin); 11 12 int len=strlen(str); 13 14 if(str[len-1]=='\n') 15 { 16 str[--len]='\0'; 17 } 18 19 for(int i=0;i<len/2;i++) 20 { 21 if(str[i]!=str[len-i-1]) 22 { 23 flag=0; 24 break; 25 } 26 } 27 28 if(flag) 29 printf("Palindrome"); 30 else 31 printf("Not Palindrome"); 32 33 return 0; 34}
Common Mistakes to Avoid
- Accessing array indexes outside their valid range.
- Forgetting that array indexing starts from
0. - Using
gets(), which is unsafe and removed from modern C standards. - Forgetting to include
<string.h>when using string functions. - Assuming
scanf("%s")can read strings containing spaces. - Forgetting that strings end with the null character (
'\0'). - Copying strings with
=instead of usingstrcpy().
Best Practices
- Use meaningful array names such as
studentMarksorsalesData. - Validate array indexes before accessing elements.
- Prefer
fgets()overgets()for reading strings safely. - Always allocate enough memory for the null terminator in strings.
- Use library functions like
strlen(),strcpy(), andstrcmp()instead of writing custom implementations unless for learning purposes. - Keep matrix dimensions consistent when performing operations such as addition and multiplication.
Module Summary
In this module, you learned:
- What arrays are and how to declare, initialize, and access them.
- How to work with one-dimensional, two-dimensional, and multidimensional arrays.
- How to traverse arrays using loops.
- How strings are represented as character arrays in C.
- The difference between
gets()and the saferfgets(). - How to display strings using
puts(). - How to use common string library functions:
strlen(),strcpy(),strcat(), andstrcmp(). - How to build practical applications such as matrix addition, matrix multiplication, string reversal, and palindrome checking.
After completing this module, you'll be ready to learn Pointers in C, including memory addresses, pointer arithmetic, dynamic memory allocation, and the relationship between pointers, arrays, and functions.