C Unit 4

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

I B.

SC - 2 Semester (‘C’ Language) UNIT-4


Reading Single Character from keyboard:
getchar():
getchar is a function in C programming language that reads a single character from the standard
input stream stdin, regardless of what it is, and returns it to the program. It is specified in ANSI-C and is the
most basic input function in C. It is included in the stdio.h header file.
The getchar function syntax is:
int getchar(void);
Eg:
#include <stdio.h>
int main()
{
char str[100];
int i=0,j=0;
printf("Enter the string into the file\n");
while((str[i]=getchar())!='\n')
i++;
str[i]='\0';
printf("\nThe string is - ");
while(str[j]!='\0')
{
putchar(str[j]);
j++;
}
}
getc():
It reads a single character from a given input stream and returns the corresponding integer value
(typically ASCII value of read character) on success. It returns EOF on failure.
Syntax:
int getc(FILE *stream);
Eg:
#include <stdio.h>
int main()
{
printf("%c", getc(stdin));
return(0);
}
Input: g (press enter key)
Output: g
getch():
getch() is a nonstandard function and is present in conio.h header file which is mostly used by
MS-DOS compilers like Turbo C. Like above functions, it reads also a single character from keyboard.
But it does not use any buffer, so the entered character is immediately returned without waiting for the
enter key.
Syntax:
int getch();
Eg:
#include <stdio.h>
#include <conio.h>
int main()
{
printf("%c", getch());
}

Aditya Degree College, GWK - By Mohana Roopa 1


I B.SC - 2 Semester (‘C’ Language) UNIT-4
Input: g (Without enter key)
Output: Program terminates immediately.
But when you use DOS shell in Turbo C,
it shows a single g, i.e., 'g'
getche():
Like getch(), this is also a non-standard function present in conio.h. It reads a single character
from the keyboard and displays immediately on output screen without waiting for enter key.
Syntax:
int getche(void);
Example:
#include <stdio.h>
#include <conio.h>
// Example for getche() in C
int main()
{
printf("%c", getche());
return 0;
}
Print a Single Character:
Putchar():
The putchar(int char) method in C is used to write a character, of unsigned char type, to stdout.
This character is passed as the parameter to this method. This function returns the character written on
the stdout as an unsigned char. It also returns EOF when some error occurs.
Syntax:
int putchar(int char);
Eg:
#include <stdio.h>
int main()
{
char ch = 'G';
putchar(ch);
}
Output:
G
putc():
putc() function is C library function, and it's used to write a character to the file. This function is
used for writing a single character in a stream along with that it moves forward the indicator's position.
Syntax:
int putc( int c, FILE * stream );
Eg:
int main (void)
{
FILE * fileName;
char ch;
fileName = fopen("anything.txt","wt");
for (ch = 'D' ; ch <= 'S' ; ch++) {
putc (ch , fileName);
}
fclose (fileName);
}

Aditya Degree College, GWK - By Mohana Roopa 2


I B.SC - 2 Semester (‘C’ Language) UNIT-4
Unit – IV
Pointers:
Understanding Computer Memory – Introduction to Pointers – declaring Pointer Variables –
Pointer Expressions and Pointer Arithmetic – Null Pointers – Generic Pointers - Passing Arguments to
Functions using Pointer – Pointer and Arrays – Passing Array to Function – Difference between Array
Name and Pointer – Pointers and Strings – Array of pointers – Pointer and 2D Arrays – Pointer and 3D
Arrays – Function Pointers – Array of Function Pointer – Pointers to Pointers – Memory Allocation in
C Programs – Memory Usage – Dynamic Memory Allocation – Drawbacks of Pointers
Structure, Union, and Enumerated Data Types:
Introduction – Nested Structures – Arrays of Structures – Structures and Functions – Self
referential Structures – Union – Arrays of Unions Variables – Unions inside Structures – Enumerated
Data Types

