array
array
Variables store single values, but when we need to store multiple related values, we use arrays.
Arrays help in efficient data management and allow indexed access to elements.
Declaration of an Array
Syntax:
data_type array_name[size];
Example:
Initialization of an Array
int numbers[5] = {10, 20, 30, 40, 50}; // Declaring and initializing an array
OR
int numbers[] = {10, 20, 30, 40, 50}; // Size is determined automatically
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
return 0;
}
4.2 Two-Dimensional Arrays
A 2D array is an array of arrays, useful for matrices, tables, etc.
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
#include <stdio.h>
int main() {
int matrix[2][2];
return 0;
}
#include <stdio.h>
int main() {
int matrix[2][2] = {{1, 2}, {3, 4}};
printf("Matrix Elements:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
OR
Displaying a String:
#include <stdio.h>
int main() {
char name[] = "Hello";
printf("%s", name);
return 0;
}
OR using gets():
char name[20];
printf("Enter your name: ");
gets(name);
printf("Your name is: %s", name);
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello";
printf("Length of string: %d", strlen(str));
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello";
char dest[10];
strcpy(dest, src);
printf("Copied String: %s", dest);
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Apple";
char str2[] = "Banana";
if (strcmp(str1, str2) == 0)
printf("Strings are equal");
else
printf("Strings are different");
return 0;
}
Summary
Arrays store multiple values of the same type.
1D and 2D Arrays are used to handle structured data efficiently.
Strings are character arrays terminated by \0.
String functions (strlen, strcpy, strcat, strcmp) help in string manipulation.