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

Module 5 - Complete Notes

Please read to have a fair idea about Structure and Union in C

Uploaded by

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

Module 5 - Complete Notes

Please read to have a fair idea about Structure and Union in C

Uploaded by

manoj hm
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Module 5- Structures and Union

Arrays allow to define type of variables that can hold several data items of the same
kind. Similarly structure is another user defined data type available in C that allows to combine
data items of different kinds.
A structure creates a data type that can be used to group items of possibly different types into a single
type. 'struct' keyword is used to create a structure. Following is an example. A structure variable can
either be declared with structure declaration or as a separate declaration like basic types.

Structures are used to represent a record. Suppose you want to keep track of your books in a
library. You might want to track the following attributes about each book −

 Title

 Author

 Subject

 Book ID

Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new
data type, with more than one member. The format of the struct statement is as follows −

struct [structure tag] {

member definition;

member definition;

...

member definition;

} [one or more structure variables];

The structure tag is optional and each member definition is a normal variable definition, such
as int i; or float f; or any other valid variable definition. At the end of the structure's definition,
before the final semicolon, you can specify one or more structure variables but it is optional.
Here is the way you would declare the Book structure −
struct Books {

char title[50];

char author[50];

char subject[100];

int book_id;

} book;

Accessing Structure Members


To access any member of a structure, we use the member access operator (.). The member
access operator is coded as a period between the structure variable name and the structure
member that we wish to access. You would use the keyword struct to define variables of
structure type. The following example shows how to use a structure in a program −
Live Demo

#include <stdio.h>

#include <string.h>

struct Books {

char title[50];

char author[50];

char subject[100];

int book_id;

};

int main( )

struct Books Book1; /* Declare Book1 of type Book */

struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */

strcpy( Book1.title, "C Programming");

strcpy( Book1.author, "Nuha Ali");


strcpy( Book1.subject, "C Programming Tutorial");

Book1.book_id = 6495407;

/* book 2 specification */

strcpy( Book2.title, "Telecom Billing");

strcpy( Book2.author, "Zara Ali");

strcpy( Book2.subject, "Telecom Billing Tutorial");

Book2.book_id = 6495700;

/* print Book1 info */

printf( "Book 1 title : %s\n", Book1.title);

printf( "Book 1 author : %s\n", Book1.author);

printf( "Book 1 subject : %s\n", Book1.subject);

printf( "Book 1 book_id : %d\n", Book1.book_id);

/* print Book2 info */

printf( "Book 2 title : %s\n", Book2.title);

printf( "Book 2 author : %s\n", Book2.author);

printf( "Book 2 subject : %s\n", Book2.subject);

printf( "Book 2 book_id : %d\n", Book2.book_id);

return 0;

When the above code is compiled and executed, it produces the following result −
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700

Examples for structure declarations


Declaration of structures for information about the country
struct country

char name[50];

char language[50];

int population;

} India, Japan, Indonesia;

Declaration of structures for to store personal information


struct country

char name[50];

char address[50];

int year_of_birth;

int month_of_birth;

int day_of_birth;

} Mayur, Henry, piyush;

Initialization of structures using first constructs


struct country

char name[50];
char language[50];

int population;

}India={“India”,”Hindi”,136},

japan={“japan,”Japaneese”,12},

Indonesia ={“Indonesia”,”english”,3}

Initialization of structures using first constructs


struct country

char name[50];

char language[50];

int population;

};

Struct country India= ={“India”,Hindi,136};

Program to display students record using array of structures concept

#include <stdio.h>
#include<conio.h>
struct student
{
char name[50];
int roll;
float marks;
} s[100];

int main()
{
int i,n;

printf("Enter the number of students\n");


scanf("%d", &n);
printf("Enter information of students:\n");
// storing information
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("%f",&s[i].marks);

printf("\n");
}

printf("Displaying Information:\n\n");

// displaying information
for(i=0; i<n; ++i)
{
printf("\nRoll number: %d\n",i+1);
printf("Name: ");
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
printf("\n");
}
getch();
}

------------------------------*-----------OUTPUT----------------*------------------------

Enter the number of students


