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

NAOE 2214: Computer Programming For Engineers

This document discusses structures in C programming. It defines a structure as a user-defined data type that groups related data items into a single unit. Structures allow storing of different data types together. The document provides examples of defining and declaring structure variables, initializing structures, accessing structure members, and arrays of structures. It demonstrates how to define a structure for student data and use it to store information for multiple students.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

NAOE 2214: Computer Programming For Engineers

This document discusses structures in C programming. It defines a structure as a user-defined data type that groups related data items into a single unit. Structures allow storing of different data types together. The document provides examples of defining and declaring structure variables, initializing structures, accessing structure members, and arrays of structures. It demonstrates how to define a structure for student data and use it to store information for multiple students.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 30

NAOE 2214

Computer Programming for


Engineers
Md Tusher Ahmed
Assistant Professor, Dept. of ME, BUET
02/06/21 1
Topic…………
1. CUSTOM DATA TYPES:
structure
union
enumeration
typedef
bit field
2. BITWISE OPERATORS

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.

* Each structure definition must end with a semicolon


* Do not confuse the tag_name with the structure variable declaration.
* Structure definitions do not reserve any space in memory; rather, each definition creates a new data type that is used
to define variables.

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

struct ME172 std1,std2,std3;


• Declares and sets aside storage for three variables – std1,
std2, and std3 – each of type struct ME172
struct ME172 std[25];
• Declares a 25-element array of struct ME172; allocates 25
units of storage, each one big enough to hold the data of one
ME172
struct ME172 *std;
• Declares a pointer to an object of type struct ME172

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...

struct ME172 struct


struct ME172
{ {
{
char std_name[50]; char std_name[50]; char std_name[50];
int roll; int roll; int roll;
float marks; float marks; float marks;
char grade; char grade; char grade;
}; } std1, std2, std3; } std1, std2, std3;

struct ME172 std1, std2, std3;

* The structure tag name is optional.


**If a structure definition does not contain a structure tag name, variables of the structure type must be declared in
the structure definition—not in a separate declaration.

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;
 

• Or , if a pointer to the struct has been declared and initialized


  Some_name *myptr = &std1 ;
  by using the structure pointer operator (the “->“):
  myptr -> roll ;
  which could also be written as:
  (*myptr).roll ;

• 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;

printf(‘’’Enter the name of the product: ”);


gets(ps4.name);
printf(“Enter the number of products: ”);
scanf(“%d”, &ps4.num);
02/06/21 12
Arrays of structures
Consider the previous structure variable which was declared:
struct ME172 student;
This is a structure variable for a single student containing the name,
roll, marks and grade of the student.
But, if one was to store the data of 30 students of section F1, 30
structure variables would have to be declared.
To overcome this problem we can declare an array of structures:
struct ME172 student[30];
The array student[30] will now contain the names, rolls, marks and
grades of the 30 students.

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

• Consider the structure format:


struct ME171
{
char student_name[50];
int roll;
float ct_marks[3];
};
Say, in the main we have declared struct ME171 student[10];

We have seen how individual characters of the structure can be accessed.


Now, if we were to access the 2nd ct mark of the 7th student, we would have to
write:
printf(“%f”, student[6].ct_marks[1]);

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 ) ;
} }

display ( char *s, char *t, int n ) display ( struct book b )


{ {
printf ( "\n%s %s %d", s, t, n ) ; printf ( "\n%s %s %d", b.name, b.author, b.callno ) ;
} }
02/06/21 18
Structure to Function

Example 2

**Write a C program to add two distances(feet-inch system)


entered by user.

•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

. .. .. . … … . . .. .. . .

grade roll student_name[6] marks


takes 1 byte takes 4 bytes takes 7 bytes takes 8 bytes
Total memory consumption 20 bytes
Memory Allocation: union
. . . .. .. .

grade takes 1 byte

roll takes 2 bytes


student_name[6] takes 7 bytes

marks takes 8 bytes


02/06/21 Total memory
ME 172 : C Programmingconsumption
Sessional only 8 bytes 22
Structure vs. Union
void main() {
struct ME
{
char student_name[6];
int roll;
float marks;
char grade;
}student_1;
union me Try yourself
{
char student_name[6];
int roll;
float marks;
char grade;
}student_2;

printf("size of struc_student_1: %d\n",sizeof(student_1));


printf("size of union_student_2: %d\n",sizeof(student_2));

}
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’;

typedef can not create a new data type.


It can just rename a complex data type.

02/06/21 ME 172 : C Programming Sessional 25


struct book typedef struct book
struct book // a new data type { {
{ char name[25] ; char name[25] ;
char name[25] ; char author[25] ; char author[25] ;
char author[25] ; int callno ; int callno ;
int callno ; }; }bk;
}; typedef struct book bk; // typedef struct book bk;
void display ( struct book); void display (bk); .
.
main( ) main( ) .
{ {
struct book b1 = { " C programming ", " ABC ", 101 } ; bk b1 = { " C programming ", " ABC ", 101 } ; // b1 is a bk type variable
display ( b1 ) ; display ( b1 ) ;
} }

display ( struct book b ) display (bk b)


{ {
printf ( "\n%s %s %d", b.name, b.author, b.callno ) ; printf ( "\n%s %s %d", b.name, b.author, b.callno ) ;
} }

02/06/21 ME 172 : C Programming Sessional 26


• If one choose an integer type variable as number, computer memory automatically assign 4 bytes(32
bits) place for its value.
• Now if I choose number = 3, it needs only 3 bits and the remaining 29 bits become useless which reduces
the effectiveness of code and memory allocation
• As a good programmer if one becomes sure about the maximum number of bits required for a
variable, then bit field operation reduces his headache.
main()
{
struct birth {int day; int month; int year;}date;
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);
}

day (4 bytes) month (4 bytes) year (4 bytes)

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);
}

day (5 bits) month (4 bits) year (4 bytes)


41 bits

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.

Write a C program to create a database of the following:


Name Attendance(30) CT(60) Term final exam(210) Grade
N. Tesla 30 57 200 A+
T. A. Edison 4 25 100 D

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

You might also like