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

Cpps Unit-3 Arrays Array:: Declaration: Syntax: Data Type Array - Name (Size of The Array)

The document provides information about arrays in C programming. It defines an array as a collection of similar data items stored in contiguous memory locations. The document discusses different types of arrays like one-dimensional and two-dimensional arrays. It provides examples of declaration, initialization, and memory layout of one-dimensional arrays. It also discusses various operations that can be performed on arrays like traversing, searching, and sorting.

Uploaded by

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

Cpps Unit-3 Arrays Array:: Declaration: Syntax: Data Type Array - Name (Size of The Array)

The document provides information about arrays in C programming. It defines an array as a collection of similar data items stored in contiguous memory locations. The document discusses different types of arrays like one-dimensional and two-dimensional arrays. It provides examples of declaration, initialization, and memory layout of one-dimensional arrays. It also discusses various operations that can be performed on arrays like traversing, searching, and sorting.

Uploaded by

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

Dr.

Pramod TC
Assistant Professor
Dept. of CSE
CPPS SIT Tumkur
[email protected]
Unit-3 Arrays

Array:
 An array is a collection of similar data items.
 An array is a variable that can store multiple values.
 An array is defined as collection of homogenous data (means data must be of similar data
type), stored in contiguous memory locations.

Ex: Set of integers


Set of floating point values
Student names in a class is an array of student names

Types of arrays:
1. One dimensional array
2. Two dimensional array

One Dimensional array

Declaration:

Syntax: data type array_name [size of the array];

data type - can be int /float/ char/ double


array_name – name of the array
size of the array – indicates size(maximum size of the array)

Ex: int marks[100];


float a[20];
char a[50];

Initialization:

There are two types:


1) Compile time initialization
2) Run time initialization
Compile time initialization: Compile time initialization of array elements is
same as ordinary variable initialization.

Syntax: data type array_name [size]={ list of values};

Ex:
int mark[5] = {19, 10, 8, 17, 9};
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

Initialization with all zeros:


int a[5]={0};

Initialization without size: If size is not specified, complier will calculate the
size of the array based on the number of initial values

float x[ ] ={3.5, 2.2, 4.50, 500.2}

x[0] x[1] x[2] x[3]


3.5 2.2 4.50 500.2

Run time initialization


Reading inputs from the user during program execution.

for(i = 0; i < n; i++) Reading array elements


{
scanf("%d", &arr[i])
}

for(i = 0; j < n; i++) Printing array elements


{
printf("%d\n", arr[i]);
}
Memory layout of one-dimensional array

int marks[5]={19, 10, 8, 17, 50};

Array index
Array Index
always start
with zero (0) Values

2000 2002 2004 2006 2008 Memory Address

Examples of Valid and Invalid declaration of one-dimensional array

Valid declaration Invalid declaration


int t[100]; int a[3] ={15, 90.18, 56, “sit”};
float aggregate[6]; int marks[6.5]
int marks[3+2]; int age(15)
char m[4]; int marks{5}
char city[5]={‘B’}; int a[5-5];
int a[5] ={10,15}; int a[3]={23,45,68,70,90,150};
int p[ ]={50,60,70};

As a programmer, when do you think of using an array? Give an example


to justify your answer.

Advantages of Array:
 For any reason a user wishes to store multiple values of similar type then the Array can be
used and utilized efficiently.
 Saves time and memory
 Easier debugging
 More compact in memory usage
 Accessing an element is very easy by using the index number.
 The search process can be applied to an array easily.
 2D Array is used to represent matrices.
 Arrays allocate memory in contiguous memory locations for all its elements. Hence
there is no chance of extra memory being allocated in case of arrays
Example:
In order to read and display 6 variables of same data type, we require six variables. In case of
1000 elements, we require 1000 variables, which take more time for declaring, initializing
and printing.

