KEMBAR78
Module 4 (Short) | PDF | Parameter (Computer Programming) | String (Computer Science)
0% found this document useful (0 votes)
5 views22 pages

Module 4 (Short)

Uploaded by

abiat2246
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)
5 views22 pages

Module 4 (Short)

Uploaded by

abiat2246
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/ 22

MODULE 4

ARRAYS AND STRINGS

ARRAY
An array is a fixed-size sequenced collection of elements of the same data type. It is simply a grouping of same-type
data. In its simplest form, an array can be used to represent a list of numbers, or a list of names etc.
Example: EmployeeIncome[10]
The above example represents the income of employees. In above example there can be maximum 10 elements.

Based on the basis of dimensions there are three types of array:

1. One - dimensional Arrays 2. Two - dimensional Arrays 3. Multi - dimensional Arrays.


One Dimensional Array
A list of item can be given one variable name using only one subscript and such a variable is called a single subscripted
variable or One- dimensional array. It can be expressed as: x[0], x[1], x[2], x[3], x[4] x[n]
C performs no bound checking and, therefore, care should be exercised to ensure that the array indices are within the
declared limits.

Declaration of one dimensional array


Syntax: data type variable_name[n];
Example: float height[50];
int group[10];

Data type can be int, float, char etc.


variable_ name is the name of an array of nelements of the type specified.
size of an array must be an integer constant.

The C language treats character strings as arrays of characters. When the compiler sees a character string, it terminates it
with an additional null character. Thus when declaring char name[10]; Example- “WELL DONE”

Initialization of one dimensional array


An array can be initialized at either of the following two stages: (1) at compile time (2) at run time.

Compile time initialization: The array is initialized when declared.


Syntax : data_type array-name [Size] = {list of value}; the values of the list are separated by commas.
Example: int array[5]={1,2,3,4,5}; will initialize the 5 elements of array to the values 1,2,3,4 and 5.

Run time initialization: An array can be explicitly initialized at run time. This approach is usually applied for
initialization of large arrays.
Example:
for(i=0;i<100:i=i+1)
{
if (i<50)
sum[i]=0.0;
else
sum[i]=1.0;
}
// The first 50 elements of the array sum are initialized to zero while remaining is initializedto 1.0 at run time.

We can also use a read function such as scanf to initialize array.


Example: int x[3];
scanf (“%d %d %d” ,&x[0],&x[1],&x[2]); will initialize array elements with the value entered through the keyboard.

Two Dimensional Arrays


Arrays whose elements are specified by two subscripts are referred as two-dimensional arrays or double dimensional
arrays. Two dimensional arrays can be declared as follows type array_name[row_size][column_size];
Here the first index contains row size and second index contains column size.

Initialization of two dimensional arrays


Like one dimensional array, two dimensional arrays may be initialized by following their declaration with a list of initial
values enclosed in braces. Here the first index is row size, second Index is column size.
Example: int table[2][3]={0,0,0,1,1,1};
int table[2][3]={ {0,0,0} ,{1,1,1}};

Example: Write a program to read and display 3x3 matrix.


