0% found this document useful (0 votes)
8 views

C language Unit-4 notes

The document outlines the concept of functions in C programming, detailing their definition, declaration, and usage. It explains the benefits of using functions, such as code reusability and modularity, and describes different types of user-defined functions and parameter passing methods. Additionally, it covers variable scope, storage classes, and provides example programs to illustrate these concepts.

Uploaded by

sainaagin123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

C language Unit-4 notes

The document outlines the concept of functions in C programming, detailing their definition, declaration, and usage. It explains the benefits of using functions, such as code reusability and modularity, and describes different types of user-defined functions and parameter passing methods. Additionally, it covers variable scope, storage classes, and provides example programs to illustrate these concepts.

Uploaded by

sainaagin123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc.

, II Semester

Unit – IV
Syllabus:

FUNCTIONS
INTRODUCTION: -
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. “A function is a self-contained
program segment that carries out some specific task.” A function can be called multiple times to provide
reusability and modularity to the C program. In other words, we can say that the collection of functions
creates a program. The function is also known as procedure or sub-routine in other programming languages.

USES OF C FUNCTIONS:
• C functions are used to avoid rewriting same logic/code again and again in a program.
• There is no limit in calling C functions to make use of same functionality wherever required.
• We can call functions any number of times in a program and from any place in a program.
• Easy to read, write and debug a function.
• Easier to maintain or modify such a function.
• Function increases the execution speed of the program.
• A Function may be used by many other programs.
• The length of the source program can be reduced using functions.
• A function increases the modularity of program.
• Function reduces the amount of work and development time.

C FUNCTION DECLARATION, FUNCTION CALL AND FUNCTION DEFINITION:


There are 3 aspects in each C function. They are,

• Function declaration or prototype– This informs compiler about the function name, function parameters
and return value’s data type.
• Function call – This calls the actual function
• Function definition – This contains all the statements to be executed.

Department of Computer Science Page 1


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

C functions aspects Syntax

Return_type function_name (arguments list)


{
function definition Body of function;
}
function call function_name (arguments list);

function declaration return_type function_name (argument list);

FUNCTION DEFINITION:
When a function is defined, space is allocated for the function in the memory. Function definition contains
two parts
• Function header
• Function body
Syntax:
Return_ type function_name(list of parameters) //Function header
{
:
:
Statements //function body
:
Return(variable);
}
List of parameters in the function header are called as formal parameters. The parameter list may contain
zero or more parameters.
The function body contains set of instructions to perform the desired task.
The function can be defined either before or after the main(). If it is defined before main(), then function
definition itself act as a function declaration. So in this situation we can skip the function declaration.
SIMPLE EXAMPLE PROGRAM FOR C FUNCTION:
• As you know, functions should be declared and defined before calling in a C program.
• In the below program, function “square” is called from main function.
• The value of “m” is passed as argument to the function “square”. This value is multiplied by itself
in this function and multiplied value “p” is returned to main function from function “square”.
#include<stdio.h>
// function prototype, also called function declaration
float square (float x);
// main function, program starts from here

