Unit-V C Language Fybsc It
Unit-V C Language Fybsc It
Unit-V C Language Fybsc It
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.
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
1st way:
struct Student
{
int roll_no;
char name[20];
int fees;
} s1, s2, s3;
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;
}
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
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
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;
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.
After defining the structure pointer, we need to initialize it, as the code is shown:
As we can see, a pointer ptr is pointing to the address structure_variable of the Structure.
#include <stdio.h>
struct Employee
{
// define the member of the structure
char name[30];
int id;
int age;
char gender[30];
char city[40];
};
int main()
{
// store the address of the emp1 and emp2 structure variable
ptr1 = &emp1;
ptr2 = &emp2;
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);
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
Defining union:
union union_name
{
member-1;
member-2
member-n;
};
Example:
union Car
{
char name[20];
int price;
};
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,
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;
}
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
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.
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.
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;
}
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);
#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
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;
}
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;
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
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
*********