0% found this document useful (0 votes)
36 views67 pages

Arrays

array notes in c language

Uploaded by

userdumb709
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views67 pages

Arrays

array notes in c language

Uploaded by

userdumb709
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 67

Arrays

Definition
• An array is a fixed-size sequenced collection of
elements of the same data type.
• An Array is a collection of similar datatype of
elements addressed by a common variable name.

• Unlike regular variables, arrays can hold multiple


values.
Declaration of One-Dimensional Array

Syntax :
type arrayname [ size ];
Where the type specifies the type of element that will be
contained in the array, such as int, float, or char.
The size indicates the maximum number of elements that can
be stored inside the array. Size must be an integer constant
greater than zero.
Declaration Example

void main()
{
int x [ 10 ] ;
}

size
Data type Array Name

Meaning- x is an array, which can hold 10


integers
Example Array Declaration

float height[50]; This declares the height to be an


array containing 50 real numbers

int group[10]; This declares the group to be an


array to contain a maximum of 10
integers.

char str[15]; This declares the str to be an array


to contain a maximum of 15
characters.
Declaring multiple arrays of same type

• Format similar to regular variables


– Example:
int b[100], x[27];

Char str1[25], str2[25];


Declaring Arrays

• Example specifies an array…


– each element is an integer
– there is space for 100 elements
– the are numbered 0 through 99
void main()
{
int scores [100] ;
}

scores
scores: : 85
85 79
79 92
92 57
57 68
68 80
80 . .. .. .
0 1 2 3 4 5 98 99

7
Array Declaration

// array of 10 uninitialized
integers
int Ar[10];

0 1 2 3 4 5 6 7 8 9
Ar -- -- -- -- -- -- -- -- -- --
Initialization of One-Dimensional Array

Assigning initial values to an array is called


array initialization. An array can be initialized
at either of the following stages.
1. At compile time
2. At run time
Compile time Initialization
Syntax:
type arrayname[size] = { list of values };
The values in the list are separated by commas.
Example
int x[3] = { 10,0,5};
Will declare x is an array of size 3 and will assign
10, 0, 5 to the array.
x
10 0 5
Some variations during initialization
1. If the number of values in the list is less than the
size of the array, then only that many elements
will be initialized. The remaining elements will
be set to 0 automatically if array type is numeric
and NULL if the type is char.
Example
int n[ 5 ] = { 0 };
Here all elements of the array n sets to 0.
Char city[5] = {‘B’};
Here city is an array whose 1st element is B and the
remaining 4 will be NULL.
Some variations during initialization …
2. The size may be omitted. In such cases, the
compiler allocates enough space for all
initialized elements.
Example
int n[ ] = {1,2,3,4,5} ;
Here n is an array initialized with values 1,2,3,4,5
Some variations during initialization …

3. If we have more initializers than the declared


size, the compiler will produce an error.
Example
int n[ 3 ] = {1,2,3,4,5} ;
This will not work. It is illegal in C.
Array Concept
If we declare
int x[5];
The computer reserves five storage locations as
shown below

First Last
X[0] X[1] X[2] X[3] X[4]
Element Element
• void main()
• {
• int x[5] = { 35,40,20,57};
• X[0]= 35;
• X[1] = 40;
• X[2] = 20;
• X[3] = 57;

• }
The values to the array elements can be
assigned as,
X[0] = 35;
X[1]= 40;
X[2]= 20;
X[3]= 57;
X[4]= 19;

35 40 20 57 19

X[0] X[1] X[2] X[3] X[4]


By using subscripts we can use the array
elements.
Eample
A = x[0] + 10;
X[4] = x[0] + x[2]
Value[6] = x[i] *3

Note : The subscripts of an array can be integer


constants, integer variables or expressions that
yield integers.
Suppose we declare an array like
int marks [10] = {12, 23, 14, 25, 16, 23, 21, 32, 52, 63};
Memory Allocation

Address at particular index = Base Address +index*scalefactor


Run Time Initialization

