Arrays
Presented by:
Dr. Rakesh Rathi
Assistant Professor
Department of Computer Science and Engining
Engineering College, Ajmer
P5
Introduction
Arrays by Dr. Rakesh Rathi
2
Introduction
Types of Arrays:
Arrays by Dr. Rakesh Rathi
3
Single dimensional arrays or 1D arrays
For example:
Arrays by Dr. Rakesh Rathi
4
50 | 60 | 70 | 80 | 90 |
A row arrangement
50 |
60 |
70 |
80 |
90 |
A column arrangement
Creating a 1D array
Arrays by Dr. Rakesh Rathi
5
int marks[5], i; for(i=0; i<5; i++) scanf(“%d”, &marks[i]); |
int marks[ ] = {50, 60, 70, 80, 90}; /* Size is optional to write, as array will assume size itself */ int marks[5] = {50, 60, 70, 80, 90}; |
50 | 60 | 70 | 80 | 90 |
marks[0]
marks[1]
marks[2]
marks[3]
marks[4]
index
Creating a 1D array
Arrays by Dr. Rakesh Rathi
6
char name[ ] = {‘R’ , ‘A’ , ‘M’ , ‘U’ , ‘\0’}; or char name[5] = {‘R’ , ‘A’ , ‘M’ , ‘U’ , ‘\0’}; |
R | A | M | U | \0 |
name[0]
name[1]
name[2]
name[3]
Name[4]
index
Why the array index starts with zero?
Arrays by Dr. Rakesh Rathi
7
1D Array Programs
Program 1:
Write a program to create a simple array and access its elements using different techniques.
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[ ] = {10, 11, 12, 13, 14};
int i;
/* accessing elements using subscript – technique1 */
for(i=0;i<5;i++)
printf(“%d\t”, arr[i]);
printf(“\n”); /* throw the cursor into next line */
Arrays by Dr. Rakesh Rathi
8
/* accessing elements using subscript – technique2 */
for(i=0;i<5;i++)
printf(“%d\t, i[arr]);
printf(“\n”);
/* accessing elements using subscript – technique3 */
for(i=0;i<5;i++)
printf(“%d\t”, *(arr+i));
printf(“\n”);
/* accessing elements using subscript – technique4 */
for(i=0;i<5;i++)
printf(“%d\t”, *(i+arr));
printf(“\n”);
1D Array Programs
Arrays by Dr. Rakesh Rathi
9
getch();
}
Output
1D Array Programs
Program 2:
Write a program to find the total marks and percentage of marks obtained by a student in 5 subjects.
#include<stdio.h>
#include<conio.h>
void main()
{
/* declare a 1D array with size 5 */
int marks[5];
/* declare other variables */
int i, tot=0;
float percent;
clrscr();
Arrays by Dr. Rakesh Rathi
10
/* store elements into the array */
for(i=0;i<5;i++)
{ printf(“\nEnter Marks of subject %d:”,i+1);
scanf(“%d”, &marks[i]);
/* find the total marks */
tot=tot + marks[i];
} /* display total marks */
printf(“\nTotal marks= %d”, tot);
/* find percentage upto two decimal place */
percent=(float)tot/5;
printf(“\n\nCorrect Percentage=%.2f”,percent);
getch();
}
1D Array Programs
Arrays by Dr. Rakesh Rathi
11
Output
1D Array Programs
Program 3:
Searching for an element in an array using linear search method.
#include<stdio.h>
#include<conio.h>
#define MAX 50
void main()
{
/* declare an array with size 50 */
float number[MAX];
/* other variables */
float search;
int i, n, location=-1;
Arrays by Dr. Rakesh Rathi
12
/* store the elements into the array */
printf(“\nHow many elements?\t”);
scanf(“%d”, &n);
for(i=0;i<n;i++)
{
printf(“\nEnter the elements in array at position %d:”, i+1);
scanf(“%f”, &number[i]);
}
/* accept the number to be searched */
printf(“\nWhich number you want to search:”);
scanf(“%f”, &search);
/* search for the number linearly */
1D Array Programs
for(i=0;i<n;i++)
{
if(search == number[i])
{
printf(“\nNumber found at location:\t%d”, i+1);
/* store the location number in i */
location = i+1;
}
}
/* if location value not changed, then number not found */
if(location == -1)
printf(“\nNumber not found in the list”);
Arrays by Dr. Rakesh Rathi
13
getch();
}
Output Continue….
1D Array Programs
Arrays by Dr. Rakesh Rathi
14
Output
1D Array Programs
Program 4:
Write a program to store a name into a character type array and display it.
#include<stdio.h>
#include<conio.h>
void main()
{
/* declaring two char type arrays to store two names */
char name1[20], name2[20];
/* Enter a name using %[^\n] format */
printf(“\nEnter a name:”);
scanf(“%[^\n]”, name1);
/* Enter a name using %s format */
Arrays by Dr. Rakesh Rathi
15
printf(“\nEnter another name:”);
scanf(“%s”, name2);
printf(“\nHello %s”, name1);
printf(“\n\nAnother Hello to %s”, name2);
getch();
}
OUTPUT
Note:
%s format specifier accepts only one word. While %[^\n] accepts several words.
1D Array Programs
Program 5(a):
Write a C program to accept different types of input and display it.
#include<stdio.h>
#include<conio.h>
void main()
{
int id;
char sex[10], name[30];
clrscr();
printf(“\nEnter id:”);
scanf(“%d”, &id);
printf(“\nEnter sex:”);
Arrays by Dr. Rakesh Rathi
16
scanf(“%s”, sex);
printf(“\nEnter Name:”);
scanf(“%[^\n]”, name);
printf(“\nId:\t%d”, id);
printf(“\nSex:\t%s”, sex);
printf(“\nName:\t%s”, Name);
getch();
}
OUTPUT
1D Array Programs
Program5(b):
Write a C program to accept different types of input and display it.
Arrays by Dr. Rakesh Rathi
17
1D Array Programs
Program 5(b):
Write a C program to accept different types of input and display it.
#include<stdio.h>
#include<conio.h>
void main()
{
int id;
char sex[10], name[30];
clrscr();
printf(“\nEnter id:”);
scanf(“%d”, &id);
fflush(stdin);
Arrays by Dr. Rakesh Rathi
18
printf(“\nEnter sex:”);
scanf(“%s”, sex);
fflush(stdin);
printf(“\nEnter Name:”);
scanf(“%[^\n]”, name);
printf(“\nId:\t%d”, id);
printf(“\nSex:\t%s”, sex);
printf(“\nName:\t%s”, Name);
getch();
}
OUTPUT
Two dimensional arrays
Arrays by Dr. Rakesh Rathi
19
50, 60, 70, 80, 90 55, 65, 75, 85, 95 59, 69, 79, 89, 99 |
Creating 2D arrays
Arrays by Dr. Rakesh Rathi
20
double marks[3][5]; |
for(i=0; i<3; i++) for(j=0; j<5; j++) { printf(“\nEnter element:”); scanf(“%lf”, &marks[i][j]); } |
Creating 2D arrays
Arrays by Dr. Rakesh Rathi
21
marks[0][0], marks[0][1], marks[0][2], marks[0][3], marks[0][4] marks[1][0], marks[1][1], marks[1][2], marks[1][3], marks[1][4] marks[2][0], marks[2][1], marks[2][2], marks[2][3], marks[2][4] |
Creating 2D arrays
Arrays by Dr. Rakesh Rathi
22
double marks[3][5] = {{50, 60, 70, 80, 90}, {55, 65, 75, 85, 95}, {59, 69, 79, 89, 99}}; |
50 | 60 | 70 | 80 | 90 | 55 | 65 | 75 | 85 | 95 | 59 | 69 | 79 | 89 | 99 |
[1][4]
[0][0]
[0][1]
[1][0]
[0][4]
[0][3]
[0][2]
[1][3]
[1][2]
[1][1]
[2][0]
[2][1]
[2][2]
[2][4]
[2][3]
2D Array Programs
Program 6:
Write a program to take 2D array with 3 rows and 5 columns and display its elements in matrix form.
Arrays by Dr. Rakesh Rathi
23
2D Array Programs
Program 6:
Write a program to take 2D array with 3 rows and 5 columns and display its elements in matrix form.
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j;
/* take 2D array */
int marks[3][5] = {{50, 60, 70, 80, 90},
{55, 65, 75, 85, 95},
{59, 69, 79, 89, 99}};
/* display in matrix form. Outer for loop represents rows and inner for loop represents columns */
Arrays by Dr. Rakesh Rathi
24
for(i=0;i<3;i++)
{
for(j=0;j<5;j++)
{
printf(“%d\t”, marks[i][j]);
}
/* new row should start in new line */
printf(“\n”);
}
getch();
}
OUTPUT
2D Array Programs
Program 7:
Write a program to accept a matrix and display its transpose matrix.
#include<stdio.h>
#include<conio.h>
void main()
{
/* declare variables */
int i, j, r, c;
int mat[50][50];
/* accept a matrix from keyboard */
printf(“\nEnter Number of rows:”);
Arrays by Dr. Rakesh Rathi
25
scanf(“%d”, &r);
printf(“\nEnter Number of columns:”);
scanf(“%d”, &c);
printf(“\n Enter Matrix: \n”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf(“%d”, &mat[i][j]);
}
}
/* display the transpose */
printf(“\nTranspose matrix is:\n”);
2D Array Programs
Arrays by Dr. Rakesh Rathi
26
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
printf(“%d\t”, mat[j][i]);
}
printf(“\n”);
}
getch();
}
Output
2D Array Programs
Program 8:
Write a program to add two matrices and display the sum of matrices.
#include<stdio.h>
#include<conio.h>
void main()
{
/* take matrics of max size 10, 10 */
float a[10][10], b[10][10], c[10][10];
int i, j, r1, r2, c1, c2;
/* read number of rows and cols for both matrices */
Arrays by Dr. Rakesh Rathi
27
printf(“\nEnter no. of rows of matrix1:”);
scanf(“%d”, &r1);
printf(“\nEnter no. of columns of matrix1:”);
scanf(“%d”, &c1);
printf(“\nEnter no. of rows of matrix2:”);
scanf(“%d”, &r2);
printf(“\nEnter no. of columns of matrix2:”);
scanf(“%d”, &c2);
/* check the condition for matrix addition */
if((r1!=r2)||(c1!=c2))
{
printf(“\n Addition cannot be done”);
exit(0); /* terminate the program */
2D Array Programs
}
/* read elements of matrix1 */
printf(“\nEnter elements of matrix:\n”);
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
scanf(“%f”, &a[i][j]);
/* read elements of matrix2 */
printf(“\nEnter elements of matrix2: \n”);
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
scanf(“%f”, &b[i][j]);
/* add the two matrices to get sum matrix */
for(i=0;i<r1;i++)
Arrays by Dr. Rakesh Rathi
28
for(j=0;j<c1;j++)
c[i][j] = a[i][j] + b[i][j];
/* display the sum matrix elements */
printf(“\n The sum matrix is:\n”);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf(“%.2f\t”, c[i][j]);
}
printf(“\n”);
}
getch(); }
2D Array Programs
Arrays by Dr. Rakesh Rathi
29
Output
2D Array Programs
Arrays by Dr. Rakesh Rathi
30
2D Array Programs
Program 9:
Write a program to multiply two matrices and display the product matrix.
Arrays by Dr. Rakesh Rathi
31
c1 == r2 /* if this condition satisfy, then only multiplication is possible */ a[r1][c1] * b[r1][c1] /* multiply both matrices */ + a[r1][c2] * b[r2][c1] /* c1 == r2 */ sum = sum + a[r1][c1] * b[c1][c2] /* sum of products */ Sum = sum + a[ i ][ j ] * b[ j ][ k ] /* statement written using indexes */ c[ i ][ k ] = sum |
for(i=0;i<r1;i++) { for(k=0;k<c2;k++) { for(j=0;j<c1;j++) { sum+=a[ i ][ j ] * b[ j ][ k ]; } c[ i ][k] = sum; } } |
2D Array Programs
Program 9:
Write a program to multiply two matrices and display the product matrix.
Why the loops are written in the sequence of i, k, j and not i, j, k?
Why c[ i ][ k ] and why not c[ i ][ j ]?
Arrays by Dr. Rakesh Rathi
32
2D Array Programs
Program 9:
Write a program to multiply two matrices and display the product matrix.
#include<stdio.h>
#include<conio.h>
void main()
{
/* take matrics of max size 10, 10 */
float a[10][10], b[10][10], c[10][10];
int i, j, k, r1, r2, c1, c2;
float sum;
clrscr();
/* read number of rows and cols for both matrices */
Arrays by Dr. Rakesh Rathi
33
printf(“\nEnter no. of rows of matrix1:”);
scanf(“%d”, &r1);
printf(“\nEnter no. of columns of matrix1:”);
scanf(“%d”, &c1);
printf(“\nEnter no. of rows of matrix2:”);
scanf(“%d”, &r2);
printf(“\nEnter no. of columns of matrix2:”);
scanf(“%d”, &c2);
/* check the condition for matrix multiplication */
if(c1!=r2)
{
printf(“\n Multiplication is not possible ”);
exit(0); /* terminate the program */
2D Array Programs
}
/* read elements of matrix1 */
printf(“\nEnter elements of matrix1:\n”);
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
scanf(“%f”, &a[i][j]);
/* read elements of matrix2 */
printf(“\nEnter elements of matrix2:\n”);
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
scanf(“%f”, &b[i][j]);
/* multiply the two matrices and display the product matrix */
Arrays by Dr. Rakesh Rathi
34
printf(“\nThe product matrix is:\n”);
for(i=0;i<r1;i++)
{
sum = 0.0;
for(k=0;k<c2;k++)
{
for(j=0;j<c1;j++)
{
sum+=a[i][j] * b[j][k];
}
c[i][k] = sum;
printf(“%.2f\t”, c[i][k]);
sum = 0.0;
2D Array Programs
Arrays by Dr. Rakesh Rathi
35
}
printf(“\n”);
}
getch();
}
Output
Three dimensional arrays
For example:
Arrays by Dr. Rakesh Rathi
36
Creating 3D arrays
Arrays by Dr. Rakesh Rathi
37
int marks[4][3][5]; |
for(i=0;i<4i++) for(j=0;j<3;j++) for(k=0;k<5;k++) { printf(“\nEnter element:”); scanf(“%d”, &marks[ i ][ j ][ k ]); } |
Creating 3D arrays
Arrays by Dr. Rakesh Rathi
38
int marks[4][3][5] = { { {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25} }, { {26, 27, 28, 29, 30}, {31, 32, 33, 34, 35}, {36, 37, 38, 39, 40} }, { {41, 42, 43, 44, 45}, {46, 47, 48, 49, 50}, {51, 52, 53, 54, 55} }, { {18, 12, 53, 14, 15}, {13, 17, 88, 19, 50}, {61, 22, 53, 24, 75} }, };
|
|
int marks[ ][3][5] = { { {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25} }, ….................}; |
3D Array Programs
Program 10:
Write a program to declare a 3D array, initialize it with elements and display all elements of 3D array.
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, k;
/* declare a 3D array with three 2D arrays, each 2D array contains 3 rows and 5 cols. */
int marks[3][3][5] = {
{{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
Arrays by Dr. Rakesh Rathi
39
{21, 22, 23, 24, 25}},
{{26, 27, 28, 29, 30},
{31, 32, 33, 34, 35},
{36, 37, 38, 39, 40}},
{{41, 42, 43, 44, 45},
{46, 47, 48, 49, 50},
{51, 52, 53, 54, 55}},
};
3D Array Programs
Arrays by Dr. Rakesh Rathi
40
/* display the 3D Array elements */
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<5;k++)
printf(“%d\t”, marks[i][j][k]);
printf(“\n”);
}
printf(“\n”);
}
getch();
}
Output
The sscanf() and sprintf() functions
sscanf():
Arrays by Dr. Rakesh Rathi
41
The sscanf() and sprintf() functions
Program 11:
Write a program to read string from a character array.
#include<stdio.h>
#include<conio.h>
void main()
{
char in[10], out[10];
clrscr();
gets(in);
sscanf(in,”%s”,out);
printf(“%s\n”,out);
getch();
}
Arrays by Dr. Rakesh Rathi
42
Output
The sscanf() and sprintf() functions
Program 12:
Write a program to read integers in character array, convert and assigns them to integer variable using sscanf() function.
#include<stdio.h>
#include<conio.h>
void main()
{
int *x;
char in[10];
clrscr();
printf(“\nEnter Integers:”);
gets(in);
Arrays by Dr. Rakesh Rathi
43
sscanf(in,”%d”,x);
printf(“\nValue of int x:%d”, *x);
getch();
}
Output
The sscanf() and sprintf() functions
sprintf():
Arrays by Dr. Rakesh Rathi
44
The sscanf() and sprintf() functions
Program 13:
Write a program to explain the use of sprintf().
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
char c=‘C’;
float p=3.14;
char spf[20];
clrscr();
sprintf(spf,“%d%c%.2f”,a,c,p);
printf(“\n%s”,spf);
Arrays by Dr. Rakesh Rathi
45
getch();
}
Output
Arrays by Dr. Rakesh Rathi
46
10 | 20 | 30 | 40 | 50 | 60 |
Delete an element from a particular position from 1D array.
A[0] A[1] A[2] A[3] A[4] A[5]
10 | 20 | 40 | 50 | 60 |
A[0] A[1] A[2] A[3] A[4]
A[2] = A[3] and A[3] = A[4] and A[4] = A[5]
Additional Program
Program 14:
Write a program to delete an element from a particular position in a given 1D array.
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[100], i, n, x;
printf(“\nEnter size of array:”);
scanf(“%d”, &n);
/* Enter elements into the array */
printf(“\nEnter elements:”);
for(i=0;i<n;i++)
Arrays by Dr. Rakesh Rathi
47
scanf(“%d”, &arr[i]);
printf(“\nEnter position number of element to delete:”);
scanf(“%d”, &x);
/* Since counting starts from 0, we should decrease x value by 1 */
--x;
/* The elements next to the position x are moved one position back */
for(i=x;i<n;i++)
arr[i]=arr[i+1];
/* decrease array size by 1 */
--n;
printf(“\nThe array after deletion:”);
Additional Program
for(i=0;i<n;i++)
printf(“%d,”, arr[i]);
getch();
}
Arrays by Dr. Rakesh Rathi
48
Output
Additional Program
Program 15:
Write a program to generate 100 random integers in the range of 1 to 100 and store them in an array and print the array elements with their sum.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int arr[100], i, num, sum=0;
clrscr();
/* initialize random number generator */
randomize();
for(i=0;i<100;i++)
Arrays by Dr. Rakesh Rathi
49
{
/* generate random no in the range of 0 to 100 */
num=random(101);
if(num==0)
num++; /* if random no is 0, make it 1 */
a[i]=num; /* store it into the array */
/* print array element */
printf(“%d\t”, a[i]);
sum=sum+a[i]; /* find their sum */
}
printf(“\nSum of random no’s:%d”, sum);
getch();
}
Additional Program
Arrays by Dr. Rakesh Rathi
50
Output
Additional Program
Program 16:
Write a program to convert an integer number from decimal number system to binary number system.
#include<stdio.h>
#include<conio.h>
void main()
{
long int n, i =0, j, arr[20];
clrscr();
printf(“Enter an integer to convert into binary:”);
scanf(“%ld”, &n);
while(n>0)
{
Arrays by Dr. Rakesh Rathi
51
arr[i]=n%2;
n=n/2; 2 24
i++; 2 12 0
} 2 6 0
printf(“the equivalent binary no is:”); 2 3 0
for(j=i-1; j >=0;j--) 2 1 1
printf(“%ld”, arr[j]); 2 0 1
getch();
}
Output
To Do yourself: Home Work
Arrays by Dr. Rakesh Rathi
52
Interview Questions?
Q1. What is the index of the array?
Ans. Index of an array is an integer number that represents the position number of the element in the array. A 1D array will have only one index that represents element position number. A 2D array will have two indexes that represents row position number and column position number.
Q2. Why array index starts with zero?
Ans. Array elements are accessed in the form of arr[i] which internally converted into (arr+1) by the compiler. When i value 0, (arr+i) gives arr which is the name of the array. This name acts as the address of the first element. When i value 1, (arr+1) represents the address of the second element, and so on. So, the index starts with zero for an array.
Q3. How can you define a constant in C?
Ans. A constant represents a fixed value. There are two ways to define a constant in C.
Const float PI = 3.14159;
This statement tells the compiler to substitute 3.14159 wherever PI is found.
#define MAX 50
This directive statement tells the compiler to substitute 50 wherever MAX is found.
Arrays by Dr. Rakesh Rathi
53
Interview Questions?
Q4. If an array is declared but not initialized with elements, then what is stored in that array?
Ans. When an array is declared, it contains garbage values by default. After storing the elements into the array, these garbage values will be replaced by the actual elements.
Q5. Can an array be treated as an lvalue?
Ans. No, because an array is composed of several separate array elements that cannot be treated as a whole for assignment purposes. For example, the following statement gives error:
int x[10], y[10];
x = y; /*error */
Here, we are using an array ‘x’ as lvalue and another array ‘y’ as rvalue. To store the elements of y into x, we should take the help of a for loop, as:
for(i=0;i<10;i++)
x[i] = y[i];
Q6. Is it possible to call main() function from within itself?
Ans: Yes, the main() function can be called recursively from within itself.
Arrays by Dr. Rakesh Rathi
54
Interview Questions?
Q7. Why can’t constant values be used to define an array’s initial size?
Ans. In C, the size of an array can be declared as:
int arr[10]; /* this is an array of size 10 */
#define MAX 10
int arr[MAX]; /* here MAX is a macro representing size 10 */
But we cannot define array size as:
const int MAX = 10;
int arr[MAX]; /*error*/
Here MAX is not treated as constant value by C compiler. But this expression is valid in C++.
Q8. How are the elements of an array stored in the memory?
Ans. Whether it is a 1D array or 2D array or nth dimensional array, it does not matter; always the array elements are stored continuously in memory. This means contiguous blocks of memory are allocated for any array, internally.
Arrays by Dr. Rakesh Rathi
55
Arrays by Dr. Rakesh Rathi
56
Queries???
Arrays by Dr. Rakesh Rathi
57
Thanks!!!