You are on page 1of 16

Unit IV

Arrays and Structures


12 Hours
14 Marks
Industry identified competency addressed by this course:
- Develop C programs to solve broad-based computer related problems.

Course Outcome addressed by Unit:


- Develop C programs using arrays and structures

Learning Outcomes those are to be achieved through practical:


- Arrays
Develop program to
i) Sort list of 10 numbers
ii) Perform addition of 3X3 matrix
(Expt. No. 11) (Compulsory)
- Structures
Develop program to
i) Create a structure called library to hold details of a book viz. accession number, title
of the book, author name, price of the book and flag indicating whether book is issued
or not. Fetch some sample data and display the same
ii) Develop and execute C program to add two distances given in kilometers using
structure
(Expt. No. 12) (Compulsory)

Major Learning Outcomes (Cognitive Domain):


4a. Write statements to read and write given array
4b. Manipulate given array of characters and numbers
4c. Use structure for solving given problem
4d. Write sample program to demonstrate use of given enumerated data type

Affective Domain Outcomes:


- Follow safety practices.
- Practice energy conservation.
- Follow ethical practices.

Topics and Subtopics:


4.1.Characteristics of array – one-dimensional array, two-dimensional array
4.2.Array declaration and initialization
4.3.Array of characters, Operation on arrays
4.4.Character and string input/output
4.5.Introduction and features of structure – declaration and initialization of structures,
using structures in C program
4.6.typedef, enumerated data type

Suggested specification table:


Distribution of Theory Marks
Remember Level Understand Level Apply and Above Level Total Marks
02 02 10 14

1 of 16
This specification table provides general guidelines to assist students for their learning
and to teachers to teach and assess students with respect to attainment of Learning
Outcomes (LOs). The actual distribution of marks at different taxonomy levels (R, U and
A) in the question paper may vary from above table.

4.1 What is array?


An array is a fixed-sized sequential collection of elements of the
same data type. Generally an array is used to represent a list of numbers or
names.
Array is an arrangement of items at equally spaced addresses in computer
memory. Array is used to specify a variable that can be indexed.
An array provides a proper structuring of representing data, it is one of
the primitive data structure in C.

Depending on dimensions array can be of three types as,


- One-dimensional array
(Array with one dimension)
- Two-dimensional array
(Array with two dimensions)
- Multi-dimensional array
(Array with more than two dimensions)

4.2.1 Declaration of One-Dimensional Array

Before using an array, its data-type and dimension must be declared.


Syntax for declaring a single-dimensional (or one-dimensional) array is given
below
data-type array-name[Size-of-array];
Following are some of the examples of declaration of one-dimensional
arrays.
int a[10];
/* Here a is array of 10 elements of type int */
float interest_rate[5];
/* Here interest_rate is array of 5 elements of type float */
long int x[20];
/* Here x is array of 20 elements of type long int */
As already seen, when a variable is declared, memory space is allocated to
it. Similarly, when an array is declared, memory is allocated to it also. Rather,
memory is allocated to each element of the array. Figure 3.1 and 3.2 shows how
memory gets allocated to arrays declared for two examples. There are two ways
of representing memory – 0th memory location is shown at bottom (memory
grows upwards) or 0th memory location is shown at top (memory grows
downwards). In these notes the first approach is used.

2 of 16
- Highest Memory Location
-
a[9]
a[8]
a[7]
a[6]
a[5]
a[4]
a[3]
a[2]
a[1]
a[0]
-
- 0 Memory Location
Figure 4.1: Memory Allocation for integer array a[10]

- Highest Memory Location


-

interest_rate[4]

interest_rate[3]

interest_rate[2]

interest_rate[1]

interest_rate[0]

-
- 0 Memory Location
Figure 4.2: Memory Allocation for float array interest_rate[5]
In C, index always starts with 0. So the last element of the array has
index one less than Size-of-array.

3 of 16
4.2.2 Initialization of One-Dimensional Array

When an array is declared in C, memory gets allocated to all its elements


