Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Structure

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

Structure

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

23GES01 – PROBLEM SOLVING AND

PROGRAMMING IN C

PREPARED BY,
Mrs.R.MOHANA,
MCA-MEC.
Structure

Structure in c is a user-defined data type that


enables us to store the collection of different data
types.

The struct keyword is used to define the


structure in the C programming language.

The items in the structure are called its


member and they can be of any valid data type.
C Structure Declaration

We have to declare structure in C before using it in our


program. In structure declaration, we specify its member
variables along with their data type.

struct structure_name
{
data_type member_name1;
data_type member_name1;
….
….
};
The above syntax is also called a structure template or
structure prototype and no memory is allocated to the structure
in the declaration.

Let’s see the example to define a structure for an entity


employee in c.

struct employee
{
int id;
char name[20];
float salary;
};
The size of the datatype depends on the type of
machine .

Here, struct is the keyword; employee is the name


of the structure; id, name, and salary are the members
or fields of the structure
Structure Variables

We can declare a variable for the structure so that we


can access the member of the structure easily. There are two
ways to declare structure variable:

1. Structure Variable Declaration with Structure Template

struct structure_name
{
data_type member_name1;
data_type member_name1;
….
….
}variable1, varaible2, …;
EXAMPLE:

struct student
{
int rollno;
char name[20];
}stud1,stud2;

Here stud1 and stud2 are structure variables .


2. Structure Variable Declaration after Structure
Template

struct structure_name variable1, variable2, …….;

struct student
{
int rollno;
char name[20];
};

struct student stud1,stud2;


Access Structure Members

We can access structure members using the ( . )


dot operator.

Syntax

structurename.member1;
strcuturename.member2;
//Program example to declare a Structure, structure member and access a
Structure varaible:
#include <stdio.h>
#include<conio.h>
struct student
{
int rollno;
char name[20];
};
void main()
{
struct student s1;
s1.rollno = 101;
s1.name=”Raksha”;
printf(“%d”,s1.rollno);
printf(“%s”,s1.name);
}
Here a structure is defined called a student,
which consists of a rollno and a name for its
members.

s1 is a structure variable declared in the


program.
Here we are assigning the value to the structure
members with the help of the dot(.) operator.

Now we are accessing the values of the members


dot operator.

Output – 101 Raksha


STRUCTURE IS INITIALIZE
We can also initialize the structure variable at the time
of creation of Variables.

For example:
struct student
{
int roll_no;
char name[20];
int age;
};
………….
struct student s1={1,”vansh”,23};

This will make following initialization,


s1.roll_no=1,s1.name=”vansh”. S1.age=23.
If all the value are not supplied but partial initialization
is made,

Then rest will be initialized as zero for number and


NULL to strings.

For Example:

struct student s1={1 ,”vansh”};

will assign 1 to s1.roll_no and “vansh” to s1.name and third


value is zero.
Array of Structures in C

An array having structure as its base type is known as


an array of structure.

In an array of structure, each element of the array


representing a structure variable.

For example: struct student s[50];

It defines an array s[50] that consists of 50 elements.

Following ex. shows how an array of structure can be


