Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

Introduction to Computer

Programming

Dr. K. Suganya Devi


Department of CSE,
National Institute of Technology Silchar
Arrays
What is Array?
An array is a fixed-size sequential collection of
elements of same data types that share a

common name.
It is simply a group of data types.
An array is a derived data type.


An array is used to represent a list of numbers ,
or a list of names.

The size and type of arrays cannot be
changed after its declaration. For Example : If
you want to store marks of 100 students you can
create an array for it.
float marks[100]; 3
Element of an array

0 1 2 3 4 Element
Array of 5 index
elements
Introducing A r r a y s
 Array is a data structure that represents a collection of
the same types of data.
int num[10];num [0]
Num reference num[1]
num[2]
num [3]
An Array of 10 Elements
num[4] of type int.
num[5]
num[6]
num[7]
num[8]
num[9]
Contd…

 An Array provides a convenient structure for representing data hence


it is classified as one of the Data Structure In C.
 Example:

income[10]

 The above example represents the income of employees.


Individual values are called elements While the complete set of
values is referred to as an array. In above example there can be
maximum 10 elements.
 An Array is a derived data type
The Le ngt h o f A r r a y s
 Once an array is created, its size is fixed. It
cannot be changed.
For Example,
int arr[10];

You can not insert any number to arr[11]


location because it is not initialized.
Contd…

Suppose you declared an array markas above. The


first element is mark[0], second element is
mark[1] and so on.

Few Keypoints:
• Arrays have 0 as the first index not 1. In this example,
mark[0].
• If the size of an array is n, to access the last element, (n-1)
index is used. In this example, mark[4].
• Suppose the starting address of mark[0] is 2120d. Then, the
next address, mark[1], will be 2124d, address of mark[2] will
be 2128d and so on. Its because the size of a float is 4 bytes.
Example of Arrays:

 For Example :
1. List of employees in an organization.
2. Test scores of a class of students.
3. List of customers and their telephone numbers.
4. List of students in the college.
 For Example, to represent 100 students in college , can
be written as
student [100]
 Here student is a array name and [100] is called index
or subscript.

9
Types of Arrays
Based on their dimensions arrays can be
classified ino three types.

Types of Array :
1. One-dimensional arrays
2. Two-dimensional arrays
3. Multidimensional arrays

10
One-dimensional Arrays.

 A variable which represent the list of items using only one


index (subscript) is called one-dimensional array.

 For Example , if we want to represent a set of five numbers


say(35,40,20,57,19), by an array variable number, then
number is declared as follows
int number [5] ;

11
One-dimensional Arrays.
 and the computer store these numbers as shown below :
number [0]
number [1]
number [2]
number [3]
number [4]
 The values can be assigned to the array as follows :
number [0] = 35;
number [1] = 40;
number [2] = 20;
number [3] = 57;
number [4] = 19;
12
DECLARATION OF ONE-DIMENSIONAL ARRAYS :

 The general form of array declaration is :


type array-name[size];
 Here the type specifies the data type of elements
contained in the array, such as int, float, or char.
 And the size indicates the maximum numbers of elements
that can be stored inside the array.
 The size should be either a numeric constant or a symbolic
constant.

13
Example

 For example :

int group [10] ;

 here int is type, group is a variable name , 10 is a size of


array and the subscripts (index) is start from 0 to 9.

14
Important thing to remember when working with Carrays:

Suppose you declared an array of 10 elements. Letssay,

int testArray[10];

You can use the array members from testArray[0] to


testArray[9].

If you try to access array elements outside of its bound, lets


say testArray[12], the compiler may not show any error.
However, this may cause unexpected output (undefined
behavior).
Creating and Initializing Arrays

 Creating and initializing can be done together:

Int myIntArray[5] = {1, 2, 3, 4, 5};

0 1 2 3 4
myIntArray … … … … …

managed heap
(dynamic memory)
Accessing Array Elements

READ AND MODIFY ELEMENTS BY INDEX


How to Access Array Element?

 Array elements are accessed using the square brackets


operator [ ] (indexer)
› Array indexer takes element’s index as parameter
› The first element has index 0
› The last element has index Length-1

 Array elements can be retrieved and changed by the [ ]


operator
Arrays: Input and Output

Reading and Printing Arrays on the Console


Reading Arrays

 Ex. Int array[5];

Scanf(“%d”,&array[5]);
-------------------------------------------------
-------------------------------------------------

Printing Arrays

printf(“a[5]=%d”,array[5]);
-------------------------------------------------
-------------------------------------------------
INITIALIZATION OF ONE-DIMENSIONAL ARRAYS :

 An array can be stored in following stages :


1. At compile time
2. At run time
Compile time initialization :
 In compile time initialization, the array is initialized when
they are declared.
 The general form of initialization of array is :
type array-name[size] = { list of values };
 The list of values are separated by commas.

