Advanced C with Madhav
1. Variable Naming Rules in C
Variables are names used to store data. Some rules are as follows:
✅ Valid Naming Rules:
-
Must start with a letter (A-Z or a-z) or underscore
_
-
Can contain letters, digits, and underscores (A-Z, a-z, 0-9, _)
-
Cannot start with a digit
-
No special characters like
@
,#
,%
,&
, etc. -
No spaces allowed
-
Cannot use C keywords (e.g.,
int
,float
,if
, etc.) -
Case-sensitive (e.g.,
score
,Score
, andSCORE
are different)
🛑 Invalid Examples:
✅ Valid Examples:
2. Format Specifiers in C
Format specifiers are used with printf()
and scanf()
for input/output.
Common Format Specifiers:
Specifier | Data Type | Example |
---|---|---|
%d | int (integer) | int age = 20; |
%f | float | float pi = 3.14; |
%lf | double | double d = 3.1415; |
%c | char | char grade = 'A'; |
%s | string (char array) | char name[20]; |
File Handling in C
File handling in C allows you to create, open, read, write, and close files. It’s a powerful feature that lets your programs store and retrieve data even after the program ends.
While handling a file in C, it has to be created/opened, perform read/write operations, and close the file as shown below:
Step 1: Creating/Opening the file
Syntax: file_pointer = fopen("file_name", "file_mode");
Example: fptr = fopen("student.dat", "r");
Step 2: Writing data to a file
Syntax: fprintf(file_pointer, "format_specifiers", variables);
Example: fprintf(fptr, "%d %s", rn, name);
Step 3: Reading data from a file
Syntax: fscanf(file_pointer, "format_specifiers", variables);
Example: fscanf(fptr, "%d %s", &rn, name);
Step 4: Closing the file
Syntax: fclose(file_pointer);
Example: fclose(fptr);
File Handling Modes in C
In C, file handling modes define how a file is opened and how you can interact with its contents. In other words, it specifies the purpose of opening a file.
There are mainly six modes, these modes are used with the fopen() function, which opens a file and returns a pointer to that file.
The various file handling (opening) modes in C are as follows:
1) "r" mode (Read): "r" mode opens an existing file for the purpose of reading only. The possible operation is reading from the file.
2) "w" mode (Write): "w" mode opens a file for the purpose of writing only. The possible operation is writing to the file.
3) "a" mode (Append): "a" mode opens an existing file for the purpose of appending (i.e., adding new information at the end of file).
4) "r+" mode (Read + Write): "r+" mode opens an existing file for the purpose of both reading and writing.
5) "w+" mode (Write + Read): "w+" mode opens a file for the purpose of both writing and reading.
6) "a+" mode (Append + Read): "a+" mode opens an existing file for the purpose of both reading and appending.
Workout Examples:
1) Write a C program to create and write data into a file.
Ans:
#include<stdio.h>
int main()
{
char name[20];
int rn, age;
FILE *fptr;
fptr=fopen("student.dat","w");
printf("Enter name:");
scanf("%s",name);
printf("Enter rollno:");
scanf("%d",&rn);
printf("Enter age:");
scanf("%d",&age);
fprintf(fptr,"\n%s\t%d\t%d",name,rn,age);
fclose(fptr);
return 0;
}
2) Write a C program to add data into a file.
Ans:
#include<stdio.h>
int main()
{
char name[20];
int rn, age;
FILE *fptr;
fptr=fopen("student.dat","a");
printf("Enter name:");
scanf("%s",name);
printf("Enter rollno:");
scanf("%d",&rn);
printf("Enter age:");
scanf("%d",&age);
fprintf(fptr,"\n%s\t%d\t%d",name,rn,age);
fclose(fptr);
return 0;
}
3) Write a C program to enter an ID, employee_name, and post of 100 employee and store them in a data file named "emp.txt".
Ans:
#include <stdio.h>
int main()
{
char employee_name[50], post[50];
int id, n, i;
FILE *fptr;
fptr = fopen("emp.txt", "w");
for (i = 0; i < 100; i++)
{
printf("Enter Employee ID: ");
scanf("%d", &id);
printf("Enter Employee Name: ");
scanf("%s", employee_name);
printf("Enter Employee Post: ");
scanf("%s", post);
fprintf(fptr, "\n%d\t%s\t%s", id, employee_name, post);
}
fclose(fptr);
return 0;
}
4) Write a C program to enter an ID, employee_name, and post of the employee and store them in a data file named "emp.txt".
Ans:
#include <stdio.h>
int main()
{
char employee_name[50], post[50];
int id, n, i;
FILE *fptr;
fptr = fopen("emp.txt", "w");
printf("Enter how many records:");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter Employee ID: ");
scanf("%d", &id);
printf("Enter Employee Name: ");
scanf("%s", employee_name);
printf("Enter Employee Post: ");
scanf("%s", post);
fprintf(fptr, "\n%d\t%s\t%s", id, employee_name, post);
}
fclose(fptr);
return 0;
}
4) Write a C program to enter an ID, employee_name, and post of the employee and store them in a data file named "emp.txt". Display each record on the screen in an appropriate format.
Ans:
#include <stdio.h>
int main()
{
char employee_name[50], post[50];
int id, n, i;
FILE *fptr;
printf("Enter the number of records: ");
scanf("%d", &n);
fptr = fopen("emp.txt", "w");
for (i = 0; i < n; i++)
{
printf("Enter Employee ID: ");
scanf("%d", &id);
printf("Enter Employee Name: ");
scanf("%s", employee_name);
printf("Enter Employee Post: ");
scanf("%s", post);
fprintf(fptr, "\n%d\t%s\t%s", id, employee_name, post);
}
fclose(fptr);
fptr = fopen("emp.txt", "r");
printf("\nID\tNAME\tPOST");
while (fscanf(fptr, "%d%s%s", &id, employee_name, post) != EOF
{
printf("\n%d\t%s\t%s", id, employee_name, post);
}
fclose(fptr);
return 0;
}
5) Write a C program to create and store name, gender, age, and mobile number of n students in a file named “ADDRESS.DAT”. The program should display records of students aged between 20 to 30 years.
Ans:
#include<stdio.h>
int main()
{
char name[50], gender, mobile[15];
int age, n, i, fc = 0;
FILE *fptr;
fptr = fopen("ADDRESS.DAT", "w");
printf("Enter number of students: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter Name: ");
scanf("%s", name);
printf("Enter Gender (M/F): ");
scanf(" %c", &gender);
printf("Enter Age: ");
scanf("%d", &age);
printf("Enter Mobile Number: ");
scanf("%s", mobile);
fprintf(fptr, "\n%s\t%c\t%d\t%s", name, gender, age, mobile);
}
fclose(fptr);
fptr = fopen("ADDRESS.DAT", "r");
printf("\nNAME\tGENDER\tAGE\tMOBILE");
while (fscanf(fptr, "%s %c %d %s", name, &gender, &age, mobile) != EOF)
{
if (age >= 20 && age <= 30)
{
printf("\n%s\t%c\t%d\t%s", name, gender, age, mobile);
}
}
fclose(fptr);
}
6) Write a C program to create and store name, gender, age, and mobile number of n students in a file named “ADDRESS.DAT”. The program should display records of students aged between 20 to 30 years and count the total number of "Female" students.
Ans:
#include<stdio.h>
int main()
{
char name[50], gender, mobile[15];
int age, n, i, fc = 0;
FILE *fptr;
fptr = fopen("ADDRESS.DAT", "w");
printf("Enter number of students: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter Name: ");
scanf("%s", name);
printf("Enter Gender (M/F): ");
scanf(" %c", &gender);
printf("Enter Age: ");
scanf("%d", &age);
printf("Enter Mobile Number: ");
scanf("%s", mobile);
fprintf(fptr, "\n%s\t%c\t%d\t%s", name, gender, age, mobile);
}
fclose(fptr);
fptr = fopen("ADDRESS.DAT", "r");
printf("\nNAME\tGENDER\tAGE\tMOBILE");
while (fscanf(fptr, "%s %c %d %s", name, &gender, &age, mobile) != EOF)
{
if (age >= 20 && age <= 30)
{
printf("\n%s\t%c\t%d\t%s", name, gender, age, mobile);
}
if (gender == 'F' || gender == 'f')
{
fc=fc+1;
}
}
printf("Total number of Female students: %d", fc);
fclose(fptr);
return 0;
}
7) Write a C program to create and store name, gender, age, and mobile number of n students in a file named “ADDRESS.DAT”. The program should display the total number of "Female" students aged between 20 to 30 years.
Ans:
#include<stdio.h>
#include<conio.h>
void main()
{
char name[50], gender, mobile[15];
int age, n, i, fc = 0;
FILE *fptr;
clrscr();
fptr = fopen("ADDRESS.DAT", "a");
printf("Enter number of students: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter Name: ");
scanf("%s", name);
printf("Enter Gender (M/F): ");
scanf(" %c", &gender);
printf("Enter Age: ");
scanf("%d", &age);
printf("Enter Mobile Number: ");
scanf("%s", mobile);
fprintf(fptr, "\n%s\t%c\t%d\t%s", name, gender, age, mobile);
}
fclose(fptr);
fptr = fopen("ADDRESS.DAT", "r");
printf("\nNAME\tGENDER\tAGE\tMOBILE");
while(fscanf(fptr, "%s %c %d %s", name, &gender, &age, mobile) != EOF)
{
if (age >= 20 && age <= 30 )
{
printf("\n%s\t%c\t%d\t%s", name, gender, age, mobile);
if (gender == 'F' || gender == 'f')
{
fc=fc+1;
}
}
}
printf("\nTotal number of Female students: %d", fc);
fclose(fptr);
getch();
}
8) Demonstrate a program in C to create a data file named score.dat to store students’ information with Reg_no, name, gender, and address. The program should ask the user to continue or not. When finished, the program should also display all the records in the proper format.
Ans:
#include<stdio.h>
int main()
{
char name[20], gender[10], address[50], ch;
int reg_no;
FILE *fptr;
fptr = fopen("students.dat", "w");
do
{
printf("Enter Registration Number: ");
scanf("%d", ®_no);
printf("Enter Name: ");
scanf("%s", name);
printf("Enter Gender (Male/Female/Other): ");
scanf("%s", gender);
printf("Enter Address: ");
scanf("%s", address);
fprintf(fptr, "\n%d\t%s\t%s\t%s", reg_no, name, gender, address);
printf("Do you need to enter more records (Y/N)? ");
scanf(" %c", &ch);
} while (ch == 'Y' || ch == 'y');
fclose(fptr);
fptr = fopen("students.dat", "r");
printf("\nREG NO\tNAME\tGENDER\tADDRESS");
while (fscanf(fptr, "%d%s%s%s", ®_no, name, gender, address) != EOF)
{
printf("\n%d\t%s\t%s\t%s", reg_no, name, gender, address);
}
fclose(fptr);
return 0;
}
(H/W) A] Write a C program to open a new file and read roll-no, name, address and phone number of students until the user says “no”, after reading the data, write it to the file then display the content of the file.
B] Write a C program to enter names, addresses and date of birth of 100 students and store them in a data file "student.dat".
Structure: Definition, Declaration, Initialization, Accessing, and Size of structure
A structure in C is a user-defined data type that allows grouping variables of different types under a single name. This helps to logically organize and manage related data. It is defined and declared using the ‘struct’ keyword followed by the structure name and a set of curly braces.
For example:
struct Student
{
int id;
float marks;
} s1;
Key Points about Structure:
1. Definition of Structure
The definition specifies the structure's layout, i.e., its members and their types.
Syntax:
struct StructureName
{
dataType member1;
dataType member2;
...
};
Example:
struct Student {
int id;
float marks;
};
2. Declaration of Structure
After defining a structure, we can declare variables of the structure type.
Syntax:
struct StructureName variableName;
Example:
struct Student s1;
3. Initialization of Structure
We can initialize a structure during declaration or later in the program.
a. Initialization at Declaration:
Syntax:
struct StructureName variableName = {value1, value2, ...};
Example:
struct Student s1 = {101, 87.5};
b. Initialization After Declaration:
We can assign values to members individually:
s1.id = 101;
s1.marks = 87.5;
4. Accessing Members of a Structure
To access individual members of a structure, use the dot operator (.).
Syntax:
structureVariable.memberName
Example:
printf("ID: %d", s1.id);
printf("Marks: %.f", s1.marks);
5. Size of Structure
The size of a structure is determined by the sizes of its members and compiler-imposed padding for alignment.
Syntax:
sizeof(struct StructureName)
Example:
printf("Size of Student structure: %d bytes", sizeof(struct Student));
4.3 Union vs Structure in C:
Both unions and structures are user-defined data types in C that allow grouping of different data types. However, they have significant differences in how they store data and how their members are accessed.
Structures:
Ø Definition: A structure is a user-defined data type that allows combining data items of different types.
Ø Memory Allocation: Each member of a structure has its own memory location.
Ø Size: The total size of a structure is the sum of the sizes of its members, including any padding bytes added for alignment.
Ø Access: All members can be accessed individually and simultaneously.
Ø Example:
struct Person {
char name[50];
int age;
float height;
}s1;
Unions:
Ø Definition: A union is a user-defined data type that allows storing different data types in the same memory location.
Ø Memory Allocation: All members of a union share the same memory location. The size of a union is equal to the size of its largest member.
Ø Size: The total size of a union is the size of its largest member.
Ø Access: Only one member can be accessed at a time, as they share the same memory location.
Ø Example:
union Data {
int i;
float f;
char str[20];
}s1;
Some important worked out examples:
Q1) Write a C program that uses structures to represent details of five books (title, author, publisher, and price) and prints them out.
1. Q2) Write a C program using structure to input staff ID, name, and the salary of 50 staff. Display staff ID, name, and salary of those staff whose salary ranges from 25 thousand to 40 thousand.
Q3) Write a C program to enter name, grade, age, and address of 10 students in a structure and display the information.
Comments
Post a Comment