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

CModuleIV

Uploaded by

Anandakrishnan
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)
2 views

CModuleIV

Uploaded by

Anandakrishnan
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/ 16

MODULE IV

STRUCTURE

● A structure is a keyword that creates user defined data types in C.


● A structure creates a data type that can be used to group items of different types into a
single type.
● ie, Unlike an array, a structure can contain many different data types (int, float, char,
etc.).

Definition:-
● Structure in c is a user-defined data type that enables us to store the collection of
different data types.
● Each element of a structure is called a member.
● ‘struct’ keyword is used to create a structure.

Syntax:-
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memberN;
};

Example:-
struct employee
{ int id;
char name[20];
float salary;
};
Declaring structure variable
There are two ways to declare structure variable:
1. By struct keyword within main() function
struct employee
{ int id;
char name[50];
float salary;
};
Give below code inside the main() function-
struct employee e1, e2;

2. By declaring a variable at the time of defining the structure.

struct employee
{ int id;
char name[50];
float salary;
}e1,e2;

Accessing members of the structure

By using . (member or dot operator)

Eg. e1.id

Example:-

#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Arun");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}

Output:

employee 1 id : 101
employee 1 name : Arun

Array of Structures

● An array of structures in C can be defined as the collection of multiple structure


variables where each variable contains information about different entities.
● The array of structures is also known as the collection of structures.

Example of an array of structures that stores information of 5 students and prints it:-
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}

Output:

Enter Records of 5 students


Enter Rollno:1
Enter Name:Arun
Enter Rollno:2
Enter Name:Ram
Enter Rollno:3
Enter Name:Vijay
Enter Rollno:4
Enter Name:John
Enter Rollno:5
Enter Name:Sam

Student Information List:


Rollno:1, Name:Arun
Rollno:2, Name:Ram
Rollno:3, Name:Vijay
Rollno:4, Name:John
Rollno:5, Name:Sam
Structure and Pointer

● A structure pointer is defined as the pointer which points to the address of the
memory block that stores a structure.
● The declaration of a structure pointer is similar to the declaration of the structure
variable.
● So, we can declare the structure pointer and variable inside and outside of the main()
function.
● To declare a pointer variable in C, we use the asterisk (*) symbol before the variable's
name.
Syntax:
struct structure_name *ptr;

Initialization of the Structure Pointer:-


ptr = &structure_variable;

Example 1:
#include <stdio.h>
struct person
{
int age;
float weight;
};

int main()
{
struct person *personPtr, person1;
personPtr = &person1;

printf("Enter age: ");


scanf("%d", &personPtr->age);

printf("Enter weight: ");


scanf("%f", &personPtr->weight);

printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);

return 0;
}

Example 2:
// C program to demonstrate structure pointer
#include <stdio.h>

struct point {
int value;
};

int main()
{

struct point s;

// Initialization of the structure pointer


struct point* ptr = &s;

return 0;
}

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

struct Student {
int roll_no;
char name[30];
char branch[40];
int batch;
};

int main()
{

struct Student s1;


struct Student* ptr = &s1;

s1.roll_no = 2;
strcpy(s1.name, "Arun");
strcpy(s1.branch, "CHE");
s1.batch = 2022;

printf("Roll Number: %d\n", (*ptr).roll_no);


printf("Name: %s\n", (*ptr).name);
printf("Branch: %s\n", (*ptr).branch);
printf("Batch: %d", (*ptr).batch);
return 0;
}

Structure and Function

passing structures to a function:-

#include <stdio.h>
struct student {
char name[50];
int age;
};

// function prototype
void display(struct student s);

int main() {
struct student s1;

printf("Enter name: ");

// read string input from the user until \n is entered


// \n is discarded
scanf("%s", s1.name);

printf("Enter age: ");


scanf("%d", &s1.age);

display(s1); // passing struct as an argument

return 0;
}

void display(struct student s) {


printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nAge: %d", s.age);
}

Output:-

Enter name: Abin


Enter age: 21
Displaying information
Name: Abin
Age: 21

Program to return struct from a function:-

#include <stdio.h>
struct student
{
char name[50];
int age;
};

// function prototype
struct student getInformation();

int main()
{
struct student s;

s = getInformation();

printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nRoll: %d", s.age);

return 0;
}
struct student getInformation()
{
struct student s1;

printf("Enter name: ");


scanf("%s", s1.name);

printf("Enter age: ");


scanf("%d", &s1.age);

return s1;
}

Passing struct by reference:-


● During pass by reference, the memory addresses of struct variables are passed to the
function.

#include <stdio.h>
struct Complex
{
float real;
float imag;
} com;

void addNumbers(com c1, com c2, com *result);

