Array Data Structure

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

Array Data Structure

▪ In computer science, an array data structure is a basic idea whereby a collection of elements is
kept in a contiguous block of memory. It is extensively applied in programming for data
organization and manipulation and provides effective access to elements utilizing indices.
▪ Every element in an array has a 0-based index. Every element in an array is reachable via its index.
▪ An array is defined as a set of finite number of homogeneous elements or same data items.

There are two main types of arrays:

✓One-dimensional arrays: These arrays store a single


row of elements.
✓Multidimensional arrays: These arrays store multiple
rows of elements.
Sales
array
17.00 Sales[0]
name
17.95 Sales[1]
12.98 Sales[2]
112.49 Sales[3]
0.00 Sales[4] array
array
indices
elements 3.00 Sales[5]
(subscripts)
65.29 Sales[6]
0.00 Sales[7]
72.98 Sales[8]
0.00 Sales[9]
Array Indices
• The array indices are similar to the subscripts used in matrix
notation:
Sales[0] is C notation for Sales 0
Sales[1] is C notation for Sales 1
Sales[2] is C notation for Sales 2
• The index is used to refer to a part of array
• Note, C does not check your index (leading to index-out-of-
range errors)
Accessing Array Elements
• Requires
– array name,
– subscript labeling individual element
• Syntax: name[subscript]
• Example
Sales[5] refers to the sales totals for employee 5
Sales[5] can be treated like any float variable:
Sales[5] = 123.45;
printf(“Sales for employee 5: $%7.2f\n”,Sales[5]);
Invalid Array Usage
Example:
float Sales[10];
Invalid array assignments:
Sales = 17.50; /* missing subscript */
Sales[-1] = 17.50; /* subscript out of range */
Sales[10] = 17.50; /* subscript out of range */
Sales[7.0] = 17.50; /* subscript wrong type */
Sales[‘a’] = 17.50; /* subscript wrong type */
Sales[7] = ‘A’; /* data is wrong type */
Conversion will still occur:
Sales[7] = 17; /* 17 converted to float */
Array Initialization
• Arrays may be initialized, but we need to give a list of
values
• Syntax:
Type Name[Size] =
{ value0, value1, value2, …, valueSize-1 };
value0 initializes Name[0], value1 initializes Name[1], etc.
values must be of appropriate type (though automatic casting will
occur)
▪ Examples of the one-dimensional array declarations,

 int xNum[20], yNum[50];


 float fPrice[10], fYield;
 char chLetter[70];

▪ The first example declares two arrays named xNum and yNum
of type int. Array xNum can store up to 20 integer numbers
while yNum can store up to 50 numbers.

▪ The second line declares the array fPrice of type float. It


can store up to 10 floating-point values.

▪ The third line declares the array chLetter of type char. It


can store a string up to 69 characters.

▪ Why 69 instead of 70? Remember, a string has a null


terminating character (\0) at the end, so we must reserve for
it.
A R R AY I N I T I A L I Z AT I O N
▪ An array may be initialized at the time of declaration.

▪ Initialization of an array may take the following form,


 type array_name[size] = {a_list_of_value};
▪ For example:
 int idNum[7] = {1, 2, 3, 4, 5, 6, 7};
 float fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1};
 char chVowel[6] = {'a', 'e', 'i', 'o', 'u', '\0'};

▪ The first line declares an integer array idNum and it immediately


assigns the values 1, 2, 3, ..., 7 to idNum[0], idNum[1],
idNum[2],..., idNum[6] respectively.

▪ The second line assigns the values 5.6 to


fFloatNum[0], 5.7 to fFloatNum[1], and so on.

▪ Similarly the third line assigns the characters 'a' to chVowel[0],


