Unit 5 Notes
Unit 5 Notes
STRUCTURES
Structure is a group of variables of different data types represented by a single name.
struct keyword to create a structure in C. The struct keyword is a short form of structured
data type.
Syntax:
struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;
…
};
struct struct_namevar_name;
or
struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;
…
} var_name;
var_name.memeber_name = value;
struct struct_namevar_name =
{value for memeber1, value for memeber2 …so on for all the members}
e.g
#include <stdio.h>
// Defining a structure
struct A {
int x;
};
int main() {
// Initializing member
a.x = 11;
printf("%d", a.x);
return 0;
}
Output:
11
e.g
#include <stdio.h>
int main() {
return 0;
}
Output
Ram 20 18.50
Krish 18 22.00
Uses of Structure in C
C structures are used for the following:
The structure can be used to define the custom data types that can be used to create some complex data
types such as dates, time, complex numbers, etc. which are not present in the language.
It can also be used in data organization where a large amount of data can be stored in different fields.
Structures are used to create data structures such as trees, linked lists, etc.
They can also be used for returning multiple values from a function.
Example of typedef
#include <stdio.h>
#include <string.h>
5.3
V.S/C.S.B.S
// struct with typedef rectangle
typedef struct rectangle {
int length;
int breath;
} rectangle;
int main() {
rectangle r1;
r1.length = 19;
r1.breath = 25;
return 0;
}
OUTPUT:
Length Of rectangle is : 19
Breath Of rectangle is: 25
Copy Structure
Copying structure is simple as copying any other variables. For example, s1 is copied into s2 using
assignment operator.
s2 = s1;
example:
#include <stdio.h>
struct Student {
int id;
char grade;
};
int main() {
struct Student s1 = {1, 'A'};
5.4
V.S/C.S.B.S
printf("\nStudent 1 ID: %d\n",
n", s1.id);
printf("Student 1 Grade: %c\n",
n", s1.grade);
return 0;
}
OUTPUT:
Student 2 ID: 1
Student 2 Grade: A
Student 1 ID: 1
Student 1 Grade: A
Student 2 ID: 1
Student 2 Grade: B
Student 1 ID: 1
Student 1 Grade: A
Note: in the above example , changing the grade of s2 does not change s1.
Array of Structures in C
An array of structures is an array with structure as elements.
For example:
Here, stu[5] is an array of structures. This array has 5 elements and these elements are structures of the
same type “student”. The element s[0] will store the values such as name, rollNum, address & marks of a
student, similarly element s[1] will store these details for another student and so on.
struct student {
char name[60];
int rollNum;
char address[60];
float marks;
} stu[5];
Designated initialization is a basic initialization of structure members that is typically used when
we only want to initialise a few structure members rather than all of them.
e.g
5.5
V.S/C.S.B.S
#include <stdio.h>
struct numbers
{
int num1, num2;
};
int main()
{
// Assignment using using designated initialization
struct numbers s1 = {.num2 = 22, .num1 = 11};
struct numbers s2 = {.num2 = 30};//num1 of s2 not initialized
Structure Pointer
A pointer to a structure allows us to access structure members using the ( -> ) arrow operator instead of
the dot operator.
#include <stdio.h>
// Structure declaration
struct Point {
int x, y;
};
int main() {
struct Point p = { 1, 2 };
return 0;
}
OUTPUT:
1 2
Nested Structures in C
The term "nested" refers to the act of placing or storing one thing inside another. Because structure in C is
a user-defined data type, we can specify another structure as its data member when creating a structure,
resulting in a structure with another structure inside it. The nested structure can also have stacked
structures.
e.g
#include <stdio.h>
5.6
V.S/C.S.B.S
// Child structure declaration
struct child {
int x;
char c;
};
int main() {
struct parent p = { 25, 195, 'A' };
Self Referential structures are those structures that have one or more pointer
pointerss which point to the same
type of structure, as their member.
#include <stdio.h>
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob1; // Node1
// Initialization
5.7
V.S/C.S.B.S
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
Output
3040
UNION
union is a user-defined data type that can contain elements of the different data types just like structure.
But unlike structures, all the members in the C union are stored in the same memory location. Due to this,
only one member can store data at the given point in time.
C Union Declaration
In this part, we only declare the template of the union, i.e., we only declare the members’ names and data
types along with the name of the union. No memory is allocated to the union in the declaration.
union name {
type1 member1;
type2 member2;
.
.
};
5.8
V.S/C.S.B.S
union name{
type member1;
type member2;
…
} var1, var2, …;
var1.member1;
where var1 is the union variable and member1 is the member of the union.
Initialize Union
The initialization of a union is the initialization of its members by simply assigning the value to it.
var1.member1 = val;
example:
#include <stdio.h>
union B{
int arr[10];
char y;
};
int main() {
return 0;
}
OUTPUT:
5.9
V.S/C.S.B.S
Sizeof A: 4
Sizeof B: 40
Example
#include <stdio.h>
int main() {
// Declare an instance of the union
union MyUnion data;
data.floatValue = 3.14;
printf("Float Value: %.2f\n",
n", data.floatValue);
5.10
V.S/C.S.B.S
return 0;
}
OUTPUT:
Integer Value: 42
Float Value: 3.14
String Value: Hello, Union!
Nested Union
example:
#include <stdio.h>
union Union1
{
int a;
char b;
};
union Union2
{
float x;
union Union1 nestedUnion;
};
int main()
{
union Union2 u;
u.nestedUnion.a = 10;
5.11
V.S/C.S.B.S
printf("Value of a: %d\n", u.nestedUnion.a);
u.x = 3.14;
printf("Value of x: %.2f\n", u.x);
u.nestedUnion.b = 'A';
printf("Value of b: %c\n", u.nestedUnion.b);
return 0;
}
OUTPUT:
Value of a: 10
Value of x: 3.14
Value of b: A
#include <stdio.h>
struct Employee
{
int empID;
char empName[20];
union
{
float hourlyRate;
int monthlySalary;
} payment;
};
int main()
{
struct Employee emp1;
emp1.empID = 101;
strcpy(emp1.empName, "Sunil");
emp1.payment.hourlyRate = 15.5;
printf("Hourly rate: %.2f\n", emp1.payment.hourlyRate);
emp1.payment.monthlySalary = 5000;
printf("Monthly salary: %d\n", emp1.payment.monthlySalary);
return 0;
}
OUTPUT:
Hourly rate: 15.50
Monthly salary: 5000
When passing structures to or from functions in C, it is important to keep in mind that the entire structure
will be copied. This can be expensive in terms of both time and memory, especially for large structures.
The passing of structure to the function can be done in two ways:
5.12
V.S/C.S.B.S
By passing all the elements to the function individually.
By passing the entire structure to the function.
struct car {
char name[30];
int price;
};
int main()
{
struct car c = { "Tata", 1021 };
print_car_info(c);
return 0;
}
OUTPUT:
Name : Tata
Price : 1021
struct car {
char name[30];
int price;
};
int main()
{
struct car c = { "Tata", 1021 };
print_car_info(&c);
return 0;
5.13
V.S/C.S.B.S
}
OUTPUT
Name : Tata
Price : 1021
struct student {
char name[20];
int age;
float marks;
};
return s;
}
int main()
{
// structure variable s1 which has been assigned the
// returned value of get_student_data
struct student s1 = get_student_data(); // return value is assigned to the structure
// displaying the information
printf("Name: %s\n", s1.name);
printf("Age: %d\n", s1.age);
printf("Marks: %.1f\n", s1.marks);
return 0;
}
OUPUT:
Enter name: ram
Enter age: 32
Enter marks: 78
Name: ram
Age: 32
5.14
V.S/C.S.B.S
Marks: 78.0
File Handling in C
File handling in C is the process in which we create, open, read, write, and close operations on a file. C
language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform
input, output, and many different C file operations in our program.
Reusability: The data stored in the file can be accessed, updated, and deleted anywhere and
anytime providing high reusability.
Portability: Without losing any data, files can be transferred to another in the computer system.
The risk of flawed coding is minimized with this feature.
Efficient: A large amount of input may be required for some programs. File handling allows you
to easily access a part of a file using few instructions which saves a lot of time and reduces the
chance of errors.
Storage Capacity: Files allow you to store a large amount of data without having to worry
wo about
storing everything simultaneously in a program.
Types of Files in C
A file can be classified into two types based on the way the file stores the data. They are as follows:
Text Files
Binary Files
C File Operations
C file operations refer to the different possible operations that we can perform on a file in C such as:
function purpose
fopen () Creating a file or opening an existing file
fclose () Closing a file
fprintf () Writing a block of data to a file
fscanf () Reading a block data from a file
getc () Reads a single character from a file
putc () Writes a single character to a file
getw () Reads an integer from a file
putw () Writing an integer to a file
Sets the position of a file pointer to a specified
fseek ()
location
5.15
V.S/C.S.B.S
function purpose
ftell () Returns the current position of a file pointer
rewind () Sets the file pointer at the beginning of a file
A file pointer is a reference to a particular position in the opened file. It is used in file handling to
perform all file operations such as read, write, close, etc. We use the FILE macro to declare the file
pointer variable. The FILE macro is defined inside <stdio.h> header file.
FILE* pointer_name;
1. Opening a file
fopen() function is used for opening a file.
Syntax:
While opening a file, you need to specify the mode. The mode that we use to read a file is “r” which is
“read only mode”.
for example:
FILE *fp;
fp = fopen("C:\\myfiles\\newfile.txt", "r");
The address of the first character is stored in pointer fp.
..
FILE fpr;
fpr = fopen("C:\\myfiles\\newfile.txt", "r");
if (fpr == NULL)
{
puts("Error while opening file");
exit();
}
Various File Opening Modes:
The file is opened using fopen() function, while opening you can use any of the following mode as per the
requirement.
Mode “r”: It is a read only mode, which means if the file is opened in r mode, it won’t allow you to write
and modify content of it. When fopen() opens a file successfully then it returns the address of first
character of the file, otherwise it returns NULL.
Mode “w”: It is a write only mode. The fopen() function creates a new file when the specified file doesn’t
exist and if it fails to open file then it returns NULL.
5.16
V.S/C.S.B.S
Mode “a”: Using this mode Content can be appended at the end of an existing file. Like Mode “w”,
fopen() creates a new file if it file doesn’t exist. On unsuccessful open it returns NULL.
File Pointer points to: last character of the file.
Mode “r+”: This mode is same as mode “r”; however you can perform various operations on the file
opened in this mode. You are allowed to read, write and modify the content of file opened in “r+” mode.
File Pointer points to: First character of the file.
Mode “w+”: Same as mode “w” apart from operations, which can be performed; the file can be read,
write and modified in this mode.
Mode “a+”: Same as mode “a”; you can read and append the data in the file, however content
modification is not allowed in this mode.
2. Reading a File
To read the file, we must open it first using any of the mode, for example if you only want to read the file
then open it in “r” mode. Based on the mode selected during file opening, we are allowed to perform
certain operations on the file.
#include <stdio.h>
int main()
{
/* Pointer to the file */
FILE *fp1;
/* Character variable to read the content of file */
char c;
5.17
V.S/C.S.B.S
This program asks the user to enter a character and writes that character at the end of the file. If the file
doesn’t exist then this program will create a file with the specified name and writes the input character
into the file.
#include <stdio.h>
int main()
{
char ch;
FILE *fpw;
fpw = fopen("C:\\newfile.txt","w");
if(fpw == NULL)
{
printf("Error");
exit(1);
}
return 0;
}
4. Closing a file
fclose(fp);
The fclose( ) function is used for closing an opened file. As an argument you must provide a pointer to the
file that you want to close.
return 0;
}
How to read/ write (I/O) Strings in Files – fgets&fputs
Here str represents the string (array of char) in which you are storing the string after reading it from file.
10 is the length of the string that needs to be read every time.
fpr is pointer to file, which is going to be read.
Why I used if(fgets(str, 10, fpr)==NULL as a logic to determine end of the file?
In the above examples, we have used ch==EOF to get to know the end of the file. Here we have used this
logic because fgets returns NULL when there is no more records are available to be read.
#include <stdio.h>
int main()
{
FILE *fpw;
fputs(str, fpw)
str – str represents the array, in which string is stored.
fpw – FILE pointer to the output file, in which record needs to be written.
5.20
V.S/C.S.B.S
Point to note about fputs:
fputs by default doesn’t add new line after writing each record, in order to do that manually – you can
have the following statement after each write to the file.
fputs("\n", fpw);
So far, we have learned file operations on text files, what if the files are binary (such as .exe file). The
above programs will not work for binary files, however there is a minor change in handling Binary files.
The main difference is the file name & modes. Lets understand this with the help of an example. Lets say
I have two binary files bin1.exe & bin2.exe – I want to copy content of bin1.exe to bin2.exe:
Types of pre-processor
processor directives
5.22
V.S/C.S.B.S
#include
#include preprocessor directive is used to include the contents of a specified file into the
source code before compilation. It allows you to use functions, constants, and variables from
external libraries or header files. There are two types:
#include <file_name>
#include "filename"
Here, file inclusion with double quotes ( ” ” ) tells the compiler to search for the header file in
the directory of source filewhile <> is used for system libraries.
Step 1. Create a own header file (let say MyHeader.h) and store it a folder ( say C:\
MyHeader.)
MyHeader.h
#include<stdio.h>
void add(int a, int b)
{
printf("Added value=%d\n", a + b);
}
void multiply(int a, int b)
{
printf("Multiplied value=%d\n", a * b);
}
Step 2: Create a C program ( say MyProgram.c) and store it in the same folder where the header file created
in step 1 ( say C:\ MyProgram.c). in this C program include the MyHeader.h as shown below:
MyProgram.c
#include <stdio.h>
#include "MyHeader.h"
int main()
{
add(4, 6);
multiply(5, 5);
printf("End");
return 0;
}
5.23
V.S/C.S.B.S
Step 3: go to the command prompt and type as follows:
-----------------------------------------------
#define
#define is a preprocessor directive used to define macros, which are essentially text
substitutions performed during compilation
int main() {
#define VALUE 2
// Check if VALUE is 3
#elif VALUE == 3
printf("Value is 3");
return 0;
}
o/p : Value is less than or equal to 2
5.24
V.S/C.S.B.S
command-line arguments
In C programming, command-line arguments allow users to pass data to a program when it's
executed from the command line. This data is accessed within the main() function using
the argc and argv parameters.
To pass command-line arguments, we typically define main() with two arguments: the first
argument is the number of command-line arguments and the second is a list of command-
line arguments.
Syntax
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
Here,
argc (ARGument Count) is an integer variable that stores the number of command-line
arguments passed by the user including the name of the program. So if we pass a value to a
program, the value of argc would be 2 (one for argument and one for program name)
The value of argc should be non-negative.
argv (ARGument Vector) is an array of character pointers listing all the arguments.
If argc is greater than zero, the array elements from argv[0] to argv[argc-1] will contain
pointers to strings.
argv[0] is the name of the program , After that till argv[argc-1] every element is command -
line arguments.
Example: lets create a c program argc1.c
#include <stdio.h>
// main function with argc (argument count) and argv (argument vector)
int main(int argc, char *argv[]) {
// Check the number of arguments passed
int i,sum=0;
printf("Number of arguments: %d\n", argc);
// Loop through and print each argument
for(i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
sum += atoi(argv[i]);
}
printf("SUM is %d",sum);
return 0;
}
5.25
V.S/C.S.B.S
E:\C_programming>gcc argc1.c -o argc1.exe
E:\C_programming>argc1.exe 1 3 5 6 7
Number of arguments: 6
Argument 0: argc1.exe
Argument 1: 1
Argument 2: 3
Argument 3: 5
Argument 4: 6
Argument 5: 7
SUM is 22
------------------------------
5.26
V.S/C.S.B.S