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

Lecture 3.2.1 Basics of Structure

Basics of Structure

Uploaded by

deepakshiraj299
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Lecture 3.2.1 Basics of Structure

Basics of Structure

Uploaded by

deepakshiraj299
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

UNIVERSITY INSTITUTE OF ENGINEERING

DEPARTMENT- ACADEMIC UNITS


FIRST YEAR ENGINEERING PROGRAMMES
Subject Name : Introduction to Problem Solving
Subject Code: 24CSH-101

Structure: Basics DISCOVER . LEARN . EMPOWER


Introduction to
Problem Solving

Course Objectives

The course aims to provide exposure to problem-


solving through programming.

The course aims to raise the programming skills


of students via logic building capability.

With knowledge of C programming language,


students would be able to model real world
problems. 2
Course
Outcomes
CO Course Outcome
Number

CO1 Remember the concepts related to fundamentals of C language,


draw flowcharts and write algorithm/pseudocode.

CO2 Understand the way of execution and debug programs in C lan-


guage.
CO3 Apply various constructs, loops, functions to solve mathematical
and scientific problem.

CO4 Analyze the dynamic behavior of memory by the use of pointers.

CO5 Design and develop modular programs for real world problems us-
ing control structure and selection structure.

3
ASSESSMENT PATTERN
The performance of students is evaluated as follows:

Theory Practical
Continuous Internal As- Semester End Examina- Continuous Internal Semester End Exam-
Components sessment (CAE) tion (SEE) Assessment (CAE) ination (SEE)

Marks 40 60 60 40
Total Marks 100 100

4
Introduction
• Structure is a user-defined datatype in C language which allows us to combine data
of different types together.
• Structure helps to construct a complex data type which is more meaningful.
• It is somewhat similar to an Array, but an array holds data of similar type only. But
structure on the other hand, can store data of any type, which is practical more
useful.

• For example: If I have to write a program to store Student information, which will
have Student's name, age, branch, permanent address, father's name etc, which
included string values, integer values etc, how can I use arrays for this problem, I
will require something which can hold data of different types together. In structure,
data is stored in form of records.

5
Defining a Structure
• struct keyword is used to define a structure. struct defines a new data type which is a collection
of primary and derived datatypes.
• Syntax:
struct [structure_tag]
{
//member variable 1
//member variable 2
...
}[structure_variables];

Note: The closing curly brace in the structure type declaration must be followed by a semicolon(;).

6
Example:
struct Student
{
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender;
};
Here struct Student declares a structure to hold the details of a student which consists of 4
data fields, namely name, age, branch and gender. These fields are called structure elements
or members.

Each member can have different datatype, like in this case, name is an array of char type and
age is of int type etc. Student is the name of the structure and is called as the structure tag.
7
Declaring Structure Variables
• It is possible to declare variables of a structure, either along with
structure definition or after the structure is defined.

• Structure variable declaration is similar to the declaration of any


normal variable of any other datatype.

• Structure variables can be declared in following two ways:


1. Declaring Structure variables separately
2. Declaring Structure variables with structure definition
8
Declaring Structure variables
separately
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};

struct Student S1, S2; //declaring variables of struct Student


9
Declaring Structure variables
with structure definition
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
}S1, S2;
Here S1 and S2 are variables of structure Student.
10
Initializing structure members
• 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.

11
Structure members can be initialized using curly braces ‘{}’. For
example, following is a valid initialization.
struct Point
{
int x, y;
};

int main()
{
// A valid initialization. member x gets value 0 and y
// gets value 1. The order of declaration is followed.
struct Point p1 = {0, 1};
}

12
Computing Size of Structure
without sizeof()
• We can calculate the size of structure using pointers. Below is the implementation.
#include<stdio.h>
struct MySize
{
int a;
int b;
};
int main()
{
struct MySize *Msz=0;
int size = ((char*)(Msz+1))-((char *)(Msz));
printf("\n Structure Size :[%d]", size);
return 0;
}
Output:
Structure Size :[8]

13
Structure Padding
• The sizeof for a struct is not always equal to the sum of sizeof of each
individual member.
• This is because of the padding added by the compiler to avoid
alignment issues.
• Padding is only added when a structure member is followed by a
member with a larger size or at the end of the structure.
• Different compilers might have different alignment constraints as C
standards state that alignment of structure totally depends on the
implementation.