as discussed in 3.2. Initially, all these elements contain garbage values. Array
can be initialized at two different stages
- At compile-time
- At run-time
At compile-time, arrays can be initialized similarly to the normal
variables. For this, declaration and initialization is combined. Syntax for the
same is given below.
data-type array-name[Size-of-array] = { list of values };
Some examples are shown below.
int a[5]={23,45,13,41,22};
/* Here the values 23, 45, 13, 41 and 22 are initialized to the
elements with indices 0, 1, 2, 3 and 4 of array a respectively */
float b[4]={15.43,17,8.65,2.2};
/* Here the values 15.43, 17.0, 8.65 and 2.2 are initialized to the
elements with indices 0, 1, 2 and 3 of array b respectively */
We may omit the size of array when declaration and initialization is
combined. In such case, compiler allocates the space for all the initialized
elements only.
int a[ ]={23,45,13,41,22,63};
/* Here size-of-array is omitted. As six elements are initialized,
compiler allocates memory space for six int elements and the values
23, 45, 13, 41, 22 and 63 are initialized to the elements with indices
0, 1, 2, 3, 4 and 5 of array a respectively */
float b[ ]={15.43,17,8.65};
/* Here size-of-array is omitted. As three elements are initialized,
compiler allocates memory space for three float elements and the
values 15.43, 17.0 and 8.65 are initialized to the elements with
indices 0, 1, and 2 of array b respectively */
Partial initialization is allowed at compile-time. In this case, whatever
values are mentioned, those values get initialized to respective elements
(starting from index 0) and the remaining elements are initialized to 0.
int a[5]={23,45};
/* Here the values 23 and 45 are initialized to the elements with
indices 0 and 1. Remaining elements of array are initialized to 0 */
float b[10]={15.43,17,8.65};
/* Here the values 15.43, 17.0 and 8.65 are initialized to the
elements with indices 0, 1, and 2. Remaining elements of array are
initialized to 0.0 */

Arrays can also be explicitly initialized at run-time. This can be done for
initializing large arrays. One example is shown here.

4 of 16
for(i=0;i<150;i++)
a[i]=i;

4.2.3 Declaration of Two-Dimensional Array

Using one-dimensional array we can store list of values. But many times
there is need of storing table of values. A table contains rows and columns (i.e.
two dimensions). So, a two-dimensional array can be used for storing such
values.
Syntax for declaring a two-dimensional array is given below
data-type array-name[no-of-rows][no-of-columns];
One example of declaration of two-dimensional array is shown below.
int m[3][3];
/* Here m is two-dimensional array (of type int) with 3 rows (0, 1
and 2) and 3 columns (0, 1 and 2) */
Generally, two-dimensional arrays are stored in memory with a row-major
technique. i.e. They are stored row-wise. Initially, all the elements of 0th row are
stored then all the elements of 1st row are stored and so on. Figure 3.3 shows the
array m[3][3] in a matrix form and figure 3.4 shows how memory gets allocated
to that array.
Column
0 1 2
0 a[0][0] a[0][1] a[0][2]
Row 1 a[1][0] a[1][1] a[1][2]
2 a[2][0] a[2][1] a[2][2]
Figure 4.3: Matrix representation of integer array m[3][3]
- Highest Memory Location
-
m[2][2]
m[2][1]
m[2][0]
m[1][2]
m[1][1]
m[1][0]
m[0][2]
m[0][1]
m[0][0]
-
- 0 Memory Location
Figure 4.4: Memory Allocation for integer array m[3][3]

5 of 16
4.2.4 Initialization of Two-Dimensional Array

Two-dimensional arrays can also be declared similar to one-dimensional


