0% found this document useful (0 votes)
16 views26 pages

Unit 5 Arrays

The document discusses various topics about arrays in C including: one-dimensional arrays which store similar elements in contiguous memory locations; two-dimensional arrays which have rows and columns like a table; and how to declare, initialize, and access elements of arrays. It also covers properties of arrays like fixed size and homogeneous data types.

Uploaded by

Aarush Pitla
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)
16 views26 pages

Unit 5 Arrays

The document discusses various topics about arrays in C including: one-dimensional arrays which store similar elements in contiguous memory locations; two-dimensional arrays which have rows and columns like a table; and how to declare, initialize, and access elements of arrays. It also covers properties of arrays like fixed size and homogeneous data types.

Uploaded by

Aarush Pitla
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/ 26

Topics to be covered in UNIT-

Arrays: 5

Introduction to Arrays
One-Dimensional Arrays
Two-Dimensional Arrays
Arrays and Functions

Strings:
Introduction to Strings
String Input/Output
String Operations with and without built-in functions

1
Arrays in C:

An array is defined as the collection of similar type of data items stored at


contiguous memory locations.

⮚An array is ordered: Data is grouped sequentially.

⮚ An array is homogenous: Every value within the array must share the
same data type.
⮚ In other words, an int array can only hold integer values, not doubles.

2
Application of Arrays
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.

3
Advantage of C Array:

⮚Code Optimization: Less code to the access the data.


⮚Ease of traversing: By using the for loop, we can retrieve the elements of an
array easily.
⮚Ease of sorting: To sort the elements of the array, we need a few lines of code
only.
⮚Random Access: We can access any element randomly using the array.

Disadvantage of C Array:

Fixed Size: Whatever size, we define at the time of declaration of the array, we
can't exceed the limit. So, it doesn't grow the size dynamically.

4
Properties of Array

The array contains the following properties.

⮚Each element of an array is of same data type and carries the same size, i.e., int
= 4 bytes.

⮚Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.

⮚Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the size of the
data element.

5
Types of arrays:

⮚In C, arrays can be classified based on how the data items are arranged
for human understanding.
⮚Arrays are broadly classified into three categories,
1. One Dimensional Arrays
2. Two Dimensional Arrays
3. Multi Dimensional Arrays

6
How to create an array:

Creation of an consists two things: Element Type and Array Size.

Element Type: What kind of data an array can hold?


An array can hold any one of the following data:
integer, double, character data.

Array Size: How many elements an array can contain?


Once an array size is defined it cannot be changed at run-time.

7
One Dimensional Arrays:

⮚ One dimensional array is a linear list consisting of related and similar


data items.
⮚ In memory all the data items are stored in contiguous memory locations
one after the other.
Syntax :
elementType arrayName[size];

⮚ Where elementType specifies data type of each element in the array,


arrayName specifies name of the variable you are declaring and
size specifies number of elements allocated for this array.
⮚ To declare regular variables we just specify a data type and a unique
name.
Example: int number;
⮚ To declare an array, we just add an array size.
Example: int temp[5]; //Creates an array of 5 integer elements.
8
Initializing One Dimensional Arrays

⮚If array is not initialized it contain garbage values.

⮚Types of array initializations:

Option 1: Initializing all memory locations

Option 2: Initialization without size

Option 3: Partial array initialization

Option 4: Initializing an entire array with zero.

9
Option 1: Initializing all memory locations:

⮚ If you know all the data at compile time, you can specify all your data
within brackets:
int temp [5] = {75, 79, 82, 70, 68};
⮚ During compilation, 5 contiguous memory locations are reserved by the
compiler for the variable temp and all these locations are initialized as
shown below.

⮚If the size of integer is 2 bytes, 10 bytes will be allocated for the
10
variable temp.
Option 2: Initialization without size:

⮚ If you omit the size of an array, but specify an initial set of data, then
the
compiler will automatically determine the size of an array.
int temp [] = {75, 79, 82, 70, 68};

⮚ In the above declaration, even though you have not specified exact
number of elements to be used in array temp, the array size will be set
with the total number of initial values specified.

⮚ Here, the compiler creates an array of 5 elements. The array temp is


initialized as shown below.

11
Option 3 Partial Array Initialization:

⮚ If the number of values to be initialized is less than the size of the


array, then the elements are initialized in the order from 0th location.

⮚ The remaining locations will be initialized to zero automatically.


int temp [5] = {75, 79, 82};

⮚ Even though compiler allocates 5 memory locations, using the above


declaration statement, the compiler initializes first three locations with
75, 79 and 82, and the next set of memory locations are automatically
initialized to 0’s by the compiler as shown below.

12
Initializing One Dimensional Arrays (Cont…)

Option 4: Initializing an entire array with zero:


⮚ If you do not know any data ahead of time, but you want to initialize
everything to 0, just use 0 within { }. For example:
int temp [5] = {0};

⮚ This will initialize every element within the array to 0 as shown below.

13
Accessing elements of one dimensional array(Cont…)
//Example for accessing array elements.
#include<stdio.h>
main() {
int arr[10];
int i = 0;
for(i=0;i<sizeof(arr);i++) {
arr[i] = i; // Initializing each element separately
}
int j = arr[5]; // Accessing the 5th element of integer array arr
//and assigning its value to integer 'j'.
printf(“Value at 5th location is: %d”,j);
}
⮚ As we can see above, the 5th element of an array is accessed as ‘arr[5]‘.

⮚ Note that for an array declared as int arr[5].