int main( )
{
float m, n;
printf ("\nEnter some number for finding square \n");

Department of Computer Science Page 2


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

scanf ("%f", &m);


// function call
n = square (m);
printf (“ \nSquare of the given number %f is %f",m,n );
}

float square (float x) // function definition


{
float p ;
p=x*x;
return ( p ) ;
}
Output:
Enter some number for finding square
2
Square of the given number 2.000000 is 4.000000

FUNCTION CALL:
The function call invokes the function. When the function is invoked the compiler jumps to the function
definition to execute the statements in the function. Once the called function is executed, the program
control passes back to the function call.
Syntax:
Function_name(list of parameters);
The list of parameters in the function call are called as actual parameters.
While calling a function, the points to be remembered is
“The function name and the number and type of the actual parameters in the function call should be
same as that given in the function definition.”
• Number of actual parameters =number of formal parameters
• Data Type of actual parameters = data type of formal parameters
• Order of actual parameters =order of formal parameters

Types of user-defined functions:


The user-defined function may be classified into 4 ways based on the passing of the formal
arguments and uses of the return statements.
1. Function with no argument and no return statement
2. Function with arguments and no returns value.
3. Function with arguments and returns value.
4. Function with no argument and return value.
Function with no argument and no return statement:
It is the simplest way of writing a user-defined function in 'C'. When a function has no arguments,
it does not receive any data from the calling function. Similarly, when it does not return a value, the called
function. In effect, there is no data communication between a calling function of a program and a called

Department of Computer Science Page 3


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

function. A calling environment invokes the function but not feeding any formal arguments and the
functions also does not return back anything to the caller.
Example:
void display();
main( )
{
display( );
}
void display( )
{
printf("Hello");
}
Output:
Hello
Function with arguments and no returns value:
The second type of writing a user-defined function is passing some formal arguments to a
function but the function does not return back any value to the caller. It is also a one way data
communication between calling function and the called function.
Example:
void square(int a);
main( )
{
int x;
x = 5;
square(x);
}
void square(int a)
{
int c;
c = a * a;
printf(" The result=%d", c);
}
Output:
The result=25

Function with arguments and returns value:


The third type of user-defined function is passing some formal arguments to a function
from calling portion of the program and the computed values, if any- is transferred back to the caller. Data is
communicated between calling portion and a function block.
Example:
int square(int a);
main( )
{
int x, ans;
x = 5;
ans = square(x);
printf(" The result=%d", ans);
}

Department of Computer Science Page 4


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

int square(int a)
{
int c;
c = a * a;
return c;
}
Output:
The result=25
Function with no arguments and returns value:
The fourth type of user-defined function is no passing formal arguments to a function
from calling portion of the program and the computed values, if any- is transferred back to the caller. Data is
communicated between calling portion and a function block.
Example:
int square();
main( )
{
int ans;
ans = square();
printf(" The result=%d", ans);
}

int square()
{
int c, a=5;
c = a * a;
return c;
}
Output:
The result=25

PASSING PARAMETERS TO THE FUNCTION:


There are two ways that a C function can be called from a program. They are,
1. Call by value
2. Call by reference
1. CALL BY VALUE:
• In call by value method, the value of the variable is passed to the function as parameter.
• The value of the actual parameter cannot be modified by formal parameter.
• Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter
is copied to formal parameter.
EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY VALUE):
• In this program, the values of the variables “m” and “n” are passed to the function “swap”.
• These values are copied to formal parameters “a” and “b” in swap function and used.
#include<stdio.h>
Department of Computer Science Page 5
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

// function prototype, also called function declaration


void swap(int a, int b);
int main()
{
int m = 22, n = 44;
// calling swap function by value
printf(" values before swap m = %d \nand n = %d", m, n);
swap(m, n);
}

void swap(int a, int b)


{
int tmp;
tmp = a;
a = b;
b = tmp;
printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}
OUTPUT:
values before swap m = 22
and n = 44
values after swap m = 44
and n = 22

2. CALL BY REFERENCE:
• In call by reference method, the address of the variable is passed to the function as parameter.
• The value of the actual parameter can be modified by formal parameter.
• Same memory is used for both actual and formal parameters since only address is used by both
parameters.
EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY REFERENCE):
• In this program, the address of the variables “m” and “n” are passed to the function “swap”.
• These values are not copied to formal parameters “a” and “b” in swap function.
• Because, they are just holding the address of those variables.
• This address is used to access and change the values of the variables.
#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b);
int main()
{
int m = 22, n = 44;
// calling swap function by reference
printf("values before swap m = %d \n and n = %d",m,n);
swap(&m, &n);
}
void swap(int *a, int *b)
Department of Computer Science Page 6
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
printf("\n values after swap a = %d \nand b = %d", *a, *b);
}
OUTPUT:

values before swap m = 22


and n = 44
values after swap a = 44
and b = 22

Return statement:
The return statement is used to return some value or simply pass the control to the calling function. The
return statement can be used in the following two ways.
1.return;
2.return expression;

The first form of the return statement is used to terminate the function and pass the control to the calling
function. No value from the called function is returned when this form of the return statement is used.

void main()
{
int sum=sumDigits();
printf(“%d\n”,sum);
return;
}

int sumDigits()
{
int sum=0;
int digit;
for(digit=0;digit<=9;digit++)
{
sum+=digit;
}
return sum;
}
The function main is called when our program is started. Then it calls the routine sumDigits. At this point
“main” is paused and sumDigits starts. The second function will do its calculations and reach
the return sum; statement. Here it ends and the control is transferred back in main. Since sumDigits returns a
value(the value of the sum variable), a value will appear in the place where the function was called.

