0% found this document useful (0 votes)
8 views

Unit 2 (1)

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit 2 (1)

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

C ARRAYS

-a collection of same type data, 1D, 2D-


 An array is a collection of elements of the same type that are referenced by a common
name.
 Compared to the basic data type (int, float & char) it is an aggregate or derived data type.
 All the elements of an array occupy a set of contiguous memory locations.
 Why need to use array type?
 Consider the following issue:

"We have a list of 1000 students' marks of an integer type. If using the basic data type (int),
we will declare something like the following…"

int studMark0, studMark1, studMark2, ..., studMark999;


Why do we need Arrays?
Array stores an extensive collection of similar data
types. We have only three variables, and then we can
easily store them using separate names like int var1,
int var2, and int var3, but what if we have an
extensive collection of these variables? Then, we
cannot assign separate names to each of them, as it
would be tedious and time-consuming.
Here comes the use of arrays in C, where we can
store multiple data type values in a contiguous
memory block. Hence, we can use an array in C
when we are working with a large number of similar
items.
 Can you imagine how long we have to write the
declaration part by using normal variable declaration?

int main(void)
{
int studMark1, studMark2, studMark3, studMark4, …, …, studMark998,
stuMark999, studMark1000;


return 0;
}
 By using an array, we just declare like this,

int studMark[1000];

 This will reserve 1000 contiguous memory


locations for storing the students’ marks.
 Graphically, this can be depicted as in the
following figure.
 This absolutely has simplified our declaration of the variables.
 We can use index or subscript to identify each element or location in the
memory.
 Hence, if we have an index of jIndex, studMark[jIndex] would refer to
the jIndexth element in the array of studMark.
 For example, studMark[0] will refer to the first element of the array.
 Thus by changing the value of jIndex, we could refer to any element in
the array.
 So, array has simplified our declaration and of course, manipulation of
the data.
C Array Initialization
 Initialization in C is the process to assign some initial value to the variable.
 When the array is declared or allocated memory, the elements of the array contain some garbage value.
 So, we need to initialize the array to some meaningful value.
 There are multiple ways in which we can initialize an array in C.

1. Array Initialization with Declaration


In this method, we initialize the array along with its declaration. We use an initializer list to initialize multiple
elements of the array. An initializer list is the list of values enclosed within braces { } separated b a comma.
 data_type array_name [size] = {value1, value2, ... valueN};
2. Array Initialization with Declaration without Size
 If we initialize an array using an initializer list, we can skip declaring the size of the array as the compiler
can automatically deduce the size of the array in these cases.
 The size of the array in these cases is equal to the number of elements present in the initializer list as the
compiler can automatically deduce the size of the array.
data_type array_name[] = {1,2,3,4,5};

The size of the above arrays is 5 which is automatically deduced by the compiler.

3. Array Initialization after Declaration (Using Loops)


• We initialize the array after the declaration by assigning the initial value to each element individually.
• We can use for loop, while loop, or do-while loop to assign the value to each element of the array.

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


array_name[i] = valuei;
}
#include <stdio.h>
int main()
{
// array initialization using initialier list
int arr[5] = { 10, 20, 30, 40, 50 };

// array initialization using initializer list without


// specifying size
int arr1[] = { 1, 2, 3, 4, 5 };
int numbers[5] = {10, 20, 30, 40, 50};

int i; // loop counter

// Printing array elements


printf("The array elements are : ");
for (i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}

return 0;
}
ARRAYS
 Single or One Dimensional array is used to represent and store data in a linear form.
 Array having only one subscript variable is called One-Dimensional array
 It is also called as Single Dimensional Array or Linear Array.
 Declaration of one-dimensional array(Single dimensional array)
 Syntax:

 datatype can be int,float,char,double.


 array_name is the name of the array and it should be an valid identifier.
 Size is the total number of elements in array.
For example:
int a[5];
The above statement allocates 5*2=10 Bytes of
memory for the array a.

a[0] a[1] a[2]


a[3] a[4]
 Each element in the array is identified using integer number called as index.
 If n is the size of array, the array index starts from 0 and ends at n-1.
 Storing Values in Arrays

 To store the values in array, there are 3 methods