3
Enter information of students:

For roll number 1,


Enter name: John
Enter marks: 87

For roll number 2,


Enter name: Sam
Enter marks: 25
For roll number 3,
Enter name: Jack
Enter marks: 77

Displaying Information:

Roll number: 1
Name: John
Marks: 87.0

Roll number: 2
Name: Sam
Marks: 25.0

Roll number: 3
Name: Jack
Marks: 77.0

a. Program to demonstrate the difference between structure and union by displaying size of a
structure and a union.

#include <stdio.h>
#include<conio.h>
#include <string.h>
struct student_Structure
{
char name[50];
int roll;
float marks;
} s;

union student_Union
{
char name[50];
int roll;
float marks;
} u;

int main()
{
strcpy(s.name,"John");
s.roll = 1;
s.marks= 100;

strcpy(u.name,"John");
u.roll = 1;
u.marks= 100;

printf("Size of structure %d\n",sizeof(s));


printf("Size of Union %d\n",sizeof(u));

printf("Printing data in a structure \n");


printf(" %s \t %d \t %f \n", s.name,s.roll, s.marks);

printf("Printing data in a union \n");


printf(" %s \t %d \t %f \n", u.name,u.roll, u.marks);
getch();
}

------------------------------*-----------OUTPUT----------------*------------------------

Size of structure 60
Size of Union 52
Printing data in a structure
John 1 100.000000
Printing data in a union
1120403456 100.000000

Module 5 – Part 2 Lecture Notes


Differences between Structures and Arrays

Arrays Structures
1. An array is a collection of related 1. Structure can have elements of
data elements of the same type. different types
2. An array is a derived data type 2. A structure is a programmer-
defined data type
3. Any array behaves like a built-in 3. But in the case of structure, first,
data types. All we have to do is to we have to design and declare a data
declare an array variable and use it. structure before the variable of the
structure type are declared and used.
4. Array allocates static memory 4. Structures allocate dynamic
memory
5. Array uses index/subscript for 5. Structures uses (.) operator for
accessing elements of the array. accessing the member of a structure.
5. An array is a pointer to the first
5. Structure is not a pointer
element of it
6. Element access takes relatively 6. Structure attributes access takes
less time. relatively large time.

Difference between Structure and Unions

The C Preprocessor
It is an instruction that processes source program before it is passed to the compiler often
called as directive.
Features of C Preprocessor
They begin with #symbol
Can be placed anywhere in a program
Offers preprocessor directives

i) Macro expansion

ii) File inclusion


Macro expansion
Consider the program given which illustrates the concept
Example:
#define UPPER 25
main ( )
{
int i;
for ( i=1;i<=UPPER; i ++)
Printf (“\n %d”,i);
}
In this program instead of writing 25 in the for loop we are writing it in the form of UPPER,
which has been defined before the main ( )
#define UPPER 25
This statement is called “ macro Definition” or called macro
What is the purpose it servers
It replaces every occurrence of UPPER in the program with 25
Example:
#define PI 3.14215
main ( )
{
float r = 6.25;
float area;
Area = PI * r * r;
printf (“\n Area of circle = %f”,area);
}
When we compile the program the source code passes to the compiler it sees the macro #define
directive, it goes through the entire program in search of the templates; wherever it finds one it
replaces the macro template with the appropriate macro expansion. In C programming it is
compulsory to use capital letters which is separated by blanks or tabs .The space between # and
define is optional and never terminated by semicolon.
Macros with Arguments
Here is the example which illustrates of macros with arguments
#define AREA (x) (3, 14 * x * x)
main ( )
{
float r1 = 6.25, r2 = 2.5, a;
a = AREA (r1);
printf(“\nArea of circle = %f”,a)
a=AREA (r2);
printf(“\n Area of circle =%f”,a);
}
Here is the output of the program
Area of circle = 122.656250
Area of circle = 19.625000
In this program wherever the processor finds the phrase AREA(x)
It expands it into the statement (3.142 * x * x). The macro template AREA(x) is an argument that
matches the x in the macro expansion (3.142*x*x) ,it causes the variable r1 to be substituted for
x. Thus the statement AREA(r1) is equivalent to (3.14 * r * r)
After the source code has passed through the preprocessor what the compiler gets to work on will
be this
main( )
{
float r1= 6.25, r2=2.5, a;
a = 3.14 * 6.25 *6.25;
printf(“\nArea of circle = %f”,a)
a=3.14 * 2.5*2.5;
printf(“\n Area of circle =%f”,a);
}
File Compilation
This directive causes one file to be included in another. The preprocessor command for the file
inclusion looks like this
#include”filename”
This simply causes the entire contents of filename to be inserted into the source code at that point
in the program
When and why this feature is used
i) If we have large program, the code is best divided into several different files each
containing a set of related function and it is included in the beginning of the program
ii) The commonly used function and macro definitions can be stored in a file that can be
included in every program we write ,which would add all the statements in the file to
our program as if we have typed them in
iii) They are two ways to write #include statement
#include “filename”
#include<filename>
The meaning of the statement is given below
#include”goto.c”
This command would look for the file goto.c in the current directory as well as the
specified list of directories as mentioned in the include search path that might have
been set up
This command would look for the file goto.c in the specified list of directories only