POINTER:
A pointer provides a way of accessing a variable without referring to the variable directly. A
pointer variable is a variable that holds the memory address of another variable. The pointer does not
hold a value. A pointer points to that variable by holding a copy of its address. It has two parts
1) the pointer itself holds the address
2) the address points to a value
Example
int a=5;
int* ptr;
ptr=&a;
About variable ―a:
1. Name of variable: a
2. Value of variable which it keeps: 5
3. Address where it has stored in memory: 1025 (assume)
About variable ―ptr:
1. Name of variable: ptr
2. Value of variable which it keeps: 1025
3. Address where it has stored in memory: 5000 (assume)

Declaring Pointer:
The pointer operator a variable in C is ‘*’ called “value at address” operator. It returns the
value stored at a particular memory the value at address operator is also called “indirection” operator a
pointer variable is declared by preceding its name with an asterisk(*) .
Syntax: datatype *pointer_variable;
Where datatype is the type of data that the pointer is allowed to hold and pointer_variable is
the name of pointer variable.
Example:
int *ptr;
char *p;
float *p1;
Initializing Pointers:
Aditya Degree College, GWK - By Mohana Roopa 3
I B.SC - 2 Semester (‘C’ Language) UNIT-4
A pointer must be initialized with a specified address operator to its use. For example to
store the address of I in p, the unary & operator is to be used.
P=&I;
Sample program:
main()
{
int num=5;
int *ptr=&num;
printf(“the address num is %p”,&num);
printf(“the address num is %p”,ptr);
}
Benefits of using pointers are:-
1) Pointers are more efficient in handling arrays and data tables.
2) Pointers can be used to return multiple values from a function via function arguments.
3) The use of pointer arrays to character strings results in saving of data storage space in memory.
4) Pointers allow C to support dynamic memory management.
5) Pointers provide an efficient tool for manipulating dynamic data structures such as structures ,
linked lists , queues , stacks and trees.
6) Pointers reduce length and complexity of programs.
7) They increase the execution speed and thus reduce the program execution time.

Arithmetic operations that can be performed on pointers:


 Like normal variables, pointer variables can be used in expressions.
Ex: x= (*p1) + (*p2); 
C language allows us to add integers to pointers and to subtract integers from pointers 
Ex: If p1, p2 are two pointer variables then operations such as p1+4, p2 - 2, p1 - p2 can
be performed.
Pointers can also be compared using relational operators. 
Ex: p1>p2, p1==p2, p1! =p2 are valid operations.
We should not use pointer constants in division or multiplication. Also, two pointers cannot be added.
p1/p2, p1*p2, p1/3, p1+p2 are invalid operations.
Pointer increments and scale factor:- Let us assume the address of p1 is 1002. After using p1=p1+1,
the value becomes 1004 but not 1003.
Thus when we increment a pointer, its values is increased by length of data type that points to.
This length is called scale factor.

Generic (or) Void pointer :


Void pointer is a specific pointer type – void * – a pointer that points to some data location in
storage, which doesn’t have any specific type. Void refers to the type. Basically the type of data that it
points to is can be any. If we assign address of char data type to void pointer it will become char
Pointer, if int data type then int pointer and so on. Any pointer type is convertible to a void pointer
hence it can point to any value.
Important Points
 void pointers cannot be de-referenced. It can however be done using typecasting the void pointer
 Pointer arithmetic is not possible on pointers of void due to lack of concrete value and thus size.
Example:
#include<stdlib.h>
int main()
{
int x = 4;
float y = 5.5;
//A void pointer

Aditya Degree College, GWK - By Mohana Roopa 4


I B.SC - 2 Semester (‘C’ Language) UNIT-4
void *ptr;
ptr = &x;
printf("Integer variable is = %d", *( (int*) ptr) );
// void pointer is now float
ptr = &y;
printf("\nFloat variable is= %f", *( (float*) ptr) );
}
Output:
Integer variable is = 4
Float variable is= 5.500000
NULL Pointer:
NULL Pointer is a pointer which is pointing to nothing. In case, if we don’t have address to be
assigned to a pointer, then we can simply use NULL.
1. NULL vs Uninitialized pointer – An uninitialized pointer stores an undefined value. A null
pointer stores a defined value, but one that is defined by the environment to not be a valid
address for any member or object.
2. NULL vs Void Pointer – Null pointer is a value, while void pointer is a type
Eg:
#include <stdio.h>
int main()
{
// Null Pointer
int *ptr = NULL;
printf("The value of ptr is %p", ptr);
}
Passing Arguments to Functions using Pointer:
Pointers provide a mechanism to modify data declared in one function using code written in
another function. In other words: if data is declared in func1 () and we want to write code in func2()
that modifies the data in func1(), then we must pass the addresses of the variables we want to change.

