You are on page 1of 38

Unit-V GE6151- COMPUTER PROGRAMMING

UNIT V - STRUCTURES AND UNIONS


Introduction – need for structure data type – structure definition – Structure
declaration – Structure within a structure - Union - Programs using structures and
Unions – Storage classes, Pre-processor directives.
5.1 STRUCTURES-INTRODUCTION:
 Structure is a collection of one or more variables of different data types grouped under
common name.
 Suppose Student record is to be stored, then for storing the record we have to group together
all the information such as Roll,name, marks which may be of different data types, structure
can be used for storing different variables under single name.
Syntax:
Structstructure_name
{
data_type1 member1;
data_type2 member2;
data_type3 member3;
};
 Each member declared in Structure is called member.
 Name given to structure is called as tag or structure_name
 Struct keyword is used to declare structure.
 Members of structure are enclosed within opening and closing braces.
 Declaration of Structure reserves no space.
 It is nothing but the “ Template / Map / Shape ” of the structure .
 Memory is created , very first time when the variable is created /Instance is created.

5.2 STRUCTURE DECLARATION:


5.2.1 DIFFERENT WAYS OF DECLARING STRUCTURE VARIABLE :
Method 1: Immediately after Structure Template
struct student
{

S.KAVITHA /AP/CSE/MSAJCE Page 1 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

char name[20];
int rollno;
float percent;
}s;
's' is name of Structure variable
Method 2: Declare Variables using struct Keyword
struct student
{
char name[20];
int rollno;
float percent;
};
struct student s;
where “student” is name of structure and “s” is name of variable.
Method 3 : Declaring Multiple Structure Variables
struct student
{
char name[20];
int rollno;
float percent;
}s1,s2,s3;
We can declare multiple variables separated by comma directly after closing curly.

5.2.2 C STRUCTURE USING TYPEDEF


Typedef is used to give New name to the Structure.
Different Ways of Declaring Structure using Typedef :
typedef struct
{
char ename[30];
int ssn;
int deptno;

S.KAVITHA /AP/CSE/MSAJCE Page 2 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

}employee;
Or
typedef struct Record
{
char ename[30];
int ssn;
int deptno;
}employee;
In the second example, Record is tag-name. ‟employee‟ is nothing but New Data Type. We can
now create the variables of type ‟employee‟ Tag name is optional.
Declaring Variable :
employee e1,e2;
Example : Using Typedef For Declaring Structure
#include<stdio.h>
typedef struct b1 {
char bname[30];
int ssn;
int pages;
}book;
book b1 = {"Let Us C",1000,90};
int main()
{
printf("\nName of Book : %s",b1.bname);
printf("\nSSN of Book : %d",b1.ssn);
printf("\nPages in Book : %d",b1.pages);
return(0);
}
Output :
Name of Book : Let Us C
SSN of Book : 1000
Pages in Book : 90

S.KAVITHA /AP/CSE/MSAJCE Page 3 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

5.3 STRUCTURE INITIALIZATION:


Values can be stored in structure members by following methods
Method 1 : Declare and Initialize
struct student
{
char name[20];
int roll;
float average;
}s = { "Pritesh",67,78.3 };
In the above structure, soon after declaration we have initialized the structure variable.

Method 2: Declaring and Initializing Multiple Variables


struct student
{
char name[20];
int roll;
float average;
}
s1 = { "Pritesh",67,78.3 };
s2 = {"Don",62,71.3};
In this example, we have declared two structure variables in above code. After declaration of
variable we have initialized two variable.
Method 3 : Initializing Single member
struct student
{
char name[20];
int roll;
float average;
}s = { "Pritesh"};

S.KAVITHA /AP/CSE/MSAJCE Page 4 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

Though there are three members of structure,only one is initialized , Then remaining two
members are initialized with Zero. If there are variables of other data type then their initial
values will be –

Data Type Default value if not initialized

Integer 0

Float 0.00

Char NULL

Method 4 : Initializing inside main