1. Initialization
2. Assigning Values
3. Input values from keyboard through scanf()
Initialization of one-dimensional array
 Assigning the required values to an array elements before processing is called initialization

data type array_name[expression]={v1,v2,v3…,vn};


Where
 datatype can be char,int,float,double
 array name is the valid identifier
 size is the number of elements in array
 v1,v2,v3… vn are values to be assigned.
 Arrays can be initialized at declaration time. Example:
int a[5]={2,4,34,3,4};

2 4 34 3 4
a[0] a[1] a[2] a[3] a[4]
 The various ways of initializing arrays are as follows:
1. Initializing all elements of array(Complete array initialization)
2. Partial array initialization
3. Initialization without size
4. String initialization

 Initializing all elements of array:


 Arrays can be initialized at the time of declaration when their initial values are known in advance.
 In this type of array initialization, initialize all the elements of specified memory size.
 Example:
int a[5]={10,20,30,40,50};

10 20 30 40 50
2. Partial array initialization

If the number of values to be initialized is less than the size of array then it is called as partial array initialization.
 In such a case elements are initialized in the order from 0th element.
 The remaining elements will be initialized to zero automatically by the compiler.
 Example:
int a[5]={10,20};
10 20 0 0 0

3. Initialization without size


 In the declaration the array size will be set to the total number of initial values specified.
 The compiler will set the size based on the number of initial values.
 Example:
int a[ ]={10,20,30,40,50};
 In the above example the size of an array is set to 5
4. String Initialization
 Sequence of characters enclosed within double quotes is called as string.
 The string always ends with NULL character(\0)

char s[5]=”ABCD”;

We can observe that string length is 4,but size is 5 because to store NULL character we need one more location

A B C D \0
/* program to read N elements from keyboard and to
print N elements on screen */
#include<stdio.h>
int main()
{
int i,n,a[10];
printf("enter number of array elements\n");
scanf("%d",&n);
printf("enter array elements\n");
for(i=0; i<n;i++)
{
scanf("%d",&a[i]);
}
printf("array elements are\n");
for(i=0; i<n;i++)
{
printf("%d\t",a[i]);
}
getch();
return 0;
}
Create a programme to print an array's element sum

#include<stdio.h> Enter a[0] :1


int main() Enter a[1] :2
{ Enter a[2] :3
int arr[5], i, s = 0; Enter a[3] :4
for(i = 0; i < 5; i++) Enter a[4] :5
{
printf("Enter a[%d]: ", i); Sum of elements = 15;
scanf("%d", &arr[i]);
}
for(i = 0; i < 5; i++)
{
s += arr[i];
}
printf("\nSum of elements = %d ", s);
return 0;
}
Two Dimensional Array in C
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be
represented as the collection of rows and columns.

The 2d array is an array that is organized in rows and columns.


Declaration of Two Dimensional Array in C
Syntax of 2D Array
In this blog section, we will explain the syntax of the two dimensional array in c.

data_type array_name[m][n];

Where,

data_type: It will tell the type of data that has to be stored in each element.
array_name: It will tell the name of the array with which it will be referenced in the whole program.
m: It is the number of rows.
n: It is the number of columns.
The array will have a total of m x n elements.

For example, the 2D array in x of 20 rows and 10 columns will be declared like this.

int x[20][10];
Initialization of 2D Array in C
Once declared, initializing a 2D array breathes life into it, filling its cells with initial values. This can be done in several ways,
including:
•At declaration, by directly specifying the values in curly braces:
•int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};

Accessing the Elements of the 2D Array in C


You can access the elements of Two dimensional array in C using the rows and columns or indices shown below.

•array_name[x][y]
Examples of 2 Dimensional Array in C
Example 1: Iterating Over a 2D Array Output Example:
grid[0][0] = 10
#include<stdio.h> grid[0][1] = 20
int main(){ grid[0][2] = 30
int i=0, j=0; grid[0][3] = 40
int grid[2][4] = {{10, 20, 30, 40}, {15, 25, 35, 45}}; grid[1][0] = 15
// Looping through a 2D array grid[1][1] = 25
for(i = 0; i < 2; i++){ grid[1][2] = 35
for(j = 0; j < 4; j++){ grid[1][3] = 45
printf("grid[%d][%d] = %d \n", i, j, grid[i][j]);
}
}
return 0;
}
Example 2: Filling a 2D Array with User Input and Displaying It
#include <stdio.h> Enter value for matrix[0][0]: 5
void main () Enter value for matrix[0][1]:
{ 10
int matrix[2][4],i,j; Enter value for matrix[0][2]:
for (i = 0; i < 2; i++) 15
{ Enter value for matrix[0][3]:
for (j = 0; j < 4; j++) 20
{ Enter value for matrix[1][0]:
printf("Enter value for matrix[%d][%d]: ", i, j); 25
scanf("%d", &matrix[i][j]); Enter value for matrix[1][1]:
} 30
} Enter value for matrix[1][2]:
printf("\nDisplaying the matrix:\n"); 35
for(i = 0; i < 2; i++) Enter value for matrix[1][3]:
{ 40
for (j = 0; j < 4; j++)
{ Displaying the matrix:
printf("%d\t", matrix[i][j]); 5 10 15 20
} 25 30 35 40
printf("\n");
}
}
Array of Strings
An array of strings can be defined as-
 An array of strings is a two-dimensional array of character-type arrays where each character array (string) is null-
terminated.
 Declare and Initialize an Array of Strings
 To declare an array of strings, you need to declare a two-dimensional array of character types, where the first subscript is
the total number of strings and the second subscript is the maximum size of each string.
 To initialize an array of strings, you need to provide the multiple strings inside the double quotes separated by the
commas.

Syntax
char strings [no_of_strings] [max_size_of_each_string];

Example
Let us declare and initialize an array of strings to store the names of 10 computer languages, each with the maximum length
of 15 characters.
char langs [10][15] = { "PYTHON", "JAVASCRIPT", "PHP", "NODE JS", "HTML", "KOTLIN", "C++", "REACT JS",
"RUST", "VBSCRIPT" };
Printing An Array of Strings
A string can be printed using the printf() function with %s format specifier. To print each string of an array of strings, you can
use the for loop till the number of strings.

#include <stdio.h> PYTHON


JAVASCRIPT
int main (){ PHP
NODE JS
char langs [10][15] = { HTML
"PYTHON", "JAVASCRIPT", "PHP", KOTLIN
"NODE JS", "HTML", "KOTLIN", "C++", C++
"REACT JS", "RUST", "VBSCRIPT" REACT JS
}; RUST
VBSCRIPT
for (int i = 0; i < 10; i++){
printf("%s\n", langs[i]);
}

return 0;
}
How an Array of Strings is Stored in Memory?
We know that each char type occupies 1 byte in the memory. Hence, this array will be allocated a block of 150 bytes. Although
this block is contagious memory locations, each group of 15 bytes constitutes a row.

Assuming that the array is located at the memory address 1000, the logical layout of this array can be shown as in the following
figure −
An Array of Strings with Pointers
To use the memory more efficiently, we can use the pointers. Instead of a 2D char array, we declare a 1D array of "char *" type.
char *langs[10] = {
"PYTHON", "JAVASCRIPT", "PHP",
"NODE JS", "HTML", "KOTLIN", "C++",
"REACT JS", "RUST", "VBSCRIPT"
};
In the 2D array of characters, the strings occupied 150 bytes. As against this, in an array of pointers, the strings occupy far less
number of bytes, as each string is randomly allocated memory as shown below −
#include <stdio.h>

int main(){ PYTHON


JAVASCRIPT
char *langs[10] = { PHP
"PYTHON", "JAVASCRIPT", "PHP", NODE JS
"NODE JS", "HTML", "KOTLIN", "C++", HTML
"REACT JS", "RUST", "VBSCRIPT" KOTLIN
}; C++
REACT JS
for (int i = 0; i < 10; i++) RUST
printf("%s\n", langs[i]); VBSCRIPT

return 0;
}

You might also like