1 of 57

Arrays

Presented by:

Dr. Rakesh Rathi

Assistant Professor

Department of Computer Science and Engining

Engineering College, Ajmer

P5

2 of 57

Introduction

  • To store the data e.g. salary of a employee, we take a variable ‘sal’ and store the value in it.
  • But if a company will have hundreds of employees, then to store the salaries of all those employees, we need to take hundreds of variables.
  • There is another way to take only one variable and store all the employees salaries in that variable.
  • Such a variable is called an ‘array’.
  • An array is a variable to store a group of elements of same datatype.
  • Same datatypes means we can store only one type of elements like integer, float or character, in the whole array.
  • We cannot store different types of elements into the same array, for example, integer and float both types will not be stored in same array.
  • An array is generally written using square braces after its name, as sal[].
  • In the square braces, we write the position number of the element starting from 0, 1, 2,….so on.
  • sal[0] represents first element, sal[1] represents second element, and……so on.

Arrays by Dr. Rakesh Rathi

2

3 of 57

Introduction

  • Here 0, 1, 2,…. are called subscript or index.
  • This is the reason array is also called ‘subscripted variable’ or ’indexed variable’.
  • In array operations like searching, sorting, etc. become easy, by developing functions to process elements of an array.

Types of Arrays:

    • Single/One dimensional arrays or 1D arrays.
    • Two dimensional arrays or 2D arrays.
    • Multi dimensional arrays

Arrays by Dr. Rakesh Rathi

3

4 of 57

Single dimensional arrays or 1D arrays

  • A 1D array represents a single row or single column of elements.

For example:

    • Marks obtained by a students in 5 subjects, can be written as a row or as a column.
  • A row represents horizontal arrangement of elements.
  • A column represents vertical arrangement of elements.

Arrays by Dr. Rakesh Rathi

4

50

60

70

80

90

A row arrangement

50

60

70

80

90

A column arrangement

5 of 57

Creating a 1D array

  • A 1D array can be created in two ways:
    • Declare a 1D array and then store elements into that array.

    • Declare as well as initialize the array using a single statement.

  • Compiler will allot 5 continues blocks of memory and stores the elements into it.

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

6 of 57

Creating a 1D array

  • Character type array declaration and initialization

  • ‘\0’ represents NULL character, which represents the end of a string.
  • Because of ‘\0’, the compiler will be able to understand where to stop and when to retrieve the characters from memory.

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

7 of 57

Why the array index starts with zero?

  • When an array arr[ ] is created, the index or the elements position starts with 0 and the elements of the array can be accessed as arr[i], where ‘i’ is called index of the array.
  • arr[i] is internally converted by the compiler into the form (arr+i).
  • When i value is 0, then (arr+i) = arr = this is the name of the array.
  • This becomes the base address of the array or it indicates the first element address.
  • When i=1, then (arr+i) = arr+1 = this becomes the address of the second element.
  • When i=2, then (arr+i) = arr+2 = refers to third element, and so on.
  • (arr+i) can also be written as (i+arr).
  • arr[i] can also be written as i[arr].
  • To access array elements, we can use arr[i] or i[arr] both equal.
  • We can access array elements by going into their memory address by using pointers as *(arr+i) or *(i+arr).
  • Here ‘*’ represents the content at the memory address.

Arrays by Dr. Rakesh Rathi

7

8 of 57

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”);

9 of 57

1D Array Programs

Arrays by Dr. Rakesh Rathi

9

getch();

}

Output

10 of 57

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();

}

11 of 57

1D Array Programs

Arrays by Dr. Rakesh Rathi

11

Output

12 of 57

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 */

13 of 57

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….

14 of 57

1D Array Programs

Arrays by Dr. Rakesh Rathi

14

Output

15 of 57

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.

16 of 57

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

17 of 57

1D Array Programs

Program5(b):