struct student
{
char name[20];
int roll;
float average;
};
void main()
{
struct student s1 = { "Pritesh",67,78.3 };
- - - - --
};
Important Notes for Declaring Structure Variable:
1. Closing brace of structure type declaration must be followed bysemicolon.
2. Don‟t forgot to use „struct„ keyword
3. Memory will not be allocated just by Creating instance or by declaring structure. Memory
will not be allocated only when you create variable or instance for the structure
4. Generally Structures are written in Global Declaration Section , But they can be written
inside main.
5. It is not necessary to initialize all members of structure.
6. For Larger program , Structures may be embedded in separate header file.

S.KAVITHA /AP/CSE/MSAJCE Page 5 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

5.4 ACCESSING STRUCTURE MEMBERS


 Array elements are accessed using the Subscript variable , Similarly Structure members are
accessed using dot [.] operator.
 (.) is called as “Structure member Operator”.
 Use this Operator in between “Structure name” & “member name”
Example :
#include<stdio.h>
struct student
{
char name[20];
int roll;
float average;
}s1 = { "Pritesh",67,78.3 };

int main()
{
printf("Name of the student : %s",s1.name);
printf("Roll Number : %d",s1.roll);
printf("Average : %f",s1.average);
return(0);
}
Output :
Name of the student : Pritesh
Roll Number : 67
Average : 78.3

Note : Dot operator has Highest Priority than unary,arithmetic,relational,logical Operators


Structure having Integer Array as Member:
Structure may contain the Array of integer as its Member.Let us discuss example of student , We
can store name,roll,percent as structure members , but sometimes we need to store the marks of
three subjects then we embed integer array of marks as structure member

S.KAVITHA /AP/CSE/MSAJCE Page 6 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

Example :
struct student
{
char sname[20];
int roll;
float percent;
int marks[3]; //Note Carefully
}s1;
Access marks of Student s1 :
Access Subject 1 Marks : s1.marks[0]
Access Subject 2 Marks : s1.marks[1]
Access Subject 3 Marks : s1.marks[2]

Example :
#include <stdio.h>
struct student
{
char sname[20];
int marks[3]; //Note Carefully
}s1;

int main()
{
printf("\nEnter the Name of Student : ");
gets(s1.sname)
printf("\nEnter the Marks in Subject 1 : ");
scanf("%d",&s1.marks[0]);
printf("\nEnter the Marks in Subject 2 : ");
scanf("%d",&s1.marks[1]);
printf("\nEnter the Marks in Subject 3 : ");
scanf("%d",&s1.marks[2]);

S.KAVITHA /AP/CSE/MSAJCE Page 7 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

printf("\n ---- Student Details -------- ");


printf("\n Name of Student : %s",s1.sname);
printf("\n Marks in Subject 1 : %d",s1.marks[0]);
printf("\n Marks in Subject 2 : %d",s1.marks[1]);
printf("\n Marks in Subject 3 : %d",s1.marks[2]);
return 0;
}
Output:
Enter the Name of Student : Vanitha
Enter the Marks in Subject 1 : 70
Enter the Marks in Subject 2 : 80
Enter the Marks in Subject 3 : 90
---- Student Details --------
Name of Student : Vanitha
Marks in Subject 1 : 70
Marks in Subject 2 : 80
Marks in Subject 3 : 90
Explanation of the Code :
marks[3] array is created inside the structure then we can access individual array element from
structure using structure variable. We even can use for loop to accept the values of the Array
Element from Structure.

5.5 ARRAY OF STRUCTURE:


 Structure is used to store the information of One particular object but if we need to store such
100 objects then Array of Structure is used.
Example :
struct student
{
char name[20];
int roll;
float average;
}s[3];

S.KAVITHA /AP/CSE/MSAJCE Page 8 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

Explanation :
 Here student structure is used to Store the information of one student.
 If we need to store the Information of 100 students then Array of Structure is used.
 s[0] stores the Information of 1st student , s[1] stores the information of 2nd student