declared:
Struct marks
{
int x;
int y;
};
void main()
{
struct marks[3]={{5,7},{7,9},{9,10}
};

This array can looks as shown in below,

S[0].x=5;
S[0].y=7;
S[1].x=7;
S[1].y=9;
S[2].x=9;
S[2].y=10;
// Program example to demonstrate Array of Structures

#include<stdio.h>
#include<conio.h>

struct student
{
char name[30];
int roll;
float marks;
};

void main()
{
struct student s[3];
int i;
for(i=0;i< 3;i++)
{
printf(“Enter name, roll and marks of student:\n”);
scanf(“%s%d%f”,s[i].name, &s[i].roll, &s[i].marks);
}

printf(“Inputted details are:\n”);

for(i=0;i< 3;i++)
{
printf(“Name: %s\n”,s[i].name);
printf(“Roll: %d\n”, s[i].roll);
printf(“Marks: %0.2f\n\n”, s[i].marks);
}

getch();
}
struct car
{
char make[20]; Inside the Memory
char model[30];
int year;
};
struct car
arr_car[10];
POINTER TO STRUCTURE
For representing complex data structures , we
can use structures and pointers together.
Pointer can be member of structure , or pointer to
structure , or an array of pointers to str.

Syntax for declare:


struct structure name
{
data type member;
datatype member;
};
------
struct structure name *ptr var structure var name;
pointer variable =&structure var name;
For Example:
struct student
{
int roll_no;
char name[20];
char address[30];
int age;
}:
……….
………..
struct student *sptr,s1;
sptr=&s1;

Now,sptr points to s1 and can be used to access member variables


of struct student.
To access member variables using pointer to
structure,we have to use an arrow -> operator.

The Syntax is: struct_pointer->member_var;

The struct_pointer is a pointer to structure, and


member_var is the name of member variable.

For Example: S1->roll_no=20;

We can also use dot(.)operator to access member


variable like: (*s1).roll_no=20;

Both above statements do the same things.


// C Program to demonstrate Structure pointer
#include <stdio.h>
#include <string.h>

// Creating Structure Student


struct Student {
int roll_no;
char name[30];
char branch[40];
int batch;
};
// variable of structure with pointer defined
struct Student s, *ptr;
int main()
{
ptr = &s;
// Taking inputs
printf("Enter the Roll Number of Student\n");
scanf("%d", &ptr->roll_no);
printf("Enter Name of Student\n");
scanf("%s", &ptr->name);
printf("Enter Branch of Student\n");
scanf("%s", &ptr->branch);
printf("Enter batch of Student\n");
scanf("%d", &ptr->batch);
// Displaying details of the student
printf("\nStudent details are: \n");

printf("Roll No: %d\n", ptr->roll_no);


printf("Name: %s\n", ptr->name);
printf("Branch: %s\n", ptr->branch);
printf("Batch: %d\n", ptr->batch);

return 0;
}
Output:
Enter the Roll Number of Student
27
Enter Name of Student
Kamlesh_Joshi
Enter Branch of Student
Computer_Science And Engineering
Enter batch of Student
2019

Student details are:

Roll No: 27
Name: Kamlesh_Joshi
Branch: Computer_Science_And_Engineering
Batch: 2019
Nested Structure in C

A nested structure in C is a structure


within structure.

One structure can be declared inside


another structure in the same way structure
members are declared inside a structure.
Syntax of Nested Structure in C

struct outer_struct
{
outer_member1;
outer_member2;
struct inner_struct
{
inner_member1;
inner_member2;
} innervariable;
};
Example –

struct college
{
int numberOfStudents;
int numberOfTeachers;
struct student
{
char name[50];
int class;
int roll_Number;
} std;
};
In the above example of nested structure in C, there are
two structures Student (depended structure) and another
structure called college(Outer structure).

The structure college has the data members like number


Of Students, number Of Teachers, etc.

And the Student structure is nested inside the structure


School and it has the data members like name, class,
roll_Number , etc.
To access the members of the nested student
structure,

you would use the following syntax:

struct college c;
c.std.name=”OJ”;
c.std.class = 10;
c.std.roll_Number = 1;
Self-referential Structures

A self-referential structure is a struct data type in C, where one or


more of its elements are pointer to variables of its own type.

They are extensively used to build complex and dynamic data structures
such as linked lists and trees.
EXAMPLE:

typedef struct Node


{
int data;
struct Node *next; // Pointer to the same type of structure
} Node;

In this structure, data holds the value, and next is a


pointer to the next Node in the list.

This self-reference (next) allows each Node to be linked


to another Node, forming a chain.
How Does It Work?

Creating Linked Elements: Each node points to the next


node in the list. The last node in the list points to NULL,
indicating the end of the list.

Dynamic Data Structure: Since each node only contains a


reference (pointer) to the next node, the total number of nodes
in the structure can grow or shrink at runtime, making it a
dynamic data structure.

Memory Efficiency: Memory for each node is allocated as


needed, which can be more efficient than allocating a large
array of data that may not be fully utilized.
typedef struct NODE
{
struct NODE *new; /* 'new' a pointer-to-struct NODE */
int value;
}Node;
int main(void)
{
Node previous, current;

/* accessing members of 'previous' */


previous.new = &current;

/* previous.new is a 'pointer-to-struct NODE' */


previous.value = 100;
}
TYPEDEF

The typedef is a keyword that is used to provide existing data


types with a new name.

The C typedef keyword is used to redefine the name of already


existing data types.

Syntax: typedef existing_data_type new_name;

typedef: The keyword that indicates the creation of a new type.


existing_data_type: The data type for which a new name is being
created.
new_name: The alias or new name assigned to the existing data type.
Example:
#include <stdio.h>

// Define an alias for the data type unsigned short integer


typedef unsigned short int UnshInt;

int main()
{
// Declare variables using the typedef'd alias
UnshInt x = 10;
UnshInt y = 20;
UnshInt sum = x + y;
printf("The sum of %d and %d is %hu\n", x, y, sum);
return 0;
}

The sum of 10 and 20 is 30.


EXAMPLE 2:

#include <stdio.h>
typedef int myint; // Define a new type name myint for the int data type
int main()
{
int x;
myint y; // Declare a variable y of type myint
typedef myint smallint; // Define a new type name smallint as an alias for
myint
smallint z;
printf("Enter 2 values: "); // Prompt the user to enter two values
scanf("%d %d", &x, &y);
z = x + y; // Calculate the sum of x and y and store the outcome in variable z
printf("Sum value is: %d", z); // Print the sum value
return 0;
}

Output:

Enter 2 values: 7 9
Sum value is: 16
Structure & typedef In C

We can use the typedef in C to create aliases for structure types and
define shorter, more descriptive names for these structures.

Syntax:
// Define a structure

struct structure_name
{
// Member variables
data_type member1;
data_type member2;
// ...
};
// Create an alias (typedef) for the structure
typedef struct structure_name alias_name;
struct structure_name: This is the name of the structure
being defined.

{ ... }: Within the curly braces, you list the member variables
of the structure.

data_type member: Each member variable consists of a data


type followed by a member name.

typedef: This keyword is used to create an alias for the


structure.

struct structure_name alias_name: Here, alias_name is the


alias that you're creating for the structure.
Example:

#include <stdio.h>
// Define a structure to represent a point in 2D space
struct Point
{
int x;
int y;
};

// Create an alias (typedef) for the Point structure


typedef struct Point Point2D;

int main()
{
Point2D p1 = {3, 5}; // Declare a variable of type Point using the typedef'd alias
// Access and print the coordinates of the point
printf("Coordinates of point p1: (%d, %d)\n", p1.x, p1.y);
return 0;
}
Output: Coordinates of point p1: (3, 5)
Pointers & typedef In C

The typedef in C allows developers to create aliases for pointer


types, providing more descriptive names for pointers and enhancing code
readability.

Syntax:
// Define a typedef for a pointer type
typedef existing_type* alias_name;

typedef: This keyword is used to create an alias for the pointer type.

existing_type*: This represents the existing pointer type that you want
to alias. It could be any valid pointer type.

alias_name: This is the alias you're creating for the pointer type. It can
be any valid C identifier.
Example:
#include <stdio.h>
#include <stdlib.h> // Include the header file for malloc and free

// Define a typedef for a pointer to an integer


typedef int* IntPtr;

int main() {
// Declare a variable of type IntPtr
IntPtr ptr;

// Allocate memory for an integer


ptr = (IntPtr)malloc(sizeof(int));

if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1; // Return error code
}
// Assign a value to the allocated memory
*ptr = 42;

// Print the value stored in the allocated memory


printf("Value stored at memory location %p: %d\n", (void*)ptr, *ptr);

// Free the allocated memory


free(ptr);

return 0;
}