#include<Stdio.h>
int main()
{
int n1,n2,n3,n4,n5,n6;
printf(“enter the values of n1, n2, n3, n4, n5 and n6”);
scanf(“%d%d%d%d%d%d”, &n1, &n2, &n3, &n4, &n5, &n6);
printf(“Elements are n1=%d n2=%d n3=%d n4=%d n5=%d n6=%d”, n1, n2, n3, n4, n5, n6);
return 0;
}

However, with arrays we require only one array (one variable). It saves time , memory space
and execute faster.

#include<stdio.h>
int main()
{
int i;
int arr[6] = {10,20,30,40,50,60};
for (i=0;i<6;i++)
{
printf(“value of arr [%d] is %d \n”, i, arr[i]);
}
}

Programs on One-dimensional array

Display the specific array elements

#include <stdio.h>
#include<stdlib.h>
int main()
{
int a[6]={10,20,30,40,50,60};
printf("%d %d %d",a[0], a[2], a[5]);
return 0;
}
Program to read elements from the key board and to display using array

#include<Stdio.h>
int main()
{
int a[10], i, n;

printf(“enter the array size”);


scanf(“%d”, &n);
printf(“Enter %d elements”,n);
for(i=0; i<n; i++)
/* read array elements */
{
scanf(“%d”, &a[i]);
}
printf(“%d elements are\n”,n);
for(i=0; i<n; i++)
/* display array elements */
{
printf(“%d\t”, a[i]);
}
return 0;
}

Program to find the sum of n elements using arrays (1+2+3+4…….n)

#include <stdio.h>

int main()
{
int a[10], i, n, sum=0;

printf("enter the number of elements");


scanf("%d", &n);

printf("Enter %d elements", n);


for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
sum =sum+a[i];
}
printf("sum of n elements is %d", sum);
return 0;
}
Program to find greatest number from one dimensional array

#include<stdio.h>
int main()
{
int a[20], n, i, max=0;
printf("\n Enter the number of elements for 1-D array : ");
scanf("%d“, &n);
for(i=0; i <n; i++)
{
scanf("%d", &a[i]);
}

for(i=0;i<n;i++)
{
if(max<a[i])
max=a[i];
}

printf("\n Greatest element from above array inserted is :


%d“, max);
return 0;
}

Searching
A method for finding an element within a list
 Linear search (sequential search)
 Binary search

Linear Search: It sequentially checks each element of the array until a match is found or
the whole array has been searched.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[100],key,n,i,j;

printf("\nEnter the number of elements\n");


scanf("%d",&n);

printf("\nEnter %d elements\n", n);


for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nEnter the key element\n");
scanf("%d",&key);

for(i=0;i<n;i++)
{
if(key==a[i])
{
printf("\nElement %d found at %d
position\n",key, i+1);
exit(0);
}
}

printf("\nElement not found\n");


}

Binary Search: The basic requirement is the elements of the array should have been sorted
alphabetically or numerically.

We basically ignore half of the elements just after one comparison.

Mid= (low+high)/2

 Compare x with the middle element. If x matches with middle element, we return the
mid index.

 Else If x is greater than the mid element, then x can only lie in right half subarray
after the mid element. So we recur for right half.

 Else (x is smaller) recur for the left half.


#include <stdio.h>
#include <stdlib.h>
int main()
{

int a[100],key,num,i,j,low,mid,high,temp;

printf("\nEnter the number of elements\n");


scanf("%d",&num);

printf("\nEnter %d elements\n", num);


for(i=0;i<num;i++)
{
scanf("%d", &a[i]);
}

printf("\nEnter the key element\n");


scanf("%d", &key);

low = 0;
high = num -1;

while(low <= high)


{
mid = (low + high)/2;
if(key== a[mid])
{
printf("\nElement %d found at %d position\n",key,
mid+1);
break;
}

else if(key < a[mid])


high = mid-1;

else
low = mid +1;
}

if(low > high)


printf("\nElement not found\n");
}
Comparison between Linear and Binary search

Linear search Binary search


Input cannot be in sorted order Input should be in a sorted order
Slow Fast
Preferred for small elements Preferred for large elements
Best case: when the search element is at Best case: when the search element is the
the beginning of the array middle element
Less efficient More efficient

Sorting
Sorting is a technique of rearranging the elements in any particular order.

Sorting methods
 Bubble sort
 Selection sort

Bubble sort
Bubble sort is an algorithm that compares the adjacent elements and swaps their positions if
they are not in the intended order. The order can be ascending or descending.

Example: {-2, 45, 0, 11, -9}


#include <stdio.h> Ascending order sorting
#include <stdlib.h>
int main()
{
int a[100], n,min,i,j,temp;

printf("\nenter the size of array \n");


scanf("%d",&n);

printf("\nenter array elements\n");


for(i=0;i<n;i++) Reading array
{
elements
scanf("%d",&a[i]);
}

for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
Bubble sort
if(a[j] > a[j+1])
{ algorithm
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}

printf("\nSorted array using Bubble sort\n");


for(i=0;i<n;i++)
{ printing array
printf("%d\n",a[i]);
elements
}
return 0;
}

// Rest of the code is same For descending order sorting


for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j] < a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
Selection sort
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning.