Write a C program to accept different types of input and display it.

  • Observe the output, the program is accepting id number and sex but not name.
  • The reason is: when sex is typed and then Enter button is pressed by the user, the Enter button releases a code ‘\n’ which is treated as a character and stored into the next variable.
  • So name value is not asked.
  • To solve this problem, clear the buffer (memory) of the keyboard after typing the sex, so that the \n character will be deleted from the buffer.
  • For this purpose, we can use fflush(stdin) statement.
  • This will flush the keyboard buffer.
  • Here ‘stdin’ represents standard input device which is nothing but our keyboard.

Arrays by Dr. Rakesh Rathi

17

18 of 57

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

19 of 57

Two dimensional arrays

  • A 2D array represents more than one row and column of elements.
  • For example:
  • Marks obtained by 3 students in 5 subjects, we can write those marks in 3 rows and 5 columns.

  • This has more than one row and more than one column.

Arrays by Dr. Rakesh Rathi

19

50, 60, 70, 80, 90

55, 65, 75, 85, 95

59, 69, 79, 89, 99

20 of 57

Creating 2D arrays

  • 2D can create using two different ways:
    • Declare the array and later enter the elements into the array.

  • There are two pairs of square braces.
  • First square braces represents the number of row and next square braces represents the number of column in each row.
  • There is a possibility for storing 3 × 5 = 15 elements into marks array.
  • In 2D array elements can stored using two for loops.
  • The outer for loop represents the rows and the inner for loop represents the columns.

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]);

}

21 of 57

Creating 2D arrays

  • Observe the marks[i][j] in scanf( ) statement.
  • Here i represents row position numbers starting from 0 to less than 3.
  • j represents column position numbers starting from 0 to less than 5.
  • There are two pairs of square braces.
  • Thus, the outer for loop executes 3 times with i values from 0 to 2 and the inner for loop executes 5 times with j values changing from 0 to 4.

  • To refer to any element of a 2D array, we can write marks[i][j].
  • These i and j are called indexes of the array.

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]

22 of 57

Creating 2D arrays

    • Declare the array and initialize it with elements.

  • Each row should be written inside { and } brackets.
  • Then all rows are inserted inside another { and } brackets.
  • In 2D arrays when array is declared and initialized with elements, than it can be written without the number of rows as marks[ ][5].
  • Row number are optional.
  • Compiler automatically during compilation allots memory for this array.
  • The memory in allotted as a continuous strip of bytes.

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]

23 of 57

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.

  • A matrix represents several rows and columns of elements.
  • If a matrix has only one row, it is called ‘row matrix’.
  • If a matrix has only one column, it is called ‘column matrix’.
  • A row matrix and column matrix can be imagined as a 1D array.
  • If a matrix has ‘m’ rows and ‘n’ columns, then it is called m × n matrix.

Arrays by Dr. Rakesh Rathi

23

24 of 57

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

25 of 57

2D Array Programs

Program 7:

Write a program to accept a matrix and display its transpose matrix.

  • Simply convert rows into columns and vice versa to get the transpose of a 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”);

26 of 57

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

27 of 57

2D Array Programs

Program 8:

Write a program to add two matrices and display the sum of matrices.

  • To add two matrices, the condition to be fulfilled is that the two matrices should have same number of rows and columns.

#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 */

28 of 57

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(); }

29 of 57

2D Array Programs

Arrays by Dr. Rakesh Rathi

29

Output

30 of 57

2D Array Programs

  •  

Arrays by Dr. Rakesh Rathi

30

31 of 57

2D Array Programs

Program 9:

Write a program to multiply two matrices and display the product matrix.

  • Now, condition to multiply two matrices:

  • The entire logic can be represented in C:

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;

}

}

32 of 57

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?

    • The reason is we are getting the new element c[ i][k] which has index i first and then k.
    • So, loops with i and then k should be written.
    • Inside them, the loop with j will come.

Why c[ i ][ k ] and why not c[ i ][ j ]?

    • The reason is when two elements at the position [ i ][ j ] and [ j ][ k ] are multiplied, we get the new element in the position[ i ][ k ].

