MODULE III: ARRAYS, STRINGS AND USER-DEFINED FUNCTIONS
Arrays: one-dimensional arrays, two-dimensional arrays, character arrays and strings
-declaring, initializing, reading and writing of strings, arithmetic operations on
characters, String manipulation functions; need for user-defined functions, structure
of a multi-function
program, functions – elements, definition, return values and their types, function
calls, function declaration, categories of functions, recursion.
Array
An array is defined as the collection of similar type of data items stored at
contiguous memory locations. Arrays are the derived data type in C programming
language which can store the primitive type of data such as int, char, double, float,
etc.
It also has the capability to store the collection of derived data types, such as
pointers, structure, etc.
The array is the simplest data structure where each data element can be
randomly accessed by using its index number.
C array is beneficial if you have to store similar elements. For example, if we want
to store the marks of a student in 6 subjects, then we don't need to define
different variables for the marks in the different subject.
Instead of that, we can define an array which can store the marks in each subject
at the contiguous memory locations.
By using the array, we can access the elements easily. Only a few lines of code are
required to access the elements of the array.
//Program to display elements of an array.
#include<stdio.h>
int main()
{
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}//end of for loop
return 0;
}
Output
80
60
70
85
75
[Link] Arrays. Explain the concept of passing arrays to functions.
Arrays in C are a fundamental data structure that allows you to store and
manipulate a collection of elements of the same data type.
They provide a way to organize and access elements by their index positions
within a contiguous block of memory.
1. Declaration and Initialization:
Arrays are declared by specifying the data type of the elements they will
contain, followed by the array name and the size of the array in square
brackets.
Initialization can be done at the time of declaration or later using the
assignment operator =.
Arrays may be initialized when they are declared, just as any other variables.
Place the initialization data in curly {} braces following the equals sign. Note
the use of commas in the examples below.
An array may be partially initialized, by providing fewer data items than the
size of the array. The remaining array elements will be automatically
initialized to zero.
If an array is to be completely initialized, the dimension of the array is not
required. The compiler will automatically size the array to fit the initialized
data. ( Variation: Multidimensional arrays - see below. )
Examples:
int i = 5, intArray[ 6 ] = { 1, 2, 3, 4, 5, 6 }, k;
float sum = 0.0f, floatArray[ 100 ] = { 1.0f, 5.0f, 20.0f };
double piFractions[ ] = { 3.141592654, 1.570796327, 0.785398163 };
2. Indexing:
Array elements are accessed using an index, starting from 0 for the first
element.
You can use square brackets [] to access an element.
int firstElement = myArray[0]; // Access the first element
int secondElement = numbers[1]; // Access the second element
3. Fixed Size:
In C, arrays have a fixed size, which means you must specify the number of
elements when you declare the array.
Changing the size of an array typically involves creating a new array.
4. Contiguous Memory:
Array elements are stored in contiguous memory locations.
This means that the elements are stored one after the other in memory.
Passing Arrays to Functions:
To pass an array to a function, you generally pass a pointer to the first element of the
array and the size of the array as separate arguments.
void printArray(int arr[], int size)
{
// Function code to work with the array
}
[Link] are the advantages and disadvantages of an Array?
Advantages of Arrays
In an array, accessing an element is very easy by using the index number.
The search process can be applied to an array easily.
2D Array is used to represent matrices.
For any reason a user wishes to store multiple values of similar type then the
Array can be used and utilized efficiently.
Arrays have low overhead.
C provides a set of built-in functions for manipulating arrays, such as sorting
and searching.
C supports arrays of multiple dimensions, which can be useful for representing
complex data structures like matrices.
Arrays can be easily converted to pointers, which allows for passing arrays to
functions as arguments or returning arrays from functions.
Disadvantages of Arrays
Array size is fixed: The array is static, which means its size is always fixed.
The memory which is allocated to it cannot be increased or decreased.
Array is homogeneous: The array is homogeneous, i.e., only one type of value
can be store in the array. For example, if an array type “int “, can only store
integer elements and cannot allow the elements of other types such as
double, float, char so on.
Multidimensional Array
Multidimensional array in C
Multidimensional arrays are one of the most powerful features of the C
programming language. They allow you to store data in a table-like format, where
each row and column can be accessed using an index. In this blog post, we'll look at
multidimensional arrays in C, including their syntax, example usage, and output.
Syntax of Multidimensional Arrays in C
To create a multidimensional array in C, you need to specify the number of
dimensions and the size of each dimension. The general syntax for declaring a
multidimensional array is as follows:
1. type array_name[size1][size2]...[sizeN];
Here, type is the data type of the elements that will be stored in the
array, array_name is the name of the array, and size1, size2, ..., sizeN are the sizes
of each dimension of the array.
For example, the following code declares a 2-dimensional array of integers with 3
rows and 4 columns:
1. int my_array[3][4];
It creates an array with 3 rows and 4 columns, for a total of 12 elements. Each
element is of type int.
Accessing Elements of Multidimensional Arrays
To access an element of a multidimensional array, you need to specify
the indices for each dimension. For example, to access the element in the second
row and third column of my_array, you would use the following syntax:
1. int element = my_array[1][2];
Note that the indices start at 0, so the first row is my_array[0], the second row
is my_array[1], and so on. Similarly, the first column of each row is my_array[i][0],
and so on.
Initializing Multidimensional Arrays
You can initialize a multidimensional array when you declare it by specifying the
values for each element in the array. For example, the following code declares and
initializes a 2-dimensional array of integers with 2 rows and 3 columns:
int my_array[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
It creates an array with 2 rows and 3 columns and initializes the elements to the
specified values.
Iterating Over Multidimensional Arrays
You can iterate over the elements of a multidimensional array using nested loops.
For example, the following code iterates over the elements of my_array and prints
their values:
for (int i = 0; i< 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", my_array[i][j]);
}
printf("\n");
}
This code loops through each row and column of my_array, and prints each element
with a space between them. The printf("\n") statement is used to print
a newline character after each row.
Example Usage of Multidimensional Arrays in C
Let's look at a practical example of using multidimensional arrays in C. Suppose we
want to create a program that stores the grades of 5 students in 4 different subjects.
We can use a 2-dimensional array to store this data, where each row represents
a student, and each column represents a subject.
Example:
Here's an example program that prompts the user to enter the grades for
each student and subject, and then calculates the average grade for
each student and subject:
#include <stdio.h>
int main() {
int grades[5][4];
// Prompt user to enter grades
for (int i = 0; i< 5; i++) {
printf("Enter grades for student %d:\n", i+1);
for (int j = 0; j < 4; j++) {
printf("Subject %d: ", j+1);
scanf("%d", &grades[i][j]);
}
}
// Calculate average grade for each student
printf("\nAverage grade for each student:\n");
for (int i = 0; i< 5; i++) {
float sum = 0;
for (int j = 0; j < 4; j++) {
sum += grades[i][j];
}
float avg = sum / 4;
printf("Student %d: %.2f\n", i+1, avg);
}
// Calculate average grade for each subject
printf("\nAverage grade for each subject:\n");
for (int j = 0; j < 4; j++) {
float sum = 0;
for (int i = 0; i< 5; i++) {
sum += grades[i][j];
}
float avg = sum / 5;
printf("Subject %d: %.2f\n", j+1, avg);
}
return 0;
}
Output:
Enter grades for student 1:
Subject 1: 80
Subject 2: 75
Subject 3: 90
Subject 4: 85
Enter grades for student 2:
Subject 1: 70
Subject 2: 85
Subject 3: 80
Subject 4: 75
Enter grades for student 3:
Subject 1: 90
Subject 2: 80
Subject 3: 85
Subject 4: 95
Enter grades for student 4:
Subject 1: 75
Subject 2: 90
Subject 3: 75
Subject 4: 80
Enter grades for student 5:
Subject 1: 85
Subject 2: 70
Subject 3: 80
Subject 4: 90
Average grade for each student:
Student 1: 82.50
Student 2: 77.50
Student 3: 87.50
Student 4: 80.00
Student 5: 81.25
Average grade for each subject:
Subject 1: 80.00
Subject 2: 80.00
Subject 3: 82.00
Subject 4: 85.00
Explanation:
In this program, we first declare a 2-dimensional array 'grades' with 5 rows and 4
columns, to store the grades for each student and subject. After that, we prompt the
user to enter the grades for each student and subject using nested loops.
The 'printf' statements are used to display the prompt, and the 'scanf' statement is
used to read the input from the user and store it in the appropriate element of the
array.
Next, we calculate the average grade for each student and subject using nested
loops. The 'sum' variable is used to keep track of the total grade for each student or
subject, and the 'avg' variable is used to calculate the average grade by dividing the
sum by the number of subjects or students. Finally, we use 'printf' statements to
display the average grades for each student and subject. As we can see, the program
successfully calculates the average grades for each student and subject based on the
input provided by the user.
In addition to the example program, we discussed earlier, there are many other
applications of multidimensional arrays in C. For example, you can use a 3-
dimensional array to store and manipulate data in a 3-dimensional space, such as
a cube or a sphere. Similarly, you can use a 4-dimensional array to represent data
that varies across four dimensions, such as time, space, temperature, and pressure.
One common use of multidimensional arrays in C is for image
processing and computer vision applications. For example, you can use a 2-
dimensional array to represent an image, with each element of the array
representing a pixel in the image. By manipulating the values of the elements in the
array, you can perform a wide range of operations on the image, such as scaling,
rotating, cropping, and filtering.
Another application of multidimensional arrays is in numerical analysis and scientific
computing. Many scientific simulations and calculations require the use of
multidimensional arrays to represent complex data structures and perform
numerical operations. By using arrays with high precision and accuracy, scientists and
engineers can model and analyze complex phenomena in fields such as physics,
chemistry, and biology. One important consideration when working with
multidimensional arrays in C is memory management. Because multidimensional
arrays can be quite large and complex, it is important to be mindful of how the data
is stored in memory and how it is accessed by the program. You should be aware of
the potential for memory leaks, buffer overflows, and other memory-related errors
that can occur when working with large and complex data structures.
To avoid these types of errors, it is important to use proper memory allocation and
deallocation techniques, such as the malloc and free functions in C. You should also
be careful to avoid accessing array elements that are outside of the bounds of the
array, which can cause undefined behavior and potentially crash the program.
Character arrays and strings
A String in C programming is a sequence of characters terminated with a null
character ‘\0’.
The C String is stored as an array of characters.
The difference between a character array and a C string is that the string in C is
terminated with a unique character ‘\0’.