NAOE 2214: Computer Programming For Engineers
NAOE 2214: Computer Programming For Engineers
02/06/21 2
STRUCTURES
• Similar to an array but more flexible
• A structure is a user defined data type that groups logically related data items of
different data types into a single unit, for convenient handling.
• A variable of structure type can store multiple data items of different data types
under the one name. As the data of employee in company that is name, Employee
ID, salary, address, phone number is stored in structure data type.
• An array allows you to store similar data types together while a structure is
different in the sense that it allows you to store different data types together.
02/06/21 3
STRUCTURES DEFINITION
Definition: •Keyword struct introduces the structure
struct tag_name definition
{
• tag_name, names the structure definition
data_type member1;
data_type member2;
------ ---------
}; •This statement defines a
Example: new data type called struct
struct ME172 ME172.
{
char student_name[50]; •Each variable of this data
int roll;
type will consist of a
float marks;
Name char grade; character variable called
of the }; student_name, an integer
type variable called roll. a float
02/06/21 variable called marks and a 4
STRUCTURES DEFINITION
• Variables declared within the braces of the structure definition are the
structure’s members.
• Members of the same structure type must have unique names, but two
different structure types may contain members of the same name
without conflict
• A structure format can be defined outside or within the main function.
Defining a structure format before the main function makes it global
and allowing it to be used by other functions which we will see later on.
02/06/21 5
Declaring Structure Variables
• Once the new structure data type has been defined one or more variables can be declared to
be of that type
02/06/21 6
Declaring Structure Variables
• It is also possible to combine the declaration of the structure type and the structure
variables in one statement
For example: is same as... or even...
02/06/21 7
Initializing Structures
• Like primary variables and arrays, structure variables can also be initialized
where they are declared. The format used is quite similar to that used to
initiate arrays.
• For example,
• struct ME172 std1= {“joy", 51 , 75.00, "A"};
* If there are fewer initializers in the list than members in the structure, the remaining
members are automatically initialized to 0 (or NULL if the member is a pointer).
* Structure variables defined outside a function definition (i.e., externally) are initialized
to 0 or NULL if they are not explicitly initialized in the external definition.
02/06/21 8
Accessing Structure Members
• Individual members of a struct variable may be accessed using the structure member
operator (the dot, “.”):
std1.roll ; std1.marks; std1.grade;
• The parentheses are needed here because the structure member operator (.) has a higher precedence than the pointer
dereferencing operator (*).
02/06/21 9
STRUCTURES
Simple examples
#include <stdio.h> printf(“Student’s name: %s \n”, student.name);
struct ME172 printf(“Student’s roll: %d \n”, student.roll);
{ printf(“Student’s marks: %f \n”, student.marks);
char name[50]; printf(“Student’s grade: %c ”, student.grade);
int roll;
float marks;
char grade;
};
void main(void)
{
struct ME172 student;
student.name = “Mohd. Aminul Hoque”;
student.roll = 58;
student.marks = 76.5;
student.grade = ‘A’;
02/06/21 10
STRUCTURES
Example 1
• Write a program that will first create a structure format of a grocery shop.
• The structure must contain a product name, the no. of products in the
inventory, the price per unit of that product, a character(Y or N) to show
whether there is a discount price available for the product.
• Declare a variable and take the following as input from the keyboard:
Product name: Playstation 4
No. of products: 30
Price per unit: 32000
Discount: N
• Finally print the input values
02/06/21 11
STRUCTURES
Solution:
#include <stdio.h> printf(“\n Enter the price of the product: ”);
struct product scanf(“%f”, &ps4.price);
{ printf(“\n Enter whether the product has discount”);
char name[50]; scanf(“%c”, &ps4.discount);
int num;
float price; printf(“Product name: %s”, ps4.name);
char discount; printf(“\n Product number: %d”, ps4.num);
}; printf(“\n Product price: %f”, ps4.price);
printf(“\n Product discount: %c”, ps4.discount);
void main(void) }
{
struct product ps4;
02/06/21 13
Arrays of structures
#include <stdio.h>
struct product
{
char name[50];
int num;
float price;
};
void main(void)
{
struct product food[3] = {{“KitKat, 10, 5.6}, {Pringles, 40, 20.8}, {Sprite, 60, 10.5}};
int i;
for (i=0; i<3; i++)
{
printf(“ Product: %s”, food[i].name);
printf(“\n Product number: %d”, food[i].num);
printf(“\n Product price: %f”, food[i].price);
printf(“\n\n\n”);
}
}
02/06/21 14
Arrays within structures
02/06/21 15
Structures within Structures(Nested Structure)
One structure can be nested within another structure. Using this facility
complex data types can be created.
The structure of Employee can be declared as The data member of structure within
struct employee structure is accessed by using dot (.)
{ int emp_id; symbol twice
char name[20];
float salary; For example:
int dept_no; e[0].joining.day;
struct date e[0].joining.month;
{ int day; e[0].joining.year;
int month;
int year;
} joining;
} e[50];
02/06/21 16
Pointers to Structures
The way we can have a pointer pointing to an int, or a pointer pointing to a char, similarly we
can have a pointer pointing to a struct. Such pointers are known as ‘structure pointers’.
main( )
{
*We can’t use ptr.name or ptr.callno because ptr is
struct book
not a structure variable but a pointer to a structure
{
char name[25] ;
char author[25] ;
int callno ;
};
struct book b1 = { "Let us C", "YPK", 101 } ;
struct book *ptr ; an arrow operator(->) must be used to refer to
ptr = &b1 ; the structure elements in case of ‘structure pointers’
printf ( "\n%s %s %d", b1.name, b1.author, b1.callno ) ;
printf ( "\n%s %s %d", ptr->name, ptr->author, ptr->callno ) ;
}
02/06/21 17
Structure to Function
Like an ordinary variable, a structure variable can also be passed to a function. Structures may be passed to
functions by passing individual structure members, by passing an entire structure or by passing a pointer to a
structure
main( ) struct book
{ {
struct book char name[25] ;
{ char author[25] ;
char name[25] ; int callno ;
char author[25] ; };
int callno ; main( )
}; {
struct book b1 = {" C programming ", " ABC ", 101 } ; struct book b1 = { " C programming ", " ABC ", 101 } ;
display ( b1.name, b1.author, b1.callno ) ; display ( b1 ) ;
} }
Example 2
•To solve this program, make a structure having two member , one is feet and
another inch.
•Then Pass structure variable (containing distance in feet and inch) to a function
and add the distance there.
02/06/21 19
Structure to Function
struct distance{
int feet; void Add(struct distance d1,struct distance d2,
float inch; struct distance d3)
}; {
void Add(struct distance d1,struct distance d2, struct distance d3);
void main() d3.feet=d1.feet+d2.feet;
{ d3.inch=d1.inch+d2.inch;
struct distance dist1, dist2, dist3; if (d3.inch>=12) {
printf("First distance\n"); d3.inch-=12;
printf("Enter feet: "); ++d3.feet;
scanf("%d",&dist1.feet); }
printf("Enter inch: "); printf("\nSum of distances = %d\'%.1f\"",d3.feet,
scanf("%f",&dist1.inch); d3.inch);
printf("Second distance\n");
printf("Enter feet: "); }
scanf("%d",&dist2.feet);
printf("Enter inch: ");
scanf("%f",&dist2.inch);
Add(dist1, dist2, dist3);
}
02/06/21 20
UNION
• Another custom data type
• Very much similar to structure
struct ME union me
{ {
char student_name[6]; char student_name[6];
int roll; int roll;
float marks; float marks;
char grade; char grade;
}student_1; }student_2;
02/06/21 21
Structure vs. Union
Memory Allocation: structure
. .. .. . … … . . .. .. . .
}
02/06/21 ME 172 : C Programming Sessional 23
Limitation of Union
void main(){
struct ME
{
char student_name[6];
int roll;
float marks;
char grade;
}student_1;
union me
{ !!!!Now Try This One!!!!
char student_name[6];
int roll;
float marks;
char grade;
}student_2;
student_1.roll=910061;
student_2.roll=910061;
student_1.marks=95;
student_2.marks=95;
printf("st1 roll: %d st1 marks: %.1f\n", student_1.roll, student_1.marks);
printf("st2 roll: %d st2 marks: %.1f\n", student_2.roll, student_2.marks);
} 02/06/21 24
• It is used to rename a built-in data type (int, char, float,…) or custom data type (struct, union, enum)
• Mainly used to reduce the complexity of codes by giving simple data type names
Format:
typedef char grade; • Rename char as grade
char first=‘A’;
• Two same statements
grade first=’A’;
12 bytes or 96
bits
02/06/21 27
main()
{
struct birth {
int day : 5; !!!!Try to run
int month : 4 ;
int year;}date;
this!!!!!
scanf("%d %d %d", &date.day, &date.month, &date.year);
printf("your date of birth is %d-%d-%d",date.day,date.month,date.year);
}
Limitations:
•bitfield can not take any manual input by scanf or other.
•bitfield can only be used in custom data type.
02/06/21 28
ASSIGNMENT
Tesla and Edison got the following marks in attendance, CT, and term
final exam of C programing.
Use Structure and bit field operation. Ensure that minimum memory is consumed
by your code.
02/06/21 ME 172 : C Programming Sessional 29
Thank you
The only true wisdom is in knowing; you know nothing.
Socrates
02/06/21 30