Conditional Compilation
We can have the compiler skip over part of a source code by inserting the
preprocessor commands #ifdef and #endifwhich would havethe general format
#ifdef macroname
Statement 1;
Statement 2;
Statement 3;
#endif
If the macroname has been #defined,the block of code will be processed as usual
otherwise not
Where can I make use of ifdef be used? when would you like to the compile only a
part of your program:
Case1:
To “comment out” obsolute line of code
Case2: to make them work on two totally different computers

Example:
main( )
{
#ifdef OKAY
Statement 1;
Statement 2;
Statement 3;
#endif
Statement 4;
Statement 5;
}
Here, statement 1,2,3 would be compiled only the macro OKAY has been defined and we have
purposefully omitted the definition of the macro OKAY. if we want them to compile all the
codes in the program we can omit the statements #ifdef and #endif.
Example:
main ( )
{
#ifdef PCAT
Code suitable for a PC/AT
#else
Code suitable for a PC/AT
#endif
Code common to both the computers
}
When you compile this program it would compile only the code suitable for a PC/XT and
the common code. This is because the macro PCAT has not been defined, the working of #ifdef-
#else-#endif is similar to the ordinary if-else controls instruction.
Below is the list of preprocessor directives that C programming language offers with few more
examples

Syntax/Description
Preprocessor

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

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

Syntax: #ifdef, #endif, #if, #else, #ifndef


Conditional
Set of commands are included or excluded in source
compilation
program before compilation with respect to the condition.

Syntax: #undef, #pragma


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

EXAMPLE PROGRAM FOR #DEFINE, #INCLUDE PREPROCESSORS IN C


LANGUAGE:
#define – This macro defines constant value and can be any of the basic data types.
#include <file_name> – The source code of the file “file_name” is included in the main C
program where “#include <file_name>” is mentioned.

#include <stdio.h>

#define height 100


#define number 3.14
#define letter 'A'
#define letter_sequence "ABC"
#define backslash_char '\?'

void main()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);

EXAMPLE PROGRAM FOR CONDITIONAL COMPILATION DIRECTIVES:


A) EXAMPLE PROGRAM FOR #IFDEF, #ELSE AND #ENDIF IN C:
“#ifdef” directive checks whether particular macro is defined or not. If it is defined, “If” clause
statements are included in source file.
Otherwise, “else” clause statements are included in source file for compilation and execution.

#include <stdio.h>
#define RAJU 100

int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in " \
"this C file\n");
#else
printf("RAJU is not defined\n");
#endif
return 0;
}

B) EXAMPLE PROGRAM FOR #IFNDEF AND #ENDIF IN C:


#ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined, “If” clause
statements are included in source file.
Otherwise, else clause statements are included in source file for compilation and execution.

#include <stdio.h>
#define RAJU 100
int main()
{
#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going to " \
"define here\n");
#define SELVA 300
}
#else
printf("SELVA is already defined in the program”);
#endif
return 0;

You might also like