Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

Structure:

 A structure is a user-defined data type available in C that allows to combining data items
of different kinds.
 Structures are used to represent a record.
 All the structure elements are stored at contiguous memory locations.
 Structure type variable can store more than one data item of varying data types under
one name.
 Structure is defined using “struct” keyword.

Syntax to define structure:


struct tag_name/structure_name
{
member-1;
member-2
};

Example:
Structure definition for storing student data
struct Student
{
int roll_no;
char name[20];
int fees;
};

Here,
 struct is a keyword.
 Student is name of the structure and it is also called as structure tag name.
 Roll_no,name and fees are the fields of the structure which is known as structure
members.
 There should be semicolon at the end of closing brace.

Note:
The structure definition does not reserve any space in memory for the members. So, it is
called a structure template and memory will not be allocated for the template. Memory is
allocated for the variables. This is pictorially represented as shown below for above defined
structure student:
 roll no -> int type = 4 bytes
 name[20]-> char type array = 20 bytes
 fees -> int type = 4 bytes
Total=28 byte

so whenever we will declare variable of student type it will take 28 bytes as per above
definition of student structure

Structure variable declaration:


Structure variables are used to access the members of structure. There are 2 ways to create a
structure variable.

1st way:

struct Student
{
int roll_no;
char name[20];
int fees;
} s1, s2, s3;

Here, s1, s2, s3 are the structure variables.

2nd way:

struct Student
{
int roll_no;
char name[20];
int fees;
};
int main()
{
struct Student s1,s2; //here s1 and s2 are the variables
return 0;
}

Structure Initialization
 Initializing structure variables is similar to that of array i.e. all the elements will be
enclosed within curly braces { } and are separated by comma (,).
 structure variables can be initialized in following ways:

1st way
struct student
{
int roll_no;
char name[20];
int fees;
} s1={10,“Neha”,54000},s2={12,”priya”,60000};

2nd way
struct Student
{
int roll_no;
char name[20];
int fees;
};
int main()
{
struct Student s1={19,”seema”,89000};
return 0;
}

3rd way
struct Student
{
int roll_no;
char name[20];
int fees;
};
int main()
{
struct Student s1;
e1.roll_no=76;
strcpy(e1.name,”Priyanka”);
e1.fees=34000;
return 0;
}

Accessing structure members


A member of a structure can be accessed using member access operator (.) dot, which in
turn is followed by member name.

Syntax
variable_name . member_name;

Example: Program to store student information using structure and display it.
#include<stdio.h>
struct student
{
int roll_no;
char name[20];
int fees;
}s1={76,"Priyanka",65000};
int main()
{
printf("Student information are\n");
printf("Name:%s",s1.name);
printf("\nRoll no:%d",s1.roll_no);
printf("\nFees:%d",s1.fees);
return 0;
}

Output:
Student information are
Name:Priyanka
Roll no:76
Fees:65000
Memory Representation

Program to display employee record and input from user for structure variable.

#include<stdio.h>
struct emp
{
int eid;
char name[20];
char desig[20];
int salary
};
int main()
{
struct emp e;
printf("Enter employee id:");
scanf("%d",&e.eid);
printf("Enter employee name:");
scanf("%s",&e.name);
printf("Enter employee designation:");
scanf("%s",&e.desig);
printf("Enter employee salary:");
scanf("%d",&e.salary);
printf("\nEmployee Details are\n");
printf("\nId:%d",e.eid);
printf("\nName:%s",e.name);
printf("\nDesignation:%s",e.desig);
printf("\nsalary:%d",e.salary);
return 0;
}
Output:
Enter employee id:1001
Enter employee name:John
Enter employee designation:Manager
Enter employee salary:45000

Employee Details are:


Id:1001
Name:John
Designation:Manager
salary:45000

ARRAY OF STRUCTURE
 As we create array of int, float, char etc. similarly we can create array of structure too.
 Suppose we want to store information of 5 students then instead of declaring 5
different variables, we can create array of structure

