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

Lecture CSP09

Uploaded by

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

Lecture CSP09

Uploaded by

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

Derived Data types

• Arrays
Declarations and Initialization
One dimensional Arrays
Two dimensional Arrays
Multi dimensional Arrays
Character Arrays

1
Arrays
•An array is fixed size sequenced collection of elements of the
same data type addressable by index or subscript.

•It is a convenient structure for representing large number of


homogenous values

•It can be used to represent a list of numbers or a list of


names.
Examples: Linear arrays
List of marks of students
List of grades of students
List of employees in an organization
List of names of students
2
One Dimensional Arrays
List of items given one variable name using only one
subscript

Declaration:
type variable_name[size];
Here size indicates the maximum number of elements
The subscript value start from 0 to size-1

Example:
int number[10];
float number[10];
char grade[10];
3
One Dimensional Arrays
Initialization
Compile time initialization
int num[5]={0,0,0,0,0};
num[0] num[1] num[2] num[3] num[4]
0 0 0 0 0

float num[5]={0.0,10.5,11,-13.25}; 0
What values will be assigned to
num[0] , num[1] , num[2] , num[3] and num[4]

int num[]={1,2,3,4,5}; is it correct?


4
More Examples
How to initialize a char array?
char name[]={‘M’,’N’,’I’,’T’,’J’,’\0’};
OR
char name[]=“MNITJ”;
Size of name???

Consider the following initialization


char grade[5]={‘A’};
int nums[4]={10,20,30,40,50}; Invalid Statement

5
Run time initialization
for(i=0; i<10; i++)
{ /* Reading an array elements */
scanf(“%d”,&nums[i]);
}

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


{ if(i%2)
sum[i]=1;
else
sum[i]=0;
}
All even indexed elements of sum are initialized by 1 and
all odd indexed elements of sum are initialized by 0

6
Processing and displaying array elements
/* Read the marks and calculate the sum */
for(sum=0,count = 0;count<N; ++count)
{ scanf(“%d”, &marks[count]);
sum = sum + marks[count];
}
average = sum/N;

/* Calculate and display the deviation */


for(i=0;i<N; ++i)
{ deviation = marks[i]-average;
printf(“MARKS=%dDEVIATION=%d”,marks[i],deviation);
}

7
Copying Arrays
int old_value[5]={10,20,30,40,50};
int new_value[5];
How to copy the elements of Old_value into
new_value?
new_value = Old_value;
It will not work. Why?
Question:
What is the correct way of copying arrays?
Sol:
Copy each individual element one by one

Exercise: Write code to Compare two arrays


8
Finding maximum number in a set of numbers
Algorithm Steps:

1. Read an array nums[] of N elements, precondition N>=1

2. Initialize max to first array element

3. Repeat 3(a) for all array elements


a) if next array element greater than current maximum
then assign it to max.

4. Display max for the array of N elements

9
Implementation
/* Find maximum of 10 numbers */
#define N 10
void main()
{ int i, nums[N], max;
for(i=0;i<N; ++i) /* Read Array elements */
scanf(“%d”, &nums[i]);
max = nums[0]; /* Initialize max */
for(i=1;i<N; ++i) /* Calculate maximum */
{ if(max<nums[i])
max = nums[i];
}
prinrf(“Maximum number is %d”,max);
}
10
Problems with arrays!!!- No Bound Checking!!!
• There is no check in C compiler to see if the subscript
used for an array exceeds the size of the array.

• Data entered with a subscript exceeding the array size will


simply be placed in memory outside the array limit and
lead to unpredictable results.

• It’s a programmers responsibility to take care.

11
More than one Dimension

Two dimensional arrays also called as matrix


Declaration:
type variable_name[row_size][column_size];

row_size –>Number of rows in matrix


column_size –> Number of columns in matrix

Examples:
int number[4][3]; /* 12 elements */
float number[3][2]; /* 6 elements */
char name[10][20]; /* 200 chars */

12
Initialization of a 2-D Array
int a[2][3]={1,2,3,4,5,6};
int a[2][3]={{1,2,3}, {4,5,6}};
int a[][3]={{1,2,3}, {4,5,6}}
int a[2][3]={0}
How values will be assigned in each case??
Following initializations are not allowed
int a[3][]={2,4,6,8,10,12};
int a[][]={2,4,6,8,10,12};

Note: If the first bracket pair is empty, then compiler takes the
size from the number of inner brace pairs

13
Accessing Two Dimensional Array
int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
for(i=0;i<3;i++)
{ Output
for(j=0;j<4;j++) 1 2 3 4
{ 5 6 7 8
printf(“%-4d”,a[i][j]); 9 10 11 12
}
printf(“\n”);
}
Run time initialization of an array can be
done in similar way by changing printf() to
scanf()inside j loop.

