1. ARRAYS AND STRINGS
ARRAYS
DEFINING AN ARRAY
An array is a collection of similar data items that are stored under a common name. A
value in array is identified by index or subscript enclosed in square brackets with array name.
The individual data items can be characters, integers, floating-point numbers, etc.
However, they must all be of the same type and the same storage class.
eg. a [n ]
a
a[0] a[1] a[2] …………………..a[n-1]
• Each array element (i.e., each individual data item) is referred to by specifying the array
name followed by one or more subscripts, with each subscript enclosed in square brackets
• In general terms, a one-dimensional array definition may be expressed as
data- type array[ expression] ;
data- type is the data type,
array is the array name, and expression is a positive-valued integer expression
which indicates the number of array elements.
Example 1:
int a[3] = {2, 3, 5};
char ch[20] = "TechnoExam" ;
float stax[3] = {5003.23, 1940.32, 123.20} ;
DECLARING AN ARRAY:
1
Definition - Declaring and initializing an array - Accessing array elements - One-
dimensional, Two-dimensional and Multi-dimensional arrays - Strings - String
Manipulation - String Functions -Introduction to Pointers, Structures and Unions.
2. To declare an array in C, a programmer specifies the type of the elements and the
number of elements required by an array as follows: <data type> < arrayName> [ Size ];
The array Size must be an integer constant greater than zero and type can be any valid C
data type.
Example 1:
int x[lOO];
char text [ 8 0 ] ;
static char message[25];
static float n[12];
• The first line states that x is a 100-element integer array, and the second defines text to be
an 80-element character array.
• In the third line, message is defined as a static 25-element character array.
• The fourth line establishes n as a static 12-element floating-point array
ARRAY INITIALIZATION:
The values can be initialized to an array, when they are declared like ordinary variables,
otherwise they hold garbage values.
The array can be initialized in the following two ways:
1. At compile time
2. At runtime
1. At compile time:
Syntax:
data- type arra_name [ size] = { value 1, value 2, . . . , value n) ;
Eg: int marks[3]= { 70,80,90 }
Like ordinary variables , the values to the array can be initialized as follows:
marks[0]= 70
marks[1]= 80
marks[2]= 90
2
3. Character array can be used in the program like ordinary variables.Character can also be
initialized in the similar fashion.
char name[ ]={‘L’,’A’,’K’}
The above ststement declares the name as an array of character initialisez with the string ‘LAK’
2. At run time:
The array can be explicitly initialized at run time.
Eg:
while(i<=10)
{
if(i<5)
sum[i]=0;
else
sum[i]=sum[i]+I;}
The array can also be initialized by reading data item from the input.
Eg: int n[2];
Scanf(“%d %d”,&n[0],n[1])
ACCESSING ARRAY ELEMENTS
An element is accessed by indexing the array name. This is done by placing the index of
the element within square brackets after the name of the array.
For example:
int salary = balance[9];
The above statement will take 10th element from the array and assign the value to salary
variable. Following is an example which will use all the above mentioned three concepts viz.
declaration, assignment and accessing arrays:
#include <stdio.h>
int main ()
3
4. {
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ )
{
printf("Element[%d] = %dn", j, n[j] );
}
return 0;
}
Output:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
TYPES OF AN ARRAY:
1. One / Single Dimensional Array
4
5. 2. Two Dimensional Array
3. Multidimensional Array
1. One Dimensional Array
For a one-dimensional array, the size is specified by a positive integer expression,
enclosed in square brackets. The expression is usually written as a positive integer
constant.
The general form is
data- type array [ expression] = { value 1, value 2, . . . , value n) ;
• where value 1 refers to the value of the first array element, value 2 refers to the value of the
second element, and so on. The appearance of the expression, which indicates the number of
array elements, is optional when initial values are present.
Total Size (in Bytes):
total size = length of array * size of data type
In above example, a is an array of type integer which has storage size of 3 elements.
The total size would be 3 * 2 = 6 bytes.
* MEMORY ALLOCATION :
Fig : Memory allocation for one dimensional array
Processing an Array
Single operations which involve entire arrays are not permitted in C. Thus, if a and b are
similar arrays (i.e., same data type, same dimensionality and same size), assignment
operations, comparison operations, etc. must be carried out on an element-by-element basis.
EXAMPLE
#include <stdio.h>
5
6. #include <conio.h>
void main()
{
int a[3], i;;
clrscr();
printf("nt Enter three numbers : ");
for(i=0; i<3; i++)
{
scanf("%d", &a[i]); // read array
}
printf("nnt Numbers are : ");
for(i=0; i<3; i++)
{
printf("t %d", a[i]); // print array
}
getch();
}
Output :
Enter three numbers: 9 4 6
Numbers are: 9 4 6
2. Two Dimensional Array
The array which is used to represent and store data in a tabular form is called as 'two
dimensional array.' Such type of array specially used to represent data in a matrix form.
The following syntax is used to represent two dimensional array.
6
7. Syntax:
<data-type> <array_nm> [row_subscript][column-subscript];
Example:
int a[3][3];
In above example, a is an array of type integer which has storage size of 3 * 3
matrix. The total size would be 3 * 3 * 2 = 18 bytes.
* MEMORY ALLOCATION :
Fig : Memory allocation for two dimensional array
EXAMPLE:
Finding sum of diagonal elements using 2-dimensional array
#include<stdio.h>
void main()
{
int matrix[3][3],i,j,sum;
sum=0;
printf(“enter the elements”);
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
scanf(“%d”,&matrix[i][j]);
7
8. }
}
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
if(i==j)
sum=sum+matrix[i][j];
}}
printf(“sum=%d”,sum);
}
OUTPUT
INPUT:enter the elements
1 2 3
2 2 3
3 3 3
Output:sum=6
Limitations of two dimensional array:
• We cannot delete any element from an array.
• If we don’t know that how many elements have to be stored in a memory in advance,
then there will be memory wastage if large array size is specified.
3. Multidimensional Arrays
• In some cases there is a need for arrays with a third or even a fourth dimension. These
arrays are called multidimensional arrays.
• You will use these multidimensional arrays relatively infrequently.
8
9. • They can facilitate an understanding of the data, improve the readability of algorithms,
and facilitate processing since the data can be processed through the use of three or more
nested loops.
• For example, with input data on temperatures referenced by day, city, county, and state,
day would be the first dimension, city would be the second dimension, county would be
the third dimension, and state would be the fourth dimension of the array.
• In any case, any temperature could be found as long as the day, the city, the county, and
the state are known.
• A multidimensional array allows the programmer to use one array for all the data.
• Figure shows a block of memory locations and their reference names for a three-
dimensional array. The recommended variable names for the indexes of a three
dimensional array are Row for row, Column for column, and Depth for depth.
• For a fourth dimension, Volume for volume is used. These arrays are processed much like
two-dimensional arrays.
Figure: Three Dimensional Array
STRINGS
Definition
9
10. A string is an array of characters terminated by a special symbol named as null character
(represented as ‘0’). Hence null character is also named as string-termination character. It is
used to identify the length of the string.
Defining a string
A string definition expressed as
Storage-class char string-name [expression];
Where Storage-class refers to the storage class of the string.
• Expression is a positive-valued integer expression which indicates the number of elements in
the string including null character.
Ex:
Char name [50];
/* name is a string that can consist of maximum 50 characters */
Null Character
• Null character is used to terminate the string. It is needed to compute the actual length of the
string. As compared to other arrays, the string size is not stored in a separate variable and
string reading, writing etc.
Ex:
Char name [50] =”welcome”;
• The length of actual string is 7. In the case 8th
element of the array i.e. name [7] location will
be used to store null character, as shown in figure
•
w e l c o m e ‘0’
[0] [1] [2] [3] [4] [5] [6] [7] [49]
• Null character is used to identify the string termination and no processing is done after the
identification of null character.
• Thus reading, writing, copying a string will be processed up to the null character’s position
i.e. up to subscript number 7 in above example.
• The null character is not counted towards the length of the string, but takes memory of one
element. Null character cannot be read or written, but is used internally only.
Initialization of Strings
10
11. • The strings can be initialized at the time of definition. It can also be initialized using double
quotes.
EX:
Char str[30] = ”Hello World”;
Char str[[30] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘w’, ‘o’, ‘r’, ‘l’, ‘d’};
H e l l o W o r l d 0
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [29]
• In both cases, the null character will get appended at the last automatically. Both of these
initializations will result into storage as shown in figure.
Reading and Writing a String
• A string can be read and written by using a single scanf and printf function
using %s (s stands for string) and no loop is needed, which was compulsory for reading &
writing arrays of other data types.
Example :
/** Read a string from keyboard and display the same on screen **/
#include<stdio.h>
#define MAX_SIZE 50
main()
{
char str [Max_SIZE];
printf(“Enter a string of maximum %d characters:”, MAX_SIZE);
scanf(”%s”, str);
printf(“The entered string is %sn”, str);
}
Output:
11
12. Enter a string of maximum 49 characters: programming
The entered string is programming
Enter a string of maximum 49 characters: C Program
The entered string is C
• This scanf function reads a string from keyboard till a whitespace character (blank, tab,
newline) is encountered.
• After the reading is complete, the null character is appended automatically at the next
position inside the array.
• In first case, the input word programming gets stored at str[0] to str[10] and null character is
appended at str[11].
• The scanf function with %s can be used to read strings not consisting of spaces. So if we
gave C Program as input, only c gets read. So the null character is appended at str[1] in case
the input was “c program”.
• If we are interested to read a string consisting of blank characters as well e.g. we want to read
a line of text, gets function is the easiest way to do it.
• But the string.h header file must be included to use gets function.
• The gets function keeps on reading the characters till the newline character (Enter key) is not
pressed.
• Similarly for printing a string puts function can be used. The gets and puts functions can be
used as follows:
Gets (string-name);
Puts (string);
where the string-name refers to the variable name of string. The puts function can be
used to print a constant string written within double quotes as well as string variable.
• The gets function also appends null character at the end of the string automatically, as done
in case of scanf with %s.
Example:
#include<stdio.h>
#include<string.h>
#define MAX_SIZE 50
main()
{
12
13. char str [MAX_Size];
printf(“Enter a line of text of maximum %d characters:”, MAX_SIZE);
gets(str);
puts(“ The entered line is :”);
puts(str);
}
Output:
Enter a line of text of maximum 49 characters: Hello World
The entered line is:
Hello world
Processing the Strings
• The Strings can be processed either by using some predefined functions with help of string.h
header file or by processing all characters individually. Some of the commonly used
predefined functions are
1. Int strlen(string_var) – to compute the length of the string, not counting null characters.
2. Strcpy(dst_string,src_string) – to copy a source string into destination string.
3. Int strcmp(str1,str2) – to compare str1 with str2.
4. Strcat(dst_string,src_string) – to append copy of the source string at the end of
destination string.
Ex:
#include<stdio.h>
#include<string.h>
main ()
{
int len1;
char str1[100], str2[100], str3[100], tempstr1[50];
printf(“enter one string”);
gets(str1);
13
14. len1=strlen (str1);
printf(“The length of the string is %d n”,len1);
strcpy(str2,str1);
printf(“ First string is %s and copied string is %s n”,str1,str2);
printf(“ Enter the string to be compared with first string:”);
gets(str3);
if (strcmp(str1,str3)==0)
printf(“Both strings are equal n’);
else if (strcmp(str1,str3)<0)
printf(“ First string is lesser than second n”);
else
printf(“ First string is greater than second string n”);
printf(“ Enter the string to be concatenated at the right of first string: “);
gets(tempstr1);
strcat(str1,tempstr1);
printf(“ The concatenated string is %s n”, str1);
}
OUTPUT
Enter one string: Programming
The length of the string is 11
First string is programming and copied string is programming
Enter the string to be compared with first string: Computer
First string is greater than second string
Enter the string to be concatenated at the right of first string: with C
The concatenated string is Programming with C
14
15. STRING FUNCTIONS
Function Explanation
strncpy(dest,src,n) Copies up to n characters from src to dest
string.
strncmp(str1,str2,n) Compares str1 and str2 looking at no more than
n characters.
strcmpi(str1,str2) Compare str1 and str2 ignoring the case
sensitivity.
strlwr(str1) Converts string str1 to all lowercase & returns
a pointer.
strupr(str1) Converts string str1 to all uppercase & returns
a pointer.
strncat(dest,src,n) Copies at most n characters of src to the end of
dest string.
memcpy(dest,src,n) Copies a block of n bytes from src to dest
memcmp(str1,str2,n) Compares first n bytes of strings str1 and str2.
memset(str1,ch,n) Sets first n bytes of array str1 to the character
ch.
strchr(str1,ch) Scans the string str1 for the first occurrence of
character ch.
strset(str1,ch) Sets all characters in the string str1 to the
character ch.
strnset(str1,ch,n) Sets first n characters in the string str1 to the
character ch.
strrev(str1) Reverses all characters in string str1.
strstr(str1,str2) Scans str1 for the first occurrence of substring
str2 and returns a pointer to starting element.
itoa(val,str1,radix) Converts the integer val to string str1 using
base as radix.
atoi(str1) Converts the string of digits str1 to integer &
15
17. i++;
}
Str3[i]=str2[j];
Printf(“the concatenated string is..%s”,str3);
Getch();
}
String2()
{
Char str1[10],str2[10];
Int I;
Clrscr();
Printf(“Enter the two string”);
Scanf(“%s%s”,str1,str2);
For(i=1;i<2;i++)
{
strcmp(str1[i]==str2[i])
Printf(“The both string is equal”);
Else
Printf(“The both the string is not equal”);
Getch();
}
}
2. String Copy And String Concatenate:
#include <string.h>
#include <stdio.h>
int main()
17
18. {
char first[100];
char last[100];
char full_name[200];
Printf(“enter the first and second string is”);
Scanf(“%s,%s”,first,last);
strcpy(first, "first");
strcpy(last, "last");
strcpy(full_name, first);
strcat(full_name, " ");
strcat(full_name, last);
printf("The full name is %sn", full_name);
return (0);
}
3. String Search:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char text[100];
char substring[40];
printf("nEnter the string to be searched(less than 100 characters):n");
fgets(text, sizeof(text), stdin);
printf("nEnter the string sought (less than 40 characters ):n");
fgets(substring, sizeof(substring), stdin);
/* overwrite the newline character in each string */
text[strlen(text)-1] = '0';
substring[strlen(substring)-1] = '0';
int i;
for(i = 0 ; (text[i] = toupper(text[i])) ; i++);
for(i = 0 ; (substring[i] = toupper(substring[i])) ; i++);
printf("nThe second string %s found in the first.",((strstr(text, substring) == NULL) ? "was not
" : "was"));
return 0;
}
18
19. 4. Searching and Sorting of Strings
• The searching of a substring requires finding whether all of the characters of the substring are
present from any position onwards in the main string.
• This can be found by starting from subscript 0 of the main string and checking whether all
characters of the substring are present in the same sequence from 0th
position onwards or not.
Ex:
#include<stdio.h>
#include<string.h>
main()
{
Char text[100], substr[30];
int text_len, sub-len,i,j;
printf(“ Enter the main string: “);
gets(text);
printf(“ Enter the sub string to be searched: “);
gets(substr);
text_len=strlen(text);
sub_len=strlen(substr);
for(i=0;i<=text_len-sub_len;i++)
{
for(j=0;j<sub_len;j++)
if(text[i+j]==substr[j])
continue;
else
break;
if(j==sub_len)
19
20. printf(“The substring is present from subscript %d onwards n”, i);
}
}
OUTPUT
Enter the main string: The Programming is a systematic process.
Enter the sub string to be searched: pro
The substring is present from subscript 4 onwards
The substring is present from subscript 32 onwards
rev(--len);
Putchar(c);
}return;
}
POINTERS
Definition:
A pointer is a variable that represents the location (rather than the value) of a data item,
such as a variable or an array element.
OR
A Pointer is a variable. It may contain the memory address of the variable.
Applications of Pointers
• Pointers can be used to pass information back and forth between a function and its
reference point.
• In particular, pointers provide a way to return multiple data items from a function via
function arguments.
20
21. • Pointers also permit references to other functions to be specified as arguments to a given
function. This has the effect of passing functions as arguments to the given function.
Pointer Notation
Syntax:
Datatype *pointername:
• Where datatype - Specifies the type of data to which the pointer points.
• Pointer name – Specifies the name of the pointer.
• When a pointer variable is declared, the variable name must be preceded by an asterisk
(*).
Ex:
int *a;
char *b;
int *a mean ‘a’ contains the address of variable, which is integer variable.
The address of v’s memory location can be determined by the expression &v, where &
is a unary operator, called the address operator, that evaluates the address of its operand.
• Now let us assign the address of v to another variable, pv. Thus,
pv = &v
• This new variable is called a pointer to v, since it “points” to the location where v is
stored in memory.
NOTE: however, that pv represents v’s address, not its value. Thus, pv is referred to as a
pointer variable.
Fig. Relationship between pv and v (where pv = &v and v = *pv)
EXAMPLE
Accessing data through pointers
1. #include<stdio.h>
21
22. main()
{
int a=22,*a;
float b=2.25,*b;
a=&a;
b=&b;
printf(“n value of a=%d”,*a);
printf(“n value of b=%d”,*b);
}
Output
Value of a=22
Value of b=2.25
2. #include<stdio.h>
main()
{
int a=22;
printf(“n Value of a=%d”,*a);
printf(“n Value of a=%u”,&a);
printf(“n Value at address %u=%d”,&a,*(&a));
}
Output
Value of a=22
Address of a=4000
Value at address 4000=22
22
23. STRUCTURE
• Structure is user defined or derived data type which is used to store heterogeneous data under
unique name.
• C provides a constructed data type known as structure which pack the data items of different
data types.
• It contains one or more data items of different type.i.e., a structure may consists of integer,
float, character elements etc,.. It is especially used to process multiple data types in a single
entity.
• The variables which are declared inside the structure are called as 'members of structure.
Structures are slightly different from the variable types .Structures are data types by
themselves. Defining a structure or union, will create a custom data type.
• Structures in C are used to encapsulate, or group together different data into one object. It can
also use other structures, arrays or pointers as some of its members
Defining a Structure
• A structure type is usually defined near to the start of a file after including header files.
Keyword 'struct' is used to define the structure. The syntax of the structure definition is given
below
Definition 1:
struct structure_name
{ <data-type> element 1;
<data-type> element 2;
- - - - - - - - - - -
- - - - - - - - - - -
<data-type> element n;
};
Example
struct student
{
char name[20];
int rollno;
int height;
23
Name
Roll No
Height
Weight
Student
24. float weight;
};
• A structure type is also defined using a typedef statement. typedef defines and names a new
type, allowing its use throughout the program.
• typedefs usually occur just after the #define and #include statements in a file. The syntax of
the typedef structure definition is given below
Definition 2:
typedef struct
{
<data-type> element 1;
<data-type> element 2;
- - - - - - - - - - -
- - - - - - - - - - -
<data-type> element n;
} structure_name;
Example
typedef struct
{ char name[20];
int rollno;
int height;
float weight;
} student;
Declaring a structure variable
Variables of defined structure type are referred as structure variables. Structure variables
are defined using the following syntax for structure definition 1
struct structure-name structure-variable1, structure-variable2,…..;
24
25. Example:
struct student s1,s2, s3;
similarly declaration syntax for structure definition 2
structure-name structure-variable1, structure-variable2,…..;
Example:
student s1,s2, s3;
Note: Definition and declaration can be combined in one statement as follows
Definition 1:
Syntax:
struct structure_name
{
<data-type> element 1;
<data-type> element 2;
- - - - - - - - - - -
- - - - - - - - - - -
<data-type> element n;
} structure-variable1, structure-variable2,…;
Example:
struct student
{
char name[20];
int rollno;
int height;
float weight;
}s1,s2,s3;
25
26. The composition of the given example is shown in figure
Definition 2:
typedef struct
{
<data-type> element 1;
<data-type> element 2;
- - - - - - - - - - -
- - - - - - - - - - -
<data-type> element n;
} structure-name structure -variable1, structure-variable2,…;
Example
typedef struct
{
char name[20];
int rollno;
int height;
float weight;
} student s1,s2,s3;
Each structure variable holds its own members as shown in figure
26
27. Accessing Members of a Structure
• Each member of a structure can be used just like a normal variable, but its name will be a bit
longer . After declaring the structure type, variables and members, the member of the
structure can be accessed by using the structure variable along with the dot(.) operator.
Syntax: structure-variable. Structure-member;
Example : s1.name,s1.rollno,s2.height
Rules for declaring a structure
1) A Structure must end with a semicolon.
2) Usually a structure appears at the top of the source program
3) Each structure element must be terminated.
4) The structure variable must be accessed with structure variable with dot(.) operator.
Example using structure concept
Program :
/* Program to demonstrate structure.
#include <stdio.h>
#include <conio.h>
struct student
{
char name;
27
Name
Roll No
Height
Weight
S1
Name
Roll No
Height
Weight
S2
28. int rollno;
char branch;
int m1,m2,m3;
}s1,s2;
void main()
{
int total,
float avg;
printf("n Enter student details s1 : n");
scanf(“%s %d %s %d %d
%d”,&s1.name,&s1.rollno,&s1.branch,&s1.m1,&s1.m2,&s1.m3);
printf("n Enter student details s2 : n");
scanf(“%s %d %s %d %d
%d”,&s2.name,&s2.rollno,&s2.branch,&s2.m1,&s2.m2,&s2.m3);
total=s1.m1+s1.m2+s1.m3;
avg=total/3;
printf(“n The details are:n”)
printf(“n %s t %d t %s t %d t %d t %d t %ft ”, s1.name, s1.rollno
,s1.branch ,s1.m1,s1.m2,s1.m3,total,avg);
total=s2.m1+s2.m2+s2.m3;
avg=total/3;
printf(“n %s t %d t %s t %d t %d t %d t %ft ”, s2.name, s2.rollno
,s2.branch ,s2.m1,s2.m2,s2.m3,total,avg);
}
28
29. Output :
Enter student details s1:
Sai 12 cse 50 60 65
Enter student details s2:
Ram 13 it 50 70 75
The details are
Sai 12 cse 50 60 65 175 58.3
Ram 13 it 50 70 75 195 65
Array in Structures
Sometimes, it is necessary to use structure members as array. Looping statement(for) is used to
access the array member.
Note: character array is referred as a string. Hence don’t use for loop to read or write a
string.
Example:
struct student
{
char name[20];
int rollno;
int marks[10];
int height;
float weight;
}s1,s2,s3;
Program :
/* Program to demonstrate array in structures.
#include <stdio.h>
29
30. #include <conio.h>
struct result
{
int rno, mrks[5];
char nm;
}res;
void main()
{
int i,total;
clrscr();
total = 0;
printf("nt Enter Roll Number : ");
scanf("%d",&res.rno);
printf("nt Enter Marks of 3 Subjects : ");
for(i=0;i<3;i++)
{
scanf("%d",&res.mrks[i]);
total = total + res.mrks[i];
}
printf("nnt Roll Number : %d",res.rno);
printf("nnt Marks are :");
for(i=0;i<3;i++)
{
printf(" %d",res.mrks[i]);
}
30
31. printf("nnt Total is : %d",total);
getch();
}
Output :
Enter Roll Number : 1
Enter Marks of 3 Subjects : 63 66 68
Roll Number : 1
Marks are : 63 66 68
Total is : 197
Copying a Structure Variable
Data items of one structure variable can be copied or assigned to another variable of the
same structure. Syntax of copying is given as follows
structure-variable1=structure-variable2 //both variables are to be declared
For the same structure
Example
s1=s2;
Where s1 & s2 are variables for struct student.
Comparison of structure variable
To compare two structure variables belonging to same structure , ternary operator i.e
conditional operator is used. Here , all the members of either variable are checked for
equality. This is illustrated in the following program
Program for Comparing and copying structure variables
struct class
{
int number;
char name[20];
float marks;
};
void main()
31
32. {
int x;
struct class student1 = {111,”Rao”,72.50};
struct class student2 = {222,”Reddy”, 67.00};
struct class student3;
student3 = student2;
x = ((student3.number == student2.number) &&
(student3.marks == student2.marks)) ? 1 : 0;
if(x == 1)
{
printf(“nStudent2 and Student3 are samenn” );
printf(“%d%s%fn”, student3.number,
student3.name,
student3.marks);
}
else
{
printf(“nStudent2 and Student3 are differentnn”);
}
y = ((student1.number == student2.number) &&
(student1.marks == student2.marks)) ? 1 : 0;
if(y== 1)
{
printf(“nStudent2 and Student3 are samenn”);
printf(%d%s%fn, student2.number,
student2.name,
student2.marks);
}
else
printf(“nStudent2 and Student3 are differentnn);
}
Output
student2 and student3 are same
222 Reddy 67.000000
Student2 and Student3 are different
UNION
32
33. • Union is user defined data type used to stored data under unique variable name at single
memory location.
• Union is similar to that of structure. Syntax of union is similar to structure. To declare union
data type, 'union' keyword is used.
• But the major difference between structure and union is 'storage.' In structures, each member
has its own storage location, whereas all the members of union use the same location.
• Union contains many members of different types; it can handle only one member at a time.
• Unions and Structures are identical in all ways, except for one very important aspect. Only
one element in the union may have a value set at any given time.
• Everything we have shown you for structures will work for unions, except for setting more
than one of its members at a time.
• Unions are mainly used to conserve memory. While each member within a structure is
assigned its own unique storage area, the members that compose a union share the common
storage area within the memory.
• Unions are useful for application involving multiple members where values are not assigned
to all the members at any one time.
• Union holds value for one data type which requires larger storage among their members.
Defining a Union
A union type is usually defined near to the start of a file after including header files.
Keyword 'union' is used to define the union. The syntax of the union definition is given below
Union union_name
{
<data-type> element 1;
<data-type> element 2;
- - - - - - - - - - -
- - - - - - - - - - -
<data-type> element n;
};
Example
union student
{
33
34. int rollno;
float gradepoint;
char grade;
};
The memory allocation for the above union example is shown below. Integer data requires
2bytes of memory(2 cells),character requires 1byte(1 cell), similarly float data type require four
bytes of memory(4 cells).Memory space allocated for union is based on larger data type.
2000 2001 2002 2003
grade
rollno
gradepoint
Program :
/* Program to demonstrate union.
#include <stdio.h>
#include <conio.h>
union techno
{
int id;
char nm[50];
}tch;
34
35. void main()
{
clrscr();
printf("nt Enter developer id : ");
scanf("%d", &tch.id);
printf("nnt Enter developer name : ");
scanf("%s", tch.nm);
printf("nn Developer ID : %d", tch.id); //Garbage
printf("nn Developed By : %s", tch.nm);
getch();
}
Output :
Enter developer id : 101
Enter developer name : technowell
Developer ID : 25972
Developed By : technowell_
Program:
#include <stdio.h>
#include <conio.h>
union student
{
char name;
int rollno;
int m1;
}s1,s2;
35
37. else if((s1.m1>=50)&&(s1.m1<60))
{
printf(“GRADE : D n”);
}
else
{
printf(“GRADE : FAIL n”);
}
printf("n Enter student details s2 : n");
scanf(“%s %d %d “,&s2.name,&s2.rollno,&s2.m1);
printf(“n NAME: %s n ROLLNO: %dn TOTAL MARK: %d n”, s2.name,
s2.rollno,s2.m1);
if(s2.m1>=90)
{
printf(“GRADE : O n”);
}
else if((s2.m1>=80)&&(s2.m1<90))
{
printf(“GRADE : A n”);
}
else if((s2.m1>=70)&&(s2.m1<80))
{
printf(“GRADE : B n”);
}
else if((s2.m1>=60)&&(s2.m1<70))
37
38. {
printf(“GRADE : C n”);
}
else if((s2.m1>=50)&&(s2.m1<60))
{
printf(“GRADE : D n”);
}
else
{
printf(“GRADE : FAIL n”);
}
}
Difference between Union & Structure:
The difference between structure and union in c is:
1. Union allocates the memory equal to the maximum memory required by the member
of the union but structure allocates the memory equal to the total memory required by
the members.
2. In union, one block is used by all the member of the union but in case of structure,
each member has their own memory space.
3. Union offers a way for a section of memory to be treated as a variable of one type on
one occasion and as a different variable of a different type on another occasion.
Comparison of structure and union:
Structure
1. Every member has its own memory space.
2. Keyword struct is used.
3. Any member can be accessed at anytime without the loss of data.
4. More storage space is required.
5. It can handle all the members or a few as required at a time.
38
39. 6. It may be initialized with all its members.
7. Different interpretation for the same memory location is not possible.
Union
1. All the members use the same memory space to store the values.
2. Keyword union is used.
3. Different interpretations for the same memory location are possible.
4. It can handle only one member at a time, even all the members use the same space.
5. Only its first members may be initialized.
6. Conversion of memory is possible.
39