Program:
#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\n");
for(i=0;i<5;i++)
{
printf("Enter Rollno:");
scanf("%d",&st[i].rollno);
printf("Enter 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:10
Enter Name:Jenny
Enter Rollno:11
Enter Name:Riya
Enter Rollno:12
Enter Name:Sam
Enter Rollno:13
Enter Name:Seema
Enter Rollno:14
Enter Name:Neha

Student Information List:


Rollno:10, Name:Jenny
Rollno:11, Name:Riya
Rollno:12, Name:Sam
Rollno:13, Name:Seema
Rollno:14, Name:Neha

Structures and functions


By passing individual member of structure
A function can be called by passing the member of a structure as an actual
parameter.

Program
#include<stdio.h>
#include<string.h>
struct book
{
int bid;
char name[20];
int price;
};
void data(char[]);
int main()
{
struct book b;
b.bid=1001;
strcpy(b.name,"C Programming");
b.price=235;

data(b.name); //passing name member as parameter


}
void data(char n[20])
{
printf("Book name is %s",n);
}

Output:
Book name is C Programming
By passing whole member structure
While passing the whole structure just we need to pass the variable name.

Program
#include<stdio.h>
#include<string.h>
struct book
{
int bid;
char name[20];
int price;
};
void data(struct book);
int main()
{
struct book b;
b.bid=1001;
strcpy(b.name,"C Programming");
b.price=235;

data(b);
}
void data(struct book b1)
{
printf("\nBook id is %d",b1.bid);
printf("\nBook name is %s",b1.name);
printf("\nBook price is %d",b1.price);
}

Output
Book id is 1001
Book name is C Programming
Book price is 235
POINTER TO STRUCTURE
The structure pointer points to the address of a memory block where the Structure is being
stored. Like a pointer that tells the address of another variable of any data type (int, char,
float) in memory. And here, we use a structure pointer which tells the address of a structure
in memory by pointing pointer variable ptr to the structure variable.

Declare a Structure Pointer


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.

struct structure_name *ptr;

After defining the structure pointer, we need to initialize it, as the code is shown:

Initialization of the Structure Pointer

struct structure_name *ptr = &structure_variable;

As we can see, a pointer ptr is pointing to the address structure_variable of the Structure.

Access Structure member using pointer:


 Using arrow ( -> ) operator or membership operator.

Program to access the structure member USING arrow (->) operator


Let's consider a program to access the structure members using the pointer and arrow (->)
operator in C.

#include <stdio.h>
struct Employee
{
// define the member of the structure
char name[30];
int id;
int age;
char gender[30];
char city[40];
};

// define the variables of the Structure with pointers


struct Employee emp1, emp2, *ptr1, *ptr2;

int main()
{
// store the address of the emp1 and emp2 structure variable
ptr1 = &emp1;
ptr2 = &emp2;

printf (" Enter the name of the Employee (emp1): ");


scanf (" %s", &ptr1->name);

printf (" Enter the id of the Employee (emp1): ");


scanf (" %d", &ptr1->id);
printf (" Enter the age of the Employee (emp1): ");
scanf (" %d", &ptr1->age);
printf (" Enter the gender of the Employee (emp1): ");
scanf (" %s", &ptr1->gender);
printf (" Enter the city of the Employee (emp1): ");
scanf (" %s", &ptr1->city);

printf (" \n Second Employee: \n");


printf (" Enter the name of the Employee (emp2): ");
scanf (" %s", &ptr2->name);

printf (" Enter the id of the Employee (emp2): ");


scanf (" %d", &ptr2->id);
printf (" Enter the age of the Employee (emp2): ");
scanf (" %d", &ptr2->age);
printf (" Enter the gender of the Employee (emp2): ");
scanf (" %s", &ptr2->gender);
printf (" Enter the city of the Employee (emp2): ");
scanf (" %s", &ptr2->city);

printf ("\n Display the Details of the Employee using Structure Pointer");
printf ("\n Details of the Employee (emp1) \n");
printf(" Name: %s\n", ptr1->name);
printf(" Id: %d\n", ptr1->id);
printf(" Age: %d\n", ptr1->age);
printf(" Gender: %s\n", ptr1->gender);
printf(" City: %s\n", ptr1->city);

printf ("\n Details of the Employee (emp2) \n");


printf(" Name: %s\n", ptr2->name);
printf(" Id: %d\n", ptr2->id);
printf(" Age: %d\n", ptr2->age);
printf(" Gender: %s\n", ptr2->gender);
printf(" City: %s\n", ptr2->city);
return 0;
}

Output:
Enter the name of the Employee (emp1): John
Enter the id of the Employee (emp1): 1099
Enter the age of the Employee (emp1): 28
Enter the gender of the Employee (emp1): Male
Enter the city of the Employee (emp1): California

Second Employee:
Enter the name of the Employee (emp2): Maria
Enter the id of the Employee (emp2): 1109
Enter the age of the Employee (emp2): 23
Enter the gender of the Employee (emp2): Female
Enter the city of the Employee (emp2): Los Angeles

Display the Details of the Employee using Structure Pointer


Details of the Employee (emp1)
Name: John
Id: 1099
Age: 28
Gender: Male
City: California

Details of the Employee (emp2) Name: Maria


Id: 1109
Age: 23
Gender: Female
City: Los Angeles
Union:
 A union is a user-defined type similar to structs in C except for one key difference.
 Structure allocate enough space to store all its members whereas unions allocate the
space to store only the largest member.
 It is defined using union keyword.
 In union all members share the same memory.

Defining union:
union union_name
{
member-1;
member-2
member-n;
};

Example:
union Car
{
char name[20];
int price;
};

Create union variables


 When a union is defined, it creates a user-defined type. However, no memory is
allocated.
 To allocate memory for a given union type and work with it, we need to create
variables.

1st way:

union car
{
char name[50];
int price;
} car1, car2;
2nd way:

union car
{
char name[50];
int price;
};
int main()
{
union car car1, car2;
return 0;
}

Here,

 car1 and car2 are variables of car type.


 members of car type are name and price, name variable will occupy 50 bytes
whereas price will occupy 4 bytes, so the variable car1 and car2 will occupy 50 bytes,
because the size of a union variable will always be the size of its largest member. In
the above example, the size of its largest member (name[50]), is 50 bytes.

Assigning value in union variable


In union only one member can be initialized at once.

Correct way:

union Car
{
char name[20];
int price;
}c;
int main()
{
strcpy(c.name,” Ferrari “);
c.price=500000;
}
Incorrect way:

union Car
{
char name[20];
int price;
}c={“Ferrari”,400000};

Incorrect way:

union Car
{
char name[20];
int price;
}c;
int main()
{
union car c={“Ferrari”,500000);
return 0;
}

Program for union


#include <stdio.h>

union Job
{
float salary;
int workerNo;
} j;
int main()
{
j.salary = 12.3;
// when j.workerNo is assigned a value,
// j.salary will no longer hold 12.3
j.workerNo = 100;
printf("Salary = %.1f\n", j.salary);
printf("Number of workers = %d", j.workerNo);
return 0;
}
Output:
Salary = 0.0
Number of workers = 100

Difference between structure and union

File handling:
File:
A file is a container in computer storage devices used for storing data. File handling
in C enables us to create, update, read, and delete the files stored on the local file
system through our C program.

The following operations can be performed on a file.


1. Creation of the new file
2. Opening an existing file
3. Reading from the file
4. Writing to the file
5. Deleting the file

Why files are 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 number 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.

Functions for file handling:


There are many functions in the C library to open, read, write, search and close the
file. A list of file functions are given below.

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file

MODES Used In File Handling:


 r : opens a text file in reading mode.
 w : opens or creates a text file in writing mode.
 a : opens a text file in append mode.
 a+ : opens a text file in both reading and appending mode. New data is
appended at the end of the file and does not overwrite the existing content.

NOTE: Writing on the file will overwrite the previous content if we use “w” (write)
mode and in “a” (append) mode the previous contents appended with the new content.

Working with files:


When working with files, you need to declare a pointer of type file. This declaration is
needed for communication between the file and the program.
Syntax: FILE *fptr;
Example: FILE *fp;

Opening a file - for creation and edit:


Opening a file is performed using the fopen() function defined in the stdio.h header
file.
1) fopen():
 The fopen()in C is a library function that is used to open a file to perform various
operations which include reading, writing etc. along with various modes.
 If the file exists then the particular file is opened else a new file is created.

Syntax:
FILE pointer=fopen (file_name, mode );

Example:
FILE *fp;
fp= fopen(“demo.txt”,”w”);

Here, We are creating a text file named “demo.txt” in write “w” mode.

Program:
#include<stdio.h>
int main()
{
FILE *fp;
fp=fopen("demo.txt","w");
printf("file created successfully");
return 0;
}

Output:
File Created Successfully.
1. fclose():
 Whenever we open a file in read or write mode then we perform appropriate
operations on file and when file is no longer needed then we close the file and
fclose() function is used to close a file.

Syntax:
fclose(file_pointer);

Program:
#include<stdio.h>
int main()
{
FILE *fp;
fp=fopen("demo.txt","w");
printf("file created successfully\n");
fclose(fp);
printf("file closed");
return 0;
}

Reading and writing to a text file:


2. fprintf():
The fprintf() function is used to write set of characters into file. It sends formatted
output to a file.

Syntax:
 fprintf(file_pointer, ”string”);
 fprintf(file-pointer, ”format-specifiers” ,variable-name);

Program 1:

#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
return 0;
}

