0% found this document useful (0 votes)
5 views31 pages

Arrays, Strings & Structures in C

The document covers the fundamentals of arrays, strings, and structures in C programming, detailing their definitions, declarations, and operations. It includes examples of one-dimensional and multidimensional arrays, string manipulation functions, and the use of structures. Each section provides syntax and practical examples to illustrate the concepts effectively.

Uploaded by

harshadnaik042
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views31 pages

Arrays, Strings & Structures in C

The document covers the fundamentals of arrays, strings, and structures in C programming, detailing their definitions, declarations, and operations. It includes examples of one-dimensional and multidimensional arrays, string manipulation functions, and the use of structures. Each section provides syntax and practical examples to illustrate the concepts effectively.

Uploaded by

harshadnaik042
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module -6 :- Arrays , String & Structures

SR NO. Topic Name Page No.


1 Chapter 1: Arrays 2
Concept of Arrays
2 Declaration of Arrays 2
3 Definition of Arrays 2
4 Access the Elements of an Array 2
5 Change an Array Element 2
6 Loop Through an Array 3
7 Set Array Size 3
8 Avoid Mixing Data Types 4
9 Get Array Size or Length 4
10 One dimensional array in C 6
11 Accessing Elements of One-Dimensional Array in C 6
12 Modifying Elements of One-Dimensional Arrays 7
13 Initializing One Dimensional Array in C 8
14 Multidimensional Arrays 10
15 Initialization of a 2d array , Initialization of a 3d array 10
16 Example 1: Two-dimensional array to store and print values 11
17 Example 2: Three-dimensional array 15
18 Chapter 2: Strings 18
What is a String?, Library Functions for Strings
19 strcpy() - String Copy 19
20 strcmp() - String Comparison 20
21 strlen() - String Length 21
22 strcat() - String Concatenation 22
23 String operations without using string.h functions 23
24 Finding the Length of a String 24
25 Copying One String to Another (like strcpy) 24
26 Concatenating Two Strings (like strcat) 25
27 Comparing Two Strings (like strcmp) 27
28 Chapter 3: Structures 28
What is a Structure?, Declaring Structures, Initialization at Declaration:
29 Accessing Structure Members 29
30 Example of Structure : 30

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.

1.1.2. Declaration of Arrays

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.

 Syntax for Declaration:

data_type array_name[array_size];

 Example:

int numbers[5]; // Declares an array of 5 integers

1.1.3. Definition of Arrays

When you define an array, you initialize it with values. The values can be provided at the time of
declaration or later.

 Syntax for Definition:

data_type array_name[array_size] = {value1, value2, ..., valueN};

 Example:

int numbers[5] = {1, 2, 3, 4, 5}; // An array with 5 elements

1.1.4. Access the Elements of an Array

To access an array element, refer to its index number.

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:

 Syntax to access array element:

array_name[index]

 Example:

int myNumbers[] = {25, 50, 75, 100};


printf("%d", myNumbers[0]);

1.1.5. Change an Array Element

To change the value of a specific element, refer to the index number:

pg. 2
 Example

myNumbers[0] = 33;

 Example

int myNumbers[] = {25, 50, 75, 100};


myNumbers[0] = 33;

printf("%d", myNumbers[0]);

// Now outputs 33 instead of 25

1.1.6. Loop Through an Array

You can loop through the array elements with the for loop.

The following example outputs all elements in the myNumbers array:

#include <stdio.h>