Department of Computer Science Page 7


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

The sum of the digits is 0+1+2…+9= 45. This value will appear in the place of invocation and the variable
sum will take this value. Then we print that value and return from the main function, which ends our program.

Scope of a variable:

A scope in any programming is a region of the program where a defined variable can have its existence and
beyond that variable it cannot be accessed. There are three places where variables can be declared in C
programming language −
• Inside a function or a block which is called local variables.
• Outside of all functions which is called global variables.
• In the definition of function parameters which are called formal parameters.
Let us understand what are local and global variables, and formal parameters.
Local Variables:
variables that are declared inside a function or block are called local variables. They can be used only by
statements that are inside that function or block of code. Local variables are not known to functions outside
their own. The following example shows how local variables are used. Here all the variables a, b, and c are
local to main() function.
Live Demo

#include<stdio.h>
int main()
{
/*local variable declaration */
int a,b;
int c;
/*actual initialization*/
a=10;
b=20;
c=a+b;
printf(“value of a=%d,b=%d and c=%d\n”,a,b,c);
return 0;
}

Global variables:
Global variables are defined outside a function, usually on top of the program. Global variables hold their
values throughout the lifetime of your program and they can be accessed inside any of the functions defined
for the program.
A global variable can be accessed by any function. That is, a global variable is available for use throughout
your entire program after its declaration. The following program show how global variables are used in a
program.

Department of Computer Science Page 8


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

#include<stdio.h>
/* global variable declaration*/
int g;
int main()
{
/* local variable declaration*/
int a,b;
/*actual initialization*/
a=10;
b=20;
g=a+b;
printf(“value of a=%d,b=%d and g=%d\n”,a,b,g);
return 0;
}

Storage Classes in C
Each variable has a storage class which defines the features of that variable. It tells the compiler about where
to store the variable, its initial value, scope (visibility level) and lifetime (global or local).
There are four storage classes in C.
• auto
• extern
• static
• register

Auto Storage class:


The auto storage class is the default storage class for all local variables.
int mount;
auto int month;
The example above defines two variables with in the same storage class. 'auto' can only be used within
functions, i.e., local variables.
Register storage class:

Department of Computer Science Page 9


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

The register storage class is used to define local variables that should be stored in a register instead of RAM.
This means that the variable has a maximum size equal to the register size (usually one word) and can't have
the unary '&' operator applied to it (as it does not have a memory location).
register int miles;
The register should only be used for variables that require quick access such as counters. It should also be
noted that defining 'register' does not mean that the variable will be stored in a register. It means that it
MIGHT be stored in a register depending on hardware and implementation restrictions.
Static storage class:
The static storage class instructs the compiler to keep a local variable in existence during the life-time of the
program instead of creating and destroying it each time it comes into and goes out of scope.
#include<stdio.h>
#include<conio.h>
void increment();
void main()
{
increment();
increment();
increment();
increment();
getch();
}
void increment()
{
static int i=0;
printf(“%d”,i);
i++;
}
Extern Storage Class:

The extern storage class is used to give a reference of a global variable that is visible to ALL the program
files. It is equivalent to global variable.

#include<stdio.h>
#include<conio.h>
int x=20;
void main()
{
extern int y;
printf(“The value of x is %d\n”,x);
printf(“The value of y is %d”,y);
getch();
}
int y=30;

Department of Computer Science Page 10


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

output:

The value of x is 20
The value of y is 30

Comparison of Storage Classes:

Recursive Functions:

Recursion is the process which comes into existence when a function calls a copy of itself to work on a smaller
problem. Any function which calls itself is called recursive function, and such function calls are called
recursive calls. Recursion involves several numbers of recursive calls. However, it is important to impose a
termination condition of recursion. Recursion code is shorter than iterative code however it is difficult to

understand.

#include<stdio.h>
int fact(int);
int main()
{
int n,f;
printf(“enter the number whose factorial you want to calculate”);
f=fact(n);
printf(“factorial=%d”,f);
}
int fact(int n)

Department of Computer Science Page 11


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