Eg: Write a program to add two integers using functions


#include <stdio.h>
void sum (int *a, int *b, int *t);
int main()
{
int numi, num2, total;
printf("\n Enter the first number: ");
scanf("%d", &numi);
printf("\n Enter the second number: ");
scanf("%d", &num2); sum (&numi, &num2, &total);
printf ("\n Total = %d", total);
}
void sum (int *a, int *b, int *t)
{
*t = *a + *b;
}
Output:
Enter the first number: 2
Enter the first number: 3
Total = 5

Aditya Degree College, GWK - By Mohana Roopa 5


I B.SC - 2 Semester (‘C’ Language) UNIT-4
Pointer and Arrays:
When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address i.e address of the first element of the array is also allocated by the
compiler.
Suppose we declare an array arr,
int arr[5] = { 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two bytes, the five elements will
be stored as follows:

we can use a pointer to point to an array, and then we can use that pointer to access the array
elements. Lets have an example,
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as
int*p = &a[0];
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
}
In the above program, the pointer *p will print all the values stored in the array one by one. We
can also use the Base address (a in above case) to act as a pointer and print all the values.
Pointers to two-dimensional arrays:-
Pointer can also be used to manipulate two-dimensional arrays.
Just like how x[i] is represented by
*(x+i) or *(p+i), similar, any element in a 2-d array can be represented by the pointer as follows.
*(*(a+i)+j) or *(*(p+i)+j)
The base address of the array a is &a[0][0] and starting from this address the complier allocates
contiguous space for all the element row – wise . i,e the first element of the second row is placed
immediately after the last element of the first row and so on
Ex:- suppose we declare an array as : int a[3][4]={{1,2,3,,4},{5,6,7,8},{9,10,11,12}};
The elements of a will be stored as shown below:

Base address =&a[0][0]


If we declare p as int pointer with the intial address &a[0][0] then a[i][j] is equivalent to *(p+4 x
i+j). You may notice if we increment „i‟ by 1, the p is incremented by 4, the size of each row.
Then the element a[2][3] is given by *(p+2 x 4+3) =*(p+11). This is the reason why when a two
–dimensional array is declared we must specify the size of the each row so that the complier can
determine the correct storage at mapping.

Aditya Degree College, GWK - By Mohana Roopa 6


I B.SC - 2 Semester (‘C’ Language) UNIT-4
Program:
/* accessing elements of 2 d array using pointer*/
#include<stdio.h>
void main()
{
int z[3][3]={{1,2,3},{4,5,6},{7,8,9}};
int i, j;
int *p;
p=&z[0][0];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("\n %d\ti=%d j=%d\t%d",*(p+i*3+j),i,j,*(*(z+i)+j));
}
for(i=0;i<9;i++)
printf("\n\t%d",*(p+i));
}
Array of Pointers(Pointer arrays):-
We have studied array of different primitive data types such as int, float, char etc. Similarly C
supports array of pointers i.e. collection of addresses.
Example :-
void main()
{
int *ap[3];
int al[3]={10,20,30};
int k;
for(k=0;k<3;k++)
ap[k]=al+k;
printf(“\n address element\n”);
for(k=0;k<3;k++)
{
printf(“\t %u”,ap[k]);
printf(“\t %7d\n”,*(ap[k]));
}
}
Pointers with String:
We can also use pointers with strings to perform any type of string manipulation in fact every
string is also gives address by itself. Hence while dealing with pointer strings no need to take the help
of address operator (&). We can declare a string pointer as follows.
Syntax: char *stringvariablename;
Eg: char *s;
The following program illustrates the use of pointers in strings.
#include<stdio.h>
void main()
{
char *s;
printf("Enter a string:");
scanf("%s",s);
printf("\n\n The string is:%s",s);
getch();
}

