Arrays
what is an array?
Arrays and strings are fundamental data structures in C and C++. They allow the efficient storage and manipulation of data. Arrays store multiple values of the same data type in contiguous memory locations, whereas strings, which are arrays of characters, handle text-based data. Understanding these concepts is essential for effective programming and memory management.
One-Dimensional Arrays
A one-dimensional array is a sequence of elements of the same type stored in contiguous memory locations. It allows efficient access to individual elements using an index and is useful for handling a collection of data of the same type. Arrays help in storing and managing large amounts of data, such as lists of numbers, scores, or names, without needing multiple variables.
Declaration of One-Dimensional Arrays
A one-dimensional array is declared by specifying the data type, the name of the array, and its size. The size determines how many elements the array can store. Defining an array reserves a block of memory that can be accessed using indexed positions.
Initialization of One-Dimensional Arrays
Arrays can be initialized at the time of declaration by providing a list of values within curly braces. If no values are provided, the array holds garbage values. If the size is not explicitly defined, the compiler determines it based on the number of values assigned.
Accessing Elements in One-Dimensional Arrays
Elements in an array are accessed using their index, starting from zero. By referencing a specific index, we can retrieve or modify the value stored at that position. Attempting to access an index outside the defined size may lead to unpredictable behavior.
Example: Storing and Printing Student Marks
The following program demonstrates how to store and print student marks using an array.
#include <stdio.h>
int main() {
int marks[5] = {85, 90, 78, 92, 88};
for(int i = 0; i < 5; i++) {
printf("Student %d: %d\n", i + 1, marks[i]);
}
return 0;
}
Two-Dimensional Arrays
A two-dimensional array is an extension of the one-dimensional array, where elements are stored in a tabular format consisting of rows and columns. It is useful for representing matrices, tables, and grid-based structures.
Declaration of Two-Dimensional Arrays
A 2D array is declared by specifying the number of rows and columns. This allocation helps structure the data in a way that allows efficient traversal and manipulation.
Initialization of Two-Dimensional Arrays
A 2D array can be initialized at the time of declaration by providing a nested list of values. Each row represents an individual array, with values separated by commas.
Accessing Elements in Two-Dimensional Arrays
Elements in a 2D array are accessed using two indices: one for the row and one for the column. This helps retrieve and modify specific values efficiently.
Example: Printing a 2D Matrix
The following program demonstrates how to declare and print a 2D array.
#include <stdio.h>
int main() {
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Character Arrays (Strings)
what is an string?
A character array, also known as a string, is an array of characters that store text-based data. Strings in C are represented as arrays terminated by a null character (\0
).
One-Dimensional Strings
A one-dimensional character array is a simple way to store and manipulate text. When defining a string, it must include space for the null character to indicate the end of the string.
Two-Dimensional Character Arrays (String Arrays)
A two-dimensional character array allows multiple strings to be stored in an organized manner. Each row represents a separate string, making it useful for handling lists of words, names, or sentences.
Reading and Writing Strings
Strings can be read from user input and printed using functions like scanf
, gets
, and fgets
. While scanf
reads single-word input, fgets
is preferred for reading entire sentences safely.
String-Handling Functions
C provides several built-in functions in <string.h>
for manipulating strings efficiently.
1. Finding String Length - strlen()
The strlen()
function returns the number of characters in a string, excluding the null terminator.
int len = strlen("Hello"); // Output: 5
2. Copying Strings - strcpy()
The strcpy()
function copies one string into another, ensuring safe duplication of text.
char source[] = "World";
char destination[10];
strcpy(destination, source);
3. Concatenating Strings - strcat()
The strcat()
function appends one string to another, combining text data efficiently.
char first[20] = "Hello ";
char second[] = "World";
strcat(first, second); // first becomes "Hello World"
4. Comparing Strings - strcmp()
The strcmp()
function compares two strings lexicographically and returns a value based on their relative order.
if (strcmp("apple", "banana") < 0) {
printf("apple comes before banana");
}
5. Finding Characters in a String - strchr()
The strchr()
function searches for a specific character within a string and returns a pointer to its first occurrence.
char *ptr = strchr("Hello", 'e'); // ptr points to "ello"
6. Finding Substrings - strstr()
The strstr()
function locates a substring within a string and returns a pointer to the first occurrence of the substring.
char *ptr = strstr("Hello World", "World"); // ptr points to "World"
Conclusion
Arrays and strings are vital concepts in C and C++. One-dimensional and two-dimensional arrays allow structured data storage, while character arrays handle textual data. String-handling functions simplify manipulation, making programming more efficient. Mastering these concepts ensures efficient memory utilization and better data handling in C and C++ programming.