Arrays by Dr. Rakesh Rathi

32

33 of 57

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 */

34 of 57

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;

35 of 57

2D Array Programs

Arrays by Dr. Rakesh Rathi

35

}

printf(“\n”);

}

getch();

}

Output

36 of 57

Three dimensional arrays

  • 3D array can be imagined as a combination of several 2D arrays.

For example:

  • Marks of all subjects of all branches in the college.

Arrays by Dr. Rakesh Rathi

36

37 of 57

Creating 3D arrays

  • There are also two ways to create 3D arrays:
    • Declare the array and later enter the elements into the array (input from user).

  • The first number 4 represents that this array contains 4 2D arrays.
  • The next numbers 3 and 5 represents the rows and columns in each 2D array.
  • So, there is a possibility for storing 4×3×5 = 60 elements into this array.
  • Elements can be stored in this array by using three for loops.
  • The outer for loop represents the number of 2D arrays, the inner for loop represents the rows in each 2D array, and the inner most for loop represents the columns in each 2D array.

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 ]);

}

38 of 57

Creating 3D arrays

    • Declare the array and initialize it directly.

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} },

};

  • Each 2D array is enclosed inside a pair of { and } brackets, and each row is also enclosed inside a pair of { and } brackets.
  • The complete 3D array is again enclosed inside another { and } brackets.
  • We can omit the first index and declare as:

int marks[ ][3][5] = {

{ {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25} }, ….................};

39 of 57

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}},

};

40 of 57

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

41 of 57

The sscanf() and sprintf() functions

sscanf():

  • The sscanf() function allows to read characters from a character array and writes them to another array.
  • This function is similar to scanf() but instead from standard input it reads data from an array.

Arrays by Dr. Rakesh Rathi

41

42 of 57

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

43 of 57

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

44 of 57

The sscanf() and sprintf() functions

sprintf():

  • The sprintf() function is similar to the printf() function except a small difference between them.
  • The printf() function sends the output to the screen whereas the sprintf() function writes the values of any data type to an array of characters.

Arrays by Dr. Rakesh Rathi

44

45 of 57

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

46 of 57

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]

47 of 57

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:”);

48 of 57

Additional Program

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

printf(“%d,”, arr[i]);

getch();

}

Arrays by Dr. Rakesh Rathi

48

Output

49 of 57

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();

}

50 of 57

Additional Program

Arrays by Dr. Rakesh Rathi

50

Output

51 of 57

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

52 of 57

To Do yourself: Home Work

  1. WAP to find the maximum and minimum element in a set of n elements.
  2. Given two sorted one-dimensional arrays A and B of size m and n, respectively. Merge them into a single-sorted array C that contains every element from arrays A and B in ascending order.
  3. WAP to check whether a given square matrix is symmetric or not.
  4. WAP to find inverse of a 3×3 matrix.
  5. WAP to swap kth and (k+1)th elements in an integer array. K is given by the user.
  6. WAP to arrange an array in reverse order by using a second array.
  7. WAP to sort an array of size n and find the position of the largest value.
  8. WAP to add two 2D arrays and to store result in first array without using a third array.
  9. WAP to multiply two 2D arrays and to store result in first array without using a third array.
  10. WAP to add two 3D arrays.

Arrays by Dr. Rakesh Rathi

52

53 of 57

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.

  • Using const keyword, we can define a constant, as:

Const float PI = 3.14159;

This statement tells the compiler to substitute 3.14159 wherever PI is found.

  • Another way to define a constant is using #define directive in C:

#define MAX 50

This directive statement tells the compiler to substitute 50 wherever MAX is found.

Arrays by Dr. Rakesh Rathi

53

54 of 57

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

55 of 57

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

56 of 57

Arrays by Dr. Rakesh Rathi

56

Queries???

57 of 57

Arrays by Dr. Rakesh Rathi

57

Thanks!!!