int main() {

int myNumbers[] = {25, 50, 75, 100};

int i;

for (i = 0; i < 4; i++) {

printf("%d\n", myNumbers[i]);

return 0;

1.1.7. Set Array Size

Another common way to create arrays, is to specify the size of the array, and add elements later:

 Example

// Declare an array of four integers:


int myNumbers[4];

// Add elements
myNumbers[0] = 25;
myNumbers[1] = 50;

pg. 3
myNumbers[2] = 75;
myNumbers[3] = 100;

1.1.8. Avoid Mixing Data Types

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

int myArray[] = {25, 50, 75, 3.15, 5.99};

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.

1.1.9. Get Array Size or Length

To get the size of an array, you can use the sizeof operator:

 Example

#include <stdio.h>

int main() {

int myNumbers[] = {10, 25, 50, 75, 100};

printf("%lu", sizeof(myNumbers));

return 0;

Why did the result show 20 instead of 5, when the array contains 5 elements?

- It is because the sizeof operator returns the size of a type in bytes.

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};

int length = sizeof(myNumbers) / sizeof(myNumbers[0]);

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() {

// An array storing different ages

int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

float avg, sum = 0;

int i;

// Get the length of the array

int length = sizeof(ages) / sizeof(ages[0]);

// Loop through the elements of the array and accumulate the sum

for (i = 0; i < length; i++) {

sum += ages[i];

// Calculate the average by dividing the sum by the length

avg = sum / length;

// Print the average

printf("The average age is: %.2f", avg);

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.

Syntax of One-Dimensional Array in C

The syntax of a one-dimensional array in C programming language is as follows:

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.

Example of One-Dimensional Array in C

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() {

int numbers[5] = {10, 20, 30, 40, 50};

for(int i=0; i<5; i++) {

printf("numbers[%d] = %d\n", i, numbers[i]);

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.

To access an element of a one-dimensional array in C programming language, we use the following


syntax:

arrayName[index]

 arrayName is the name of the array.


 index is the index of the element we want to access.

Example of Accessing Elements of One-Dimensional Array in C

Let's take an example to understand how to access elements of a one-dimensional array in C


programming language.

#include <stdio.h>

int main() {

int numbers[5] = {10, 20, 30, 40, 50};

printf("The first element of the array is: %d\n", numbers[0]);

printf("The third element of the array is: %d\n", numbers[2]);

return 0;

Output:

The first element of the array is: 10

The third element of the array is: 30

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.

1.2.3. Modifying Elements of One-Dimensional Arrays

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 =.

Example of Modifying Elements of One-Dimensional Array in C

#include <stdio.h>

int main() {

int numbers[5] = {10, 20, 30, 40, 50};

pg. 7
printf("The third element of the array is %d\n", numbers[2]);

numbers[2] = 35;

printf("The third element of the array is now %d\n", numbers[2]);

return 0;

Output:

The third element of the array is 30

The third element of the array is now 35

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.

1.2.4. Initializing One Dimensional Array in C

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:

dataType arrayName[arraySize] = {element1, element2, ..., elementN};

- "dataType' specifies the data type of the array.

- "arrayName' is the name of the array.

- "arraySize' specifies the number of elements in the array.

- "{element1, element2, ..., elementN}' specifies the values of the elements in the array. The number
of elements must be equal to "arraySize'.

Example of Initializing One Dimensional Array in C

Let's take an example to understand how to initialize a one-dimensional array in C programming


language.

#include <stdio.h>

int main() {

int numbers[5] = {10, 20, 30, 40, 50};

for(int i=0; i<5; i++) {

printf("numbers[%d] = %d\n", i, numbers[i]);

return 0;

pg. 8
}

Output of the code:

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;

- arrayName is the name of the array.

- index is the index of the element we want to assign a value to.

- value is the value we want to assign to the element.

Example of Initializing One Dimensional Array in C

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;

for(int i=0; i<5; i++) {

printf("numbers[%d] = %d\n", i, numbers[i]);

return 0;

pg. 9
}

Output of the code:

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.

1.3.1 Multidimensional Arrays


In C programming, you can create an array of arrays. These arrays are known as multidimensional
arrays. For example,

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.

Two dimensional Array

Similarly, you can declare a three-dimensional (3d) array. For example,

float y[2][4][3];

Here, the array y can hold 24 elements.

pg. 10
1.3.2. Initializing a multidimensional array

Here is how you can initialize two-dimensional and three-dimensional arrays:

1.3.3. Initialization of a 2d array

// Different ways to initialize two-dimensional array

int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[2][3] = {1, 3, 0, -1, 5, 9};

1.3.4. Initialization of a 3d 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] = {

{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},

{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};

Example 1: Two-dimensional array to store and print values

#include <stdio.h>

int main() {

// Declare and initialize a 2D array

int matrix[3][4] = {

{1, 2, 3, 4},

{5, 6, 7, 8},

{9, 10, 11, 12}

};

pg. 11
// Print the values of the array

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 4; j++) {

printf("%d ", matrix[i][j]);

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().

 printf() is used to display output on the screen.

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.

3. Declaring and Initializing the 2D Array:

int matrix[3][4] = {

{1, 2, 3, 4},

{5, 6, 7, 8},

{9, 10, 11, 12}

};

pg. 12
This line declares and initializes a 2D array called matrix.

 matrix[3][4] means that the array has:

o 3 rows (each representing a row of data).


o 4 columns (each representing an individual data element in that row).

The array is initialized with values:

Row 1: {1, 2, 3, 4}

Row 2: {5, 6, 7, 8}

Row 3: {9, 10, 11, 12}

So, the array matrix looks like this:

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.

4. Nested for Loops to Print the Array:

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 4; j++) {

printf("%d ", matrix[i][j]);

printf("\n");

Outer for Loop (Iterates Over Rows):

for (int i = 0; i < 3; i++) {

 This loop iterates over the rows of the array.


 The variable i is the row index. It starts at 0 and goes up to 2, so it iterates 3 times (for rows 0, 1,
and 2).
 For each row, the inner loop will execute to print all the elements in that row.

Inner for Loop (Iterates Over Columns):

for (int j = 0; j < 4; j++) {

printf("%d ", matrix[i][j]);

 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).

Printing a New Line After Each Row:

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.

Complete Output Explanation:

Given the array:

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.

Example 2: Three-dimensional array

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() {

// Declare and initialize a 3D array with 2 layers, 2 rows, and 2 columns

int matrix[2][2][2] = {

{1, 2},

{3, 4}

},

{5, 6},

{7, 8}

};

// Print the values of the 3D array

for (int i = 0; i < 2; i++) { // Loop over the layers (depth)

printf("Layer %d:\n", i + 1); // Print which layer we are on

for (int j = 0; j < 2; j++) { // Loop over the rows

for (int k = 0; k < 2; k++) { // Loop over the columns

printf("%d ", matrix[i][j][k]);

printf("\n"); // Newline after each row

printf("\n"); // Newline after each layer

return 0;

pg. 15
Explanation:

1. Array Declaration:

o int matrix[2][2][2] declares a 3D array with 2 layers, 2 rows, and 2 columns.

o The array is initialized with values:

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.

3. Printing the Values:

o For each element matrix[i][j][k], we print its value.

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

2.1. What is a String?

In C, a string is an array of characters, terminated by the special character '\0' (null character).

 Example:

char name[] = "John"; // A string in C

 The string "John" is automatically stored as an array: {'J', 'o', 'h', 'n', '\0'}.

2.2. Library Functions for Strings

C provides many built-in functions to manipulate strings. These functions are available in the string.h
library.

 Common String Functions


 In C programming, string manipulation functions are provided in the string.h library. Here’s
an explanation of four commonly used functions:
 1. strcpy() - String Copy
 2. strcmp() - String Comparison
 3. strlen() - String Length
 4. strcat() - String Concatenation

pg. 18
1. strcpy() - String Copy

The strcpy() function is used to copy a string from one location to another.

Syntax:

char *strcpy(char *destination, const char *source);

 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.

Returns: The function returns the destination string.

Example:

#include <stdio.h>

#include <string.h>

int main() {

char source[] = "Hello, World!";

char destination[50];

// Copy source to destination

strcpy(destination, source);

// Print the copied string

printf("Source: %s\n", source);

printf("Destination: %s\n", destination);

return 0;

Output:

Source: Hello, World!

Destination: Hello, World!

pg. 19
2. strcmp() - String Comparison

The strcmp() function is used to compare two strings lexicographically (based on ASCII values).

Syntax:

int strcmp(const char *str1, const char *str2);

 str1 and str2: The two strings to be compared.

Returns:

 0: If the strings are identical.


 < 0: If str1 is lexicographically smaller than str2.
 0: If str1 is lexicographically greater than str2.

Example:

#include <stdio.h>

#include <string.h>

int main() {

char str1[] = "Apple";

char str2[] = "Banana";

int result = strcmp(str1, str2);

if (result < 0) {

printf("'%s' is lexicographically smaller than '%s'.\n", str1, str2);

} else if (result > 0) {

printf("'%s' is lexicographically greater than '%s'.\n", str1, str2);

} else {

printf("'%s' and '%s' are identical.\n", str1, str2);

return 0;

Output:

'Apple' is lexicographically smaller than 'Banana'.

 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:

size_t strlen(const char *str);

 str: The string whose length is to be determined.

Returns: The number of characters in the string.

Example:

#include <stdio.h>

#include <string.h>

int main() {

char str[] = "Hello, World!";

// Get the length of the string

int length = strlen(str);

// Print the length of the string

printf("Length of the string: %d\n", length);

return 0;

Output:

Length of the string: 13

 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:

char *strcat(char *destination, const char *source);

 destination: The string to which source will be appended.


 source: The string that will be appended to destination.

Returns: It returns a pointer to the concatenated string (the destination string).

Example:

#include <stdio.h>

#include <string.h>

int main() {

char str1[50] = "Hello, ";

char str2[] = "World!";

// Concatenate str2 to str1

strcat(str1, str2);

// Print the concatenated string

printf("Concatenated String: %s\n", str1);

return 0;

Output:

Concatenated String: Hello, World!

 Explanation: The strcat() function appends the string "World!" to the string "Hello, ",
resulting in "Hello, World!".

pg. 22
Summary of Functions:

Function Description Example Usage

strcpy() Copies a string from source to destination strcpy(destination, source);

strcmp() Compares two strings lexicographically strcmp(str1, str2);

strlen() Returns the length of a string strlen(str);

strcat() Concatenates two strings strcat(destination, source);

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.

 strcmp(): It compares strings character by character using ASCII values.

 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.

String operations without using string.h functions:


1. Finding the Length of a String

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'.

Example: Finding String Length

#include <stdio.h>

int string_length(char str[]) {

int length = 0;

while (str[length] != '\0') {

length++;

return length;

int main() {

char str[] = "Hello, World!";

int length = string_length(str);

printf("Length of the string: %d\n", length);

return 0;

Output:

Length of the string: 13

 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.

2. Copying One String to Another (like strcpy)

To copy one string to another without using strcpy(), we can use a loop to copy each character one
by one.

Example: Copying a String

#include <stdio.h>

pg. 24
void string_copy(char dest[], char src[]) {

int i = 0;

while (src[i] != '\0') {

dest[i] = src[i];

i++;

dest[i] = '\0'; // Add the null terminator to the copied string

int main() {

char src[] = "Hello, World!";

char dest[50]; // Make sure the destination array is large enough

string_copy(dest, src);

printf("Copied String: %s\n", dest);

return 0;

Output:

Copied String: Hello, World!

 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.

3. Concatenating Two Strings (like strcat)

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.

Example: Concatenating Strings

#include <stdio.h>

void string_concat(char dest[], char src[]) {

int i = 0, j = 0;

// Move to the end of the first string

while (dest[i] != '\0') {

i++;

pg. 25
// Append characters of the second string

while (src[j] != '\0') {

dest[i] = src[j];

i++;

j++;

// Add null terminator at the end

dest[i] = '\0';

int main() {

char str1[50] = "Hello, "; // Ensure enough space in dest

char str2[] = "World!";

string_concat(str1, str2);

printf("Concatenated String: %s\n", str1);

return 0;

Output:

Concatenated String: Hello, World!

 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.

Example: Comparing Strings

#include <stdio.h>

int string_compare(char str1[], char str2[]) {

int i = 0;

while (str1[i] != '\0' && str2[i] != '\0') {

if (str1[i] != str2[i]) {

return str1[i] - str2[i]; // Return the difference of first mismatched characters

i++;

return str1[i] - str2[i]; // If both strings are of different lengths

int main() {

char str1[] = "apple";

char str2[] = "apple";

int result = string_compare(str1, str2);

if (result == 0) {

printf("Strings are equal.\n");

} else if (result > 0) {

printf("First string is greater.\n");

} else {

printf("Second string is greater.\n");

return 0;

Output:

Strings are equal.

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.

Summary of Manual String Operations

Operation Description Example Code

Count the number of characters


Find Length while(str[i] != '\0') length++;
before '\0'

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') {...}

Compare two strings while(str1[i] == str2[i]) { if(str1[i] != str2[i])


Compare
lexicographically return str1[i] - str2[i];}

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

3.1. What is a Structure?

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;

};

3.2. Declaring Structures

You can declare a structure variable by using the structure type followed by the variable name.

 Syntax:

struct structure_name variable_name;

 Example:

struct Student student1;

3.3. Initializing Structures

Structures can be initialized at the time of declaration, or their members can be assigned values later.

 Initialization at Declaration:

struct Student student1 = {"John", 20, 85.5};

 Assigning Values Later:

struct Student student1;

strcpy([Link], "John");

[Link] = 20;

[Link] = 85.5;

3.4. Accessing Structure Members

You can access the members of a structure using the dot (.) operator.

 Example:

printf("Name: %s\n", [Link]);

printf("Age: %d\n", [Link]);

pg. 29
printf("Marks: %.2f\n", [Link]);

 Example of Structure :

#include <stdio.h>

#include <string.h>

// Define the structure

struct Student {

char name[50]; // Name of the student

int age; // Age of the student

float grade; // Grade of the student

};

int main() {

// Declare a variable of type 'struct Student'

struct Student student1;

// Assign values to the members of the structure

strcpy([Link], "John Doe");

[Link] = 20;

[Link] = 85.5;

// Access and print the values of the members

printf("Student Name: %s\n", [Link]);

printf("Student Age: %d\n", [Link]);

printf("Student Grade: %.2f\n", [Link]);

return 0;

pg. 30
Explanation:

1. Defining the structure:


o The struct Student defines a structure with three members: name, age, and
grade.
o The name is an array of characters (char name[50]), which can store a string
up to 49 characters (leaving space for the null terminator).
o The age is an integer (int age), which stores the student's age.
o The grade is a float (float grade), which stores the student's grade.
2. Declaring a structure variable:
o In the main() function, we declare a structure variable student1 of type
struct Student.
3. Assigning values:
o The strcpy() function is used to assign a string (name) to [Link].
o The other members [Link] and [Link] are assigned directly
with integer and float values respectively.
4. Accessing structure members:
o We use the dot operator (.) to access and print the values of the structure's
members (name, age, and grade).

Summary

 Arrays: Concepts, Declaration, Definition, Accessing Elements, One-dimensional Arrays, and


Multi-dimensional Arrays.

 Strings: Basics, Library Functions, and Operations on Strings without using string.h.

 Structures: Definition, Declaration, Initialization, and Accessing Structure Members.

These concepts are fundamental to programming in C, and mastering them will help you understand
more advanced topics in C programming.

pg. 31

You might also like