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

Chapter 2 Structure Part 1

The document outlines a course on Problem Solving with Programming, focusing on C programming language and the use of structures and unions. It details course objectives, outcomes, evaluation schemes, and provides an introduction to structures, their declaration, initialization, and usage. Additionally, it includes examples, comparisons between structures and unions, and references for further reading.

Uploaded by

Sarthak Puri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Chapter 2 Structure Part 1

The document outlines a course on Problem Solving with Programming, focusing on C programming language and the use of structures and unions. It details course objectives, outcomes, evaluation schemes, and provides an introduction to structures, their declaration, initialization, and usage. Additionally, it includes examples, comparisons between structures and unions, and references for further reading.

Uploaded by

Sarthak Puri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

INSTITUTE - UIE

DEPARTMENT- ACADEMIC UNIT-2

Bachelor of Engineering (Computer Science & Engineering)


Subject Name: Problem solving with programming

Code:20CST111
Unit-3

Structure: Basics DISCOVER . LEARN . EMPOWER


Problem solving
with
programming
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 Title Level
Number

CO1 Identify​ situations where Understand


computational methods would
be useful.
CO2 Approach the programming tasks Remember
using techniques learnt and
write pseudo-code.
CO3 Choose the right data Understand
representation formats based on
the requirements of the
problem.
CO4 Use the comparisons and Understand
limitations of the various
programming constructs and
choose the right one for the task.
3
Scheme of Evaluation
Sr. Type of Assessment Weightage of actual Frequency of Task Final Weightage in Internal Remarks
No. Task conduct Assessment (Prorated
Marks)

1. Assignment* 10 marks of One Per Unit 10 marks As applicable to


each assignment course types depicted
above.
2. Time Bound 12 marks for each One per Unit 4 marks As applicable to
Surprise test course types
Test depicted above.
3. Quiz 4 marks of each quiz 2 per Unit 4marks As applicable to
course types
depicted above.
4. Mid-Semester Test** 20 marks for one 2 per semester 20 marks As applicable to
MST. course types
depicted above.
5. Presentation*** Non Graded: Engagement Only for Self Study
Task MNGCourses.

6. Homework NA One per lecture topic Non-Graded: Engagement As applicable to


(of 2 Task course types
questions) depicted above.
7. Discussion Forum NA One per Non Graded: Engagement As applicable to
Chapter Task course types depicted
above.
8. Attendance and NA NA 2 marks
Engagement Score
on BB
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
12
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};
}

13
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

14
Accessing Structure Members by Dot Operator
Example:
#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

15
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

16
17
18
Union
Like Structures, union is a user defined data type.

19
20
21
• In union, all members share the same memory location

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

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

24
Structure Vs Union

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

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

27
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

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

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

30
Output:

31
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;
}
32
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;};

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

34
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

35
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:
1. https://www.geeksforgeeks.org/structures-c/
2. https://www.studytonight.com/c/structures-in-c.php
3. https://www.tutorialspoint.com/cprogramming/c_structures.htm
4. https://www.geeksforgeeks.org/union-c/

YouTube Links:
1. https://www.youtube.com/watch?v=Ranc3VvjI88
2. https://www.youtube.com/watch?v=zdUhS4YSWHg
3. https://www.youtube.com/watch?v=t7MD-Elr05k
36
THANK YOU

For queries
Email: [email protected]

You might also like