void main()
{
int i,j,a[3][3];
printf("Enter the elements of 3 x 3 Matrix: \n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("The various elements in 3 x 3 matrix are : \n");
for(i=0;i<3;i++)
{
printf("\n\t\t");
for(j=0;j<3;j++)
printf("%d\t", a[i][j]);
}
}
Multi-Dimensional Arrays
C allows arrays of three or more dimensions. The exact limit is determined by the compiler.
The general form of a multi –dimensional array is…..type array_name[s1][s2][s3][s4] [sm];

Example: int survey[3][5][12];


float table[5][4][5][3];

ANSI C does not specify any limit for array dimension. However, most compiler permitseven to ten dimension.
Static Array
The array created at compile time cannot be modified at run time so they are called static array. The process of
allocating memory at compile time is known as static memory allocation. This approach works fine as long as we know
exactly what our data requirements are.
Dynamic Arrays
In C it is possible to allocate memory to arrays at run time, which known as dynamic memory allocation and the array
called dynamic array. Dynamic array are created using what are known as pointer variables and memory management
function malloc, calloc and realloc which are in <stdlib.h>.

CHARACTER ARRAYS AND STRINGS


String : A string is an array or sequence of characters. Any group of characters defined between double quotation
marks is a constant string. EXAMPLE: “Man is obviously made to think.”
Example: printf(“Well Done !”);
Output: Well Done!
Common operations performed on strings are:

 Reading and writing strings.


 Combining strings together.
 Copying one string to another.
 Comparing strings for equality.
 Extracting a portion of a string.
Declaring And Initializing String Varaibles
A string variable is any valid C variable name and is always declared as an array.
SYNTAX: char string_name[size]; // The size determines the number of characters in the string_name.
EXAMPLE: char city[10];
When the compiler assigns a character string to any character array, it automatically supplies a null character (‘\0’) at the
end of the string. The size should be equal to the maximum number of characters in the string plus one.
Character arrays may be initialized when they are declared in the following two forms:
char city[9] = “NEW YORK”;
char city[9] = {‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’\0’};
We can also declare the size much larger than the string size in the initializer.char str[10] = “GOOD”;
Following will result in a compile time error. char str[3] = “GOOD”;

READING STRING FROM TERMINAL

Using scanf Function :The input function scanf can be used with %s format to read in a string of character.
Example: char address[15];
scanf(“%s”, address);
Using getchar function : We have used getchar function to read a single character from the terminal.
The getchar function takes theform: char ch;
ch = getchar();
Example: do
{
character = getchar();
line[c] = character;
c++;
} while(character != '\n');

Using gets function : It reads characters into str from the keyboard until a new-line character is encountered and then
appends a null character to the string. It takes the form: gets(str);
Example: char line[80];
gets(line); // reads a line of text from keyboard and displays it on the screen.
printf(“%s”,line);
The last two statementsmay be combined as: printf(“%s”,gets(line));

WRITING STRINGS TO SCREEN


Using printf Function :The printf function with %s format is used to print strings to the screen. The format %s can be
used to display an array of characters that is terminated by the null character. Example: printf(“%s”, name);
This displays the entire content of the array name.
Using putchar and puts :C supports putchar to output the values of character variables. It takes the followingform:
char ch = 'A';
putchar(ch); //This statement is equivalent to printf(“%c”,ch);
Can use this function repeatedly to output string of characters stored in an array using aloop.
Example: char name[6] = “PARIS”;
for(i=0;i<5;i++)
putchar(name[i]);
To print the string values another way is to use the function puts declared in the headerfile <stdio.h>.
It takes the form: puts(str);
where str is a string variable containing a string value. This prints the value of the string variable str and then moves the
cursor to the beginning of the next line on the screen. Example: char line[80];
gets(line);
puts(line);
Reads a line of text from the keyboard and displays it on the screen.

ARITHMETIC OPERATIONS ON CHARACTERS


C allows manipulating characters the same way we do with the numbers. Whenever acharacter constant or character
variable is used in an expression, it is automatically converted into an integer value by the system.
Example 1: x = ‘a’; printf(“%d\n”,x);
OUTPUT: 97
Example 2: x = ‘z’ – 1; The value of z is 122 and the above statement assigns 121 to the variable x.
STRING-HANDLING FUNCTIONS
C library supports large number of string-handling functions. Some are
Function Action
strcat() Concatenates two strings
strcmp() Compares two strings
strcpy() Copies one string over another
strlen() Finds the length of a string
strcat() FUNCTION : The strcat function joins two strings together. It takes the following form: strcat(string1, string2);
where string1 and string2 are character array. Here string2 is appended to string1.
The null character at the end of the string1 is removed and string2 is placed from there. Thestring2 remains unchanged.
Example: strcat("Hello", "world");
Output : Helloworld
strcmp() FUNCTION : Compares two strings identified by the arguments and has a value 0 if they are equal. If they are
not, it has the numeric difference between the first non-matching characters inthe strings.
It takes the form: strcmp(string1, string2);
Returns - Zero if they are same.
- Negative integer if string1<string2.
- Positive integer if string1>string2.
Example:
strcmp(“Rom”, “Rom”); -> Returns 0.
strcmp(“their”, ”there”); -> Returns -9
strcpy() FUNCITON :It works almost like a string-assignment operator. assigns the content of string2 to string1
It takes the form: strcpy(string1, string2);
Example: strcpy(city, “DELHI”); Assign the string “DELHI” to the string variable city.
strcpy(city1, city2); Assign the contents of the string variable city2 to the string variable city1.
strlen() FUNCTION
This function counts and returns the number of characters in a string. It takes the form: n = strlen(string);
Where n is the integer variable which receives the value of the length of the string.
Example: char ch = “NEW YORK”;
n = strlen(ch);
printf(“String Length = %d\n”, n);
Output: String Length = 8
Example:
#include <string.h>
int main ()
{
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len , x;
x = strcmp(str1,str2); /* compare str1 to str2*/
printf("strcmp(str1, str2) : %d\n", x );
strcpy(str3, str1); /* copy str1 into str3 */
printf("strcpy( str3, str1) : %s\n", str3 );
printf("strcat( str1, str2):%s\n", str1 ); /* concatenates str1 and str2 */ strcat( str1, str2);
len = strlen(str1); /* total length of str1 after concatenation */
printf("strlen(str1) : %d\n", len );
return 0;
}
Output
strcmp(str1,str2): -15
strcpy( str3, str1) : Hello
strcat(str1,str2): HelloWorld
strlen(str1) : 10
Other string functions
strncpy() : Copies only the leftmost n characters of source string to target string.
strncpy ( s1, s2, n) ; Copies the first n characters of s2 to s1.
strncmp() : strncmp(s1,s2,n); Compares left most n characters of s1 to s2 and returns.
strncat() : strncat(s1,s2,n); Concatenates left most n characters of s2 to the end of s1.
Strstr() : strstr(s1,s2); Search the string s1 to see whether s2 is present in s1.
Example:
#include <string.h>
int main ()
{
char str1[12] = "Hello ";
char str2[12] = "Hero";
char str3[12];
int x ;
x=strncmp(str1,str2, 2); /* compare str1 to str2*/
printf("strncmp(str1, str2, 2):%d\n", x );
strncpy(str3, str1, 3); /* copy str1 into str3 */
printf("strncpy( str3, str1, 3) : %s\n", str3 );
strncat( str1, str2, 2); /* concatenates str1 and str2 */
printf("strncat( str1, str2, 2):%s\n", str1 );
return 0;
}
Output
strncmp(str1, str2,2): 0
strncpy( str3, str1,3) : Hel
strncat( str1, str2,2): Hello He
Table of Strings
We use lists of character strings, such as list of name of students in a class, list of name ofemployees in an organization,
list of places etc. These list can be treated as a table of strings and a two dimensional array can be used to store the
entire list. Example: student [30][15];
It is an character array which can store a list of 30 names, each of length not more than 15characters.
char city[ ][ ] = { “Chandigarh”, “Mumbai”, “Ahmedabad”, ”Hyderabad” };
Programs
1. Program to sort a list of names in alphabetical order
#include<string.h>
#include<stdio.h>
int main()
{
int i,j,n;
char str[20][20],temp[20];
puts("Enter the no. of string to be sorted : ");
scanf("%d",&n);
for(i=0;i<=n;i++)
gets(str[i]);
for(i=0;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
}
printf("The sorted string\n");
for(i=0;i<=n;i++)
puts(str[i]);
}
Output:
Enter the no. of string to be sorted : 3
Tara Appu Rani
The sorted string
Appu Rani Tara
FUNCTIONS
A function is a group of statements that together perform a task. Every C program has at least one function, which
is main(), and all the most trivial programs can define additional functions.
1. LIBRARY FUNCTIONS: Library functions are inbuilt functions. printf, scanf,sqrt,cos,strcpy etc belong to the
category of library function.
2. USER-DEFINED FUNCTIONS: User-defined functions has to be developed by the user at the time of
writing a program.A user-defined functions can later become a part of the C program library. main is an
example of user-defined functions.
NEED FOR USER-DEFINED FUNCTIONS :
The division approach in functions clearly results in a number of advantages:
 The length of a source program can be reduced by using functions at appropriate places. This factor is
particularly critical with microcomputers where memory space is limited
 It is easy to locate and isolate a faulty function for further investigations
 A function may be used by many other programs, this means that a C programmer can build on what others
have already done, instead of starting over, from scratch.
Top-down modular programming using functions
A MULTI-FUNCTION PROGRAM

Example :
void main()
{
printline();
printf("This illustrated the use of C functions \n");
printline();
}
void printline()
{
int i;
for(i=1; i<40; i++)
printf("-");
printf("\n");
}
Output : -------------------------------------------------------------------
This illustrated the use of C functions
-------------------------------------------------------------------
MODULAR PROGRAMMING
It is defined as organizing a large program into small, independent program segments called modules that are separately
named and individually called program units. These modules are carefully integrated to become software systems that
satisfy the system requirements. It is basically a divide and conquer approach.
Some characteristics of modular programming are:
 Each module should do only one thing
 Communication between modules is allowed only by a calling module
 A module can be called by one and only one higher module
 All modules are designed as single entry, single exit system using controlstructures

ELEMENTS OF USER-DEFINED FUNCTIONS


Functions are classified as one of the derived data types in C. Can define functions and use them like any other
variables in C programs. Similarities between functions and variables in C. Both function name and variable names
are considered identifiers and therefore they must adhere to the rules for identifiers. Like variables, functions have
types (such as int) associated with them. Like variables, function names and their types must be declared and defined
before they areused in a program
There are three elements related to functions
1. Function definition
2. Function call
3. Function declaration

1. FUNCTION DEFINITION
The function definition is an independent program module that is specially written to implement the requirements of the
function. It include thefollowing elements;
1. Function name; 2. Function type; 3. List of parameters; 4. Local variable declaration;
5. Function statements; 6. A return statement.
All six elements are grouped into two parts, namely,
Function header (First three elements); and Function body (Second three elements)
The format of c function:
function_type function_name(parameter list)
{
local variable declaration;
executable statement1;
executable statement2;
return statement;
}
The first line function_type function_name(parameter list) is known as the functionheader. The statements within
the opening and the closing brace constitute the function body.
Function Header: The header consists of three parts: the function type (also known as return type like float or
double), the function name and formal parameter list- Theseparameters can also be used to send values to the calling
programs. The parameter is known as arguments. Semicolon is not used at the end of the function header.
Example:
float quadratic (int a, int b, int c)
{
}
int sum (int a, int b)
{
}
Many compiler accept an empty set of parentheses void printline()
Function body
The function body contains the declarations and statements necessary for performing the required task. The body
enclosed in braces, contains three parts: Local declarations that specify the variables needed by the function.
Function statements that perform the task of the function.
A return statement that returns the value evaluated by the function.
If a function does not return any value, we can omit the return statement. Its return typeshould be specified as void.
return (expression);
Return the value of the expression. Returns the value of p which is the product of the values of x and y.
Example:
int mul(x,y)
{
int p;
p = x*y;
return(p);
}
2. FUNCTION CALL
A function can be called by simply using the function name in a statement. When the function encounters a function call,
the control is transferred to the function mul(x,y).
3.FUNCTION DECLARATION
A function declaration (Function Prototypes) consists of four parts:
 Function type (return type)
 Function name
 Parameter list
 Terminating semicolon
Format : function-type function-name (parameter list);

Very similar to the function header line expect the terminating semicolon. int mul(int m, int n);
Equally acceptable forms of declarations are int mul (int, int);
mul (int a, int b);
mul (int, int);
CATEGORY OF FUNCTIONS
 Category 1: Functions with no arguments and no return values
 Category 2: Functions with arguments and no return values
 Category 3: Functions with arguments and one return values
 Category 4: Functions with no arguments but return a value
 Category 5: Functions that return multiple values

1. No arguments and no return values


When a function has no arguments and no return value, it does not receive any data from the calling function and the
calling function does not receive any data from the called function. There is no data transfer between the calling
function and the calledfunction. There is only a transfer of control but not data.

Example:
#include <stdio.h>
void add(void);
void main()
{
add();
}
void add() //called function
{
int a,b,c;
printf("\nEnter two number:");
scanf("%d%d",&a,&b);
c=a+b;
printf("\nSum is:%d",c);
}
OUTPUT:
Enter two number:34
Sum is:7
2. Arguments but no return values
It is a one way data communication, i.e. the called program receives data from callingprogram but it does not return
any value to the calling program.
Example:
add(int, int);
void main()
{
int a,b;
printf("\nEnter two number:");
scanf("%d%d",&a,&b);
add(a,b);
}
add(int x, int y) //function with arguments
{
int z; z=x+y;
printf("\nSum is:%d",z);
}
OUTPUT:
Enter two number:2 4
Sum is:6

3. Arguments with return values


It is a two way data communication, i.e. the called program receives data from calling program and it return some
value to the calling program.
Example:
add(int, int);
void main()
{
int a,b;
float c;
printf("\nEnter two number:");
scanf("%d%d",&a,&b); c=add(a,b);
printf("\nSum is:%f",c);
}
add(int x, int y)
{
float z;
z=x+y/3;
return(z);
}
OUTPUT:
Enter two number:67
Sum is:8.000000

4. No arguments but returns a value


There could be occasions where we may need to design functions that may not take anyarguments but returns a value
to the calling function. When a function has no arguments, it does not receive any data from the calling function, but
it can do some process and then return the result to the called function.
Example:
int get_number(void);
main()
{
int m = get_number();
printf("%d",m);
}
int get_number(void)
{
int number; scanf("%d", &number);
return(number);
}
Output:
2
2

5. Functions that return multiple values


A return statement can return only one value. We can get more information from a function, in C using the arguments
not only to receive information but also to send back information to the calling function. The arguments that are used
to “send out” information are called output parameters. The mechanism of sending back information through
arguments is achieved using address operator (&) and indirection operator (*). The use of pointer variables as actual
parameters for communicating data between functions is called “pass by pointers” or “call by address or reference”.

Example:

#include<stdio.h>
void mathoperation(int x, int y, int *s, int *d);
main()
{
int x = 20, y = 10, s, d;
mathoperation(x,y,&s,&d);
printf("s=%d\n d=%d\n", s,d);
}
void mathoperation (int a, int b, int *sum, int *diff)
{
*sum = a+b;
*diff = a-b;
}

Output:
s=30
d=10

Here x and y – input arguments, s and d – output arguments. We pass value of x to a andvalue of y to b. Address of s to
sum and address of d to diff. The body of the function when executed add the value and find difference and store the
result in memory location pointed by sum and diff.

NESTING OF FUNCTIONS
C permits nesting of functions freely. main can call function1, which calls function2,which calls function3, …..and so on
This program calculates the ratio a / (b-c).

. Call by Value and Call by Reference


In call by value method, the value of the actual parameters is copied into the formal parameters. Here we cannot
modify the value of the actual parameter by the formal parameter.
In call by reference, the address of the variable is passed into the function call as the actual parameter. The value of the
actual parameters can be modified by changing the formal parameters since the address of the actual parameters is
passed. Here the memoryallocation is similar for both formal parameters and actual parameters.

Call by Value Example Call by Reference Example


RECURSION
When a called function in turn calls another function a process of ‘chaining’ occurs. Recursion is a special case,
where a function calls itself.
Example: Factoial of a number
void main()
{
int a;
printf("\nEnter the number:");
scanf("%d",&a);
printf("The factorial of %d! is %d",a,factorial(a));
}
int factorial(int x)
{
int f;
if(x==1)
return(1);
else
f=x*factorial (x-1);

return(f);
}
OUTPUT:
Enter the number:5
The factorial of 5! is 120

FUNCTIONS WITH 1 DIMENSIONAL ARRAYS


It is possible to pass the values of an array to a function. To pass an array to a called function, it is sufficient to list the
name of the array without any subscripts, and the sizeof the array as arguments.
Example: the call largest(a,n); It will pass all the elements contained in the array a of size n.
The called function expecting this call must be appropriately defined. : float largest (float array[], int size)

FUNCTIONS WITH 2 DIMENSIONAL ARRAYS


We can also pass multi-dimensional arrays to functions. The rules are: The function must be called by passing only
the array name.In the function definition, we must indicate that the array has two-dimensional byincluding two sets of
brackets. The size of the second dimension must be specified.
Example : int M=3, N=2;
int matrix[M][N] = { {1,2},{3,4}, {5,6} };
float mean = average(matrix, M, N);
PASSING STRINGS TO FUNCTIONS
The strings are treated as character arrays in C and therefore the rules for passing strings to function are very similar to
those for passing arrays to functions. Basic rules are
1. The string to be passed must be declared as a formal
argument of the function when itis defined
Example: void display(char item_name[])
{
}
2. The function prototype should show that the argument is a string.Example: void display(char str[]);
3. call to the function must have a string array name without subscripts.Example: display(names);
THE SCOPE, VISIBILITY AND LIFETIME OF VARIABLES
In C there are four storage classes :
1. Automatic variables
2. External variables
3. Static variables
4. Register variables

MULTIFILE PROGRAMS
More than one source file is compiled separately and linked later to form an executable object code. This approach is
very useful because any change in one file does not affectother files thus eliminating the need for recompilation of the
entire program. Multiple source files can share a variable declared as an external variable. Variables that are shared
by two or more files are global variables and we must declare them accordingly in one file and then explicitly define
them with extern in other file.
Structures and Union

Structure
A structure is a user defined data type that groups logically related data items of different data types into a single
unit. Structures help to organize complex data in a meaningful way. A variable of structure type can store multiple
data items of differentdata types under the one name.

Definition of structure
A structure has to defined, before it can be used. The syntax of defining a structure is:
struct tag_name
{
data_type member-name1;
data_type member-name2;
……….
};

Example: The structure of Employee is declared as


struct employee
{
int emp_id;
char name[20];
float salary;
char address[50];
};
Array vs Structure
 Array is a collection of related data elements of same type. Structure can haveelements of different types.
 Array is derived data type whereas a structure is a programmer defined one.
 An array behaves like a built in data type. But in case of structure, first we have to design and declare a data
structure before the variables of that type are declared and used.
Accessing structure members
The structure members cannot be directly accessed in the expression. They are accessed by using the name of structure
variable followed by a dot and then the name of member variable.
Ex : struct employee e1;
The method used to access the structure variables are e1.emp_id, e1.name, e1.salary, e1.address, e1.dept_no, e1.age.
The data within the structure is stored and printed by this method using scanf and printf statement in c program.
Structure Initialization
The members of individual structure variable are initialized one by one or in a singlestatement.
Example: struct employee e1 = {1, “Hemant”,12000 , “Sector 3 Villa area new delhi”,10,35};
OR
e1.emp_id=1; e1.dept_no=10;
e1.name=“Hemant”; e1.age=35;
e1.salary=12000; e1.address=“Sector 3 Villaarea New Delhi ”;
Rules:
1. We cannot initialize individual members inside structure template.
2. The order of values enclosed in braces must match the order of members instructure definition.
3. We can do partial initialization. But the uninitialized members must be at the endof the list.
4. The default values for uninitialized members are zero for int and float type and‘\0’ for char.
Size of structure : The size of a structure variable can be found by using sizeof() operator. sizeof(struct x);
It will give the total number of bytes required to hold all the members of structure x.
Program to implement structure
struct employee
{
int emp_id;
char name[20];
float salary;
};
void main()
{
struct employee e1, e2;
int size;

printf(“Enter the employee id of employee”);


scanf(“%d”,&e1.emp_id);
printf (“Enter the name of employee”);
scanf(“%s”,e1.name);
printf (“Enter the salary of employee”);
scanf(“%f”,&e1.salary);
printf (“Enter the employee id of employee”);
scanf(“%d”,&e2.emp_id);
printf (“Enter the name of employee”);
scanf(“%s”,e2.name);
printf (“Enter the salary of employee”);
scanf(“%f”,&e2.salary);
printf (“The employee id of employee is : %d”, e1.emp_id);
printf (“The name of employee is : %s”, e1.name);
printf(“The salary of employee is : %f”, e1.salary);
size=sizeof(e1);
printf(“\n No. of bytes required for e1=%d ”,size);
printf (“The employee id of employee is : %d”, e2.emp_id);
printf (“The name of employee is : %s”, e2.name);
printf (“The salary of employee is : %f”, e2.salary);
}

Output of Program
Enter the employee id of employee 1
Enter the name of employee Rahul
Enter the salary of employee 15000
No. of bytes required for e1=28 (4+20+4)

Enter the employee id of employee 2


Enter the name of employee Rajeev
Enter the salary of employee 14500

The employee id of employee is : 1


The name of employee is : Rahul
The salary of employee is : 15000
The employee id of employee is : 2
The name of employee is : Rajeev
The salary of employee is : 14500

Arrays of Structure
C language allows creating an array of variables of structure. The array of structure is used to store the large number
of similar records. For example to store the record of 100 employees then array of structure is used. The method to
define and access the array element of array of structure is similar to other array. The syntax to define the array of
structure is
The syntax : struct <tag_name> <array_name> [<value>];
Example: struct employee e [100];

Arrays within Structures :


C permits use of array as structure member. An array of int or float type can be used.Example:

struct student
{
int regno;
char name[20];int
marks [5];
}

Example
#include <stdio.h>
struct employee
{
int emp_id;
char name[20];
float salary;
};
void main ( )
{
struct employee e[10];
int n,i;
printf("Enter the no: of employees: ");
scanf("%d", &n);
for (i=1; i<=n; i++)
{
printf ("Enter the employee id of employee: ");
scanf ("%d",&e[i].emp_id);
printf ("Enter the name of employee: ");
scanf ("%s",e[i].name);
printf ("Enter the salary of employee: ");
scanf ("%f",&e[i].salary);
}
for (i=1; i<=n; i++)
{
printf ("The employee id of employee is : %d\n", e[i].emp_id);
printf ("The name of employee is: %s\n",e[i].name);
printf ("The salary of employee is: %f\n", e[i].salary);
}
getch();
}

Output
Enter the no: of employees: 2

Enter the employee id of employee: 1


Enter the name of employee: Anu
Enter the salary of employee: 13000

Enter the employee id of employee: 2


Enter the name of employee: Sam
Enter the salary of employee: 14500

The employee id of employee is : 1


The name of employee is: Anu
The salary of employee is: 13000.000000
The employee id of employee is : 2
The name of employee is: Sam
The salary of employee is: 14500.000000
Structures within structures
C language defines a variable of structure type as a member of other structure type.
The syntax to define the structure within structure is:
struct tag_name
{
data_type variable_name;
struct struct_name
{
data_type variable_name;
……..
}struct_variable;

}struct_variable;
Example: The structure of Employee is declared as
struct employee
{
int emp_id;
char name[20];
struct date
{
int day;
int month;
int year;
}doj;
}e1;

Accessing Structures within Structures


The data member of structure within structure is accessed by using two period (.) symbols. The syntax to access the
structure within structure is: struct_var . nested_struct_var . struct_member;
For Example:-
e1.doj.day;
e1.doj.month;
e1.doj.year;
Union
A union is a user defined data type like structure. The union groups logically related variables into a single unit. The
union data type allocate the space equal to space need to hold the largest data member of union. The union allows
different types of variable to share same space in memory unlike structures where each member has its own storage
location. There is no other difference between structure and union. The syntax of defining a union is

union tag_name
{
data-type member1;
data-type member2;
};

Example: The union of Employee is declared as


union employee
{
Int emp_id;
char name[20];
float salary;
char address[50];
};

Difference between structure and union


1) The memory occupied by structure variable is the sum of sizes of all the members but memory occupied by
union variable is equal to space hold by the largest data member of a union.
2) In the structure all the members are accessed at any point of time but in union onlyone of union member can be
accessed at any given time.

Bit fields
It is a set of adjacent bits whose size can be from 1 to 16 bits in length. The name and size of bit field is defined
using structure. It is used to utilize the computer memory efficiently. The general form is:
struct tag_name
{
data_type name1;
bit_length;
data-type name2;
bit_length;
};
struct Date
{
unsigned int day : 5;
unsigned int month : 4;
unsigned int year;
};

*******************************************

You might also like