Output:
Value stored at memory location 0xa002a0: 42
Union
A union in C programming is a user-defined data type that allows different
types of data to be stored in the same memory location.

Union can only hold the value of one of its members at any given time.

Syntax
union UnionName
{
member1_type member1_name;
member2_type member2_name;
// ... additional members ...
};
The union keyword indicates that we are declaring a union construct
whose name/ identifier is given by UnionName.

The terms member1_type and member2_type refer to the data types of the
members of the union. These can be different data types.

The identifiers/ names of the union members are member1_name, member2_name,


and so on.
Compiler Define The Size Of Union
Example
#include <stdio.h>

// Define a union named Data with three members: int, float, and char
union Data
{
int i;
float f;
char c;
};

int main()
{
// Declare a union variable named myUnion
union Data myUnion;

// Assign a value to the integer member 'i'


myUnion.i = 42;
printf("Integer value: %d\n", myUnion.i);
// Assign a value to the float member 'f'
myUnion.f = 3.14;
printf("Float value: %f\n", myUnion.f);

// Assign a value to the character member 'c'


myUnion.c = 'A';
printf("Character value: %c\n", myUnion.c);

/* Reprinting the value of union member i, but since all members of a union share the
same memory space this will lead to undefined behavior since the last value assigned
was to member c */
printf("Integer value: %d\n", myUnion.i);

return 0;
}