Output:

Program 2:

#include <stdio.h>
int main()
{
FILE *fp;
int a=10,b=20;
fp = fopen("file.txt", "a+");//opening file in append mode
fprintf(fp, "%d %d\n",a,b);
fclose(fp);//closing file return 0;
}
Output:

5) fscanf():
The fscanf() function is used to reads formatted input from a file and returns EOF
at the end of file.

Syntax:
fscanf( file-pointer, ”format specifiers”, variable_names);

program to read data from “sahyog.txt” file.

PROGRAM 1: without Condition

#include <stdio.h>
int main()
{
FILE *g;
g=fopen("sahyog.txt","r");
fscanf(g,"%d%s",&id,name);
printf("\n id is %d\n name is %s",id,name);
return 0;
}

Note: if you are not using Any Conditionusing NULL then only one record will bedisplayed.

Output:
PROGRAM 2: with Condition

#include <stdio.h>
int main()
{
int id;
char name[30];
FILE *g;
g=fopen("sahyog.txt","r");
while((fscanf(g,"%d%s",&id,name)!=EOF))
{
printf("%d\t %s\n",id,name);
}
return 0;
}

Output

6) rename(): This function is used to rename a file.

Syntax:
rename(old_name,New_name);
program:
#include <stdio.h>
int main()
{
rename("sahyog.txt", "priya.txt");
// renaming sahyog to priya printf("renamed");
return 0;
}