arrays. Some examples of initializing two dimensional arrays are shown below.
int m[2][3] = {1,2,3,4,5,6};
/* Three elements of 0th row are initialized to 1, 2 and 3 and three
elements of 1st row are initialized to 4, 5 and 6. */
int t[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
/* Three elements of 0th row are initialized to 1, 2 and 3, three
elements of 1st row are initialized to 4, 5 and 6 and three elements
of 2nd row are initialized to 7, 8 and 9. */
int a[3][2] = {
{1,2},
{3,4},
{5,6}
};
/* Two elements of 0th row are initialized to 1, 2, two elements of 1st
row are initialized to 3, 4 and two elements of 2nd row are initialized
to 5, 6. */

If array is initialized completely with all values, there is no need to specify


first dimension. An example is shown below.
int m[ ][3] = {{1,2,3},{4,5,6}}; /* or int m[ ][3]={1,2,3,4,5,6}; */
/* An array with 2 rows and 3 columns get created. Three elements
of 0th row are initialized to 1, 2 and 3 and three elements of 1st row
are initialized to 4, 5 and 6. */
Partial initialization is also allowed. In such case uninitialized elements
are initialized to 0. Some examples are shown below.
int m[2][3] = {
{1},
{2,3}
};
/* Three elements of 0th row are initialized to 1, 0 and 0 and three
elements of 1st row are initialized to 2, 3 and 0. */
int t[3][3] = {0,0};
/* All the elements are initialized to 0. */

4.2.5 Accessing Array Elements

Once an array has been declared, its individual element can be accessed
by using array-name and index value that specifies the position of the element in
the array. In C, index values start from 0.
Values can be read from user through keyboard and stored in individual
array element using scanf( ) function as shown in following examples.
scanf(“%d”,&a[3]);

6 of 16
/* A integer value will be read from user and stored at 3rd location in
the array a. */
scanf(“%f”,&b[i]);
/* A float value will be read from user and stored at i th location in
the array a. Here i should be integer variable. */
scanf(“%d”,&a[2][1]);
/* A integer value will be read from user and stored at 1 st location in
the 2nd row of array a. */
Values of array elements can be displayed using printf( ) function as
shown in following example.
printf(“%d %f %d”,a[3],b[i],c[2][1]);
/* This statement will display following values
Value of 3rd element of integer array a
Value of ith element of float array b (i should be integer variable)
Value of 1st location in 2nd row of integer array c */
We can assign values to array elements as shown in following examples.
b[6]=34.7;
/* Value 34.7 is assigned to 6th element of float array b. */
a[i]=7;
/* Value 7 will be assigned to ith element of array a. Here i should be
integer variable. */

m[0][2]=62;
/* Value 62 will be assigned to 2nd location in the 0th row of array m.
*/

4.3.1 Character Array

We can create character arrays just like any other data types. One
example is shown below.
char name[10];
Character arrays can be initialized as shown in following examples.
char name[10]={„V‟,„e‟,„n‟,„k‟,„a‟,„t‟,„e‟,„s‟,„h‟,„\0‟};
/* Here name is declared as array of 10 characters and is initialized
to a string “Venkatesh” ending with a null character („\0‟). */
char first_name[ ]={„S‟,„a‟,„c‟,„h‟,„i‟,„n‟,„\0‟};
/* Here first-name is declared as array of 7 characters and is
initialized to a string “Sachin” ending with a null character („\0‟). */
char first_name[ ]=“Sachin”;
/* Effect is same as that of previous example. */
char last_name[10]={„T‟,„e‟};

7 of 16
/* The values „T‟ and „e‟ are initialized to array elements with index
0 and 1. Remaining elements are initialized to null values („\0‟). */

4.3.2 Declaration of String Variables

String is a null-terminated sequence of characters that is treated as a


single data item. Character strings are useful for building meaningful and
readable programs.
C does not support string as a data type. But strings can be used in C in
the form of character arrays. General form of declaration of a string variable is
as follows,
char string-name[ size ];
Some examples of string variables are shown below,
char first_name[15];
char last_name[20];
As string is assumed to be null-terminated, when a sting is assigned to a
character array, a null character („\0‟) is appended at the end of the string. So,
while declaring size of string variable, it should be mentioned as one more than
the maximum number of characters in the string.
e.g. If you want to store a string “Programming” (which contains 11
characters), the size of character array should be at least 12.

4.3.3 Initialization of String Variables

Just like numeric arrays, string variables (i.e. character arrays) can also
be initialized at the time of declaration.

Some examples of initialization of string variables is shown in following


examples.
char name[10]={„V‟,„e‟,„n‟,„k‟,„a‟,„t‟,„e‟,„s‟,„h‟,„\0‟};
/* Here name is declared as array of 10 characters and is initialized
to a string “Venkatesh” ending with a null character („\0‟). As the
string “Venkatesh” contains 9 characters, size of the string variable
is declared as 10. */
char name[10]=“Venkatesh”;
/* Effect is same as that of previous example. */

char name[ ]={„V‟,„e‟,„n‟,„k‟,„a‟,„t‟,„e‟,„s‟,„h‟,„\0‟};


/* Effect is same as that of previous example. */
char name[ ]=“Venkatesh”;
/* Effect is same as that of previous example. */

char last_name[10]={„P‟,„a‟};
/* The values „P‟ and „a‟ are initialized to array elements with index
0 and 1. Remaining elements are initialized to null values („\0‟). */

8 of 16
Figure 3.5 shows how the memory is allocated to the string variable name
and how the characters are stored in it.

- Highest Memory Location


-
„\0‟ name[9]
„h‟ name[8]
„s‟ name[7]
„e‟ name[6]
„t‟ name[5]
„a‟ name[4]
„k‟ name[3]
„n‟ name[2]
„e‟ name[1]
„V‟ name[0]
-
- 0 Memory Location
Figure 3.5: Memory Allocation for string name

4.3.4 Reading strings

A string can be read by using different ways. A string can be read by using
following functions.
- scanf( )
- getchar( )
- gets( )

4.3.4.1 Reading string using scanf( ) function


For reading a string from keyboard, we can use scanf( ) function with a
format specifier %s. One example is shown below.
char name[20];
scanf(“%s”,name);
/* & may be omitted as array works as a constant pointer. Here
name is array and sequence of characters is read at a time. */
Only problem with scanf( ) function is that, it terminates the input when it
gets first delimiter character (white space, tab or newline character). So, in the
above example if user enters following input,
Sachin Tendulkar
as after “Sachin” there is a white space, input is terminated. Only “Sachin”
(followed by null character) is stored in the string name and “Tendulkar” is
carried forward for next input.
We can specify width of input using %ws as shown in following example
(Second example shown in table 1.16 is also valid).
char surname[10];
scanf(“%7s”,surname);

9 of 16
The above code executes differently according to input as shown below,
i) If user enters a string “Deo”, it will get stored followed by null
character.
ii) If user enters a string “Tendulkar”, the string “Tendulk” will get stored
followed by null character (as width is mentioned as 7).
iii) If user enters a string “Kolhe Patil”, the string “Kolhe” will get stored
followed by null character and the string “Patil will be carried forward
for next input. (As after characters „K‟, „o‟, „l‟, „h‟ and „e‟ there is a white
space.)
Even after specifying width of input field, scanf( ) function terminates its
input when white space is received. We can read a whole line containing any
characters using scanf( ) function as shown in following example (4th example
shown in table 1.16 is also valid).
char text[80]; /*As single line may contain 80 characters. */
/* we may have less or more than 80 characters also. */
scanf(“%[^\n]”,text);

