0% found this document useful (0 votes)
21 views30 pages

FPL Unit 4 AAB

The document provides an overview of arrays in C programming, detailing one-dimensional and two-dimensional arrays, including their declaration and initialization methods. It also covers character arrays and strings, explaining how to read, write, and manipulate strings using various functions from the C Standard Library. Additionally, a case study on matrix multiplication illustrates practical application of arrays.

Uploaded by

pprenank
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)
21 views30 pages

FPL Unit 4 AAB

The document provides an overview of arrays in C programming, detailing one-dimensional and two-dimensional arrays, including their declaration and initialization methods. It also covers character arrays and strings, explaining how to read, write, and manipulate strings using various functions from the C Standard Library. Additionally, a case study on matrix multiplication illustrates practical application of arrays.

Uploaded by

pprenank
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
You are on page 1/ 30

Unit 4

Arrays
CO4: To design a solution using Arrays, Character and
String Arrays
One-Dimensional Arrays

Definition :
A one-dimensional array in C is a sequence of elements of the same
type stored in contiguous memory locations. You can think of it as a
list of items where each item is accessed using a single index.

Declaration :
To declare a one-dimensional array in C, you specify the type of the
elements and the number of elements (size) the array will hold:

type name[size];

-Example :
int arr[5]; // Declares an array named 'arr' that can hold 5 integers

In this example, `int` is the type of elements, `arr` is the name of the
array, and `5` is the number of elements.
Arrays
Initialization :
Arrays in C can be initialized at the time of declaration or later. Here are the
common methods:

- At Declaration:
You can initialize an array with specific values when you declare it:

int arr[5] = {1, 2, 3, 4, 5}; // Initializes the array with the values 1 through 5

If you provide fewer initializers than the size, the remaining elements are
set to 0:

int arr[5] = {1, 2}; // Initializes arr[0] to 1, arr[1] to 2, and the rest to 0

If you omit the size, the compiler calculates it based on the number of
initializers:

int arr[] = {1, 2, 3, 4, 5}; // Size is inferred to be 5


Post-Declaration Initialization:
You can also initialize an array using a loop or individual
assignment after declaration:

int arr[5];
for(int i = 0; i < 5; i++)
{
arr[i] = i * 2; // Initializes each element with twice its
index
}
Two-Dimensional Arrays
Definition :
A two-dimensional array in C is essentially an array of arrays. It can be
visualized as a matrix or table with rows and columns. Each element
is accessed using two indices: one for the row and one for the
column.

Declaration :
To declare a two-dimensional array, specify the type of the elements,
the number of rows, and the number of columns:

type name[rows][columns];

Example:
int matrix[3][4]; // Declares a 2D array with 3 rows and 4 columns

In this example, `int` is the type of elements, `matrix` is the name of


the array, `3` is the number of rows, and `4` is the number of
columns.
Initialization :
Two-dimensional arrays can be initialized in several ways:

-At Declaration:
You can initialize a 2D array with specific values directly:

int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
}; // Initializes the array with the specified values
If fewer values are provided, the remaining
elements are set to 0:

int matrix[3][4] = {
{1, 2},
{3, 4},
{5} // Initializes the first two rows with specified
values and the last row with the remaining elements
set to 0
};
Default Initialization:
If the array is declared but not explicitly initialized, all elements are
set to 0:

int matrix[3][4]; // All elements are initialized to 0 by default

Post-Declaration Initialization:
You can initialize elements individually or via a loop:

int matrix[3][4];
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 4; j++)
{
matrix[i][j] = i + j; // Initializes each element with the sum of its
indices
}
}
Summary

One-Dimensional Arrays:
Declaration: `type name[size];` (e.g., `int arr[5];`)
Initialization: At declaration (e.g., `int arr[5] = {1, 2, 3, 4,
5};`) or later using loops.

Two-Dimensional Arrays:
Declaration : `type name[rows][columns];` (e.g., `int
matrix[3][4];`)
Initialization : At declaration (e.g., `int matrix[3][4] =
{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};`), default to 0, or
using loops.
Character Arrays and Strings

Character Array: An array of `char` type elements. Each element


stores a single character, and a sequence of characters can be used to
form a string. In C, a string is a special kind of character array that
ends with a null terminator (`'\0'`).

1. Declaration and Initialization of String Variables :

Declaration :
To declare a string in C, you use a character array. The size of the
array should be sufficient to hold all characters including the null
terminator.

Example :
char str[50]; // Declares a character array with space for 50
characters
Initialization :
Strings can be initialized in several ways:

At Declaration:

char str[] = "Hello, World!"; // Array size is inferred, includes null


terminator

Here, `str` is initialized with the string "Hello, World!" including


the null terminator (`'\0'`).

Using a Character Array:

char str[50] = "Hello"; // Initializes the first 6 elements (5


characters + null terminator)
2. Reading Strings from Terminal
To read a string from the terminal, you use the `scanf` function or `fgets`
function.

Using `scanf`:
char str[50];
scanf("%s", str); // Reads a string from the terminal until a space or newline is
encountered

Limitations:`scanf` stops reading at whitespace (space, tab, newline). It can


cause buffer overflow if the input exceeds the size of the array.

Using `fgets` :
char str[50];
fgets(str, sizeof(str), stdin); // Reads a string including spaces, up to a newline
or the buffer size

Advantages:`fgets` reads until a newline character is found or the buffer size is


reached, and it handles spaces correctly.
3. Writing Strings to Screen
To display a string, you use the `printf` function:

Example:

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


printf("%s\n", str);

// Prints the string followed by a newline


4. Putting Strings Together
To concatenate strings, you use the `strcat` function from the C
Standard Library's `<string.h>`:

Example:

#include <string.h>

char str1[50] = "Hello";


char str2[] = " World!";
strcat(str1, str2);
// Appends str2 to str1, resulting in "Hello World!"

Ensure that the destination array is large enough to hold the


concatenated result.
5. Comparison of Two Strings
To compare two strings, use the `strcmp` function:

Example:

#include <string.h>

char str1[] = "Hello";


char str2[] = "Hello";
int result = strcmp(str1, str2);
// Returns 0 if the strings are equal

Return Values:
- `0`: Strings are equal.
- Negative value: `str1` is less than `str2`.
- Positive value: `str1` is greater than `str2`.
6. Introduction to String Handling Functions
The C Standard Library provides several functions to handle strings, declared in
`<string.h>`:
`strlen`: Computes the length of a string (excluding the null terminator).
#include <string.h>
char str[] = "Hello";
size_t len = strlen(str); // len is 5

`strcpy`: Copies one string to another.


char src[] = "Hello";
char dest[50];
strcpy(dest, src); // Copies "Hello" to dest

`strncpy`: Copies up to a specified number of characters.


char src[] = "Hello";
char dest[50];
strncpy(dest, src, 3); // Copies "Hel" to dest
dest[3] = '\0'; // Ensures null termination
strcat: Concatenates two strings.
char str1[50] = "Hello";
char str2[] = " World!";
strcat(str1, str2); // str1 now contains "Hello World!"

`strncat`: Appends up to a specified number of characters.


char str1[50] = "Hello";
char str2[] = " World!";
strncat(str1, str2, 3); // str1 now contains "Hello Wor"

`strcmp`: Compares two strings.


char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2); // result is negative because "Hello" < "World"

`strchr’: Finds the first occurrence of a character.


char str[] = "Hello, World!";
char *ptr = strchr(str, 'W'); // ptr points to the "World!" in str

`strstr`: Finds the first occurrence of a substring.


char str[] = "Hello, World!";
char *ptr = strstr(str, "World"); // ptr points to "World!" in str
Summary

• Character Arrays: Fundamental for storing strings.


Declared as `char array[size];`.
• String Initialization: Can be done at declaration or
using functions.
• Reading Strings:Use `scanf` or `fgets` for user
input.
• Writing Strings: Use `printf` for output.
• String Operations: Concatenate with `strcat`,
compare with `strcmp`, and use functions like
`strlen`, `strcpy`, and `strstr` from `<string.h>` for
various string manipulations.
Case Study

• In C, matrix multiplication involves multiplying


two matrices and producing a third matrix as
the result.
#include <stdio.h>

int main() {
// Declare matrices and dimensions
int A[2][3] = {{1, 2, 3}, {4, 5, 6}};
int B[3][2] = {{7, 8}, {9, 10}, {11, 12}};
int C[2][2] = {0}; // Resultant matrix initialized to zero
int rowsA = 2, colsA = 3, rowsB = 3, colsB = 2;

// Check if multiplication is possible


if (colsA != rowsB)
{
printf("Matrix multiplication is not possible.\n");
return 0;
}
// Perform matrix multiplication
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
for (int k = 0; k < colsA; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
// Print the resultant matrix
printf("Resultant matrix:\n");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
printf("%d ", C[i][j]);
}
printf("\n"); Resultant matrix:
58 64
} 139 154
return 0;
}

You might also like