{
if(n==0)
{
return 0;
}
else if(n==1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}

Structure, Union and Enumerated Datatype:


Structure:
A structure is a user defined data type in C. A structure is a collection of variables of different data types under
a single name.

Structure can be defined in 2 ways

Department of Computer Science Page 12


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

1.Tagged Structure 2. Typedefined structure


Tagged structure typedefined structure
Syntax: Syntax:
Struct tag typedef struct
{ {
Field list; field list;
} }
Ex: Ex:
struct student typedef struct
{ {
int sno; int sno;
char name[20]; char name[20];
float fees; float fees;
char DOB[10]; char DOB[10];
}; }student;

How to create a structure?


‘struct’ keyword is used to create a structure. Following is an example.
struct student
{
char student_name[10];
char roll_no[5];
float percent;
};

How to declare structure variables?


A structure variable can either be declared with structure declaration or as a separate declaration like basic
types.
Tagged typedefined
struct student s; student s;

// A variable declaration with structure declaration.


struct Point

Department of Computer Science Page 13


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

{
int x, y;
} p1; // The variable p1 is declared with 'Point'

// A variable declaration like basic data types


struct point
{
int x, y;
};

int main()
{
struct point p1; // The variable p1 is declared like a normal variable
}
How to initialize structure members?
Structure members cannot be initialized with declaration. The initializers or values are enclosed in braces and
separated by commas
Ex: student s={172,”raj”,10000.0,”01-Aug-90”};

For example the following C program fails in compilation.


struct point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
The reason for above error is simple, when a datatype is declared, no memory is allocated for it. Memory is
allocated only when variables are created.
Structure members can be initialized using curly braces ‘{}’. For example, following is a valid initialization.
struct point
{
int x, y;
};

int main()
{
// A valid initialization. member x gets value 0 and y
// gets value 1. The order of declaration is followed.
struct point p1 = {0, 1};

}
How to access structure elements?
Structure members are accessed using dot (.) operator.
#include<stdio.h>

Department of Computer Science Page 14


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

struct point
{
int x, y;
};

int main()
{
struct point p1 = {0, 1};

// Accessing members of point p1


p1.x = 20;
printf ("x = %d, y = %d", p1.x, p1.y);

return 0;
}

Output:

x=20,y=1

Initializing Structure members:

We can initialize structure members like this

struct car

char name[100];

float price;

};

struct car car1={“xyz”,987432.50};

//car1 name as “xyz”

//price as 987432.50

HOW to acess the structure members?

To acess the structure members we have to use dot(.)operator.


It is also called member acess operator.
To access the price of car1,

Department of Computer Science Page 15


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