void main()
{
int x [10], i;
for (i = 0; i<10; i++)
{
x[i] = 1;
}
}
1
• Void main()
• {
• int x [10],i;
• for(i=0; i<10; i++)
• {
• scanf(“%d”, &x[i];
• }

• }

13 50 25
Reading Data into an Array
Using scanf() function.

void main()
{
int x [3];
scanf(“%d%d%d”, &x[0], &x[1], &x[2]);
}
Reading Data into an Array
Using scanf() function.

void main()
{
int x [10], i;
for (i = 0; i<10; i++)
{
scanf(“%d”, &x[i]);
}
}
• void main()
• int x[] ={1, 2, 3, 4, 5,6,7,8,9,10};
• for (i=0; i<10; i++)
• {
• printf(“%d”, x[i];
• }
• }
Printing the contents of an Array

void main()
{
int x [5] = {1,2,3,4,5};
for (i = 0; i<10; i++)
{
printf(“%d”, x[i]);
}
}
1 2 3 4 5
void main()
{
int x[10],i;
printf(“Enter 10 integers”);
for(i=0; i<5; i++)
{
scanf(“%d”, &x[i]);
}
for (i=0; i<10; i++)
{
printf(“%d”, x[i]);
}
}
Write a program to read data from keyboard into an
array and display the array content.

void main()
{
int x [10],i;
for (i = 0; i<10; i++)
{
scanf(“%d”, &x[i]);
}
for (i = 0; i<10; i++)
{
printf(“%d”, x[i]);
}
}
One Dimensional Array

A list of items can be given one variable name using


only one subscript and such a variable is called a
single-subscripted variable or a one-dimensional
array.
Sample Array Program

program to find average of the elements in the array


#include<stdio.h>
void main()
{
int array[5], i , sum;
float Avg;
sum = 0;
printf("Enter 5 numbers to store them in array \n");
for(i=0;i<5;i++)
{
scanf("%d", &array[i]);
}
for(i=0;i<5;i++)
{
sum = sum + array[ i];
}
Avg = sum/5.0;
printf(“%f”, Avg);
}
Sample Array Program
Program to print odd numbers present in the array
#include<stdio.h>
void main()
{
int array[5], i;
printf("Enter 5 numbers to store them in array \n");
for(i=0;i<5;i++)
{
scanf("%d", &array[i]);
}
for(i=0;i<5;i++)
{
if ( array[i] %2 != 0)
{
printf(“%d”, array[i]);
}
}
}
Sample Programs
1. Write a program to find the sum of integers available in an
array.
2. Write a program to separate out all the odd numbers and
even numbers into array named odd and even respectively.
3. Write a program to find the largest among some numbers.
4. Write a program to print the contents of an array in reverse
order.
5. Write a program to search a number in an array of numbers
using linear search.
6. Write a program to search a number in an array of numbers
using binary search.
7. Write a program to sort the numbers available in an array.
void main()
{ int array[10], search, c; Linear Search
for (c = 0; c <10; c++)
{
scanf("%d", &array[c]);
}
printf("Enter the number to search\n"); scanf("%d", &search);
for (c = 0; c < 10; c++)
{
if (array[c] == search) /* if required element found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == 10)
{
printf("%d is not present in array.\n", search);
}
}
void main()
{ int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d",&n); Binary Search
printf("Enter %d integers\n", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d",&array[c]);
printf("Enter value to find\n");
scanf("%d",&search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
printf("Not found! %d is not present in the list.\n", search);
}
Sorting

• Sorting takes an unordered collection and makes


it an ordered one.
1 2 3 4 5 6

77 42 35 12 101 5

1 2 3 4 5 6

5 12 35 42 77 101
"Bubbling Up" the Largest Element
• Traverse a collection of elements
– Move from the front to the end
– “Bubble” the largest value to the end using pair-wise comparisons
and swapping

1 2 3 4 5 6

77 42 35 12 101 5
"Bubbling Up" the Largest Element
• Traverse a collection of elements
– Move from the front to the end
– “Bubble” the largest value to the end using pair-wise comparisons
and swapping

1 2 3 4 5 6
42 Swap4277
77 35 12 101 5
"Bubbling Up" the Largest Element
• Traverse a collection of elements
– Move from the front to the end
– “Bubble” the largest value to the end using pair-wise comparisons
and swapping

1 2 3 4 5 6

42 35Swap35
77 77 12 101 5
"Bubbling Up" the Largest Element
• Traverse a collection of elements
– Move from the front to the end
– “Bubble” the largest value to the end using pair-wise comparisons
and swapping

1 2 3 4 5 6

42 35 12Swap12
77 77 101 5
"Bubbling Up" the Largest Element
• Traverse a collection of elements
– Move from the front to the end
– “Bubble” the largest value to the end using pair-wise comparisons
and swapping

1 2 3 4 5 6

42 35 12 77 101 5

No need to swap
"Bubbling Up" the Largest Element
• Traverse a collection of elements
– Move from the front to the end
– “Bubble” the largest value to the end using pair-wise comparisons
and swapping

1 2 3 4 5 6

42 35 12 77 5 Swap101
101 5
"Bubbling Up" the Largest Element
• Traverse a collection of elements
– Move from the front to the end
– “Bubble” the largest value to the end using pair-wise comparisons
and swapping

1 2 3 4 5 6

42 35 12 77 5 101

Largest value correctly placed


Items of Interest

• Notice that only the largest value is correctly


placed
• All other values are still out of order
• So we need to repeat this process

1 2 3 4 5 6

42 35 12 77 5 101

Largest value correctly placed


Repeat “Bubble Up” How Many Times?

• If we have N elements…

• And if each time we bubble an element, we


place it in its correct location…

• Then we repeat the “bubble up” process


N – 1 times.

• This guarantees we’ll correctly


place all N elements.
“Bubbling” All the Elements
1 2 3 4 5 6
42 35 12 77 5 101

1 2 3 4 5 6
35 12 42 5 77 101

1 2 3 4 5 6
N-1

12 35 5 42 77 101

1 2 3 4 5 6
12 5 35 42 77 101

1 2 3 4 5 6
5 12 35 42 77 101
Program to sort the elements of an array (Using Bubble Sort)
#include <stdio.h>
void main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < n – 1 ; c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For increasing order use < */
{ swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
}
2- Dimensional Array
2- Dimensional Array

A two-dimensional array consists of both rows


and columns of elements. It is essentially a
matrix.
2 – Dimensional Array Declaration

• To declare a two-dimensional array, we merely use


two sets of square brackets.
– The first contains the number of rows
– The second contains the number of columns
Syntax:
datatype arrayname [row_sizw][col_size]
Example of 2-D Array Declaration
int val[3][4];
Assume that the two dimensional array called
val is declared and looks like the following:

val Col 0 Col 1 Col 2 Col 3

Row 0 8 16 9 52

Row 1 3 15 27 6

Row 2 14 25 2 10
val Col 0 Col 1 Col 2 Col 3

Row 0 8 16 9 52

Row 1 3 15 27 6

Row 2 14 25 2 10

• To access the cell containing 6, we reference


val[1][3], that is, row 1, column 3.
Initializing 2D arrays

1. Two-dimensional arrays can be initialized by


following their declaration with a list of initial
values enclosed in braces. For example,
int table[2][3] = { 0, 0, 0, 1, 1, 1 };

This will initialize the first row to zero and the


second row to one
• 0 0 0
• 1 1 1
Initializing 2D arrays

2. The initialization can be done row by row by


surrounding the elements of each row by
braces.
int table[2][3] = { {0, 0, 0}, { 1, 1, 1 }};

This will initialize the first row to zero and the


second row to one
Initializing 2D arrays

3. The initialization can be done row by row by


surrounding the elements of each row by braces in the
form of a matrix.
int table[2][3] = {
{0, 0, 0},
{ 1, 1, 1 }
};

This will initialize the first row to zero and the second row
to one
Initializing 2D arrays

4. When the array is completely initialized with all values,


explicitly, we need not specify the size of the first dimension.

int table[][3] = {
{0, 0, 0},
{ 1, 1, 1 },
{2 , 2, 2 }
};
This is permitted.

This will initialize the first row to zero and the second row to one
Initializing 2D arrays

5. If the values are missing in an initializer, they are automatically


set to zero.

int table[2][3] = {
{ 1, 1 },
{2}
};
This is permitted.

This will initialize the first two elements of first row to 1 , the first
element of the second row to 2, and all other elements to 0.
A
1 1 0 A[0][0] A[0][1] A[0][2]
2 0 0
A[1][0] A[1][1] A[1][2]
void main()
{
int x[3][3] row, col;
for(row = 0; row<3; row++)
{
for(col = 0; col<3; col++)
{
X[0][0] x[0][1] x[0][2]
scanf(“%d”, &x[row][col]; X[1][0] x[1][1] x[1][2]
} X[2][0] x[2][1] x[2][2]
}
For(row = 0; row<3; row++)
{
for(col = 0; col<3; col++)
{
printf(“%d”, x[row][col];
}

Printf(“\n”);
}
}
}
Reading data into an 2-Dimensional Array

void main()
{
int a[3][3], i, j;
for(i=0; i < 3; i++)
{
for(j=0; j < 3; j++)
{
scanf(“%d”, &a[i][j]);
}
}
}
Displaying the contents of an
2-Dimensional Array
void main()
{
int a[3][3], i, j;
for(i=0; i < 3; i++)
{
for(j=0; j < 3; j++)
{
scanf(“%d”, &a[i][j]);
}
}
for(i=0; i < 3; i++)
{
for(j=0; j < 3; j++)
{
printf(“%d”, &a[i][j]);
}
printf(“\n”);
}

}
Exercise

• Find the maximum of int matrix[3][4]


• Find the number of times x appears in int matrix[3][4]
• Compute the addition of two matrices
• Compute the Transpose of a matrix
• Compute the multiplication of two matrices
Matrix Multiplication

j
j 0 1 2 3
0 1 2 3
0 3 4 0 22 29 45 35
2 3 7 1
1 5 2 x = 1 18 40 47 21
4 5 6 8 2
2
1 6 26 33 43 49
i i
j=0
c[i][j] =
2
i=0 3 4 x k = a[i][k=0]*b[k=0][j] +
4 a[i][k=1]*b[k=1][j]
k
62
Matrix Multiplication
Logic of Matrix Multiplication
#define N 3
#define M 2
#define L 4
void matrix_mul(a[N][M], int b[M][L], int c[N][L])
{
int i, j, k;
for(i=0; i < N; i++) {
for(j=0; j < L; j++) {
c[i][j] = 0;
for(k=0; k < M; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
return;
}

63
Passing One-Dimensional Array to Function
Program to find the largest value in an
array of elements. void FindLargest(int a[], int n)
{
#include<stdio.h>
int I;
void main() int max;
{ max = a[0];
void FindLargest(int a[], int n) for(i= 1; i < n; i++)
int value[5] = { 12, 27, 32, 15,95 }; {
FindLargest (value, 4); if (max < a[i])
max = a[i];
}
}
printf(“%d”, max);
}
Passing One-Dimensional Array to Function
Program to find the largest value in an
array of elements. void FindLargest(int a[4])
{
#include<stdio.h>
int I;
void main() int max;
{ max = a[0];
void FindLargest(int a[4]) for(i= 1; i < 4; i++)
int value[5] = { 12, 27, 32, 15,95 }; {
FindLargest (value); if (max < a[i])
max = a[i];
}
}
printf(“%d”, max);
}
Passing Two-Dimensional Array to Function
Program to find the average of the values void FindLargest(int a[][2], int r, int c )
in a two dimensional matrix. {
#include<stdio.h> int i;
float avg;
void main()
int sum=0;
{ for(i= 0; i < r; i++)
void FindLargest(int a[][2], int r, int c) {
int value[2][2] = { 1,2,3,4 }; for(j=0; j<c; j++)
FindAverage (value, 2,2); {
} sum = sum + a[i][j];
}
}
avg = sum /4.0;
Printf(“%f”, avg);
}
Passing Two-Dimensional Array to Function
Program to find the average of the values void FindLargest(int a[2][2])
in a two dimensional matrix. {
#include<stdio.h> int i;
float avg;
void main()
int sum=0;
{ for(i= 0; i < 2; i++)
void FindLargest(int a[2][2]) {
int value[2][2] = { 1,2,3,4 }; for(j=0; j<2; j++)
FindAverage (value); {
} sum = sum + a[i][j];
}
}
avg = sum /4.0;
Printf(“%f”, avg);
}

You might also like