14
Memory Map for 2-D Arrays
Kept in memory as a linear sequence of variables.
• Two methods for storing-
• Row major
• Column major
Example:
int a[3][3];
Row major storage:
a[0][0], a[0][1], a[0][2], a[1][0], a[1][1],
a[1][2], a[2][0], a[2][1], a[2][2]
Column major storage:
a[0][0], a[1][0], a[2][0], a[0][1], a[1][1],
a[2][1], a[0][2], a[1][2], a[2][2]

15
Methods for storing multidimensional arrays in linear storage
Working with two dimensional Arrays
Matrix Addition and Subtraction
Let A[m][n] and B[p][q] are two matrices.
Precondition: m equals to p and n equals to q
Algorithm Steps:

1. Read two matrices A and B and initialize C matrix to zero


2. Repeat (3) for i=0 to m-1
3. Repeat (3.a) for j=0 to n-1
3.a) C[i][j] = A[i][j] + B[i][j]
4. Display C matrix.

17
Implementation
#define ROW 10
#define COL 10
int main()
{ int M1[ROW][COL],M2[ROW][COL],M3[ROW][COL],i,j;
int row1,col1,row2,col2;
printf(“Enter row value for M1\n”);
scanf(“%d”,&row1);
printf(“Enter column value for M1\n”);
scanf(“%d”,&col1);
printf(“Enter row value for M2\n”);
scanf(“%d”,&row2)
printf(“Enter column value for M2\n”);
scanf(“%d”,&col2)

18
if(row1!=row2 || col1!=col2)
{ printf(“Invalid Input: Addition is not possible”);
return;
}
printf(“Enter data for Matrix M1\n”);
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf(“%d”,&M1[i][j]);
}
printf(“\n”);
}

19
printf(“Enter data for Matrix M2\n”);
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
scanf(“%d”,&M2[i][j]);
}
printf(“\n”);
}
printf(“Addition of Matrices is as follows\n”);
for(i=0;i<row2;i++)
for(j=0;j<col2;j++)
M3[i][j]= M1[i][j] + M2[i][j]);

20
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
printf(“%-3d”,&M3[i][j]);
}
printf(“\n”);
}

Note:
Similarly Subtraction operation can be done

21
Matrix Multiplication: M1xM2
Condition: Number of columns in M1 should be equal
to number of rows in M2
Algorithm Steps:
1. Read two matrices M1[m][n] and M2[n][r] and
initialize another matrix M3[m][r] for storing result.
2. Repeat for i=0 to m-1
Repeat for j=0 to r-1
M3[i][j] = 0
Repeat for k=0 to n-1
M3[i][j] += M1[i][k] * M2[k][j]
3. Print matrix M3.

22
Implementation
#include <stdio.h>
#define row1 4
#define col1 3
#define row2 3
#define col2 4
#define row3 4
#define col3 4

void main()
{
int M1[row1][col1],M2[row2][col2],M3[row3][col3];
int i,j,k;

23
printf(“Enter data for Matrix M1\n”);
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf(“%d”,&M1[i][j]);
}
printf(“\n”);
}

24
printf(“Enter data for Matrix M2\n”);
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
scanf(“%d”,&M2[i][j]);
}
printf(“\n”);
}

25
if (col1!= row2)
{ printf(“Multiplication is not possible”);
return;
}
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
M3[i][j] = 0;
for(k=0;k<col1;k++)
{
M3[i][j] += M1[i][k]*M2[k][j];
}
}
printf(“\n”);
}

26
printf(“RESULT MATRIX IS\n ”);
for(i=0;i<row3;i++)
{
for(j=0;j<col3;j++)
{
printf(“%d”,M3[i][j]);
}
printf(“\n”);
}
return;
}

27
Multi-Dimensional 3D Arrays

int test[2][3][4] = { {{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
Exampel 3-D array reading and writing
#include <stdio.h>
#include <stdio.h> int main()
int main() { int test[2][3][2];
{ int test[2][3][2]; printf("\nDisplaying values:\n");
printf("Enter 12 values: \n"); for (int i = 0; i < 2; ++i)
for (int i = 0; i < 2; ++i) {
{ for (int j = 0; j < 3; ++j) for (int j = 0; j < 3; ++j)
{ for (int k = 0; k < 2; ++k) {
{ scanf("%d", &test[i][j][k]); for (int k = 0; k < 2; ++k)
} {
} printf("test[%d][%d][%d] = %d\n",
} i, j, k, test[i][j][k]);
}
return 0; }
} }
return 0;
}
Practice Assignment
1. Write a program to copy one two dimensional array
into another two dimensional array.
2. Write a program to merge two given array into a
single array.
3. Generate Factorial of a number using Array.
4. Generate Fibonacci series using Array.
5. Write a program to find binary equivalent of a
decimal number using Array.
6. Write a C program to determine transpose of a
matrix.

30

You might also like