7) remove(): This function is used to remove (delete) a file.

Syntax:
remove(“file name”);
program:
#include <stdio.h>
int main()
{
remove("demo.txt");
printf(" file removed successfully.");
return 0;
}

Error:
Basically there are three types of errors in c programming:
1. Runtime Errors
2. Compile Errors
3. Logical Errors

1. Runtime Errors:
Runtime errors are those errors that occur during the execution of a c
program and generally occur due to some illegal operation performed in the
program.
Examples of some illegal operations that may produce runtime errors are:
 Dividing a number by zero
 Trying to open a file which is not created
2. Compile Errors:
Compile errors are those errors that occur at the time of compilation of the
program. C compile errors may be further classified as:

a) Syntax Errors:
When the rules of the c programming language are not followed, the
compiler will show syntax errors. For example, consider the statement,
int a,b :
The above statement will produce syntax error as the statement is terminated with :
rather than ;
Most frequent syntax errors are:
a. Missing Parenthesis ( } )
b. Printing the value of variable without declaring it
c. Missing semicolon (;)

b) Semantic errors :
This error occurs when the statements written in the program are not
meaningful to the compiler.
For example, consider the statement,
b+c=a;

In the above statement we are trying to assign value of a in the value


obtained by summation of b and c which has no meaning in c.
The correct statement will be
a=b+c;

3.Logical Errors:
On compilation and execution of a program, desired output is not obtained
when certain input values are given.
These types of errors which provide incorrect output but appears to be error
free are called logical errors.
 for(i = 0; i < 3; i++); // logical error : a semicolon after loop
 if(a=1) // logical error: assignment operator ”=” is used instead of “==”
Comparison operator

Command Line arguments


 The most important function of C/C++ is the main() function. It is mostly
defined with a return type of int and without parameters as shown below:

int main()
{
...
}
 Command-line arguments are handled by the main() function of a C/C++
program.
 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[])
{
/* ... */
}

 Here, argc counts the number of arguments. It counts the file name as the first
argument.
 The argv[] contains the total number of arguments. The first argument is the file name
always.

Program:
#include <stdio.h>
int main(int argc, char* argv[])
{
printf("You have entered %d arguments:\n", argc);
for (int i = 0; i < argc; i++)
{
printf("%s\n", argv[i]);
}
return 0;
}

Steps to run:
To pass parameter in main function click on execute->parameter->in the
first textbox enter values->click ok->execute the code.

Output:
You have entered 5 arguments:
C:\Users\Deepa\Desktop\fg.exe
10
hello
20
1.2

*********

You might also like