5.5.1 INITIALIZING ARRAY OF STRUCTURE:


Array elements are stored in consecutive memory Location.
Method 1 : Initializing After Declaring Structure Array :
struct student
{
char name[20];
int roll;
float average;
}s[3] = {
{"Anita", 123, 78.3},
{"Venkat", 124, 88.9},
{"Ganga:, 125, 90.2}
};
Explanation :
 After declaration of structure we initialize structure with the pre-defined values. For each
structure variable we specify set of values in curly braces. Suppose we have 3 Array
Elements then we have to initialize each array element individually and all individual sets are
combined to form single set.
Method 2 : Initializing in Main
struct student
{
char name[20];
int roll;
float average;
}s[3];
void main()

S.KAVITHA /AP/CSE/MSAJCE Page 9 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

{
struct Book b1[3] = {
{"Anita", 123, 78.3},
{"Venkat", 124, 88.9},
{"Ganga:, 125, 90.2}
};
}
Example :
#include <stdio.h>
struct student
{
char name[20];
int roll;
float average;
}s[3];

int main()
{
int i;
for(i=0;i<3;i++)
{
printf("\nEnter the Name of Student : ");
scanf("%s",s[i].name);
printf("\nEnter the Roll Number : ");
scanf("%d",&s[i].roll);
printf("\nEnter the average : ");
scanf("%f",&s[i].average);
}
printf("\n--------- Student Details ------------ ");
for(i=0;i<3;i++)
{

S.KAVITHA /AP/CSE/MSAJCE Page 10 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

printf("\nName of Student : %s",s[i].name);


printf("\nRoll Number: %d",s[i].roll);
printf("\nAverage : %f",s[i].average);
}
}
Output:
Enter the Name of Student : ANITA
Enter the Roll Number : 20
Enter the average : 80.5
Enter the Name of Student : VINAY
Enter the Roll Number : 21
Enter the average : 89.2
Enter the Name of Student : SARANYA
Enter the Roll Number : 23
Enter the average : 90.2
--------- Student Details ------------
Name of Student : ANITA
Roll Number: 20
Average : 80.500000
Name of Student : VINAY
Roll Number: 21
Average : 89.199997
Name of Student : SARANYA
Roll Number: 23
Average : 90.199997

5.6 STRUCTURE WITHIN STRUCTURE: NESTED STRUCTURE


 Structure written inside another structure is called as nesting of two structures.
 We can write one Structure inside another structure as member of another structure.
Method 1 : Declare two separate structures
struct date

S.KAVITHA /AP/CSE/MSAJCE Page 11 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

{
int date;
int month;
int year;
};

struct Employee
{
char ename[20];
int ssn;
float salary;
struct date doj;
}emp1;

Accessing Nested Elements:


 Structure members are accessed using dot operator. „date„ structure is nested within
Employee Structure.
 Members of the „date„ can be accessed using ‟employee‟ emp1 & doj are two structure
names (Variables)
Accessing Month Field : emp1.doj.month
Accessing day Field : emp1.doj.day
Accessing year Field : emp1.doj.year

Method 2 : Declare Embedded structures


struct Employee
{
char ename[20];
int ssn;
float salary;
struct date
{

S.KAVITHA /AP/CSE/MSAJCE Page 12 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

int date;
int month;
int year;
}doj;
}emp1;
Accessing Nested Members :
Accessing Month Field : emp1.doj.month
Accessing day Field : emp1.doj.day
Accessing year Field : emp1.doj.year
Complete Example :
#include <stdio.h>
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp = {"Pritesh",1000,1000.50,{22,6,1990}};

void main()
{
printf("\nEmployee Name : %s",emp.ename);
printf("\nEmployee SSN : %d",emp.ssn);
printf("\nEmployee Salary : %f",emp.salary);
printf("\nEmployee DOJ : %d/%d/%d", \
emp.doj.date,emp.doj.month,emp.doj.year);

S.KAVITHA /AP/CSE/MSAJCE Page 13 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

}
Output :
Employee Name : Pritesh
Employee SSN : 1000
Employee Salary : 1000.500000
Employee DOJ : 22/6/1990

5.7 SIZE OF THE STRUCTURE:


 Structure is used for collecting different data types together.Structure is Collection of
different data types. There are different ways of calculating size of structure.
Different ways of calculating size of structure
1. By observation
2. By Using sizeof Operator
Method 1 : Calculate by adding Individual Sizes
struct Book
{
int pages;
char name[10];
char author[10];
float price;
}b1;
Calculating Size of Structure :
Size = size of 'Pages' + size of 'Name' + size of 'Author' + size of 'Price'
= 2 + 10 * 1 + 10 * 1 + 4
= 2 + 10 + 10 + 4
= 26

Method 2 : Using Sizeof Operator


Sizeof Operator is used to Calculate size of data type,variable,expression result.Syntax of sizeof
is much like function, but sizeof is not a library function. Sizeof is C Operator.
#include<stdio.h>

S.KAVITHA /AP/CSE/MSAJCE Page 14 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

typedefstruct b1 {
char bname[30];
int ssn;
int pages;
}book;
book b1 = {"Let Us C","1000",90};
int main()
{
printf("\nSize of Structure : %d",sizeof(b1));
return(0);
}
Output :
Size of Structure : 26

Some Observations and Important Points :


Tip #1 : All Structure Members need not be initialized
Tip #2 : Default Initial Value
struct Book
{
char bname[20];
int pages;
char author[20];
float price;
}b1[3] = {
{},
{"Book2",500,"AAK",350.00},
{"Book3",120,"HST",450.00}
};
Output :
Book Name :
Book Pages : 0

S.KAVITHA /AP/CSE/MSAJCE Page 15 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

Book Author :
Book Price : 0.000000
It is clear from above output , Default values for different data types.

Data Type Default Initialization Value

Integer 0

Float 0.0000

Character Blank

5.8 UNION- INTRODUCTION:


 A union is a special data type available in C that allows to store different data types in the
same memory location. You can define a union with many members, but only one member
can contain a value at any given time.

5.9 UNION DECLARATION:


 Union is similar to that of Structure. Syntax of both are same but major difference between
structure and union is „memory 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,Union can
handle only one member at a time.
Syntax :
union tag
{
union_member1;
union_member2;
union_member3;
..
union_memberN;
}instance;

S.KAVITHA /AP/CSE/MSAJCE Page 16 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

Unions are Declared in the same way as a Structure.Only “struct Keyword” is replaced
with union

Sample Declaration of Union :


union stud
{
int roll;
char name[4];
int marks;
}s1;

Memory Allocation for union:

 Union Members that compose a union, all share the same storage area within the computers
memory
 Each member within a structure is assigned its own unique storage area
 Unions are useful for application involving multiple members , where values need not be
assigned to all the members at any one time.

5.10 ACCESSING UNION MEMBERS


 While accessing union, we can have access to single data member at a time.
 we can access single union member using following two Operators –
1. Using DOT Operator
2. Using ARROW Operator

S.KAVITHA /AP/CSE/MSAJCE Page 17 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

Accessing union members DOT operator:


In order to access the member of the union we are using the dot operator.
Syntax :
variable_name.member
consider the below union, when we declare a variable of union type then we will be accessing
union members using dot operator.
union emp
{
int id;
char name[20];
}e1;

Syntax Explanation

e1.id Access id field of union

e1.name Access name field of union

Program #1 : Using dot operator


#include <stdio.h>
union emp
{
int id;
char name[20];
}e1;
void main( )
{
e1.id = 10;
printf("\nID : %d",e1.id);
strcpy(e1.name,"Pritesh");
printf("\nName : %s",e1.name);
}

S.KAVITHA /AP/CSE/MSAJCE Page 18 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

Output :
ID : 10
Name : Pritesh

Program #2 : Accessing same memory


#include <stdio.h>
union emp
{
int id;
char name[20];
}e1;
void main( )
{
e1.id = 10;
strcpy(e1.name,"Pritesh");
printf("\nID : %d",e1.id);
printf("\nName : %s",e1.name);
}
Output :
ID : 1953067600
Name : Pritesh

DIFFERENCE BETWEEN STRUCTURE AND UNION:


S.no C Structure C Union

1 Structure allocates storage Union allocates one common storage space for all its
space for all its members members.
separately. Union finds that which of its member needs high storage
space over other members and allocates that much space

2 Structure occupies higher Union occupies lower memory space over structure.
memory space.

S.KAVITHA /AP/CSE/MSAJCE Page 19 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

3 We can access all members of We can access only one member of union at a time.
structure at a time.

4 Structure example: Union example:


struct student union student
{ {
int mark; int mark;
char name[6]; char name[6];
double average; double average;
}; };

5 For above structure, memory For above union, only 8 bytes of memory will be allocated
allocation will be like below. since double data type will occupy maximum space of
int mark – 2B memory over other data types.
char name[6] – 6B Total memory allocation = 8 Bytes
double average – 8B
Total memory allocation =
2+6+8 = 16 Bytes

5.11 STORAGE CLASSES


A storage class defines the scope (visibility) and life-time of variables and/or functions within a
C Program.
The following storage classes are most often used in C programming,
1. Automatic variables
2. External variables
3. Static variables
4. Register variables

AUTOMATIC VARIABLES
 A variable declared inside a function without any storage class specification, is by default
an automatic variable.

S.KAVITHA /AP/CSE/MSAJCE Page 20 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

 They are created when a function is called and are destroyed automatically when the function
exits. Automatic variables can also be called local variables because they are local to a
function.
 By default they are assigned garbage value by the compiler.
void main()
{
int detail;
or
auto int detail; //Both are same
}

EXTERNAL OR GLOBAL VARIABLE


 A variable that is declared outside any function is a Global variable. Global variables remain
available throughout the entire program.
 One important thing to remember about global variable is that their values can be changed by
any function in the program.
int number;
void main()
{
number=10;
}
fun1()
{
number=20;
}
fun2()
{
number=30;
}
Here the global variable number is available to all three functions.

S.KAVITHA /AP/CSE/MSAJCE Page 21 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

EXTERN KEYWORD
The extern keyword is used before a variable to inform the compiler that this variable is declared
somewhere else. The extern declaration does not allocate storage for variables.
Problem when extern is not used
main()
{
a = 10; //Error:cannot find variable a
printf("%d",a);
}

Example Using extern in same file


main()
{
extern int x; //Tells compiler that it is defined somewhere else
x = 10;
printf("%d",x);
}

int x; //Global variable x

S.KAVITHA /AP/CSE/MSAJCE Page 22 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

STATIC VARIABLES
 A static variable tells the compiler to persist the variable until the end of program.
 Instead of creating and destroying a variable every time when it comes into and goes out of
scope, static is initialized only once and remains into existence till the end of program.
 A static variable can either be internal or external depending upon the place of declaration.
 Scope of internal static variable remains inside the function in which it is defined. External
static variables remain restricted to scope of file in each they are declared.
They are assigned 0 (zero) as default value by the compiler.
void test(); //Function declaration (discussed in next topic)
main()
{
test();
test();
test();
}
void test()
{
static int a = 0; //Static variable
a = a+1;
printf("%d\t",a);
}
output :
1 2 3
Register variable
 Register variable inform the compiler to store the variable in register instead of
memory. Register variable has faster access than normal variable.
 Frequently used variables are kept in register. Only few variables can be placed inside
register.
NOTE : We can never get the address of such variables.
Syntax :
register int number;

S.KAVITHA /AP/CSE/MSAJCE Page 23 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

5.12 THE C PREPROCESSOR


 Before a C program is compiled in a compiler, source code is processed by a program called
preprocessor.
 This process is called preprocessing. They are invoked by the compiler to process some
programs before compilation.

Fig: Working of pre-processor directive


 Commands used in preprocessor are called preprocessor directives and they begin with “#”
symbol. A preprocessor directive statement must not end with a semicolon (;).
 Below is the list of preprocessor directives that C language offers.

S.no Preprocessor Syntax Description

1 Macro #define This macro defines constant value and can be any of the
basic data types.

2 Header file #include <file_name> The source code of the file “file_name” is included in
inclusion the main program at the specified place

3 Conditional #ifdef, #endif, #if, Set of commands are included or excluded in source
compilation #else, #ifndef program before compilation with respect to the
condition

S.KAVITHA /AP/CSE/MSAJCE Page 24 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

4 Other directives #undef, #pragma #undef is used to undefine a defined macro variable.
#Pragma is used to call a function before and after main
function in a C program

1.6.1 Types of pre-processor directives:

1.6.1.1 File Inclusion


 Both user and system header files are included using the preprocessing directive „#include‟.
It has two variants:
#include <file>
 This variant is used for system header files. It searches for a file named file in a standard list
of system directories.
#include "file"
 This variant is used for header files of your own program. It searches for a file
named file first in the directory containing the current file, then in the quote directories and
then the same directories used for<file>.
 when an included file is changed, all files that depend on it must be recompiled.

1.6.1.2 Macro Substitution


 Macro is used to define symbolic constants in the source program. The identifier or string or
integer defined is replaced by macro substitution
Syntax:
#define identifier string/integer

S.KAVITHA /AP/CSE/MSAJCE Page 25 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

 This statement is placed before the main() function in source program. The pre-processor
replaces the every occurrence of an identifier by the specified string or integer in source
program.
 Macros are generally declared with capital letters for quick identification. It can be declared
as small letters
 Macro definition should not be terminated with a semicolon
 There are three different types of macros.
1. Simple macros
2. Argumened macros
3. Nested macros

Simple macros:
 This is commonly used to define symbolic constants
Example:
#define age 20
#define CITY “Chennai”
Program:
#define PI 3.14
void main()
{
float r, area;
printf(“enter the radius of the circle\n”);
scanf(“%f”,&r);
area=PI*r*r;
printf(“area of circle=%f\n”,area);
}
OUTPUT:
enter the radius of the circle: 7
area of circle=153.86

S.KAVITHA /AP/CSE/MSAJCE Page 26 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

 The expressions can also be defined in macros as follows:


 Example:
#define A 10-5
#define B 20+10
Consider an arithemetic peration in source program
C=(A)+(B)
This will be evaluated as
C=(10-5)+(20+10)
Argumened macros
 The argumented macros are used to define more complex and useful form of replacements in
the source program
Syntax:
#define identifier (v1 v2 v3....vn) string/integer
Program to print square and cube values using macros
#define sq(n) (n*n)
#deine cube(n) (n*n*n)
#include <stdio.h>
main()
{
int a=5,b=3,s,c;
s=sq(a);
c=cube(b);
printf(“square value of 5 is %d\n”, s);
printf(“Cube value of 3 is %d\n”,c);
}
OUTPUT:
square value of 5 is 25
Cube value of 3 is 27
Another eg: #define LARGE(x,y)((x)>(y)?(x):(y))

S.KAVITHA /AP/CSE/MSAJCE Page 27 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

Nested macros:
 The macros defined within another macro called nested macros
Example:
#include <stdio.h>
#define sq(n) (n*n)
#define cube(n) (n*sq(n))
main()
{
int a=5,b=3,s,c;
s=sq(a);
c=cube(b);
printf("square value of 5 is %d\n", s);
printf("Cube value of 3 is %d\n",c);
}
Output :
square value of 5 is 25
Cube value of 3 is 27

1.6.1.3 Conditional Compilation Directives


#if statement :
These Conditional Compilation Directives allow us to include certain portion of the code
depending upon the output of constant expression
Syntax :
#if Expression
Statement 1
Statement 2
.
.
Statement n
#endif
Expression allows only constant expression

S.KAVITHA /AP/CSE/MSAJCE Page 28 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

Result of the Expression is TRUE , then Block of Statement between #if and #endif is followed
Result of the Expression is FALSE , then Block of Statement between #if and #endif is skipped

#else statement :
 These Conditional Compilation Directives allow us to include certain portion of the code
depending upon the output of constant expression

Example:
#include<stdio.h>
#define NUM 11

void main()
{
#if((NUM%2)==0)
printf("\nNumber is Even");
#else
printf("\nNumber is Odd");
#endif
}
Output :
Number is Odd
#elif statement :
These Conditional Compilation Directives allow us to include certain portion of the code
depending upon the output of constant expression
Syntax :
#if Expression1
Statement_block 1;
#elif Expression2
Statement_block 2;
#elif Expression3
Statement_block 3;

S.KAVITHA /AP/CSE/MSAJCE Page 29 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

#else
Statement_block 4;
#endif
Expression allows only constant expression
#elif directive means “else if”
#elif establishes an if-else-if chain for multiple compilation options.
Result of the Expression is TRUE , then Block of Statement between #if and fist #elif is
compiled , then it jumps to #endif.
Result of the Expression is FALSE , then Corresponding #elif condition is tested , if true the the
block followed by that elif is Compiled otherwise it checks for Next condition followed by next
elif statement
#endif is the end of #if statement
Example :
#include<stdio.h>
#define NUM 10
void main()
{
#if(NUM == 0)
printf("\nNumber is Zero");
#elif(NUM > 0)
printf("\nNumber is Positive");
#else
printf("\nNumber is Negative");
#endif
}
Output :
Number is Positive

#ifdef statement :
These Conditional Compilation Directives allow us to include certain portion of the code
depending upon the output of constant expression

S.KAVITHA /AP/CSE/MSAJCE Page 30 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

Syntax :
#ifdef MACRONAME
Statement_block;
#endif
If the MACRONAME specified after #ifdef is defined previously in #define
then statement_block is followed otherwise it is skipped.The conditional succeeds if MACRO is
defined, fails if it is not.
Example:
#include<stdio.h>
void main()
{
#ifdef MAX
#define MIN 90
#else
#define MIN 100
#endif
printf("MIN number : %d",MIN);
}
Output :
MIN number : 100

#include<stdio.h>
#define MAX 10
void main()
{
#ifdef MAX
#define MIN 90
#else
#define MIN 100
#endif
printf("MIN number : %d",MIN);

S.KAVITHA /AP/CSE/MSAJCE Page 31 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

}
Output:
MIN number : 90

#ifndef statement :
 #ifndef works exactly opposite to that of #ifdef. It tests whether the identifier has defined
substitute text or not. If the identifier is defined then #else block is compiled
Syntax :
#ifndef MACRONAME
Statement_block;
#endif
If the MACRONAME specified after #ifndef is not defined previously in #define then
statement_block is followed otherwise it is skipped, the conditional succeeds if MACRO is not
defined, fails if it is not.
Example:
#include<stdio.h>
#define MAX 90
void main()
{
#ifndef MAX
#define MIN 90
#else
#define MIN 100
#endif
printf("MIN number : %d",MIN);
}
Output :
MIN number : 100

S.KAVITHA /AP/CSE/MSAJCE Page 32 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

#undef Directive
 Removes (undefines) a name previously created with #define.
Syntax
#undef identifier

 The #undef directive removes the current definition of identifier. subsequent occurrences
of identifier are ignored by the preprocessor.
 To remove a macro definition using #undef, give only the macro identifier ; do not give a
parameter list.
 You can also apply the #undef directive to an identifier that has no previous definition. This
ensures that the identifier is undefined.
 The #undef directive also works with the #if directive to control conditional compilation of
the source program. In the following example, the #undef directive removes definitions of a
symbolic constant and a macro. Note that only the identifier of the macro is given.
#define WIDTH 80
#define ADD( X, Y ) ((X) + (Y))
.
.
.
#undef WIDTH
#undef ADD

PROGRAMS:
1. Write a C Program to Store Information of Single Student
#include <stdio.h>
struct student{
char name[50];
int roll;
float marks;
};
int main(){

S.KAVITHA /AP/CSE/MSAJCE Page 33 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

struct student s;
printf("Enter information of students:\n\n");
printf("Enter name: ");
scanf("%s",s.name);
printf("Enter roll number: ");
scanf("%d",&s.roll);
printf("Enter marks: ");
scanf("%f",&s.marks);
printf("\nDisplaying Information\n");
printf("Name: %s\n",s.name);
printf("Roll: %d\n",s.roll);
printf("Marks: %.2f\n",s.marks);
return 0;
}
Output
Enter information of students:

Enter name: Adele


Enter roll number: 21
Enter marks: 334.5

Displaying Information
name: Adele
Roll: 21
Marks: 334.50

2. Write a C program to maintain a record of ―n student details using an array of


structures with four fields (Roll number, Name, Marks, and Grade). Each field is of an
appropriate data type. Print the marks of the student given student name as input.
#include <stdio.h>
#include<conio.h>

S.KAVITHA /AP/CSE/MSAJCE Page 34 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

/* Structure to maintain student record*/


struct student
{
int roll;
char name[50];
int marks; char
grade[3];
};
void main()
{
struct student s[100]; /* Array of structure*/
int i,n,found=0,choice=1;
char name[50];
printf("\nEnter number of students:");
scanf("%d",&n);
printf("\nEnter information of %d students:\n",n);
/* Read student records into structure*/
for(i=0;i<n;i++)
{
s[i].roll=i+1;
printf("\nFor roll number %d\n",s[i].roll);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%d",&s[i].marks);
printf("Enter grade:");
scanf("%s",s[i].grade);
printf("\n");
}
/* Display stored record*/
printf("Displaying information of students:\n\n");

S.KAVITHA /AP/CSE/MSAJCE Page 35 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

printf("Roll No Name Marks Grade\n");


for(i=0;i<n;i++)
{
printf("%d\t",i+1);
printf("%s",s[i].name);
printf("\t%d\t ",s[i].marks);
puts(s[i].grade);
}
/* Repeat search from the stored information*/
while(choice)
{
printf("\nEnter the name of student to display marks: ");
scanf("%s",name);
for(i=0;i<n;i++)
{
if((strcmp(name,s[i].name))==0)
{
found=1;
printf("\nMarks of %s student: %d",s[i].name,s[i].marks);
}
}
if(found==0)
{
printf("\nNo record found of %s student",name);
}
found=0;
printf("\n\nPress 0 to exit 1 to continue:");
scanf("%d",&choice);
}
getch();
}

S.KAVITHA /AP/CSE/MSAJCE Page 36 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

OUTPUT:
Enter number of students:5
Enter information of 5 students:
For roll number 1
Enter name: Veena
Enter marks: 90
Enter grade:A
For roll number 2
Enter name: Roopa
Enter marks: 95
Enter grade:A+
For roll number 3
Enter name: Pooja
Enter marks: 92
Enter grade:A
For roll number 4
Enter name: Lata
Enter marks: 96
Enter grade:A+
For roll number 5
Enter name: Aditi
Enter marks: 85
Enter grade:B
Displaying information of students:
Roll No Name Marks Grade
1 Veena 90 A
2 Roopa 95 A+
3 Pooja 92 A
4 Lata 96 A+
5 Aditi 85 B

S.KAVITHA /AP/CSE/MSAJCE Page 37 of 38


Unit-V GE6151- COMPUTER PROGRAMMING

Enter the name of student to display marks: Veena


Marks of Veena student: 90
Press 0 to exit 1 to continue:1
Enter the name of student to display marks: Lata
Marks of Lata student: 96.

S.KAVITHA /AP/CSE/MSAJCE Page 38 of 38

You might also like