21
The type specifies the type of the element that will be
contained in the array, such as int, float, or char and the size
indicates the maximum number of elements that can be stored
inside the array.
Now as we declare a array
int number[5];
Then the computer reserves five storage locations as
the size o the array is 5 as show below.

ReservedSpace Storing values after Initialization

number[0] number[0] 35
number[1] number[1] 20
number[2] number[2] 40
number[3] number[3] 57
number[4] number[4] 19
Initialization of onedimensional array:

After an array is declared, its elements must be


initialized. In C programming an array can be initialized at
either of the following stages:

At compile time
At run time
Compile Time Initialization:
The general form of initialization of array is:
type array-name[size] ={list of values};
The values in the list are separated by commas.
For example:
int number[3] ={0,5,4};

will declare the variable ‘number’ as an array of


size 3 and will assign the values to each elements.
If the number of values in the list is less than the
number of elements, then only that many elements will be
initialized.
The remaining elements will be set to zero
automat ically.
Remember, if we have more initializers than the
declared size, the compiler will produce an error.
Compile time initialization

Example :
int number[3] = {4,5,9};
 Here array number of size 3 and will assign 4 to first
element(number[0]), 5 is assign with second
element(number[1]) and 9 is assign with third
element(number[2]).

 If the number of values in the list is less than the number of


elements, then only that many elements will be intialized. The
remaining elements will be set to zero automatically.

25
Compile time initialization

Example :
int number[ ] = {1,2,3,4};

 The character array can be initialized as follows :

char name[ ] = {‘j’,’o’,’h’,’n’,’\0’};

 The character array can also be initialized as follows :


char name[ ] = “john”;

26
Run time initialization:
An array can also be explicitly initialized at run time.
For example consider the following segment of a c program.

for(i=0;i<10;i++)
{
scanf(“%d”, &x[i]);
}
In the run time initialization of the arrays looping
statements are almost compulsory.

Looping statements are used to initialize the values of the


arrays one by one using assignment operator or through the
keyboard by the user.
Run time initialization :
 In run time initialization, the array is explicitly initialize at run
time.
 This concept generally used for initializing large arrays.
 Example:
for(i=0; i < 100; i++)
{
if( i < 50)
sum[i] = 0.0;
else
sum[i] = 1.0;
}
 Here first 50 elements of the array sum are initialized to 0
and the remaining 50 elements are initialized to 1 at run
time. 13
One dimensional Array Program:
#include<stdio.h>
void main()
{
int array[5];
printf(“Enter 5 numbers to store them in array \n”);
for(i=0;i<5;i++)
{
Scanf(“%d”, &array[i]);
}
printf(“Element in the array are: \n”);
For(i=0;i<5;i++)
{
printf(“Element stored at a[%d]=%d \n”, i, array[i]);
}
getch();
}
Input:
Enter 5 elements in the array: 23 45 32 25 45
Output:
Element in the array are: Element
stored at a[0]:23 Element stored at
a[0]:45 Element stored at a[0]:32
Element stored at a[0]:25 Element
stored at a[0]:45
Two Dimensional Array

 If we have store the value as table then we have to use 2-D


array.
 Ex:-

i-1 i-2 i-3


1. 10 20 30
2. 20 10 13

 C allow s us to define such tables of items by using 2-D


arrays.
 Syntax::
 Type array name[raw size][column size];
Hear the first index contains row size, second index
contains column size.
Twodimensional A r r a y
Illustration

0 1 2 3 4 0 1 2 3 4
0 1 2
0 0
0 1 2 3
1 1
1 4 5 6
2 2 7
2 7 8 9
3 3
3 10 11 12
4 4

int matrix[5] [5]; int[][] array ={


matrix[2] [1] =7
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11,12}};
Two-dimensional Arrays

 A variable which represent the list of items using two index


(subscript) is called two-dimensional array.

 In Two dimensional arrays, the data is stored in rows and


columns format.

 For example:
int table[2][3];

33
DECLARATION OF TWO-DIMENSIONAL ARRAYS :

 The general form of two dimensional array declaration is :

type array-name[row_size][column_size];

 Here the type specifies the data type of elements


contained in the array, such as int, float, or char.
 The size should be either a numeric constant or a
symbolic constant.

34
INITIALIZATION OF TWO-DIMENSIONAL ARRAYS :

 The general form of initializing two-dimensional array is :


type array-name[row_size][column_size] = {list
of values};
 Example :
int table[2][3] = {0,0,0,1,1,1};
 Here the elements of first row initializes to zero and the
elements of second row initializes to one.
 This above statement can be written as :
int table[2][3] = {{0,0,0}, {1,1,1}};
 In two-dimensional array the row_size can be omitted.

35
INITIALIZATION OF TWO-DIMENSIONAL ARRAYS :

 Example :
int table[ ][3] = {{0,0,0}, {1,1,1}};
 If the values are missing in an initializer, they are
automatically set to zero.

 Example :
int table[2][3] = {1,1,2};
 Here first row initialize to 1,1 and 2, and second row