Output:
Integer value: 42
Float value: 3.140000
Character value: A
Integer value: 1078523201
Creating Variable Outside Main
This method allows you to define the union and create a
variable of that type in one block.
Syntax:
union UnionName
{
member1_type member1_name;
// Additional members, if any
};
union UnionName variableName;
Different Syntax for Initialization of Members of a Union
in C:
var1.member1 = value;

union unionName variableName = { .memberName = value};


EXAMPLE:

#include <stdio.h>

// Define a union named Person


union Person
{
int age;
float height;
char gender;
};

int main()
{
union Person person = { .age = 25 };
printf("Age: %d\n", person.age); // Output: Age: 25
return 0;
}

Output:
Age: 25
Accessing Members Pointer
Accessing members of a union in C with the arrow pointer (->) is
used when the union variable is a pointer.
It involves first declaring a pointer variable of the union type and
then using the arrow operator to access and manipulate its members.

The arrow pointer dereferences the pointer and accesses the


member directly.

Syntax:
//Declaring a pointer type union variable
union UnionName *ptrVariable;

// Accessing member using arrow operator


ptrVariable->member1_name;
EXAMPLE:
#include <stdio.h>
#include <stdlib.h> // For malloc and free
union Shape // Define a union with two members
{
int sides;
float radius;
};

int main()
{
union Shape *ptrShape; // Declare a pointer to a union variable
// Allocate memory for the union variable
ptrShape = (union Shape *)malloc(sizeof(union Shape));
ptrShape->sides = 4; // Access and assign value to union member using
arrow operator
printf("Number of sides: %d\n", ptrShape->sides); // Print the value of
the union member
free(ptrShape); // Free allocated memory
return 0;
}

Output: Number of sides: 4


Differences Between Structure & Union

Memory Allocation to Members:

Structures:Each member occupies its own separate memory space, resulting


in a size equal to the sum of the sizes of all its members. This means that a structure
holds all its members simultaneously, allowing access to each member individually.

Union: Memory is allocated to accommodate the largest member, but only


one member can be active or used at any given time.

Type Safety & Code Clarity:

Structures offer better type safety and clarity in code due to their explicit
declaration of multiple members.