Example: {4, 9, 5, 1, 0}

Example: {20, 12, 10, 15, 2}


#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[100], n,min,i,j,temp;

printf("enter the size of array \n");


scanf("%d",&n);

printf("enter array elements\n");


for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}

for(i=0;i<n;i++)
{
min=i;

for(j=i+1;j<n;j++)
{
if(a[j]<a[min]) Selection sort
min=j; algorithm
}

temp=a[i];
a[i]=a[min];
a[min]=temp;
}

printf("sorted array\n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
return 0;
}
Two Dimensional Arrays
 Used when data is in tabular format (rows and columns)
 The 2D array is organized as matrices which can be represented as the collection of
rows and columns.
 Applications: matrix multiplication, addition, transpose , tic-tac-toe game etc.

Declaration:

Syntax: data type array_name [row size][column size];

data type - can be int /float/ char/ double


array_name – name of the array
row size – indicates number of rows in the matrix
column size – indicates number of columns in the matrix

Ex: int marks[100][100];


int a[10][15];
float a[20][5];

Initialization:

There are two types:


1) Compile time initialization
2) Run time initialization

Compile time initialization:

Syntax: data type array_name [row size][col size]={ var1, var2, ……varn};

Ex:
int a[2][4] = {
{10, 20, 30, 40} ,
{45, 55, 65, 75} ,
};

int abc[3][3] = { {1, 2, 3} , {4, 5, 6} , {7, 8, 9} };

int a[3][3] ={0}; // initializes all elements to zero (0)


Run time initialization:
rows
for ( i = 0; i < r1; i++ ) Reading two dimensional
{ columns array elements
for ( j = 0; j < c1; j++ )
{
scanf(“%d” , &a[i][j] );
}
}
for ( i = 0; i < r1; i++ ) Printing two dimensional
{ array elements
for ( j = 0; j < c1; j++ )
{
printf("%d”, a[i][j]);
}
}

Memory layout of two dimensional array

int x[3][4] ={ {1, 2, 3, 4} , { 5, 6,7,8} , {9,10,11,12}};

3 rows 4 columns Array index

00 01 02 03
1 2 3 4 Array element

10 11 12 13
5 6 7 8

20 21 22 22
9 10 11 12
Example: To read and display two dimensional array elements

#include<stdio.h>
int main ()
{
int a[3][2], i, j;

printf(”enter the array elements of 3 rows and 2


columns\n”);
for ( i = 0; i < 3; i++ )
{
for ( j = 0; j < 2; j++ )
{
scanf(“%d” &a[i][j] );
}
}

printf(”Array elements are\n”);


for ( i = 0; i < 3; i++ )
{
for ( j = 0; j < 2; j++ )
{
printf(" %d\n", a[i][j] );
}
}
}

Example: Matrix addition


#include<stdio.h>
int main()
{
int a[100][100], b[100][100], c[100][100],i,j,r1,c1,r2,c2;
printf("Enter the size of the matrix \n");
scanf("%d%d", &r1, &c1);

printf("Enter the size of the second matrix \n");


scanf("%d%d", &r2, &c2);

printf("Enter the elements of first matrix”);


for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter the elements of second matrix”);
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}

for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{ Matrix addition
c[i][j]=a[i][j]+b[i][j];
}
}

