Unit 4 Arrays
Unit 4 Arrays
Syllabus:
Character Arrays and Strings: Declaration and Initialization String Variables, Reading
Strings from Terminal, Writing Strings to Screen, Putting Strings Together, Comparison of
Two Strings, Introduction to String handling Functions
Introduction to Arrays
An array is a collection of variables of the same data type stored in contiguous memory
locations. It allows storing multiple values of the same type in a single data structure and
accessing them using an index.
2. Characteristics of Arrays
Fixed Size: The size of the array is defined at compile-time and cannot be changed
dynamically (in C).
Homogeneous Data: All elements of an array must be of the same data type.
Contiguous Memory: Array elements are stored in adjacent memory locations.
Indexed Access: Array elements are accessed using an index, which starts from 0.
a. Declaration
data_type array_name[size];
Example:
int numbers[5];
b. Initialization
At Declaration:
Partial Initialization: If fewer values are provided, the remaining elements are initialized to
0.
Using Loops:
Example:
Modifying an Element:
5. Memory Representation
7. Limitations of Arrays
8. Example Programs
#include <stdio.h>
int main() {
int numbers[5] = {12, 35, 7, 10, 22};
int max = numbers[0];
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int size = 5;
return 0;
}
One Dimensional Array?
A one-dimensional array is a list of elements, all of the same data type, stored in contiguous
memory locations. Each element is identified by its index or subscript.
data_type array_name[size];
Example:
int numbers[5];
Here:
2. Using loops:
int numbers[5];
for(int i = 0; i < 5; i++) {
numbers[i] = i * 10;
}
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50}; // Array declaration and
initialization
int sum = 0;
float average;
return 0;
}
1. Using malloc
The malloc function allocates memory for an array without initializing its elements.
Syntax:
#include <stdio.h>
#include <stdlib.h> // For malloc and free
int main() {
int *array, size;
if (array == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
return 0;
}
Initialization of One-Dimensional Arrays in C
In C, arrays can be initialized either at the time of declaration or after declaration. The
initialization process involves assigning values to the elements of an array, either explicitly or
through loops.
When initializing an array at the time of declaration, you provide a list of values within curly
braces {}. The size of the array can either be explicitly provided or inferred by the compiler
based on the number of elements in the initializer list.
Syntax:
Example 1:
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50}; // Static initialization
return 0;
}
Output:
10 20 30 40 50
In this case, the size is explicitly set to 5, and the array elements are initialized with the
values provided.
Example 2:
If you omit the size in the declaration, the compiler will determine the size based on the
number of elements in the initialization list.
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 50}; // Size is inferred by compiler
return 0;
}
Output:
10 20 30 40 50
Here, the array size is automatically determined to be 5 based on the number of elements in
the initializer list.
2. Partial Initialization
You can also initialize only part of the array, and the remaining elements will be
automatically set to zero (if the array is of a simple type like int, float, etc.).
Example:
#include <stdio.h>
int main() {
int numbers[5] = {10, 20}; // First two elements initialized, others
set to 0
return 0;
}
Output:
10 20 0 0 0
In this case, only the first two elements are explicitly initialized to 10 and 20, while the
remaining three elements are initialized to 0.
3. Initialization Using a Loop
If you don't know the values of the array elements at the time of declaration, you can
initialize the array using a loop after declaring it.
Example:
#include <stdio.h>
int main() {
int numbers[5];
return 0;
}
Output:
10 20 30 40 50
In this example, a loop is used to initialize the array with multiples of 10.
Character arrays (strings) are initialized similarly to other arrays, but each element is a single
character.
Example:
#include <stdio.h>
int main() {
char names[3][10] = {"John", "Alice", "Bob"}; // Array of strings
return 0;
}
5. Omitting Array Size During Initialization in C
When you initialize an array in C without specifying the size, the compiler automatically
determines the size of the array based on the number of elements in the initializer list.
data_type: Specifies the type of the elements (e.g., int, float, etc.).
array_name: Name of the array.
value1, value2, ..., valueN: The elements used to initialize the array.
When the size is omitted, the compiler counts the number of elements in the initializer list
and assigns the appropriate size to the array.
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 50}; // Size is omitted
return 0;
}
Output:
10 20 30 40 50
Dynamic Initialization of Arrays in C
Dynamic initialization refers to the process of assigning values to array elements at runtime,
rather than at compile time. This can be done using loops or functions like malloc, calloc,
or realloc, which allow for dynamic memory allocation and manipulation of arrays.
In dynamic initialization, you assign values to the elements of an array during the program
execution, usually in a loop. This can be useful when the size of the array is not known at
compile time, or when values are generated or read from external sources (e.g., user input,
files, etc.).
#include <stdio.h>
int main() {
int n;
return 0;
}
Output:
Syntax:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *numbers;
int n;
if (numbers == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
return 0;
}
Output:
The calloc (contiguous allocation) function is similar to malloc but additionally initializes
the memory to zero.
Syntax:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *numbers;
int n;
if (numbers == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
return 0;
}
Output:
Here, the calloc function allocates memory and initializes it to 0, but we still modify the
elements in the loop after allocation.
The realloc function is used to resize an already allocated block of memory, either
increasing or decreasing the size.
Syntax:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *numbers;
int n;
if (numbers == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
if (numbers == NULL) {
printf("Memory reallocation failed!\n");
return 1;
}
return 0;
}
Output:
#include <stdio.h>
int main() {
int n;
return 0;
}
Two-Dimensional Arrays in C
data_type array_name[row_size][column_size];
#include <stdio.h>
int main() {
// Initialize a 3x3 matrix
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
return 0;
}
Output:
In this example, a 3x3 matrix is initialized with values, and each element is accessed using
two indices matrix[i][j].
If fewer values are provided than the number of elements in the array, the remaining elements
are automatically initialized to 0.
int main() {
// Partially initialize a 3x3 matrix
int matrix[3][3] = {
{1, 2}, // First row with two elements
{4, 5, 6}, // Second row with three elements
{7} // Third row with one element
};
return 0;
}
Output:
You can also use loops to initialize a two-dimensional array dynamically, particularly useful
when you don't know the values in advance.
#include <stdio.h>
int main() {
int matrix[3][3]; // Declare a 3x3 matrix
return 0;
}
Output:
This approach allows you to enter elements at runtime, providing more flexibility.
When initializing a two-dimensional array, you can omit the column size, and the compiler
will calculate it based on the number of values in the initializer list.
#include <stdio.h>
int main() {
// Initialize a 2D array where column size is omitted
int matrix[][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
return 0;
}
Output:
#include <stdio.h>
int main() {
// Declare and initialize a 2x3 matrix
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
return 0;
}
Explanation:
Sample Output:
Enter row and column to access an element (row 0-1, column 0-2): 1 2
Element at position (1, 2) is: 6
Character Arrays
A Character Array is simply an array of char type, and it is commonly used to store strings.
Each element of the array holds a single character.
char array_name[size];
String Variables in C
You can declare a character array in C by specifying the size of the array or using a string
literal for initialization.
This creates an array of 20 characters, which can store a string of up to 19 characters, as the
last character will be reserved for the null character ( '\0').
You can initialize a character array either with individual characters or using a string literal.
Here, the compiler automatically adds the null character '\0' at the end of the string, and the
array will be of size 5.
When you initialize a string, it is important to include the null character '\0', which tells the
program where the string ends.
#include <stdio.h>
int main() {
// String initialization using a string literal
char greeting[] = "Hello, World!";
Here, the string greeting is initialized with the value "Hello, World!". The array
greeting[] is automatically sized to hold 14 characters (13 characters + '\0').
#include <stdio.h>
int main() {
// Declare and initialize a character array with individual characters
char name[5] = {'J', 'o', 'h', 'n', '\0'}; // Null character is added
manually
return 0;
}
Output:
Name: John
Explanation: The array name is explicitly initialized with the characters 'J', 'o', 'h', 'n',
followed by the null character '\0' to mark the end of the string. When the string is printed
using %s, it correctly displays "John".
#include <stdio.h>
int main() {
// Declare and initialize a character array with a string literal
char greeting[] = "Hello, World!";
return 0;
}
Output:
#include <stdio.h>
int main() {
// Declare a character array without initialization
char name[20];
return 0;
}
Output:
Name: Alice
Explanation: In this example, the character array name is declared without initialization. The
individual characters are assigned to the array manually, and the null character '\0' is
added at the end to terminate the string properly.
#include <stdio.h>
int main() {
char name[30]; // Declare a character array to hold the string
return 0;
}
Output (Example):
Explanation: The program uses scanf("%s", name) to read a string input from the user
and stores it in the name array. The string will be terminated automatically by the null
character when entered.
In C, there are several ways to read strings from the terminal (input) provided by the user.
The most common methods are scanf(), fgets(), and getchar(). Each method has its
advantages and limitations, especially when dealing with strings that contain spaces.
1. Using scanf()
The scanf() function is used to read input from the terminal. However, by default, scanf()
only reads a string up to the first whitespace (spaces, tabs, or newlines). This means it doesn't
handle strings with spaces very well.
Syntax:
scanf("%s", string_variable);
Example:
#include <stdio.h>
int main() {
char name[30]; // Declare a character array to hold the string
return 0;
}
Output:
Limitation:
If the user enters a name with spaces (e.g., "John Doe"), scanf() will only read the first
word ("John") and stop at the first space.
2. Using fgets()
The fgets() function is more flexible than scanf() because it can read strings with spaces
and includes the newline character (\n) at the end of the input.
Syntax:
Example:
#include <stdio.h>
int main() {
char name[50]; // Declare a character array to hold the string
return 0;
}
Output:
Advantages of fgets():
Limitation:
fgets() includes the newline character '\n' when the user presses Enter. This can be
removed by manually replacing the newline character if needed.
3. Using getchar()
The getchar() function reads a single character at a time, so you can use it to read a string
character by character. You need a loop to read multiple characters and store them in a
character array.
Syntax:
ch = getchar();
Example:
#include <stdio.h>
int main() {
char name[50]; // Declare a character array to hold the string
int i = 0;
char ch;
return 0;
}
Output:
Enter your name: John Doe
Your name is: John Doe
Advantages of getchar():
It reads each character, so it can handle spaces and any character input.
You can easily control the input loop to manage the string format.
In C, strings can be written to the screen (or standard output) using various methods. The
most commonly used functions are printf(), puts(), and fputs().
The printf() function is one of the most versatile and widely used functions in C for output.
It allows formatted output, meaning you can specify how the string should be displayed.
Syntax:
printf("format_specifier", string_variable);
"format_specifier": The format string that specifies how the data should be displayed
(e.g., %s for strings).
string_variable: The variable or string literal to be printed.
Example:
#include <stdio.h>
int main() {
char greeting[] = "Hello, World!"; // Declare and initialize a string
return 0;
}
Output:
Explanation: The %s format specifier tells printf() to output the string. The string
greeting is printed on the screen.
The puts() function is a simpler alternative to printf() for printing strings. It automatically
appends a newline (\n) at the end of the string.
Syntax:
puts(string_variable);
Example:
#include <stdio.h>
int main() {
char greeting[] = "Hello, World!"; // Declare and initialize a string
return 0;
}
Output:
Hello, World!
Explanation: The puts() function prints the string followed by a newline. You don’t need to
manually include \n, as puts() does it for you.
3. Using fputs() to Write Strings
The fputs() function is similar to puts(), but it does not append a newline character at the
end. It is often used when you need more control over the output format, especially when you
want to direct the output to a specific file or stream.
Syntax:
fputs(string_variable, stream);
Example:
#include <stdio.h>
int main() {
char greeting[] = "Hello, World!"; // Declare and initialize a string
return 0;
}
Output:
Hello, World!
Explanation: fputs() writes the string directly to the specified stream (stdout in this case,
which refers to the screen). Unlike puts(), it does not add a newline automatically.
In C, you can combine or concatenate strings using different methods. The most common
ways are using the strcat() function from the C standard library, and manual character-by-
character manipulation. Below are the various ways to put strings together:
The strcat() function from the <string.h> library is specifically designed for
concatenating (joining) two strings. It appends the contents of one string to the end of another
string.
Syntax:
strcat(destination_string, source_string);
Example:
#include <stdio.h>
#include <string.h> // Include the string.h library for strcat()
int main() {
char str1[50] = "Hello, "; // Initialize str1 with a string
char str2[] = "World!"; // Initialize str2 with a string
return 0;
}
Output:
Explanation: The function strcat() appends str2 to the end of str1. After the
concatenation, str1 contains the combined string.
Important Notes:
Ensure that the destination_string (in this case, str1) has enough space to hold the
concatenated result. If the destination array is too small, it may lead to a buffer overflow.
Always leave extra space in the destination string for the combined content and the null
terminator ('\0').
The sprintf() function is often used for more complex concatenation or when you need to
format strings as you combine them.
Syntax:
Example:
#include <stdio.h>
int main() {
char str1[] = "Hello, ";
char str2[] = "World!";
char result[50]; // Declare an array to store the concatenated result
return 0;
}
Output:
Explanation: sprintf() is used to combine str1 and str2 into the result array. It uses
the format "%s%s" to specify that both strings should be concatenated.
Advantages:
You can format the strings or add additional text during concatenation (e.g., numbers,
special characters).
You can specify a destination array where the formatted string will be placed.
3. Manual Concatenation Using a Loop
If you want more control over the concatenation process, you can manually append each
character from one string to another using a loop.
Example:
#include <stdio.h>
int main() {
char str1[50] = "Hello, ";
char str2[] = "World!";
int i = 0, j = 0;
return 0;
}
Output:
Explanation: This code manually appends each character from str2 to str1 using two
while loops. After the loop completes, the str1 array holds the concatenated result.
Finally, we ensure that the concatenated string is null-terminated by adding '\0'.
Although C does not support the + operator for string concatenation (unlike languages like
Python or JavaScript), C++ does support it with std::string. However, in C, we use
functions like strcat() or sprintf() to concatenate strings.
Summary of Methods to Concatenate Strings in C:
Method Description Limitation
Manual Manually appends each character from one Gives complete control, but requires
Loop string to another. more code.
In C, comparing two strings involves determining whether they are identical or whether one
is lexicographically greater than the other. There are two primary methods to compare
strings:
The strcmp() function from the <string.h> library is used to compare two strings
lexicographically. It compares the strings character by character and returns an integer value
based on the comparison.
Syntax:
Return Value:
Example:
#include <stdio.h>
#include <string.h> // Include string.h for strcmp
int main() {
char str1[] = "apple";
char str2[] = "banana";
char str3[] = "apple";
return 0;
}
Output:
Explanation:
o The first comparison checks if "apple" is lexicographically less than "banana",
which is true.
o The second comparison checks if "apple" is equal to "apple", which is true.
If you prefer, or need, to compare strings manually (for example, when you're implementing
your own string comparison function), you can do so by iterating through each character in
the strings and comparing them one by one.
Logic:
1. Compare characters at the same position in both strings.
2. If the characters are different, the strings are not equal, and you can stop the comparison.
3. If all characters are the same but the lengths of the strings are different, then the shorter
string is considered smaller.
4. If all characters match and the strings end at the same point (i.e., both are terminated by the
null character \0), then the strings are equal.
Example:
#include <stdio.h>
int main() {
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "hello";
if (compareStrings(str1, str2)) {
printf("str1 and str2 are equal.\n");
} else {
printf("str1 and str2 are not equal.\n");
}
if (compareStrings(str1, str3)) {
printf("str1 and str3 are equal.\n");
} else {
printf("str1 and str3 are not equal.\n");
}
return 0;
}
Output:
Null Terminator ('\0'): It is important to check for the null terminator to prevent accessing
memory outside the string bounds.
Case Sensitivity: By default, the manual comparison is case-sensitive, just like strcmp(). If
you want a case-insensitive comparison, you would need to convert both strings to
lowercase (or uppercase) before comparing.
Using strcmp():
o Pros: Simple and concise.
o Cons: Case-sensitive by default, but can be modified using strcasecmp() for case-
insensitive comparison.
Manual Comparison:
o Pros: Gives you complete control over the comparison process, allowing for custom
logic (e.g., case-insensitivity or ignoring certain characters).
o Cons: More code to write and maintain.
If you need to compare two strings without considering case sensitivity, you can use the
strcasecmp() function (available in POSIX-compliant systems, but not in the C standard
library).
Syntax:
In C, strings are arrays of characters terminated by a special null character ( '\0'). C provides
a range of built-in functions for handling strings, which are included in the <string.h>
library. These functions allow you to manipulate and process strings easily. Below, we'll
introduce the most commonly used string handling functions, categorized by their
functionality.
The strcpy() function copies the contents of one string to another. The destination string
must be large enough to hold the copied string, including the null terminator ( '\0').
Syntax:
dest: The destination string where the source string will be copied.
src: The source string that will be copied.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello, World!";
char dest[50];
return 0;
}
Output:
The strcat() function appends the content of one string (source) to another string
(destination). The destination string must be large enough to hold both strings.
Syntax:
dest: The destination string to which the source string will be appended.
src: The source string that will be appended to dest.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello, ";
char str2[] = "World!";
return 0;
}
Output:
The strlen() function calculates the length of a string by counting the number of characters
before the null terminator ('\0').
Syntax:
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
int length = strlen(str); // Find the length of str
return 0;
}
Output:
Length of string: 13
Syntax:
Return Values:
0: If the strings are equal.
A negative integer: If str1 is lexicographically less than str2.
A positive integer: If str1 is lexicographically greater than str2.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "banana";
if (result == 0) {
printf("Strings are equal.\n");
} else if (result < 0) {
printf("str1 is less than str2.\n");
} else {
printf("str1 is greater than str2.\n");
}
return 0;
}
Output:
The strchr() function searches for the first occurrence of a specified character in a string.
Syntax:
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *ptr = strchr(str, 'o'); // Find first occurrence of 'o'
if (ptr != NULL) {
printf("Character found at position: %ld\n", ptr - str);
} else {
printf("Character not found.\n");
}
return 0;
}
Output:
Syntax:
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *result = strstr(str, "World"); // Search for "World" in str
if (result != NULL) {
printf("Substring found: %s\n", result);
} else {
printf("Substring not found.\n");
}
return 0;
}
Output:
The strtok() function splits a string into tokens based on a delimiter (such as spaces or
commas).
Syntax:
str: The string to be tokenized. On subsequent calls, this parameter should be NULL.
delim: A string containing delimiter characters.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "C is a powerful language!";
char *token = strtok(str, " "); // Split by spaces
return 0;
}
Output:
Token: C
Token: is
Token: a
Token: powerful
Token: language!
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello world!";
strupr(str); // Convert string to uppercase
Output:
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "HELLO WORLD!";
strlwr(str); // Convert string to lowercase
Output:
#include <stdio.h>
#include <string.h>
int main() {
// 1. Demonstration of strcpy() - Copying a string
char source[] = "Hello, C programming!";
char destination[50];
if(result == 0) {
printf("Strings are equal (using strcmp).\n");
} else if(result < 0) {
printf("String str3 is lexicographically less than str4 (using
strcmp).\n");
} else {
printf("String str3 is lexicographically greater than str4 (using
strcmp).\n");
}
if (found != NULL) {
printf("Substring found: %s\n", found); // Substring starting from
"C"
} else {
printf("Substring not found.\n");
}
return 0;
}
1. strcpy(): Copies the content of source string into destination. In this example,
the string "Hello, C programming!" is copied to destination.
o Output: "Copied String (using strcpy): Hello, C programming!"
2. strcat(): Appends the string str2 ("world!") to str1 ("Hello, "). After
concatenation, str1 will contain "Hello, world!".
o Output: "Concatenated String (using strcat): Hello, world!"
3. strlen(): Calculates and returns the length of the string source ("Hello, C
programming!"). The length excludes the null terminator.
o Output: "Length of the string (using strlen): 23"
4. strcmp(): Compares two strings, str3 ("apple") and str4 ("banana"). It returns:
o 0 if both strings are equal.
o A negative value if the first string is lexicographically smaller.
o A positive value if the first string is lexicographically larger.
o In this case, "apple" is lexicographically smaller than "banana", so the output will
indicate that.
o Output: "String str3 is lexicographically less than str4 (using
strcmp)."
5. strstr(): Searches for the first occurrence of a substring ("C") within a string
(source). It returns a pointer to the first character of the found substring or NULL if the
substring is not found.
o Output: "Substring found: C programming!"
6. strtok(): Tokenizes the string str5 ("C programming is fun") by spaces, extracting
individual words as tokens.
o Output:
kotlin
Copy code
Token: C
Token: programming
Token: is
Token: fun
Summary of Output:
Suppose we have two matrices A and B, and we want to compute their product matrix C.
#include <stdio.h>
#define MAX 10
int main() {
int first[MAX][MAX], second[MAX][MAX], result[MAX][MAX];
int row1, col1, row2, col2;
if (col1 != row2) {
printf("Matrix multiplication is not possible.\n");
return 1; // Exit if multiplication is not possible
}
return 0;
}
1. Input matrices:
o First, the program takes the dimensions of matrix A (rows and columns) and matrix
B.
o Then, it takes the elements for both matrices.
2. Check for multiplication feasibility:
o Before multiplying, it checks if the number of columns in A is equal to the number of
rows in B. If not, matrix multiplication is not possible, and the program terminates.
3. Matrix Multiplication:
o The function multiplyMatrices() performs the multiplication using three nested
loops:
The outer two loops iterate over the rows of matrix A and the columns of
matrix B.
The innermost loop performs the summation for the product of the
corresponding elements.
4. Display Result:
o The resulting matrix is printed row by row.
Input:
Output:
Product of matrices:
19 22
43 50