initialize to 0,0 and 0 automatically.

36
Memory Layout of Two-dimensional array :

 In Two dimensional arrays, the data is stored in rows and


columns format.
 For example:
int table[2][3] = {1,2,3,4,5,6};

 The memory layout of above example :


table[0][0] = 1;
table[0][1] = 2
table[0][2] = 3;
table[1][0] = 4;
table[1][1] = 5;
table[1][2] = 6;

37
multi-dimensional Arrays

 A variable which represent the list of items using more than


two index (subscript) is called multi-dimensional array.

 The general form of multi dimensional array is :


type array-name[s1][s2][s3]…….[sn];

38
multi-dimensional Arrays

 Where S is the size. Some examples are :


int survey[3][5][6];

float table[5][4][5][3];

 Here survey is a three-dimensional array And table is a


four-dimensional array.

39
Declaration of Multidimensional Array
A multidimensional array is declared using the
following syntax
Syntax:
data_type array_name[d1][d2][d3][d4]....[dn];
Above statement will declare an array on N
dimensions of name array_name, where each element of
array is of type data_type.
The maximum number of elements that can be
stored in a multi dimensional array array_name is size1 X
size2 X size3....sizeN.
For example:
char cube[50][60][30];
Dynamic Arrays

 We created array at run time, so we can not modify it at run


time so they are called static array. This approach works fine
as long as we know exactly what our data requirement are..
 In C it is possible to allocate memory to arrays at run time ,
which known as dynamic memory allocation and the array
called dynamic array.
 Dynamic array are created using what are known as pointer
variables and memory management function malloc, calloc,
realloc, which are in <stdio.h>
Applications Of arrays

 Using pointers for accessing arrays.


 Passing arrays as function parameters.
 Arrays as members of structures.
 Using structure type data as array elements.
 Arrays as dynamic data structures.
 Manipulating character arrays and strings.

42
Some Examples of Array
Ex: Write a program to print first 10 number.
::
#include<stdio.h>
void main() // pr [ 1 0 ] i s a r r a y o f 10
{

Int i, r[10];
elements.
// assign value to array
for (i = 1; i < =10; i++)
{
r[i]=i;
printf("%d",r[i]);
printf(”\n”);
}
}
:: output::
1
2
3
4
5
6
7
8
9
10
Write a program to read and display 3x3matrix.

#include<stdio.h>
v oi d main()
{
int i,j,a[3][3];
p r i n t f ( “ E n t e r t h e e l e m e n t s of 3 x 3 matrix”);
for(i=0;i<3;i++)

for(j=0;j<3;j++)
{
p r i n t f ( “ a [ % d ] [ % d ] = s c a n f (“% d ” , a [ i ] [ j ] ) ;

p r i n t f ( “ T h e v a r i o u s e l e m e n t s in 3x3 matrix are:\n”);


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

{
p r i n t f (“ \ n \ t \ t ”);
for(j=0;j<3;j++)

p r i n t f (“%d \ t ” , a [ i ] [ j ] ) ;
}}
: : o u t p u t ::

Enter the elements of the 3 x 3 matrix :


a[0][0]=1
a[0][1]=2
a[0][2]=3
a[1][0]=4
a[1][1]=5
a[1][2]=6
a[2][0]=7
a[2][1]=8
a[2][2]=9
The various elements of the 3 X 3 matrix:
1 2 3
4 5 6
7 8 9
Multidimensional Array program:
#include<stdio.h>
int main()
{
int r,c,a[50][50],b[50][50],sum[50][50],i,j;
printf("\t\n Multi-dimensional array");
printf("\n Enter the row matrix:");
scanf("%d",&r);
printf("\n Enter the col matrix:");
scanf("%d",&c);
printf("\n Element of Amatrix");
for(i=0;i<r;++i)
for(j=0;j<c;++j)
{
printf("\n a[%d][%d]:",i+1,j+1);
scanf("%d",&a[i][j]);
}
printf("\n Element of Bmatrix"); for(i=0;i<r;++i)
for(j=0;j<c;++j)
{
printf("\n b[%d][%d]:",i+1,j+1);
scanf("%d",&b[i][j]);
}
printf("\n Addition of matrix"); for(i=0;i<r; i++)
{
for(j=0;j<c;j++) sum[i][j]=a[i][j]+b[i][j];
}
for(i=0;i<r;i++)
{
printf("\n"); for(j=0;j<c;j++)
{
printf("\t%d",sum[i][j]);
}
printf("\n\t");
}
if(j==c-1)
{
printf("\n");
}
return 0;
}
Output
Multidimensional array
Enter the row matrix:2
Enter the col matrix:2

Element of Amatrix
a[1][1]:1
a[1][2]:4
a[2][1]:6
a[2][2]:3
Element of Bmatrix
b[1][1]:1
b[1][2]:7
b[2][1]:3
b[2][2]:9

Addition of a matrix is
2 11
9 12
THANK YOU

You might also like