14
Let’s take a look at the following examples for better understanding:
Case 1:
// C program to illustrate
// size of struct
#include <stdio.h>
int main()
{
struct A {
// sizeof(int) = 4
int x;
// Padding of 4 bytes
// sizeof(double) = 8
The red portion represents the padding added for
double z;
// sizeof(short int) = 2
data alignment and the green portion represents
short int y; the struct members. In this case, x (int) is followed
// Padding of 6 bytes by z (double), which is larger in size as compared to
}; x. Hence padding is added after x. Also, padding is
printf("Size of struct: %ld", sizeof(struct A)); needed at the end for data alignment.
return 0;
}
Output:
Size of struct: 24
15
Case 2:
// C program to illustrate
// size of struct
#include <stdio.h>
int main()
{
struct B {
// sizeof(double) = 8
double z; In this case, the members of the structure
// sizeof(int) = 4 are sorted in decreasing order of their
int x; sizes. Hence padding is required only at
// sizeof(short int) = 2 the end.
short int y;
// Padding of 2 bytes
};
printf("Size of struct: %ld", sizeof(struct B));
return 0;
}
Output:
Size of struct: 16
16
Case 3:
// C program to illustrate
// size of struct
#include <stdio.h>
int main()
{
struct C {
// sizeof(double) = 8
double z; In this case, y (short int) is followed by x (int) and
// sizeof(short int) = 2 hence padding is required after y. No padding is
short int y; needed at the end in this case for data alignment.
// Padding of 2 bytes
// sizeof(int) = 4 C language doesn’t allow the compilers to
int x; reorder the struct members to reduce the
}; amount of padding. In order to minimize
printf("Size of struct: %ld", sizeof(struct C)); the amount of padding, the struct
return 0; members must be sorted in a descending
} order (similar to the case 2).
Output:
Size of struct: 16
17
Accessing Structure Members
• Structure members can be accessed and assigned values in a number
of ways.
• Structure members have no meaning individually without the
structure.
• There are two types of operators used for accessing members of a
structure.
1. . Member operator
2. -> -Structure pointer operator

18
Accessing Structure Members by
Dot
Example: Operator
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {0, 1};

// Accessing members of point p1


p1.x = 20;
printf ("x = %d, y = %d", p1.x, p1.y);

return 0;
}

Output:
x = 20, y = 1
19
Accessing Structure Members by
Structure pointer operator
Example:
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {1, 2};
// p2 is a pointer to structure p1
struct Point *p2 = &p1;
// Accessing structure members using structure pointer
printf("%d %d", p2->x, p2->y);
return 0;
}
Output:
12

20
Union
• Like Structures, union is a user defined data type.
• In union, all members share the same memory location.

21
For example, In the following C program, both x and y share the same location. If we change x, we can
see the changes being reflected in y.

#include <stdio.h>
// Declaration of union is same as structures
union test {
int x, y;
};
int main()
{
// A union variable t
union test t;
t.x = 2; // t.y also gets value 2
printf("After making x = 2:\n x = %d, y = %d\n\n",
t.x, t.y);

t.y = 10; // t.x is also updated to 10


printf("After making y = 10:\n x = %d, y = %d\n\n",
t.x, t.y);
return 0;
}
22
Output:
After making x = 2:
x = 2, y = 2

After making y = 10:


x = 10, y = 10

• To access any member of a union, we use the member access


operator (.).
• The member access operator is coded as a period between the
union variable name and the union member that we wish to
access.

23
Structure Vs Union

24
Uses of C Structure
• C Structures can be used to store huge data. Structures act as a
database.
• C Structures can be used to send data to the printer.
• C Structures can interact with keyboard and mouse to store the data.
• C Structures can be used in drawing and floppy formatting.
• C Structures can be used to clear output screen contents.
• C Structures can be used to check computer’s memory size etc.

25
Summary

A structure is a user defined data A structure creates a data type


type in C/C++In dynamic memory that can be used to group items ‘struct’ keyword is used to create
allocation, memory is allocated of possibly different types into a a structure.
at a run time. single type.

