You are on page 1of 66

EC104: Applied

Programming
Unit 1: Structure and Union
Topics
• Defining a Structure, Declaring Structure Variables
• Initialization Of Structure Variables, Accessing Members of a
Structure, Assignment of Structure Variables
• Storage of Structures in Memory, Size of Structure
• Array of Structures, Arrays Within Structures, Nested Structures
• Pointers to Structures, Pointers Within Structures, Structures And
Functions
• Definition of Union, Difference Between Structure and Union
Defining a Structure
struct name_of_structure
{ Name of structure or structure tag
Keyword
char title[20];
char author[20];
int pages; Data fields also called as structure elements
float price; or members

};
General format of Structure
struct tag_name
{
data type member1;
data type member2;
data type member2;
------------ ------------
};
Declaring structure variables

• Method 1: Like basic declaration of variables


struct struct_name variable1, variable2, variable3;

• Method 2: During declaration of structure(with structure)


Struct struct_name
{ datatype member1;
datatype member2;
----------------- -----------
} variable1, variable2, variable3;
Lets do practice
1. Create a structure called Library to hold accession number, title of
the book, author name, price of the book and flag indicating whether
the book is issued or not.
2. Create a structure called Result for students. Structure will have
members like roll number, marks for three subjects and total of three
subjects.
3. Create a structure called Emp_Details which contains members like
name of employee, designation, department name, basic pay.
Initialization of structure variables
• Structure members cannot be initialized with declaration.

• 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 ‘{}’.

struct Point
A valid initialization.
{
Member x gets value 0
int x, y;
and y gets value 1.
};
The order of declaration
int main()
is followed.
{
struct Point p1 = {0, 1};
}
Type defined structures
• We can also use keyword typedef to define a structure as follows:

typedef struct
{
type member1;
type member2;
}
Variables defining methods:
#include<stdio.h> #include<stdio.h>
struct Point{
typedef struct Point{
int x; int x;
int y;
}; int y;
} Point;
int main() {
struct Point p1; int main()
{
p1.x = 1;
Point p1;
p1.y = 3; p1.x = 1;
printf("%d \n", p1.x); p1.y = 3;
printf("%d \n", p1.x);
printf("%d \n", p1.y);
printf("%d \n", p1.y);
return 0; return 0;
} }
Accessing Structure Members
• The members themselves are not
#include<stdio.h>
variables.
struct Point{
• They should be linked to the
int x;
structure variables in order to make
int y;
them meaningful members.
};
• The link between a member and a
int main() {
variable is established using the
struct Point p1;
member operator ‘.’
p1.x = 1;
p1.y = 3;
printf("%d \n", p1.x);
printf("%d \n", p1.y);
return 0;
}
Rules for Initializing for structures
• We cannot initialize individual members inside the structure
template.
• The order of values enclosed in braces must match the order of
members in the structure definition.
• It is permitted to have a partial initialization. We can initialize only
first few members and leave the remaining blank. The uninitialized
members should be only at the end of the list.
• The uninitialized members will be assigned default values as follows:
• Zero for integer and floating point numbers.
• ‘\0’ for characters and strings.
Copying and comparing structure variables
• Two variables of same structure type can be copied the same way as
ordinary variables.
• If p1 and p2 belong to the same structure, then p1=p2;
p2=p1; are valid
C does not permits any logical operations on structure variables.
Exercise 1:
• Define a structure that describes a student having members Roll_no,
Name, Mark1, Mark2, Mark3. Write a program for five students to
print the total marks and average of marks for each student.
ARRAY AS MEMBER OF STRUCTURE

• Let’s create structure called student to store name, roll no and marks of 5
subjects.

struct student
{
char name[20];
int roll_no;
float marks[5];
}std1;

std1.marks[0] – refers to the marks


in the first subject
std1.marks[1] – refers to the marks
ARRAY OF STRUCTURE VARIABLE

• Like other primitive data types, we can create an array of structures.


struct student
{
char name[20];
int roll_no;
float marks[5];
}std[5];

std[0].marks[0] – refers to the marks of first


student in the first subject
std[1].marks[2] – refers to the marks of the
second student in the third subject
OUTPUT
EXAMPLE

#include<stdio.h> for(i = 0; i < MAX; i++ )