Union require careful handling to ensure that the correct member is accessed
or modified at any given time.
File Handling
In C, you can create, open, read, and write to files by declaring a pointer of
type FILE, and use the fopen() function:

FILE *fptr;
fptr = fopen(filename, mode);

FILE is basically a data type, and we need to create a pointer variable to work
with it (fptr).
For now, this line is not important. It's just something you need when working
with files.

To actually open a file, use the fopen() function, which takes two parameters:
Filename-The name of the actual file you want to open (or create),
like filename.txt mode - A single character, which represents what
you want to do with the file (read, write or append):
w - Writes to a file
a - Appends new data to a file
r - Reads from a file
Create a File(open a file)

To create a file, you can use the w mode inside the fopen() function.

The w mode is used to write to a file. However, if the file does not exist,
it will create a file.

Closing the file

fclose() -- This will close the file when we are done with it.

it makes sure that,

Changes are saved properly

Other programs can use the file (if you want)

Clean up unnecessary memory space


Example

FILE *fptr;

// Create a file
fptr = fopen("filename.txt", "w");

// Close the file


fclose(fptr);

Note: The file is created in the same directory as your other C


files, if nothing else is specified.

On our computer, it looks like the following


Tip: If you want to create the file in a specific folder, just provide an absolute path
(remember to use double backslashes to create a single backslash (\),
like we specified in strings special characters):

fptr = fopen("C:\\directoryname\\filename.txt", "w");


Write To a File

The w mode means that the file is opened for writing.


To insert content to it, you can use the fprintf() function and add the
pointer variable (fptr in our example) and some text:

Example

FILE *fptr;

// Open a file in writing mode


fptr = fopen("filename.txt", "w");

// Write some text to the file


fprintf(fptr, "Some text");

// Close the file


fclose(fptr);
As a result, when we open the file on our computer, it looks like this:
Example

fprintf(fptr, "Hello World!");

As a result, when we open the file on our computer, it says "Hello


World!" instead of "Some text":
Append Content To a File
If you want to add content to a file without deleting the old content, you can use
the a mode.
The a mode appends content at the end of the file:
Example
FILE *fptr;

fptr = fopen("filename.txt", "a"); // Open a file in append mode

fprintf(fptr, "\nHi everybody!"); // Append some text to the file

fclose(fptr); // Close the file


As a result, when we open the file on our computer, it looks like this:
Read a File
To read from a file, you can use the r mode:
Example
FILE *fptr;

// Open a file in read mode


fptr = fopen("filename.txt", "r");

This will make the filename.txt opened for reading.

Next, we need to create a string that should be big enough to store the content of the file.

For example, let's create a string that can store up to 100 characters:

Example
FILE *fptr;

// Open a file in read mode


fptr = fopen("filename.txt", "r");

// Store the content of the file


char myString[100];
In order to read the content of filename.txt, we can use
the fgets() function.

The fgets() function takes three parameters:

Example
fgets(myString, 100, fptr);

The first parameter specifies where to store the file content, which
will be in the myString array we just created.

The second parameter specifies the maximum size of data to read,


which should match the size of myString (100).

The third parameter requires a file pointer that is used to read the
file (fptr in our example).
EXAMPLE:

FILE *fptr;

// Open a file in read mode


fptr = fopen("filename.txt", "r");

// Store the content of the file


char myString[100];

// Read the content and store it inside myString


fgets(myString, 100, fptr);

// Print the file content


printf("%s", myString);

// Close the file


fclose(fptr);

OUTPUT : Hello World!


To read every line of the file, you can use a while loop:
Example
FILE *fptr;

// Open a file in read mode


fptr = fopen("filename.txt", "r");

// Store the content of the file


char myString[100];

// Read the content and print it


while(fgets(myString, 100, fptr))
{
printf("%s", myString);
}

// Close the file


fclose(fptr);

OUTPUT:

Hello World!
Hi everybody!
THANK YOU

You might also like