Aditya Degree College, GWK - By Mohana Roopa 7


I B.SC - 2 Semester (‘C’ Language) UNIT-4
Pointers to functions:-
A function, like a variable has a type and address location in the memory. It is therefore possible
to declare a pointer to a function, which can then be used as an argument in another function.
A pointer to a function can be declared as follows.
type (*fptr)();
This tells the complier that fptr is a pointer to a function which returns type value the
parentheses around *fptr is necessary. Because type *gptr(); would declare gptr as a function returning
a pointer to type.
We can make a function pointer to point to a specific function by simply assigning the name of
the function to the pointer.
Eg: double mul(int,int);
double (*p1)();
p1=mul();
It declares p1 as a pointer to a function and mul as a function and then make p1 to point to the
function mul.
To call the function mul we now use the pointer p1 with the list of parameters.
i,e (*p1)(x,y); //function call equivalent to mul(x,y);
Program:
double mul(int ,int);
void main()
{
int x,y;
double (*p1)();
double res;
p1=mul;
printf("\n enter two numbers:");
scanf("%d %d",&x,&y);
res=(*p1)(x,y);
printf("\n The Product of X=%d and Y=%d is res=%lf",x,y,res);
}
double mul(int a,int b)
{
double val;
val=a*b;
return(val);
}
pointer to pointer
It is possible to make a pointer to point to another pointer variable. But the pointer must be of a
type that allows it to point to a pointer. A variable which contains the address of a pointer. variable is
known as pointer to pointer. Its major application is in referring the elements of the two dimensional
array.
Syntax for declaring pointer to pointer,
int *p; // declaration of a pointer
int **q; // declaration of pointer to pointer
This declaration tells compiler to allocate a memory for the variable „q‟ in which address of a
pointer variable which points to value of type data type can be stored.
Syntax for initialization
q = & p;
This initialization tells the compiler that now „q‟ points to the address of a pointer variable „p‟.
Accessing the element value we specify, ** q;

Aditya Degree College, GWK - By Mohana Roopa 8


I B.SC - 2 Semester (‘C’ Language) UNIT-4
Example:-
void main( )
{
int a=10;
int *p, **ptr;
p = &a;
ptr = &p;
printf(“ \n the value of a =%d “, a);
printf(“ \n Through pointer p, the value of a =%d “, *p);
printf(“ \n Through pointer to pointer q, the value of a =%d “, **ptr);
}

Dynamic Memory Allocation:


Create memory at runtime by the programmer is known as “Dynamic Memory Allocation”. In
static memory allocation some amount of space is unused. This unused space is empty. But it is filled
with garbage values.
To avoid this problem, DMA technique was introduced. DMA allows allocating memory
at run time, so no memory will be wasted. Here we are using different functions for manipulate
memory. They are
1. malloc()
2. calloc()
3. realloc()
4. free()
malloc():
This function is used to allocate memory space in the form of bytes to the variables that
variables are of different data types. This functions reserves size of bytes for the variables and returns a
pointer to some amount of memory size. The memory pointed to will be on the heap, not on the stack,
so make sure to free it when you are doing this.
Syn: pointer variable=(data type*) malloc (given size);
Ex: ptr=(int*) malloc (n);
The following program illustrated about malloc()
Aim: To write a C program that allocates the memory dynamically.
#include<stdio.h>
void main()
{
int *a,n,i;
printf("\nEnter the size of the array:\n");
scanf("%d",&n);
a=(int *)malloc(n*sizeof(int));
//Reading array elemenents
printf("\nEnter array elements\n");
for(i=0;i<=n-1;i++)
scanf("%d",(a+i));
//Printing array elements
printf("\nThe array elements are....\n");
for(i=0;i<=n-1;i++)
printf("%d \t",*(a+i));
}
calloc ():
This function is useful for allocating multiple blocks of memory. It is declared with two
arguments. This function is usually used for allocating memory for array and structure. The calloc ()