#include<string.h> {
#define MAX 2 printf("\nEnter details of student %d\n\n", i+1);
#define
SUBJECTS 2 printf("Enter name: ");
scanf("%s", std[i].name);
struct student
{ printf("Enter roll no: ");
char name[20]; scanf("%d",
int roll_no; &std[i].roll_no);
float
marks[SUBJE for(j = 0; j <
CTS]; SUBJECTS; j++)
}; {
printf("Enter marks:
int main() ");
{ scanf("%f",
struct student std[MAX]; &std[i].marks[j]);
int i, j; }
printf("\n");

printf("Name\tRoll no\tAverage\n\n");

for(i = 0; i < MAX; i++ )


{
sum = 0;

for(j = 0; j < SUBJECTS; j++)


{
sum += std[i].marks[j];
}
printf("%s\t%d\t%.2f\
n",std[i].name, std[i].roll_no,
sum/SUBJECTS);
}
return 0;
}
SIZE OF STRUCTURE
#include<stdio.h>

struct student
{
char name[20]; //1 Byte each = 20
int roll_no; Bytes Question:
float marks[2]; //4 Bytes How do we get the size of the
}; //4 Byte each = 8 Bytes structure?

int main() Answer:


{ • By adding the size of all elements of
struct student std[2]; the structure.
• std[0] and std[1] will each get
printf("\nstructure size : %d Bytes\n",sizeof(struct student));
return 0; 32
} Bytes of memory.
LET’S PRACTICE

struct Student struct Person struct Address


{ { {
int id; char name[40]; char name[50];
char name[20]; int citNo; char street[100];
float percentage; float salary; char city[50];
}; }; char state[20];
int pin;
};
NESTED STRUCTURE OR STRUCTURE
WITHIN STRUCTURE

• C provides us the feature of nesting one structure within another structure by using which, complex
data types are created.
• For example, we may need to store the address of an entity employee in a structure. The attribute
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.
• The structure can be nested in the following ways.
• By Separate structure
• By Embedded structure
1. SEPARATE STRUCTURE

• Here, we create two structures, but the struct Date


{
dependent structure should be used inside the
int dd;
main structure as a member. int mm;
int yyyy;
• As you can see, doj (date of joining) is the
};
variable of type Date. Here doj is used as a
member in Employee structure. struct Employee
{
• In this way, we can use Date structure int id;
in char name[20];
many structures. struct Date doj;// Date structure
variable
}emp1; // Employee structure variable
2. EMBEDDED STRUCTURE
struct Employee
{
• The embedded structure enables us to declare int id;
the structure inside the structure. char name[20];
• Hence, it requires less line of codes but it can struct Date
not be used in multiple data structures. {
int dd;
int mm;
int yyyy;
}doj; // Date
structure
variable
}emp1;// Employee
ACCESSING NESTED STRUCTURE

• We can access the member of the nested structure For Example:


by…

Outer_structure.Nested_structure.Member emp1.doj.dd;

emp1.doj.mm;
emp1.doj.yyyy;
Pointers to Structure
• A structure pointer is defined as the pointer which points to the
address of the memory block that stores a structure known as the
structure pointer.
• Complex data structures like Linked lists, trees, graphs, etc. are
created with the help of structure pointers.
• The structure pointer tells the address of a structure in memory by
pointing the variable to the structure variable.
Accessing the Structure Member with the Help of Pointers

• There are two ways to access the members of the structure with the
help of a structure pointer:
• With the help of (*) asterisk or indirection operator and (.) dot
operator.
• With the help of ( -> ) Arrow operator.
// C Program to demonstrate Structure pointer
#include <stdio.h> s1.batch = 2023;
#include <string.h>
printf("Roll Number: %d\n", (*ptr).roll_no);
struct Student {
int roll_no; printf("Name: %s\n", (*ptr).name);
char name[30];
char branch[40]; printf("Branch: %s\n", (*ptr).branch);
int batch;
}; printf("Batch: %d", (*ptr).batch);
int main() return 0;
{ }
struct Student s1;
struct Student* ptr = &s1;

s1.roll_no = 27;
strcpy(s1.name, "Kamlesh Joshi");
strcpy(s1.branch, "Computer Science And Engineering");
// C Program to demonstrate Structure pointer ptr = &s;
// Taking inputs
printf("Enter the Roll Number of Student\n");
#include <stdio.h> scanf("%d", &ptr->roll_no);
#include <string.h> printf("Enter Name of Student\n");
scanf("%s", &ptr->name);
// Creating Structure Student printf("Enter Branch of Student\n");
struct Student { scanf("%s", &ptr->branch);
int roll_no; printf("Enter batch of Student\n");
char name[30]; scanf("%d", &ptr->batch);
char branch[40];
int batch; // Displaying details of the student
}; printf("\nStudent details are: \n");
printf("Roll No: %d\n", ptr->roll_no);
// variable of structure with pointer defined printf("Name: %s\n", ptr->name);
printf("Branch: %s\n", ptr->branch);
struct Student s, *ptr; printf("Batch: %d\n", ptr->batch);

int main() return 0;


{ }
PASSING STRUCTURE TO A
FUNCTION
• A structure can be passed to any function from main function or from any sub function.
• If structure is defined within the function only then it won’t be available to other functions unless
it is passed to those functions by value or by address.
• Else, we have to declare structure variable as global variable. That means, structure variable
should be declared outside the main function. So, this structure will be visible to all the functions
in a C program.
• It can be done in below ways.
EXAMPLE
#include <stdio.h> record.id=1;
#include <string.h> strcpy(record.name, "Raju");
record.percentage = 86.5;
struct student
{ func(record);
int id; return 0;
char name[20]; }
float percentage;
}; void func(struct student record)
{
void func(struct student record); printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
int main() printf(" Percentage is: %f \n", record.percentage);
{ }
struct student record;
EXAMPLE
#include <stdio.h> record.id=1;
#include <string.h> strcpy(record.name, "Raju");
record.percentage = 86.5;
struct student
{ func(&record);
int id; return 0;
char name[20]; }
float percentage;
}; void func(struct student *record)
{
void func(struct student *record); printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
int main() printf(" Percentage is: %f \n", record->percentage);
{ }
struct student record;
UNION
• A union is a special data type available in C that allows storing 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.
• Unions provide an efficient way of using the same memory location for multiple
purposes.
• Defining a Union: To define a union, you must use the union statement in the
same way as you did while defining a structure. The union statement defines a
new data type with more than one member for your program.
UNION
SYNTAX
union keyword

union union_name
{
//Members / Fields of Union
}union_var; semicolon
STRUCTURE VS UNION IN C
structure union

Keyword “struct” is used to define the structure. “union” is used to define union.

Size When a variable is associated with the When a variable is associated with the union,
structure, compiler allocates memory for each compiler allocates memory by considering
member. the size of the largest member.
The size of structure is greater than or equal The size of union is the size of the largest
to the sum of the sizes of it’s members. member.
Memory Each member is assigned a unique storage Memory allocated is shared by
location. individual members.
Value altering Altering value of a member will not affect Altering value of a member will affect value
other members. of other members.
Accessing Individual members can be accessed at Only one member can be accessed at a time.
members a time.
Initialization Many members of a structure can Only the first member of a union can be
of members be initialized at a time. initialized.
Example of Restrictions

#include<stdio.h>

union Address
{
char name[50];
char street[100];
};

int main()
{
union Address std = {"dipsi", "75th Street"};

printf("\nname: %s",std.name);
printf("\nstreet: %s",std.street);
printf("\n");
return 0;
}
SIMILARITIES BETWEEN STRUCTURE
AND UNION

• Both are user-defined data types used to store data of different types as a single unit.
• A structure or a union can be passed by value to functions and returned by value by functions.
The argument must have the same type as the function parameter.
• ‘.’ Operator is used for accessing members.
SIZE OF UNION
#include<stdio.h>

union student
{
char name[20]; //1 Byte each = 20
int roll_no; Bytes Question:
float marks[2]; //4 Bytes How do we get the size of the
}; //4 Byte each = 8 Bytes union?
Answer:
int main() • By size of the largest
{ member.
union student std[2];

printf("\n union size : %d Bytes\n",sizeof(union student));


return 0;
}
LET’S PRACTICE

union Student union Person union Address


{ { {
int id; char name[40]; char name[50];
char name[20]; int citNo; char street[100];
float percentage; float salary; char city[50];
}; }; char state[20];
int pin;
};
Unit 2:

Introduction to OOP
• Programmers write instructions in various programming languages to
perform their computation tasks such as:
(i) Machine level Language
(ii) Assembly level Language
(iii) High level Language

• The high-level programming languages are broadly categorized in to


two categories:
(i) Procedure oriented programming(POP) language.
(ii) Object oriented programming(OOP) language.
Procedure Oriented Programming
Language
• In the procedure oriented approach, the problem is viewed as
sequence of things to be done such as reading , calculation and
printing.
• Procedure oriented programming basically consist of writing a list of
instruction or actions for the computer to follow and organizing these
instruction into groups known as functions.
• The disadvantage of the procedure oriented programming languages
is:
1. Global data access
2. It does not model real word problem very well
3. No data hiding
Characteristics of procedure oriented
programming:
• Emphasis is on doing things(algorithm).
• Large programs are divided into smaller programs known as functions.
• Most of the functions share global data.
• Data move openly around the system from function to function.
• Function transforms data from one form to another.
• Employs top-down approach in program design.
Object Oriented Programing
• Object oriented programming as an approach that provides a way of
modularizing programs by creating partitioned memory area for both
data and functions that can be used as templates for creating copies
of such modules on demand.
Features of the Object Oriented programming
• Emphasis is on doing rather than procedure.
• programs are divided into what are known as objects.
• Data structures are designed such that they characterize the objects.
• Functions that operate on the data of an object are tied together in
the data structure.
• Data is hidden and can’t be accessed by external functions.
• Objects may communicate with each other through functions.
• New data and functions can be easily added.
• Follows bottom-up approach in program design.
BENEFITS OF OOP:
• Oop offers several benefits to both the program designer and the user. Object-oriented
contributes to the solution of many problems associated with the development and quality of
software products.
• The principal advantages are :
1. Through inheritance we can eliminate redundant code and extend the use of existing
classes.
2. We can build programs from the standard working modules that communicate with one
another, rather than having to start writing the code from scratch. This leads to saving of
development time and higher productivity.
3. This principle of data hiding helps the programmer to build secure programs that can’t be
invaded by code in other parts of the program.
4. It is possible to have multiple instances of an object to co-exist with out any interference.
5. It is easy to partition the work in a project based on objects.
6. Object-oriented systems can be easily upgraded from small to large systems.
7. Message passing techniques for communication between objects makes the interface
description with external systems much simpler.
8. Software complexity can be easily managed.
APPLICATION OF OOP:
• The most popular application of oops up to now, has been in the area
of user interface design such as windows. There are hundreds of
windowing systems developed using oop techniques. Real business
systems are often much more complex and contain many more
objects with complicated attributes and methods. Oop is useful in this
type of applications because it can simplify a complex problem. The
promising areas for application of oop includes.
1. Real – Time systems.
2. Simulation and modeling
3. Object oriented databases.
4. Hypertext, hypermedia and expertext.
5. Al and expert systems.
6. Neural networks and parallel programming.
7. Decision support and office automation systems.
8. CIM / CAM / CAD system.
BASIC CONCEPTS OF OBJECTS
ORIENTED PROGRAMMING
• Objects
• Classes
• Data abstraction and encapsulation
• Inheritance
• Polymorphism
• Dynamic binding
• Message passing
OBJECTS
• Objects are the basic run-time entities in an object-oriented system.
• They may represent a person, a place, a bank account, a table of data or any item
that the program must handle.
• The fundamental idea behind object oriented approach is to combine both data
and function into a single unit and these units are called objects.
• The term objects means a combination of data and program that represent some
real word entity.
CLASS
• A group of objects that share common properties for data part and
some program part are collectively called as class.
• In C ++ a class is a new data type that contains member variables and
member functions that operate on the variables.
• DATA ABSTRACTION : Abstraction refers to the act of representing
essential features without including the back ground details or
explanations. Classes use the concept of abstraction and are defined
as size, width and cost and functions to operate on the attributes.

• DATA ENCAPSALATION : The wrapping up of data and function into a


single unit (called class) is known as encapsulation. The data is not
accessible to the outside world and only those functions which are
wrapped in the class can access it. These functions provide the
interface between the objects data and the program.
• INHERITENCE : Inheritance is the process by which objects of one
class acquire the properties of another class. In the concept of
inheritance provides the idea of reusability.
• This mean that we can add additional features to an existing class
with out modifying it. This is possible by designing a new class will
have the combined features of both the classes.
• POLYMORPHISIM: Polymorphism means the ability to take more
than one form. An operation may exhibit different instance. The
behavior depends upon the type of data used in the operation. A
language feature that allows a function or operator to be given more
than one definition. The types of the arguments with which the
function or operator is called determines which definition will be
used.
• DYNAMIC BINDING : Binding refers to the linking of a procedure call
to the code to the executed in response to the call. Dynamic binding
means the code associated with a given procedure call is not known
until the time of the call at run-time. It is associated with a
polymorphic reference depends upon the dynamic type of that
reference.
• MESSAGE PASSING : An object oriented program consists of a set of
objects that communicate with each other. A message for an object
is a request for execution of a procedure and therefore will invoke a
function (procedure) in the receiving object that generates the
desired result. Message passing involves specifying the name of the
object, the name of the function (message) and information to be
sent.

You might also like