printf("\nThe Addition of two matrix is\n");


for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c1;j++)
{
printf("%d\t",c[i][j]);
}
}
return 0;
}

Note: For subtraction put minus sign (-) c[i][j]=a[i][j] - b[i][j];


Example: Matrix Transpose

#include<stdio.h>
int main()
{
int a[100][100], i,j,r1 ,c1;
printf("Enter the size of the matrix \n");
scanf("%d%d", &r1, &c1);

printf("Enter the elements of the matrix “);


for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Transpose of matrix: \n");
for(i=0; i<r1; i++)
{
for(j=0; j<c1; j++)
{
printf("%d\t", a[j][i]);
}
printf("\n");
}
}

Example: Matrix Multiplication

Note: Let r1 and c1 be the size of matrix 1 (r1 X c1)


Let r2 and c2 be the size of matrix 2 (r2 X c2)
To perform matrix multiplication c1 == r2 (i.e. Column of first matrix
should be equal to row of second matrix)
#include<stdio.h>
int main(){
int a[100][100],b[100][100],c[100][100],i,j,k,sum=0,r1,c1,r2,c2;

printf("\nEnter the row and column of first matrix");


scanf("%d%d",&r1,&c1);

printf("\nEnter the row and column of second matrix");


scanf("%d%d",&r2,&c2);

if(c1!=r2){
printf("Matrix mutiplication is not possible");
exit(0);
}

printf("\nEnter the First matrix:");


for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);

printf("\nEnter the Second matrix:");


for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
scanf("%d",&b[i][j]);

for(i=0;i<r1;i++)
{
for(j=0;j<c2j++)
{
c[i][j]=0;

for(k=0;k<c1;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}

printf("\nThe multiplication of two matrix is\n");


for(i=0;i<r1;i++){
printf("\n");
for(j=0;j<c2;j++){
printf("%d\t",c[i][j]);
}
}
return 0;
}
Square matrix or not:
Square matrix is a matrix which has same number of rows and columns

Trace of a matrix
Trace of a n x n square matrix is sum of diagonal elements.

#include<stdio.h>
int main()
{
int a[100][100], b[100][100], i,j,r1 ,c1, sum=0;
printf("Enter the size of the matrix \n");
scanf("%d%d", &r1, &c1);

printf("Enter the elements of the matrix “);


for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}

if(r1!=c1)
{ Square matrix
printf(“not a square matrix”); or not
exit(0);
}

for(i=0;i<r1;i++)
{
sum=sum+a[i][i];
}

printf(“Trace of the matrix is %d”, sum);


return 0;
}
Norm of a matrix

#include<stdio.h>
#include<math.h>
int main()
{
int a[100][100], b[100][100], i,j,r1 ,c1,
sum=0,norm;
printf("Enter the size of the matrix \n");
scanf("%d%d", &r1, &c1);

printf("Enter the elements of the matrix “);


for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}

if(r1!=c1)
{
printf(“not a square matrix”);
exit(0);
}

for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
sum=sum+a[i][j]*a[i][j];
}
}

norm=sqrt(sum);

printf(“Norm of the matrix is %d”, norm);


return 0;
}
Identity matrix: The entries on the diagonal from the upper left to the
bottom right are all 1's, and all other entries are 0.