Aditya Degree College, GWK - By Mohana Roopa 9


I B.SC - 2 Semester (‘C’ Language) UNIT-4
can be used in place of malloc () function. and returns starting address of the memory to the pointer
variable.
Syn: pointer variable= (datatype*) calloc (n,2);
Ex: ptr= (int*) calloc (4,2);
the above declaration allocates 4 blocks of memory, each block contains 2 bytes.
To write a C program that uses calloc ().
#include<stdio.h>
void main()
{
int *a,n,i;
printf("\nEnter the size of the array:");
scanf("%d",&n);
//allocating memory using calloc()
a=(int *)calloc(n,2);
printf("\nEnter the elements into the array\n");
for(i=0;i<=n-1;i++)
scanf("%d",(a+i));
printf("\nThe array elements are\n");
for(i=0;i<=n-1;i++)
printf("%d \t",*(a+i));
}
realloc():
This realloc() function is used to reallocates the memory i.e., enlarge the previously allocated
memory by malloc() or calloc() functions. It returns the address of the reallocated block, which can be
different from the original address. If the block cannot be reallocated realloc () returns NULL.
Syn: pointer_name=(data_type *) realloc( pointer_name, new_size);
Aim: To write a C program using realloc()
#include<stdio.h>
void main()
{
char *s;
//allocating memory for string 's'
s=(char *)malloc(6);
s="Bsc";
printf("\nBefore reallocating string:%s",s);
//reallocating memory of string 's'
s=(char *)realloc(s,15);
s="\n\nWelcome to Bsc";
printf("\n\nAfter reallocating string:%s",s);
getch();
}
free():
The free() function is used to release the memory allocated by memory allocating functions.
Thus, using this function wastage of memory is prevented.
Syn: free(pointer variable);
Aim: To write a C program that uses free()
#include<stdio.h>
void main()
{
char *s;

Aditya Degree College, GWK - By Mohana Roopa 10


I B.SC - 2 Semester (‘C’ Language) UNIT-4
//allocating memory for string 's'
s=(char *)malloc(6);
s="Computers";
printf("\nBefore reallocating string:%s",s);
//reallocating memory of string 's'
s=(char *)realloc(s,15);
s="\n\nWelcome to Computers";
printf("\n\nAfter reallocating string:%s",s);
free(s);
getch();
}
Differentiate between static and dynamic memory allocation:
Memory can be reserved for the variables either during the compilation time or during execution
time. Memory can be allocated for variables using two different techniques:
1. Static allocation
2. Dynamic allocation
1) Static allocation:
If the memory is allocated during compilation time itself, the allocated memory space cannot be
expanded to accommodate more data or cannot be reduced to accommodate less data.
In this technique once the size of the memory is allocated it is fixed. It cannot be altered even
during execution time. This method of allocating memory during compilation time is called static
memory allocation.
2) Dynamic allocation:
Dynamic memory allocation is the process of allocating memory during execution time. This
allocation technique uses predefined functions to allocate and release memory for data during execution
time.
Static memory Allocation Dynamic Memory Allocation

Drawbacks of pointers in c:
 Uninitialized pointers might cause segmentation fault.
 Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to memory
leak.
 Pointers are slower than normal variables.
 If pointers are updated with incorrect values, it might lead to memory corruption.
Basically, pointer bugs are difficult to debug. Its programmers responsibility to use pointers effectively
and correctly.

Aditya Degree College, GWK - By Mohana Roopa 11