int main()
{
com c1, c2, result;

printf("For first number,\n");


printf("Enter real part: ");
scanf("%f", &c1.real);
printf("Enter imaginary part: ");
scanf("%f", &c1.imag);

printf("For second number, \n");


printf("Enter real part: ");
scanf("%f", &c2.real);
printf("Enter imaginary part: ");
scanf("%f", &c2.imag);

addNumbers(c1, c2, &result);


printf("\nresult.real = %.1f\n", result.real);
printf("result.imag = %.1f", result.imag);

return 0;
}
void addNumbers(com c1, com c2, com *result)
{
result->real = c1.real + c2.real;
result->imag = c1.imag + c2.imag;
}

Union in C

● A union is a special data type available in C that allows to store different data types in
the same memory location.
● Unions provide an efficient way of using the same memory location for
multiple-purpose.

Syntax:

union [union name]


{
member definition;
member definition;
...
member definition;
};

(OR)

union [union name]


{
member definition;
member definition;
...
member definition;
}union variable declaration;

Example:

union abc
{
int a;
char b;
}var;
int main()
{
var.a = 66;
printf("\n a = %d", var.a);
printf("\n b = %d", var.b);
}

Advantages of union

● It occupies less memory compared to the structure.


● When you use union, only the last variable can be directly accessed.
● Union is used when you have to use the same memory location for two or more data
members.
● It enables you to hold data of only one data member.
Enumerated data type

● Enumeration (or enum) is a user defined data type in C.


● It is mainly used to assign names to integral constants, the names make a program
easy to read and maintain.

// An example program to demonstrate working of enum in C

#include<stdio.h>

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}

Output:
2

// Another example program to demonstrate working of enum in C

#include<stdio.h>

enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};

int main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);

return 0;
}

Output:

0 1 2 3 4 5 6 7 8 9 10 11

File
A file is a container in computer storage devices used for storing data. Or, A File can be used
to store a large volume of persistent data.

Why are files needed?


● When a program is terminated, the entire data is lost. Storing in a file will preserve
your data even if the program terminates.
● If you have to enter a large amount of data, it will take a lot of time to enter them all.
● However, if you have a file containing all the data, you can easily access the contents
of the file using a few commands in C.
● You can easily move your data from one computer to another without any changes.

Types of Files

1. Text files
● Text files are the normal .txt files.
● You can easily create text files using any simple text editors such as Notepad.
● When you open those files, you'll see all the contents within the file as plain text.
● You can easily edit or delete the contents.

2. Binary files
● Binary files are mostly the .bin files in your computer.
● Instead of storing data in plain text, they store it in the binary form (0's and 1's).

The following operations can be performed on a file.

Creation of the new file


Opening an existing file
Reading from the file
Writing to the file
Deleting the file

Following are the most important file management functions:-


How to Create a File:-
Whenever you want to work with a file, the first step is to create a file. A file is nothing but
space in a memory where data is stored.

FILE *fp;
fp = fopen ("file_name", "mode");

fopen is a standard function which is used to open a file.

● If the file is not present on the system, then it is created and then opened.
● If a file is already present on the system, then it is directly opened using this function.
Example:

#include <stdio.h>
int main() {
FILE *fp;
fp = fopen ("data.txt", "w");
}

How to Close a file:-


● One should always close a file whenever the operations on file are over. It means the
contents and links to the file are terminated. This prevents accidental damage to the
file.
Syntax:
fclose (file_pointer);

Example:

FILE *fp;
fp = fopen ("data.txt", "r");
fclose (fp);

Writing to a File:-

Library functions to write to a file:


● fputc(char, file_pointer): It writes a character to the file pointed to by file_pointer.
● fputs(str, file_pointer): It writes a string to the file pointed to by file_pointer.
● fprintf(file_pointer, str, variable_lists): It prints a string to the file pointed to by
file_pointer. The string can optionally include format specifiers and a list of variables
variable_lists.

Reading data from a File:-

● fgetc(file_pointer): It returns the next character from the file pointed to by the file
pointer. When the end of the file has been reached, the EOF is sent back.
● fgets(buffer, n, file_pointer): It reads n-1 characters from the file and stores the string
in a buffer in which the NULL character ‘\0’ is appended as the last character.
● fscanf(file_pointer, conversion_specifiers, variable_adresses): It is used to parse and
analyze data. It reads characters from the file and assigns the input to a list of variable
pointers variable_adresses using conversion specifiers. Keep in mind that as with
scanf, fscanf stops reading a string when space or newline is encountered.

Command Line Arguments

● It is possible to pass some values from the command line to C programs when they
are executed.
● These values are called command line arguments.
● The command line arguments are handled using main() function arguments where
argc refers to the number of arguments passed, and argv[] is a pointer array which
points to each argument passed to the program.

Example:-
#include <stdio.h>

int main( int argc, char *argv[] ) {

if( argc == 2 ) {
printf("The argument given is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments given.\n");
}
else {
printf("One argument expected.\n");
}
}
Output:-
./a.out hai
The argument given is testing

./a.out
One argument expected

Notes:
argc - argc (ARGument Count) is int and stores number of command-line arguments passed
by the user including the name of the program. So if we pass a value to a program, value of
argc would be 2 (one for argument and one for program name).

argv - argv(ARGument Vector) is array of character pointers listing all the arguments.

You might also like