4.3.4.2 Reading string using getchar( ) function


We can use getchar( ) function (defined in stdio.h file) for reading a single
character. This function can be read repeatedly for reading a string. General
form of using this function is given below.
char ch;
ch=getchar( );
We can use following code segment for reading a line of text from user.
char text[60],c;
int i=0;
do
{
c=getchar( );
text[i]=c;
i++;
}while(c!=„\n‟);
text[i–1]=„\0‟;

4.3.4.3 Reading string using gets( ) function


We can use gets( ) function (defined in stdio.h file) for reading a string
containing white spaces. An example showing how this function can be used is
shown below.
char text[100];
gets(text);

4.3.5 Displaying strings

A string can be displayed by using different ways. A string can be


displayed by using following functions.
- printf( )
10 of 16
- putchar( )
- puts( )

4.3.5.1 Displaying string using printf( ) function


For displaying a string on monitor, we can use printf( ) function with a
format specifier %s. One example is shown below.
printf(“%s”,name);
We can also use various formatting options as discussed in point 1.9.1.
any characters using scanf( ) function as shown in following example (4 th
example shown in table 1.16 is also valid).

4.3.5.2 Displaying string using putchar( ) function


We can use putchar( ) function (defined in stdio.h file) for displaying a
single character. This function can be read repeatedly for displaying a string.
General form of using this function is given below.
putchar(ch);
We can use following code segment for displaying whole string.
int i=0;
while(text[i]!=„\0‟)
{
putchar(text[i]);
i++;
}

4.3.5.3 Displaying string using puts( ) function


We can use puts( ) function (defined in stdio.h file) for displaying a string.
An example showing how this function can be used is shown below.
puts(text);

4.5 What is structure?


As discussed previously, array is collection of elements of the same data
type. But, structure is a collection of inter-related elements of same or
different data types. Generally structure is used for maintaining records.
Record is a set of inter-related data elements.
Major features of structure are
- Provides mechanism for packing data of different types
- Represents collection of data items using single name
- Convenient tool for handling logically related data

Examples:
1. Student: roll, name, branch
2. Employee: ID, name, department, salary
3. Date: day, month, year
4. Time: seconds, minutes, hours
5. Bank_Customer: account_number, name, mobile, balance

11 of 16
4.5.1 Defining structure

Syntax for defining/creating structure is shown below.

struct struct-name
{
data-type membername;
---
---
};

Example 1:
struct student
{
int roll;
char name[15];
float percent;
};

Example 2:
struct date
{
short day;
short month;
int year;
};

4.5.2 Declaring structure variable

When a programmer want to use a structure defined as per previous topic,


(s)he has to declare a structure variable. Syntax for defining structure is shown
below.
struct structure-name struct-var-name;

Examples:
struct student s1;
struct date b_date;

One may combine definition of structure and declaration of a structure