I B.SC - 2 Semester (‘C’ Language) UNIT-4
Structures and Unions
Structures are introduced to combine different data types into single block. We can access
entire block of data with the structure. It can store different data elements information as a single
unit.
Definition of Structure:
Structure is a user defined data type and it is a combination of different data types called as
members. All these members are referred by a single name known as structure name. Structure can be
placed before or within the main.
Syntax to Create Structure:
struct tagname
{
data type member 1;
…………..
data type member n;
};
We can access the members of structures using structure variable. This structure variable should
be created after completion of structure definition. We can create structure variable in two ways.
Structure variable can be created as follows:
Syntax: struct tagname(structurename) structure_variable_name;
Ex: struct student s;
We can also create the structure variable along with the structure definition as follows:
Syntax:
struct tagname
{
data type member 1;
…………..
data type member n;
}structure variable name;
Accessing members of a Structure:
We can access members of structure by using dot (.) operator along with the structure variable
name.
Syntax: structure_variable_name.member;
Ex: e.eno;
e.name;
e.sal;

Aim: To write a C-Program to read and print an employee data using structure.
Program:
#include<stdio.h>
struct Employee
{
int eno;
char ename[20];
Aditya Degree College, GWK - By Mohana Roopa 12
I B.SC - 2 Semester (‘C’ Language) UNIT-4
int esal;
};
void main()
{
struct Employee e;
clrscr();
printf("\nEnter Employee Number:");
scanf("%d",&e.eno);
printf("\nEnter Employee Name:");
scanf("%s",&e.ename);
printf("\nEnter Employee Salaray:");
scanf("%d",&e.esal);
printf("\n\nThe Employee Details are....\n");
printf("Employee Number:%d",e.eno);
printf("\nEmployee Name:%s",e.ename);
printf("\nEmployee Salary:%d",e.esal);
getch();
}
Array of Structures:
Array is a collection of similar data types. In the same way we can also define array of
structures. In this structure array, every element is of structure type. The array of structure is declared as
follows
Syntax: struct tagname
{
Data type member1;
Data type member2;
--------------------------
---------------------------
}array variable name[3];
Ex: struct emp
{
int eno;
char name[20];
float sal;
}e[10];
In the above example e[10] is an array of 10 elements containing 10 objects of type
structure. Each element of e[10] has structure type with three members that are eno,ename and
esal.
The following program illustrates the above concept.
Aim:
To Write a C-Program that creates a structure of 10 students having student number (sno),
student name (sname), marks in three subjects (m1,m2,m3), total marks of the students (tot) and
average (avg) and display the names of failed students.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
struct Student
{
int sno;
char sname[20];

Aditya Degree College, GWK - By Mohana Roopa 13


I B.SC - 2 Semester (‘C’ Language) UNIT-4
int m1,m2,m3;
int tot,avg;
};
int n,i;
struct Student s[10];
clrscr();
printf("\nEnter the Number of Students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter %d Student Details\n",i+1);
printf("Student Number:");
scanf("%d",&s[i].sno);
printf("Student Name:");
scanf("%s",&s[i].sname);
printf("Student Three Subjects Marks\n");
scanf("%d%d%d",&s[i].m1,&s[i].m2,&s[i].m3);
s[i].tot=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].tot/3;
}
printf("\n\nThe failed students are...\n");
for(i=0;i<n;i++)
{
if(s[i].avg<35)
printf("%s\n",s[i].sname);
}
getch();
}

Pointer to Structures:
Pointer is a variable can store the address of another variable .The variable may be of any data
type. In the same way we can also define pointer to structure. Here, starting address of the member
variables can be accessed. Thus, such pointers are called structure pointers.
Ex: Struct book
{
char name[25];
char author[25];
int pages;
};struct book *ptr;
In the above example *ptr is pointer to structure book. The syntax for using pointer with member is as
given below
1) ptr-> name 2) ptr -> author 3) ptr -> pages

Structure and Functions:


Like variables of standard data type structure variables also can be passed to the function by
value or address. The syntax for the same is as follows
Syntax:
struct tagname
{
Data type member1;
Data type member 2;
---------------------------
---------------------------
Aditya Degree College, GWK - By Mohana Roopa 14
I B.SC - 2 Semester (‘C’ Language) UNIT-4
}Structure_variable_name;
void main()
{
<return type> <function name>( struct tagname[], argument list);//Protoype of function
------------------------------------------------------------------------
------------------------------------------------------------------------
------------------------------------------------------------------------
function name( structure variable, argument list);//Function caller
}
<return type> <function name>( struct tagname structure array variable name, argument list)

{
-----------------------------------------
------------------------------------------
------------------------------------------
}
Example:
struct book
{
char name[20];
char author[20];
int pages;
}b1;
void main()
{
void show(struct book);//Prototype
---------
---------
show(b1);//Caller
---------
---------
}
void show(struct book b2)//Callee
{
-------
-------
}
Whenever a structure element is to be passed to any other function, it is essential to declare the
structure outside the main() function i.e., global.
The following program illustrates the above concept.
Aim: To write a C program to find the sum of two complex numbers.
Program:
#include<stdio.h>
#include<conio.h>
struct Complex
{
int real;
int img;
};
void f1(struct Complex x1,struct Complex x2)
{
struct Complex x3;
x3.real=x1.real + x2.real;
Aditya Degree College, GWK - By Mohana Roopa 15
I B.SC - 2 Semester (‘C’ Language) UNIT-4
x3.img=x1.img + x2.img;
printf("\n The Complex Sum is: %d+i%d",x3.real,x3.img);
}
void main()
{
struct Complex c1,c2;
clrscr();
printf("\nEnter the real and imag parts of first Complex Number:\n");
scanf("%d%d",&c1.real,&c1.img);
printf("\nEnter the real and img parts of second Complex Number:\n");
scanf("%d%d",&c2.real,&c2.img);
f1(c1,c2);
getch();
}

Unions:
A union is a user defined data type available in C that enables us to store different data types in
the same memory location. We can define a union with many members, but only one member can
contain a value at any given time. Unions provide an efficient way of using the same memory location
for multi-purpose.
Defining a Union
To define a union, we must use the union statement. The format of the union statement is
as follows:
union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
Example:
union Data
{
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters.
The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in above example Data type will occupy 20 bytes of memory space because this is the
maximum space which can be occupied by character string.
Following is the example which will display total memory size occupied by the above union:

#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};

Aditya Degree College, GWK - By Mohana Roopa 16


I B.SC - 2 Semester (‘C’ Language) UNIT-4

int main( )
{
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
When the above code is compiled and executed, it produces the following result:
Memory size occupied by data : 20

Accessing Union Members


To access any member of a union, we use the member access operator (.).
Following is the example to explain usage of union:
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}

Enumerated Data types in C:


Enumeration type allows programmer to define their own data type . Keyword “enum” is used
to defined enumerated data type.
enum type_name{ value1, value2,...,valueN };
Here, type_name is the name of enumerated data type or tag and value1, value2,....,valueN are
values of type type_name.
By default, value1 will be equal to 0, value2 will be 1 and so on but, the programmer can change
the default value as below:
enum suit{
club=0;
diamonds=10;
hearts=20;
spades=3;
};

Declaration of enumerated variable


The above code defines the type of the data but, no variable is created for the enum data type.
The following will shows the creation of a variable of type enum.
enum boolean{
false;
Aditya Degree College, GWK - By Mohana Roopa 17
I B.SC - 2 Semester (‘C’ Language) UNIT-4
true;
};
enum boolean check;
Here, a variable check is declared which is of type enum boolean.

Example of enumerated type


#include <stdio.h>
enum week
{
sunday, monday, tuesday, wednesday, thursday, friday, Saturday
};
int main(){
enum week today;
today=wednesday;
printf("%d day",today+1);
return 0;
}
Output
4 day
We can write any program in C language without the help of enumerations but, enumerations
helps in writing clear codes and simplify programming.

Difference between structures and unions:

Aditya Degree College, GWK - By Mohana Roopa 18

You might also like