car1.price
To access the name of car1,
car1.name
#include<stdio.h>
int main()
{

struct car
{

char name[100];
float price;

}
//car1.name->”xyz”
//car1.price->987432.50
struct car car1={“xyz”,987432.50};
//printing values using dot(.)operator or member acess operator

printf(“name of car1=%s\n”,car1.name);
printf(“price of car1=%f\n”,car1.price);
return 0;

}
Program: To read and display the information about a structure
#include<stdio.h>
main()
{
typedef struct
{

int sno;
char name[25];
float fees;
char DOB[10];

}student;

student s1;
printf(“\n Enter the rollno:”);

Department of Computer Science Page 16


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

scanf(“%d”,&s1.sno);
printf(“\n Enter name:”);
scanf(“%s”,s1.name);
printf(“\n Enter DOB”);
scanf(“%s”,s1.DOB);
printf(“\n Enter fee”);
scanf(“%f”,&s1.fees);
printf(“\n *******STUDENT DETAILS********”);
printf(“\n ROLL NO=%d”,s1.sno);
printf(“\n NAME=%s”,s1.name);
printf(“\n FEES=%f”,s1.fees);
printf(“\n DOB=%s”,s1.DOB);

Nested structures
A structure can be placed within another structure. Ie a structure may contain another structure as its membe
r. A structure that contains another structure as its member is called NESTED STRUCTURE.
Ex:

struct address
{

char city[20];
int pin;
char phone[14];

};
struct employee
{

char name[20];
struct address add;

};
void main()
{

struct employee emp;


printf(“enter employee information\n”);
scanf(“%s %d %s”,emp.name,emp.add.city,&emp.add.pin,emp.add.phone);
printf(“printing the employee information”);

Department of Computer Science Page 17


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

printf(“name:%s\ncity:%s\npincode:%d\nphone:%s”,emp.name,emp.add.city,emp.add.city,emp.add.
pin,emp.add.phone);

C provides us the feature of nesting one structure within another structure by using which, complex data typ
es are created. For example, we may need to store the address of an entity employee in a structure. The attrib
ute address may also have the subparts as street number, city, state, and pin code. Hence, to store the address
of the employee, we need to store the address of the employee into a separate structure and nest the structure
address into the structure employee.
Enter employee information

Arun

Delhi

110001

1234567890

Printing the employee information....

name: Arun

City: Delhi

Pincode: 110001

Phone: 1234567890

Array of structures

Structure is collection of different data type. An object of structure represents a single record in me
mory, if we want more than one record of structure type, we have to create an array of structure or object. As
we know, an array is a collection of similar type, therefore an array can be of structure type.

Syntax for declaring array of structures:

struct struct_name
{

data type var1;


data type var2;
………….

Department of Computer Science Page 18


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

…………
data type varn;

}
struct struct-name obj[size];

Example for declaring structure array


#include<stdio.h>
struct employee
{

int id;
char name[25];
int age;
long salary;

};
void main()
{

int i;
struct employee emp[3];
for(i=0;i<3;i++)
{

printf(“enter details of %d employee”i+1);


printf(“\n\t enter employee id”);
scanf(“%d”,&emp[i].id);
printf(“\n\t enter employee name”);
scanf(“%d”,&emp[i].name);
printf(“\n\t enter employee age”);
scanf(“%d”,&emp[i].age);
printf(“\n\t enter employee salary”);
scanf(“%d”,&emp[i].salary);

}
printf(“details of employees”);
for(i=0;i<3;i++)
printf(“\n%d\t%s\t%d\t%ld”,emp[i].id,emp[i].age,emp[i].salary);

}
Output:
Enter details of 1 Employee

Department of Computer Science Page 19


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

Enter Employee Id:101


Enter Employee Name:Suresh
Enter Employee Age:29
Enter Employee Salary:45000

Enter details of 2 Employee


Enter Employee Id:102
Enter Employee Name:Mahesh
Enter Employee Age:30
Enter Employee Salary:48000

Enter details of 3 Employee


Enter Employee Id:103
Enter Employee Name:Naresh
Enter Employee Age:38
Enter Employee Salary:50000

Details of Employees

101 Suresh 29 45000


102 Mahesh 30 48000
103 Naresh 38 50000

In the above example, we are getting and displaying the data of 3 employee using array of object. Statement
1 is creating an array of Employee Emp to store the records of 3 employees.
Structures and Functions
A function may access the member of a structure in 3 ways

Passing individual members

Passing structures to
function Passing the entire structure

Passing the address of the structure

1 Passing individual members:

#include<stdio.h>
typedef struct
{

Department of Computer Science Page 20


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

int x;
int y;

}point;
void disp(int,int);
main()
{

point p1={2,3};
disp(p1.x,p1.y);

}
void disp(int a,int b)
{
printf(“%d%d”,a,b);
}

Output:

23

2. Passing the entire structure:


An entire structure can be passed to a function as a other variable. It is passed by call by value method.
Ex: #include<stdio.h>

typedef struct
{

int x;
int y;

}point;
void disp(point);
main()
{

point p1={2,3};
disp(p1);

}
void disp(point m)
{
printf(“%d%d”,m.x,m.y);

Department of Computer Science Page 21


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

Output:

23

3.Passing the address of the structure:


It is called call by reference method
#include<stdio.h>

typedef struct
{

int x;
int y;

}point;
void disp(point * m);
main()
{

point p1={2,3};
disp(&p1);

}
void disp(point *m)
{
printf(“%d%d”,m->x,m->y);
}

Output:

23

Unions in C
A union is a special data type available in C that allows to store different data types in the same memory loc
ation. You can define a union with many members, but only one member can contain a value at any given ti
me. Unions provide an efficient way of using the same memory location for multiple-purpose.

Department of Computer Science Page 22


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

A union is a memory location that is shared by 2 or more different types of variables. Declaring a union is simi
lar to Structures.

union tag typedef union


{ {

Type member name; Type member name;


Type member name; Type member name;
: :

}union_variable; }union_name;

Ex: typedef union


{
int i;
char ch;
}u_type;
u_type xyz;
u_type *p;

in xyz, both i and ch share the same memory location. i occupies 2 bytes, ch uses only 1 byte.

When a union variable ie xyz is declared, the complier automatically allocates enough storage to hold the large
st memory of the union.
To access the member of a union, the same syntax of structure is used

• Dot operator
• Arrow operator

Ex:

• xyz,i=10;
• p=&xyz; p->i=20;

Department of Computer Science Page 23


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

Array of union variable:


Like array of structures we can also create array of unions and access them in similar way. When array of
unions are created it will create each element of the array as individual unions with all the features of union.
That means, each array element will be allocated a memory which is equivalent to the maximum size of the
union member and any one of the union member will be accessed by array element.

union category
{
int class;
char deptid[10];
};
union category catg[10]; //creates an array of unions with 10 elements of union type.

Unions Inside Structures:

Unions can be very useful when declared inside a structure. Consider an example

#include<stdio.h>
struct stud
{
union
{
char name[20];
int rno;
};
int marks;
};
main()
{
struct stud s;
char c;
printf(“|n u can enter name or roll number of the student”);
printf(“\n Do u want to enter the name? (y or n):”);
gets(c);
if(c==’y’||c==’Y’)
{
printf(“\nEnter the name:”);
gets(s.name);
}
else
{
printf(“\n Enter roll number:”):
scanf(“%d”,&s.rno);
}
printf(“\n Enter the marks:”);
scanf(“%d”,&s.marks);
Department of Computer Science Page 24
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

if(c==’y’||c==’Y’)
printf(“\n Name:%s”,s.name);
else
printf(“\n roll number{%d”,s.rno);
printf(“\n Marks:%d”,s.marks);
return 0;
}

Department of Computer Science Page 25


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

Enumerated Data types

Enumerated Data Type:

Enumeration is a user defined datatype in C language. It is used to assign names to the integral constants
which makes a program easy to read and maintain. The keyword “enum” is used to declare an enumeration.
Each integer value is given an identifier called enumeration constant.
Here is the syntax of enum in C language,
Enum enum_name{const1,const2,…};
The enum keyword is also used to define the variables of enum type. There are two ways to define the variables
of enum type as follows.

1.enum week{Sunday,Monday,Tuesday,wenesday,Thursday,Friday,Saturday};
enum week day;
2 enum color{red,blue,green,white};
Now we can define variables of type color
enum color x;
enum color y;
enum color z;
Assigning values to enumerated type
• x=blue;
z=purple;//error-coz there is no purple color in the list
• x=y;
z=y;
Comparing enumerated types
• if (x==y)
• if (x==blue)
• enum month{jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec};
Ex:
enum month x;
:
:
switch(x)
{
case jan:---
break;
case feb:----
break;
:
:
}

Enumeration type Conversion:


int x;
enum color y;
Department of Computer Science Page 26
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

x=blue;//valid coz x contains 1


here, the compiler implicitly casts an enumerated type to an integer.
• when implicit casting, an integer to an enumerated type we get warning or an error.
Ex:
int x;
enum color y;
y=2;//compiler error
y=(enum color)2;//valid coz y contains blue
Initializing:

The Compiler automatically assigns values to enumerated type starting with ‘0’ & we can over ride it &assigns
our own value.
Ex:
• Enum month{jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec};
This jan is assigned the value 0
Fed is assigned the value 1 & soon until dec with 11.
• To make Jan start with 1, we can declare
Enum month{jan=1,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec};
The rest will be automatically assigned by the compiler.
I/P-O/P Operation:
When we read an enumerated type, we must read it as an integer. When we write it, it displays as an integer.
Ex:
main()
{
enum month{jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec};
enum months a,b;
printf(“\n Enter a and b values:”);
scanf(“%d%d”,&a,&b); //enter 1,11
printf(“%d%d”,a,b);
}

O/P:
Enter a and b value
1
11
111

2.Print selected TV station for our TV

#include<stdio.h>
main()
{
enum tv{maa=17,abc=11,espn=39,hbo=15,bbc=21};
printf(“Here are my favorite cable stations:\n”);
printf(“maa=%d\n”,maa);
printf(“abc=%d\n”,abc);
printf(“espn=%d\n”,espn);
printf(“hbo=%d\n”,hbo);

Department of Computer Science Page 27


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

printf(“bbc=%d\n”,bbc);
}

O/P:
Here are my favorite cable stations:
maa=17
abc=11
espn=39
hbo=15
bbc=21

Department of Computer Science Page 28

You might also like