Arrays, Strings & Structures in C
Arrays, Strings & Structures in C
pg. 1
Chapter 1: Arrays
1.1.1. Concept of Arrays
An array is a collection of variables of the same type, stored in contiguous memory locations. Arrays
allow you to store multiple values in a single variable, making it easier to manage data.
Example: An array of integers can store multiple integer values under a single name.
When you declare an array, you define its type and size. The array is indexed from 0 to n-1, where n
is the size of the array.
data_type array_name[array_size];
Example:
When you define an array, you initialize it with values. The values can be provided at the time of
declaration or later.
Example:
Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
This statement accesses the value of the first element [0] in myNumbers:
array_name[index]
Example:
pg. 2
Example
myNumbers[0] = 33;
Example
printf("%d", myNumbers[0]);
You can loop through the array elements with the for loop.
#include <stdio.h>
int main() {
int i;
printf("%d\n", myNumbers[i]);
return 0;
Another common way to create arrays, is to specify the size of the array, and add elements later:
Example
// Add elements
myNumbers[0] = 25;
myNumbers[1] = 50;
pg. 3
myNumbers[2] = 75;
myNumbers[3] = 100;
It is important to note that all elements in an array must be of the same data type.
This means you cannot mix different types of values, like integers and floating point numbers, in the
same array:
Example
In the example above, the values 3.15 and 5.99 will be truncated to 3 and 5. In some cases it might
also result in an error, so it is important to always make sure that the elements in the array are of the
same type.
To get the size of an array, you can use the sizeof operator:
Example
#include <stdio.h>
int main() {
printf("%lu", sizeof(myNumbers));
return 0;
Why did the result show 20 instead of 5, when the array contains 5 elements?
You learned from the Data Types chapter that an int type is usually 4 bytes, so from the example
above, 4 x 5 (4 bytes x 5 elements) = 20 bytes.
Knowing the memory size of an array is great when you are working with larger programs that
require good memory management.
But when you just want to find out how many elements an array has, you can use the
following formula (which divides the size of the array by the size of the first element in the
array):
#include <stdio.h>
int main() {
pg. 4
int myNumbers[] = {10, 25, 50, 75, 100};
printf("%d", length);
return 0;
Real-Life Example
To demonstrate a practical example of using arrays, let's create a program that calculates the average
of different ages:
Example
#include <stdio.h>
int main() {
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
int i;
// Loop through the elements of the array and accumulate the sum
sum += ages[i];
return 0;
pg. 5
1.2.1. One dimensional array in C
Arrays are a fundamental concept in programming, and they come in different dimensions. One-
dimensional arrays, also known as single arrays, are arrays with only one dimension or a single row.
In this article, we'll dive deep into one-dimensional arrays in C programming language, including
their syntax, examples, and output.
dataType arrayName[arraySize];
dataType specifies the data type of the array. It can be any valid data type in C programming
language, such as int, float, char, double, etc.
arrayName is the name of the array, which is used to refer to the array in the program.
arraySize specifies the number of elements in the array. It must be a positive integer value.
Let's take a simple example of a one-dimensional array in C programming language to understand its
syntax and usage.
#include <stdio.h>
int main() {
return 0;
Output:
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50
Explanation:
In the above example, we have declared a one-dimensional array of integers named numbers. The
array contains five elements, and each element is initialized with a value.
We have used a for loop to iterate over the elements of the array and print their values using
the printf function.
pg. 6
1.2.2. Accessing Elements of One-Dimensional Array in C
In a one-dimensional array, each element is identified by its index or position in the array. The index
of the first element in the array is 0, and the index of the last element is arraySize - 1.
arrayName[index]
#include <stdio.h>
int main() {
return 0;
Output:
Explanation:
In the above example, we have declared a one-dimensional array of integers named numbers. We
have accessed the first element of the array using the index 0 and the third element of the array
using the index 2.
We can modify the value of individual elements of a one-dimensional array using their index. To
modify an element, we simply assign a new value to it using the assignment operator =.
#include <stdio.h>
int main() {
pg. 7
printf("The third element of the array is %d\n", numbers[2]);
numbers[2] = 35;
return 0;
Output:
Explanation:
In the above example, we have declared a one-dimensional array of integers named numbers and
initialized it with the values {10, 20, 30, 40, 50}. We have used the printf function to print the third
element of the array, which is accessed using the index 2.
After that, we modified the value of the third element by assigning a new value of 35 to it. Finally, we
have used the printf function again to print the new value of the third element.
In C programming language, we can initialize a one-dimensional array while declaring it or later in the
program. We can initialize a one-dimensional array while declaring it by using the following syntax:
- "{element1, element2, ..., elementN}' specifies the values of the elements in the array. The number
of elements must be equal to "arraySize'.
#include <stdio.h>
int main() {
return 0;
pg. 8
}
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50
Explanation:
In the above example, we have declared a one-dimensional array of integers named numbers and
initialized it with the values {10, 20, 30, 40, 50}. We have used a for loop to iterate over the elements
of the array and print their values using the printf function.
1.2.5. We can also initialize a one-dimensional array later in the program by assigning values to its
elements using the following syntax:
arrayName[index] = value;
Let's take an example to understand how to initialize a one-dimensional array later in the program
in C programming language.
#include <stdio.h>
int main() {
int numbers[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
return 0;
pg. 9
}
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50
Explanation:
In the above example, we have declared a one-dimensional array of integers named numbers. We
have initialized the elements of the array later in the program by assigning values to them. We have
used a for loop to iterate over the elements of the array and print their values using
the printf function.
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array as a
table with 3 rows and each row has 4 columns.
float y[2][4][3];
pg. 10
1.3.2. Initializing a multidimensional array
You can initialize a three-dimensional array in a similar way to a two-dimensional array. Here's an
example,
int test[2][3][4] = {
#include <stdio.h>
int main() {
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
};
pg. 11
// Print the values of the array
printf("\n");
return 0;
Output:
1234
5678
9 10 11 12
Explaination:
1. #include <stdio.h>
This line is a preprocessor directive that tells the compiler to include the stdio.h library. The stdio.h
library provides standard input/output functions such as printf() and scanf().
2. int main()
This is the main function, where the execution of the C program begins.
int indicates that the function will return an integer value to the operating system when the
program finishes execution.
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
};
pg. 12
This line declares and initializes a 2D array called matrix.
Row 1: {1, 2, 3, 4}
Row 2: {5, 6, 7, 8}
1 2 3 4
5 6 7 8
9 10 11 12
The rows are indexed as 0, 1, and 2 (since indexing in C starts from 0).
The columns are indexed as 0, 1, 2, and 3.
printf("\n");
This inner loop iterates over the columns of the current row.
pg. 13
The variable j is the column index. It starts at 0 and goes up to 3, so it iterates 4 times (for
columns 0, 1, 2, and 3).
For each iteration, it prints the element at matrix[i][j] (i.e., the element at the i-th row and j-
th column).
printf("\n");
After printing all the elements of a row, printf("\n") prints a newline character, which moves
the cursor to the next line. This makes the matrix appear as a grid with each row on a new
line.
5. return 0;
This line ends the main() function and returns the value 0 to the operating system.
Returning 0 typically indicates that the program ran successfully without any errors.
1 2 3 4
5 6 7 8
9 10 11 12
The outer loop iterates over the rows, one row at a time.
The inner loop iterates over the columns of the current row and prints each element.
The program prints the following output, with each row on a new line:
1234
5678
9 10 11 12
Conclusion:
2D arrays are used to represent matrices or grids. In this case, we represented a 3x4 matrix.
Nested loops are used to access and print all the elements of a 2D array row by row.
pg. 14
A 3D array is essentially an array of 2D arrays, where each element in the 3D array is itself a 2D array.
It can be visualized as a collection of matrices, stacked one on top of the other.
#include <stdio.h>
int main() {
int matrix[2][2][2] = {
{1, 2},
{3, 4}
},
{5, 6},
{7, 8}
};
return 0;
pg. 15
Explanation:
1. Array Declaration:
Layer 1:
1 2
3 4
Layer 2:
5 6
7 8
2. Nested Loops:
o Outer loop (i): Loops over the 2 layers (depth), from 0 to 1 (2 layers).
o Middle loop (j): Loops over the 2 rows in each layer, from 0 to 1.
o Inner loop (k): Loops over the 2 columns in each row, from 0 to 1.
o After each row is printed, we move to the next line using printf("\n").
o After each layer is printed, an extra newline is added to separate the layers.
Output:
Layer 1:
12
34
Layer 2:
56
78
Output Explanation:
Layer 1 contains:
12
pg. 16
34
Layer 2 contains:
56
78
Each layer consists of 2 rows, and each row contains 2 columns. The output clearly shows the
structure of the 3D array.
Conclusion:
This simple example demonstrates the basic usage of a 3D array with 2 layers, 2 rows, and
2 columns.
Nested loops are used to traverse through each dimension of the array (depth, rows, and
columns) to print all elements in the array.
pg. 17
Chapter 2: Strings
In C, a string is an array of characters, terminated by the special character '\0' (null character).
Example:
The string "John" is automatically stored as an array: {'J', 'o', 'h', 'n', '\0'}.
C provides many built-in functions to manipulate strings. These functions are available in the string.h
library.
pg. 18
1. strcpy() - String Copy
The strcpy() function is used to copy a string from one location to another.
Syntax:
destination: A pointer to the destination string where the content will be copied.
source: A pointer to the source string that you want to copy.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char destination[50];
strcpy(destination, source);
return 0;
Output:
pg. 19
2. strcmp() - String Comparison
The strcmp() function is used to compare two strings lexicographically (based on ASCII values).
Syntax:
Returns:
Example:
#include <stdio.h>
#include <string.h>
int main() {
if (result < 0) {
} else {
return 0;
Output:
Explanation: The comparison is done based on ASCII values. Since the ASCII value of 'A' is
smaller than 'B', "Apple" is considered lexicographically smaller than "Banana".
pg. 20
3. strlen() - String Length
The strlen() function returns the length of a string (i.e., the number of characters in the string,
excluding the null terminator '\0').
Syntax:
Example:
#include <stdio.h>
#include <string.h>
int main() {
return 0;
Output:
Explanation: The length of the string "Hello, World!" is 13 because there are 13 characters
before the null terminator ('\0').
pg. 21
4. strcat() - String Concatenation
The strcat() function is used to concatenate (append) one string to the end of another.
Syntax:
Example:
#include <stdio.h>
#include <string.h>
int main() {
strcat(str1, str2);
return 0;
Output:
Explanation: The strcat() function appends the string "World!" to the string "Hello, ",
resulting in "Hello, World!".
pg. 22
Summary of Functions:
Important Notes:
strcpy(): Be careful with buffer sizes when using strcpy(). The destination array must be large
enough to hold the source string and the null terminator.
strlen(): Does not count the null terminator ('\0'), only the actual characters.
strcat(): Always ensure that the destination array is large enough to hold the concatenated
result, otherwise, it could lead to a buffer overflow.
These functions are part of the string.h library, so you need to include it in your program to use
them.
pg. 23
In C programming, string manipulation can be done without using the functions from the string.h
library. This requires manually implementing operations such as copying, concatenating, comparing,
and finding the length of strings.
To find the length of a string without using the strlen() function, we can loop through each character
of the string until we encounter the null character '\0'.
#include <stdio.h>
int length = 0;
length++;
return length;
int main() {
return 0;
Output:
Explanation: We iterate through the string until we encounter the null character ('\0'). The
variable length will hold the number of characters before the null character.
To copy one string to another without using strcpy(), we can use a loop to copy each character one
by one.
#include <stdio.h>
pg. 24
void string_copy(char dest[], char src[]) {
int i = 0;
dest[i] = src[i];
i++;
int main() {
string_copy(dest, src);
return 0;
Output:
Explanation: We loop through the source string and copy each character to the destination
string. Finally, we manually add the null terminator ('\0') to the destination string.
To concatenate two strings without using strcat(), we can first find the end of the first string and then
append the second string to it.
#include <stdio.h>
int i = 0, j = 0;
i++;
pg. 25
// Append characters of the second string
dest[i] = src[j];
i++;
j++;
dest[i] = '\0';
int main() {
string_concat(str1, str2);
return 0;
Output:
Explanation: First, we find the null terminator in the first string (str1), which marks the end
of the string. Then, we append each character of the second string (str2) to the end of str1.
Finally, we add a null terminator ('\0') to the end of the concatenated string.
pg. 26
4. Comparing Two Strings (like strcmp)
To compare two strings without using strcmp(), we can compare the characters of both strings one
by one until a mismatch is found or both strings end.
#include <stdio.h>
int i = 0;
if (str1[i] != str2[i]) {
i++;
int main() {
if (result == 0) {
} else {
return 0;
Output:
pg. 27
Explanation: We compare each character of both strings. If any character is different, the
function returns the difference in their ASCII values. If the strings are identical, the function
returns 0. If one string is longer than the other, the function compares the null terminators.
Copy String Copy one string to another while (src[i] != '\0') dest[i] = src[i];
Concatenate Append one string to another while (dest[i] != '\0') i++; while (src[j] != '\0') {...}
These examples demonstrate how string operations can be implemented manually in C, without
using the built-in string functions from string.h. By understanding these concepts, you gain a deeper
understanding of how strings work internally in C.
pg. 28
Chapter 3: Structures
A structure is a user-defined data type in C that allows you to group variables of different data types
under a single name. Each variable inside a structure is called a member.
Example:
struct Student {
char name[50];
int age;
float marks;
};
You can declare a structure variable by using the structure type followed by the variable name.
Syntax:
Example:
Structures can be initialized at the time of declaration, or their members can be assigned values later.
Initialization at Declaration:
strcpy([Link], "John");
[Link] = 20;
[Link] = 85.5;
You can access the members of a structure using the dot (.) operator.
Example:
pg. 29
printf("Marks: %.2f\n", [Link]);
Example of Structure :
#include <stdio.h>
#include <string.h>
struct Student {
};
int main() {
[Link] = 20;
[Link] = 85.5;
return 0;
pg. 30
Explanation:
Summary
Strings: Basics, Library Functions, and Operations on Strings without using string.h.
These concepts are fundamental to programming in C, and mastering them will help you understand
more advanced topics in C programming.
pg. 31