#include<stdio.h>
#include<math.h>
int main()
{
int a[100][100], i,j,r1 ,c1, flag=0;
printf("Enter the size of the matrix \n");
scanf("%d%d", &r1, &c1);

printf("Enter the elements of the matrix “);


for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}

for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
if(i==j && a[i][j]!=1)
{
flag=1;
break;
}
else if(i!=j && a[i][j]!=0)
{
flag=1;
break;
}
}
If(flag==0)
printf(“identity matrix”);
else
printf(“not a identity matrix”);
}
return 0;
}
Symmetric matrix or not

#include<stdio.h>
void main()
{
int a[100][100], b[100][100], i,j,r1 ,c1;
printf("Enter the size of the matrix \n");
scanf("%d%d", &r1, &c1);

printf("Enter the elements of the matrix “);


for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Transpose of matrix: \n");
for(i=0; i<r1; i++)
{
for(j=0; j<c1; j++)
{
b[i][j]=a[j][i];
}
}

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


{
for(j=0; j<c1; j++)
{
if(a[i][j]!=b[i][j])
{
printf(“not a symmetric matrix”);
exit(0);
}
}
}
printf(“It is a symmetric matrix”);
}
Previous year exam Questions
1 Define an array. 4
2 Give the general format for declaring and initialization (compile time and run time) of 6
one-dimensional array with an example. *****

Or
Explain the initialization of an array at compile time and run time.
Or
How are arrays declared and initialized? Explain with an example.
3 As a programmer, when do you think of using an array? Give an example to justify 5
your answer. ***
Or
What is the necessity of one-dimensional array?
4 Define two-dimensional array. Explain memory layout of a two dimensional array. List out 5
the applications/use of 2-D array? ***
5 Explain the initialization of a two-dimensional array. Give the general syntax of declaring a 5
two dimensional array. *****
Or
How do you initialize a two dimensional array at compile time and at run time?
Or
Discuss the various methods to initialize 2-dimensional array
6 Write C program to read a matrix of size m x n and print its transpose. Also find the sum 8
of all the elements in the matrix. ****
Or
Write a C program to find the transpose of a matrix.
7 Define sorting. Develop a C program to sort ‘n’ array elements in ascending order using 6
bubble sort technique. *****
Or
Write a program in ‘C’ that uses a function to sort an array of integers
8 What is searching? Discuss any two searching techniques used in array searching.
9 Develop a C program to search for an element in an array using linear search technique. 7
Or ***
Develop a C program to search whether item x is present in a set of M items
10 Develop a C program to display the first ‘n’ terms of Fibonacci numbers using arrays. 5
11 Mention the advantage and disadvantage of binary search over linear search. Write a C 6
program to read ‘n’ integers in an ascending order and search a ‘key’ using binary search ****
technique.
12 Write a C program to multiply two matrices of order MXN and PXQ respectively 8
13 Write a C program to read n integers and sort them in descending order using bubble sort 6
technique and display the sorted array with suitable message. **
14 Develop a C program to read 2-D array and compute i) sum of odd numbers ii) sum of 6
even numbers iii) average of all numbers. **
15 Write a program that reads an array A of n-elements, generates two arrays B and C which 8
contain odd elements and even elements respectively. Program also finds the sum and 6
average of all the elements.
16 Write a C program to accept 60 students name and marks scored in C Programming 6
Course. Also, display the name and marks of the students who have scored more than 80. **
17 Write a C program to find redundant elements from a given 1 dimensional array. Count 6
the number of times the particular element occurred. **
18 Write a program to check whether the elements in an array are unique or not. 6
19 Write a program that reads a matrix of order m x n and then determines whether the 10
given **
matrix is a i) Square matrix ii) Symmetric matrix iii) Identity matrix
20 Write a C Program to find the norm of a matrix. The norm is defined as the square root of 6
the sum of squares of all elements in the matrix.
21 Develop a program that reads a matrix of order M x N and fills the matrix by following 6
i. 1’s in the principal diagonal.
ii. 0’s in the remaining positions.

You might also like