variable as shown in following example.
struct date
{
short day;
short month;
int year;
}admission_date;

12 of 16
4.5.3 Accessing members of structure

It is compulsory to create structure variable. One can access members of


structure through structure variables. The members can be accessed using
member operator (also called dot operator or period operator) with following
syntax.
structure-var-name.member-name

Examples:
b_date.day=26;
scanf(“%d”,&admission_date.year);

4.5.4 Initializing structure

Just like any other variable, structure can also be initialized while
creating a structure variable. Some examples are shown below.

struct date admission_date = {12,10,2021};


struct date b_date = {15,8,1947};
struct student s1 = {85,“Bharat”,91.50};

Sequence of values enclosed in braces must match with the sequence in


which members are declared in the structure. Initialization of members cannot
be done inside the structure definition.

4.5.5 Example program for structure

#include<stdio.h>
#include<conio.h>

struct student
{
int roll;
char name[20];
float percent;
};

main( )
{
struct student s1,s2;
clrscr( );

printf(“Enter data of first student:\n”);


printf(“Enter roll number: ”);
scanf(“%d”,&s1.roll);
printf(“Enter name: ”);
scanf(“%s”,s1.name);
printf(“Enter percent: ”);
scanf(“%f”,&s1.percent);

13 of 16
printf(“Enter data of second student:\n”);
printf(“Enter roll number: ”);
scanf(“%d”,&s2.roll);
printf(“Enter name: ”);
scanf(“%s”,s2.name);
printf(“Enter percent: ”);
scanf(“%f”,&s2.percent);

printf(“Data of first student:\n”);


printf(“Roll No: %d\nName: %s\n”,s1.roll,s1,name);
printf(“Percentage marks: %f\n”, s1.percent);

printf(“Data of second student:\n”);


printf(“Roll No: %d\nName: %s\n”,s2.roll,s2,name);
printf(“Percentage marks: %f\n”, s2.percent);

getch( );
}

4.5.6 Nested structure

One may use a structure within another structure. The concept is called
nested structure.
Example:

struct date
{
short d;
short m;
int y;
};

struct student
{
int roll;
char name[20];
struct date admission_date; //variable of another structure
};

4.5.7 Array of structures

In the example program discussed in 4.5.4 we have handled records of two


students. But practically, plenty of records are needed to be handled. The
solution for this is to use array of structure. Syntax for declaring array of
structure is:
struct struct-name struct-var-name[size];

Example:
struct student s[75];
14 of 16
4.6.1 typedef

C supports a type-definition feature that allows user to define his/ her own
data type identifier. This user-defined identifier can then be further used for
declaring variables. This can be achieved by using following syntax.
typedef type identifier;
e.g.
typedef int my_int;
Then the variables can be declared by using the user-defined identifier (in
above example it is my_int) as,
my_int x,y,z;

One more example is


typedef struct student STUD;

4.6.2 Enumerated data type

It helps to create our own data type and define possible values that a
variable of that data type can take.
Example:
enum gender
{
male,female,other
};

When we create enum variable, it can accept any one value from the
listing only.

enum gender person1,person2;


person1=female;
person2=male;

Sample Questions

1. Define array. [2M]


2. Define array. List its types. [2M]
3. Define i) Two-dimensional array ii) Multi-dimensional array [2M]
4. Explain one-dimensional and two-dimensional array. [4M]
5. Illustrate initialization of two-dimensional array with example. [4M]
6. Design a program in C to read n number of values in an array and display
it in reverse order. [6M]
7. State difference between array and string. [2M]
8. Differentiate between character array and integer array with respect to
size and initialization. [4M]
9. Write a program to accept ten numbers and print average of them. [6M]
10. Write a program to accept 10 numbers in array and arrange them in
ascending order. [4M]

15 of 16
11. Write a program to sort elements of an array in ascending order. [6M]
12. Define array. Write a program to accept ten numbers in array. Sort array
elements and display them. [6M]
13. With suitable example, explain how two-dimensional arrays can be
created. [4M]
14. Write a program for addition of two 3X3 matrices. [6M]
15. Declare structure student with elements roll-no and name. [2M]
16. Write a program to declare structure employee having data member name,
age, street and city. Accept data for two employees and display it. [6M]
17. Write a program to declare structure student having rollno, name and
marks. Accept and display data for three students. [4M]
18. Develop a program using structure to print data of three students having
data members name, class and percentage. [4M]
19. Give a method to create, declare and initialize structure. Develop a
program to demonstrate nested structure. [6M]

16 of 16

You might also like