A structure variable can either be


declared with structure
Structure members are accessed
declaration or as a separate Structure members cannot be
using dot (.) operator and ->
declaration like basic types.that initialized with declaration.
operator.
allocates multiple memory
blocks at a time initialized to 0

A union is a special data type


Size of a union is taken according
available in C that allows to store
the size of largest member in
different data types in the same
union.
memory location.

26
Frequently Asked question
Q1 What will be the output of the C program?
#include<stdio.h>
int main()
{
struct leader
{
char *lead;
int born;
};
struct leader l1 = {"AbdulKalam", 1931};
struct leader l2 = l1;
printf("%s %d", l2.lead, l1.born);

Ans: AbdulKalam 1931

27
Q2. What will be the output of the C program?
void main()
{
struct bitfields {
int bits_1: 2;
int bits_2: 9;
int bits_3: 6;
int bits_4: 1;
}bit;
printf("%d", sizeof(bit));
}
Ans: 3

Q3. What are the similarities between structure and union?


Ans: Both are user-defined data types used to store data of different types as a single unit. Their members can be objects of any type,
including other structures and unions or arrays. A member can also consist of a bit field. Both structures and unions support only
assignment = and sizeof operators. The two structures or unions in the assignment must have the same members and member types.
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. A structure or union is passed by value just like a scalar variable as a corresponding parameter.
‘.’ operator is used for accessing members.

28
Q4. Write a program to Store Information in Structure and Display it?
#include <stdio.h> scanf("%s", s[i].firstName);
struct student { printf("Enter marks: ");
char firstName[50]; scanf("%f", &s[i].marks);
int roll; }
float marks;
} s[10]; printf("Displaying Information:\n\n");

int main() { // displaying information


int i; for (i = 0; i < 5; ++i) {
printf("Enter information of students:\n"); printf("\nRoll number: %d\n", i + 1);
printf("First name: ");
// storing information puts(s[i].firstName);
for (i = 0; i < 5; ++i) { printf("Marks: %.1f", s[i].marks);
s[i].roll = i + 1; printf("\n");
printf("\nFor roll number%d,\n", s[i].roll); }
printf("Enter first name: "); return 0;
}

29
Output:

30
Assessment Questions:
1. What is the output?

#include <stdio.h>

int main()
{
struct xyz{
int a;
};

struct xyz obj1={1};


struct xyz obj2 = obj1;
printf("%d", obj2.a);
obj2.a = 100;
printf("%d", obj1.a);
return 0;
}
31
2. What will be the output of the C program?

#include<stdio.h>
int main()
{
struct simp
{
int i = 6;
char city[] = "chennai";
};
struct simp s1;
printf("%d",s1.city);
printf("%d", s1.i);
return 0;

3. Which of the following is a properly defined struct?


A. struct {int a;}
B. struct a_struct {int a;}
C. struct a_struct int a;
D. struct a_struct {int a;};

32
4. What will be the output of the program?
#include <stdio.h>
struct cppbuzz{
};
int main()
{
printf("%d",sizeof(struct cppbuzz));
return 0;
}

33
Discussion forum.
• Watch this video to know more about how structures are stored in
memory and what is meant by structure padding.

https://www.youtube.com/watch?v=aROgtACPjjg

34
REFERENCES
Reference Books
1. Programming in C by Reema Thareja.
2. Programming in ANSI C by E. Balaguruswamy, Tata McGraw Hill.
3. Programming with C (Schaum's Outline Series) by Byron Gottfried Jitender
Chhabra, Tata McGraw Hill.
4. The C Programming Language by Brian W. Kernighan, Dennis Ritchie, Pearson
education.

Websites:
5. https://www.geeksforgeeks.org/structures-c/
6. https://www.studytonight.com/c/structures-in-c.php
7. https://www.tutorialspoint.com/cprogramming/c_structures.htm
8. https://www.geeksforgeeks.org/union-c/

YouTube Links:
9. https://www.youtube.com/watch?v=Ranc3VvjI88
10. https://www.youtube.com/watch?v=zdUhS4YSWHg
35
11. https://www.youtube.com/watch?v=t7MD-Elr05k
THANK YOU

You might also like