⮚ The five values are represented as: arr[0] arr[1] arr[2] arr[3] arr[4]
and not arr[1] arr[2] arr[3] arr[4] arr[5]

⮚ The first element of array always has a subscript of ’0′. 14


//Program to calculate sum of all the array elements.

#include <stdio.h>
void main()
{
int a[10];
int i, size, total=0;
printf("\n Enter the size of the array : ");
scanf("%d", &size);
printf("\n Enter the elements of an array : ");
for (i = 0; i < size ; i++)
scanf("%d",&a[i]);
for (i = 0; i < size ; i++)
total += a[i];
printf(“Sum of all array elements: %d", total);
}

15
Two Dimensional Arrays:

⮚ Two-dimensional array are those type of array, which has finite number
of rows and finite number of columns.

⮚ An array of array is called a two-dimensional array and can be


represented as a table with rows and columns.

⮚ This is an array of size 3 names whose elements are arrays of size 4.

16
Declaration of Two Dimensional Arrays:

Syntax: elementType arrayName [row_size][column_size];

Two-dimensional Array representation


17
Two Dimensional Arrays(Cont…)
⮚The declaration form of 2-dimensional array is
elementType arrayName [row_size][column_size];

⮚ The elementType may be any valid type supported by C.


⮚ The rule for giving the arrayName is same as the ordinary variable.
⮚ The row_size and column_size should be an individual constant.

⮚ The following declares a two-dimensional 3 by 3 array of integers and


sets the first and last elements to be 10.
int matrix [3][3]; [0] [1] [2]

matrix[0][0] = 10; [0] 10


matrix[2][2] = 10; [1]
[2] 10
⮚ In the declaration of two dimensional array the column size should be
specified, so that it can arrange the elements in the form of rows and
columns.
⮚ Two-dimensional arrays in C are stored in "row-major format": the
array is laid out contiguously, one row at a time. 18
Initialization of Two Dimensional Arrays:
⮚ An array may be initialized at the time of declaration as follows:
char names [3][4] = {
{‘J’, 'o', 'h', 'n'},
{‘M’, 'a', 'r', 'y'},
{‘I’, 'v', 'a', 'n'}
};
⮚ An integer array may be initialized to all zeros as follows
int nums [3][4] = {0};

⮚ An integer array may be initialized to different values as follows


int nums [3][4] = {
{1,2,3,4},
{5,6,7,8},
{9,0,10,11}
};
⮚ To access an element of a 2D array, you need to specify both the row
and the column:
printf ("%d", nums[1][2]);
19
Initialization of Two Dimensional Arrays(Cont…)

Example:

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

OR

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

OR

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

20
//Program to print sum of elements of a matrix.
#define M 3 /* Number of rows */
#define N 4 /* Number of columns */
main() {
, int a [ M ] [ N ], i, j, sum = 0;
for ( i = 0; i < M; ++i ) {
for (j = 0; j < N, ++j ){
scanf (%d”, &a [i] [j]);
}
}
for ( i = 0; i < M; ++i ) {
for (j = 0; j < N, ++j ) {
printf(“a [ %d ] [ %d ] = %d “, i, j, a[ i ] [ j ]);
}
printf (“\n”);
}
for ( i = 0; i < M; ++i ) {
for (j = 0; j < N, ++j ) {
sum += a[ i ] [ j ];
}
printf(“\nsum = %d\n\n”);
}
21
}
Multi Dimensional Arrays:

⮚ C allows three or more dimensions. The exact limit is determined by the


compile.

⮚The general form of multidimensional array is


elementType arrayName [s1][s2][s3]…[sm];
⮚ Where si is the size of the ith dimension.

⮚ Array declarations read right-to-left


⮚ For Example: int a[3][5][4];

⮚ It is represented as “an array of ten arrays of three arrays of two ints”


⮚ In memory the elements are stored as shown in below figure.

22
Example:
int table[3][5][4] = {
{
{000,001,002,003},
{010,011,012,013},
{020,021,022,023},
{030,031,032,033},
{040,041,032,043}
},
{
{100,101,102,103},
{110,111,112,113},
{120,121,122,123},
{130,131,132,133},
{140,141,142,143}
},
{
{200,201,202,203},
{210,211,212,213},
{220,221,222,223},
{230,231,232,233},
{240,241,242,243}
}
}; 23
Functions with Arrays:
⮚ Like the values of variable, it is also possible to pass values of an array
to a function.

⮚There are two types of passing an array to the function:


⮚ 1. Passing Individual Elements
⮚ 2. Passing the whole array

1. Passing Individual Elements:


int a[10];
int a;
fun(a[2]);
fun(a);
void fun(int x)
{
-------
-------
} 24
2. Passing the whole array:

⮚ To pass an array to a called function, it is sufficient to list the name of


the array, without any subscripts, and the size of the array as arguments.

⮚ For example, the function call findMax(a, n); will pass all the elements
contained in the array a of size n.

⮚ The function prototype takes of the form


int findMax (int [], int );
int findMax (int a [], int );

25
//Program to read an array of elements and find max value.
#include<stdio.h>
int findMax(int[],int); int findMax(int x[],int size)
void main() {
{ int temp;
int a[10], n ,i , max; temp=x[0];
printf(“\n Enter the size of the array “); for(i=1;i<size; i++)
scanf(“%d”,&n); {
printf(‘\n Enter the elements of the array : “); if(x[i]>temp)
for(i=0;i<n;i++) {
scanf(“%d”,&a[i]); temp=x[i];
max=findMax(a, n); }
printf(“\n The Maximum value =%d”, max); }
} return temp;
}

26

You might also like