'e' to chVowel[1], and so on. Note again, for characters we must
use the single apostrophe/quote (') to enclose them.
▪ Also, the last character in chVowel is NULL character ('\0').
▪ Initialization of an array of type char for holding strings
may take the following form,
⚫ char array_name[size] =
"string_lateral_constant";

▪ For example, the array chVowel in the previous example


could have been written more compactly as follows,
⚫ char chVowel[6] = "aeiou";

▪ When the value assigned to a character array is a string


(which must be enclosed in double quotes), the compiler
automatically supplies the NULL character but we still
have to reserve one extra place for the NULL.
▪ For unsized array (variable sized), we can declare as
follow,
⚫ char chName[ ] = "Dr. Divya Rishi Shrivastava";

▪ C compiler automatically creates an array which is big


enough to hold all the initializer.
The Sizeof()
• Once an array is created, its size is fixed. It cannot be
changed. You can find its size using:

int array_size = sizeof(Array);


giving the total amount of storage required (in bytes)
Array’s Length: divide the total array size by the size of one datatype
char chName[ ] = "Dr. Divya Rishi Shrivastava";
int size = sizeof(chName)/sizeof(chName[0]);
printf("%d\n",size);
Processing All Elements of Array
• Process all elements of array A using for:
/* Setup steps */
for (I = 0; I < ArraySize; I++)
process A[I]
/* Clean up steps */
• Notes
I initialized to 0
Terminate when I reaches ArraySize
R E T R I E V I N G A R R AY
ELEMENTS
 If you want to retrieve specific element then then
you have to specify not only the array or variable
name but also the index number of interest.

 For example:
 int Arr[]={1,3,5,6,8};

 printf(“%d\t%d\n”,Arr[1],Arr[2]);

 Output: 3 5
A R R AY
EXAMPLE
 Take 10 integer input from user and store then in an
array and find the sum of all numbers stored in array.

#include<stdio.h>
int main(){
int i,sum=0,arr[10];
for(i=0;i<10;i++)
scanf(“%d”,&arr[i]);
for(i=0;i<10;i++)
sum+=arr[i];
printf(“Sum of input integers is %d\n”,sum);
return 0;
}
 Wr i te a pro g ra m t h a t f i n d s o u t
Problem i f a n I n te g e r i s re p e a te d m o re
#include<stdio.h> t h a n o n c e i n l i s t o f 1 0 i n te g e r s
int main(){
int i,j,x,arr[10];
a u s e r i n s e r te d .
printf("Enter 10 integer Enter 10 integer number
number\n"); for(i=0;i<10;i++){ 23
scanf("%d",&arr[i]); 34
5
}
6
for(i=0;i<9;i++){ 7
x=arr[i]; 7
for(j=i+1;j<10;j++ 6
){ 34
9
if(x==arr[j]) 8
printf("%d number appeared more than 34 number appeared more than once
once\n",x); 6 number appeared more than once
7 number appeared more than once
}
} --------------------------------
return 0; Process exited after 7.535 seconds with return value 0
Press any key to continue . . .
}
Pro b le m
 A six faced die is rolled 600 times. Find the frequency of the occurrence of
each face?

 int rand(void): returns a pseudo-random


number in the range of 0 to R A N D _ M A X .
 R A N D _ M A X : is a constant whose default value may vary between implementations
but it is granted to be at least 32767.
 Issue: If we generate a sequence of random number with rand() function, it will
create the same sequence again and again every time program runs.
 The srand() function sets the starting point for producing a series of
pseudo-random integers. If srand() is not called, the rand() seed is set
as if srand(1) were called at program start.

 The pseudo-random number generator should only be seeded once,


before any calls to rand(), and the start of the program.

 Standard practice is to use the result of a call to srand(time(0)) as


the seed. However, time() returns a time_t value which vary everytime
and hence the pseudo-random number vary for every program call.
➢ srand() Function: The srand() function is used to set the starting // Generate and print five
random numbers
point (seed) for generating a sequence of pseudo-random integers
#include <stdio.h>
by the rand() function. #include <stdlib.h>
➢ srand() takes an unsigned integer as an argument, which it uses as #include <time.h>

the seed.time(0) or time(NULL):time(0) returns the current time as int main() {


srand(time(0)); // Seed the random
the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC number generator with the current
(commonly referred to as the "Unix epoch"). time

➢ This value is generally used as a unique seed because it changes // Generate and print five random
numbers
every second, ensuring that the random number sequence generated
for (int i = 0; i < 5; i++) {
by rand() is different each time the program is run. printf("%d\n", rand());
}
➢ srand(time(0)) seeds the random number generator with the current
time. return 0;
}
➢ This makes the sequence of numbers generated by rand() different
each time the program is executed.
#include<stdio.h> 1 came out for 108 times
2 came out for 96 times
3 came out for 96 times
int main(){ 4 came out for 90 times
int i,j,arr[7]={0}; 5 came out for 109 times
srand(time(0)); 6 came out for 101 times
for (i=0;i<600;i++){
j=rand()%6; --------------------------------
Process exited after 0.07046 seconds with return value 0
j=j+1; Press any key to continue . . .
arr[j]++;
}
for(i=1;i<=6;i++)
printf("%d came out for %d times\n",i,arr[i]);
return 0;
}
Problem
 Remove an element from a specific position in the array and shift
the remaining elements accordingly
#include <stdio.h>
// Function to remove an element from a specific position
// Shift the elements to the left from the position
// Reduce the size of the array
// Print the updated array
int main() {
// Input the size of the array
// Input the elements of the array
// Input the position of the element to remove
// Call the function to remove the element
return 0;
}
Problem
 Remove an element from a specific position in the array and shift
the remaining elements accordingly
#include <stdio.h>
// Print the updated array
printf("Array after removing the element at position %d:\n", pos);
// Function to remove an element from a specific position
for (int i = 0; i < n; i++) {
void removeElement(int arr[], int n, int pos) {
printf("%d ", arr[i]);
// Check if the position is valid
}
if (pos < 0 || pos >= n) {
printf("\n");
printf("Invalid position!\n");
}
return;
}
int main() {
// Shift the elements to the left from the position int n, pos;
for (int i = pos; i < n - 1; i++) {
arr[i] = arr[i + 1]; // Input the size of the array
} printf("Enter the size of the array: ");
scanf("%d", &n);
// Reduce the size of the array
n--; int arr[n];
Pro b le m
 Remove an element from a specific position in the array and shift
the remaining elements accordingly

// Input the elements of the array


printf("Enter the elements of the array:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Input the position of the element to remove


printf("Enter the position of the element to remove (0-based index): ");
scanf("%d", &pos);

// Call the function to remove the element


removeElement(arr, n, pos);

return 0;
}
Assignment 1

Write C program for 1 D array over the Problem:


Rotate the elements of an array
(a) to the left by a given number of positions
(b) right by a given number of positions
T WO D I M E N S I O N A L / 2 D A R R AY S

▪ A two dimensional array has two subscripts/indexes.


▪ The first subscript refers to the row, and the second, to the
column.
▪ Its declaration has the following form,

⚫ data_type array_name[1st dimension size][2nd dimension


size];

▪ For examples,

⚫ int xInteger[3][4];
⚫ float matrixNum[20][25];

▪ The first line declares xInteger as an integer array with 3


rows and 4 columns.
▪ Second line declares a matrixNum as a floating-point array
with 20 rows and 25 columns.
D O U B L E S C R I P T E D A R R AY WITH 3 RO WS
AND 4
COLUMNS
I N I T I A L I Z AT I O N OF 2D A R R AY

 int disp[2][4] = { {10, 11, 12, 13}, {14, 15, 16, 17} };

 OR

 int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};

 1st one is recommended.


 #include <stdio.h>
 int main() {
⚫ int abc[5][4] ={ {0,1,2,3}, {4,5,6,7}, {8,9,10,11},
{12,13,14,15}, {16,17,18,19} };
⚫ for (int i=0; i<=4; i++) {
 printf("%d ",abc[i]);
⚫ }
⚫ return 0;
 }
 Output: 1600101376 1600101392 1600101408
1600101424 1600101440
THINGS T H AT YO U M U S T C O N S I D E R W H I L E
INITIALIZING A 2D A R R AY

 We already know, when we initialize a normal array (or


you can say one dimensional array) during declaration, we
need not to specify the size of it. However that’s not the
case with 2D array, you must always specify the second
dimension even if you are specifying elements during the
declaration.

 /* Valid declaration*/
 int abc[2][2] = {1, 2, 3 ,4 }
 /* Valid declaration*/
 int abc[][2] = {1, 2, 3 ,4 }
 /* Invalid declaration – you must specify second
dimension*/
 int abc[][] = {1, 2, 3 ,4 }
 /* Invalid because of the same reason mentioned above*/
 int abc[2][] = {1, 2, 3 ,4 }
LIST OF STUDENTS AND THEIR S U B J E C T
MARKS

Marks
10 23 31 11
Students 20 43 21 21
12 22 30 13
30 31 26 41
13 03 41 15

Find the average mark scored by each


student?
#include<stdio.h>
#define ROW 5
#define C O L 4

int main(void)
{
int i, j;
double total;
int marks[ROW][COL]= { 10, 23, 31, 11, 20, 43, 21, 21,12,
22, 30, 13, 30, 31, 26, 41,13, 03, 41, 15 };
for(i = 0; i < ROW ; i++)
{
total = 0.0;
for (j=0; j<COL; j++)
total+=marks[i][j];
printf("Average of student %d is %f \n", i, total/4.0);
}
}
▪ For array storing string

⚫ char Name[6][10] = {"Mr. Bean", "Mr. Bush",


"Nicole", "Kidman", "Arnold", "Jodie"};

▪ Here, we can initialize the array with 6 strings, each with


maximum 9 characters long.
▪ If depicted in rows and columns it will look something
like the following and can be considered as contiguous
arrangement in the memory.
3D: A 3D A R R AY I S A N A R R AY O F 2D
A R R AY S .

 #include<stdio.h>
 int main(){
 int
i,j,k,x[][2][3]={{{1,2,3},{4,5,6}},{{7,8,9},{10,11,12}}};
 for(i=0;i<2;i++)
 for(j=0;j<2;j++)
 for(k=0;k<3;k++){

printf("x[%d,%d,%d]=%d\n",i,j,k,x[i][j][k]);
 }
 return 0;
 }
Sa mple P ro b le ms
 Print Transpose of a Matrix

 Add Two Matrix Using Multi-dimensional Arrays

 Multiply to Matrix Using Multi-dimensional


Arrays
#include <stdio.h>
void main()
{
static int array[10][10];
int i, j, m, n;
printf("Enter the order of the matrix \n");
scanf("%d %d", &m, &n);
printf("Enter the coefiicients of the matrix\n");
for (i = 0; i < m; ++i){
for (j = 0; j < n; ++j){
scanf("%d", &array[i][j]);
}
}
printf("The given matrix is \n");
for (i = 0; i < m; ++i){
for (j = 0; j < n; ++j){
printf(" %d", array[i][j]);
}
printf("\n");
}
printf("Transpose of matrix is \n");
for (j = 0; j < n; ++j){
for (i = 0; i < m; ++i){
printf(" %d", array[i][j]);
}
printf("\n");
}
}
#include <stdio.h>
int main()
{
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter number of columns (between 1 and 100): ");
scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n");
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j) {
printf("Enter element a%d%d: ",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
printf("Enter elements of 2nd matrix:\n"); for(i=0; i<r; ++i)
for(j=0; j<c; ++j) {
printf("Enter element a%d%d: ",i+1, j+1); scanf("%d", &b[i][j]);
}
// Adding Two matrices for(i=0;i<r;++i)
for(j=0;j<c;++j) { sum[i][j]=a[i][j]+b[i][j];
}
// Displaying the result
printf("\nSum of two matrix is: \n\n"); for(i=0;i<r;++i)
for(j=0;j<c;++j) {
printf("%d ",sum[i][j]);
if(j==c-1) { printf("\n\n"); }
}
return 0;
}
 #include <stdio.h>
 int main() {
⚫ int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i,
j, k;
⚫ printf("Enter rows and column for first matrix: ");
⚫ scanf("%d %d", &r1, &c1);
⚫ printf("Enter rows and column for second matrix: ");
⚫ scanf("%d %d",&r2, &c2);
⚫ while (c1 != r2) {
 printf("Error! Not compatible for multiplication\n");
⚫ }
⚫ printf("\nEnter elements of matrix 1:\n");
⚫ for(i=0; i<r1; ++i)
 for(j=0; j<c1; ++j) {
 printf("Enter elements a%d%d: ",i+1, j+1);

 scanf("%d", &a[i][j]);

 }

⚫ printf("\nEnter elements of matrix 2:\n");


⚫ for(i=0; i<r2; ++i)
 for(j=0; j<c2; ++j) {
 printf("Enter elements b%d%d: ",i+1, j+1);

scanf("%d",&b[i][j]);
 }
⚫ //Initializing all elements of result matrix to 0
⚫ for(i=0; i<r1; ++i)
 for(j=0; j<c2; ++j) {
 result[i][j] = 0;

 }

⚫ // Multiplying matrices a and b and //storing result in result matrix


for(i=0; i<r1; ++i)
 for(j=0; j<c2; ++j)
 for(k=0; k<c1; ++k) {

⚫ result[i][j]+=a[i][k]*b[k][j];
 }
⚫ //Displaying the result
⚫ printf("\nOutput Matrix:\n");
⚫ for(i=0; i<r1; ++i)
 for(j=0; j<c2; ++j) {
 printf("%d ", result[i][j]);

 if(j == c2-1) printf("\n\n");

 }

⚫ return 0;
 }
Thanks!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy