Tuesday, November 5, 2024

Chapter : 4 Programming in C

Rules for Naming a Variable in C:

  1. Can only contain letters (A-Z, a-z), digits (0-9), and underscores (_).

    • student_age, num1, total_marks

    • student-age (hyphen not allowed)

  2. Must begin with a letter or an underscore (_), but not a digit.

    • _temp, data1

    • 1number (cannot start with a digit)

  3. Cannot be a C keyword (reserved word).

    • int, float, return (invalid because they are reserved words)

  4. Case-sensitive (uppercase and lowercase are different).

    • Total, total, and TOTAL are three different variables.

  5. Should not contain spaces.

    • studentMarks

    • student marks (space is not allowed)


4.2 Functions

4.2.1 Concept of library and user defined functions and advantages

Function: A function in C is a self-contained block of statements that performs a specific task, and it can be called from another part of the program whenever needed. It helps in modular programming, code reusability, and easy debugging. Functions are very important in C programming because they help in:

  1. Modular Programming: Breaks a program into small, manageable parts (modules).

  2. Code Reusability: Once a function is written, it can be used multiple times in a program.

  3. Easy Debugging and Maintenance: Errors are easier to find and fix in small functions.

  4. Improves Readability: Programs are easier to understand when divided into functions.

  5. Avoids Repetition: Common tasks can be written once as a function and called wherever needed.


Different types of functions are as follows:

1. Predefined (Library) Functions: Pre-written, built-in functions provided by C standard libraries. e.g. printf, scanf, sqrt.

2.  User-Defined Functions: Functions created by the programmer(user) to perform specific tasks. e.g. int add(int a, int b). The different types of user-defined functions are as follows:

a) Functions with No Arguments and No Return Value. e.g. void greet()

b) Functions with No Arguments but Return Value. e.g. int getFive()

c) Functions with Arguments but No Return Value. e.g. void printSquare(int n)

d) Functions with Arguments and Return Value. e.g. int add(int a, int b) 

Differences Between Library Functions and User-Defined Functions in C

Feature

Library Functions

User-Defined Functions

Origin

These are pre-defined functions that come bundled with the C compiler.

These are created by the programmer to meet the specific needs of a program.

Modification

The programmer cannot change the internal code of these functions.

The programmer has full control and can modify the code at any time.

Requirement

A specific header file (like <stdio.h>) must be included to use them.

No standard header file is required; the programmer defines them in the source code.

Naming

The names are fixed by the C standard (e.g., printf, sqrt).

The programmer can choose any valid name for the function.

Example

printf(), scanf(), strlen(), sqrt()

int add(int a, int b)

A function in C has three main components as follows:

1. Function Declaration (Prototype): It tells the compiler about the function before it is used.

Syntax:

return_type function_name(parameters);

Example:

int add(int, int);

2. Function Definition: It contains the actual code of the function.

Syntax:

return_type function_name(parameters)

{

    statements;

}

Example:

int add(int a, int b)

{

    return a + b;

}

Parts of function definition:

Return type → int

Function name → add

Parameters → int a, int b

Function body → code inside { }

3. Function Call: It is used to execute the function.

Syntax:

function_name(arguments);

Example:

sum = add(5, 3);

 

Some important worked out examples:

Q1) WAP in C to find sum of two number(integer) using user defined function.

#include <stdio.h>

int sum(int, int);

int main()

{

    int a, b, s;

    printf("Enter first number: ");

    scanf("%d", &a);

    printf("Enter second number: ");

    scanf("%d", &b);

    s = sum(a, b);

    printf("The sum of two numbers is %d", s);

    return 0;

}

int sum(int x, int y)

{

    int sm;

    sm = x + y;

    return sm;

}


Q2) Write a C program to enter the radius of a football and find the area of the football by using a user-defined function.

#include <stdio.h>

float area(float);

int main()

{

    float r, a;

    printf("Enter radius: ");

    scanf("%f", &r);

    a = area(r);

    printf("The area of the ball is %f", a);

    return 0;

}

float area(float x)

{

    float ar;

    ar = 4 * 3.14 * x * x;

    return ar;

}


Q 3) Write a C program to enter an integer(number) and find whether that number is even or odd using a user-defined function.
#include <stdio.h>
void check(int);
int main()
{
    int n;
    printf("Enter an integer number: ");
    scanf("%d", &n);
    check(n);
    return 0;
}
void check(int x)
{
    if (x % 2 == 0)
        printf("The number is Even");
    else
        printf("The number is Odd");
}


Q4) Write a C program to enter an integer(number) and find whether that number is positive, negative or zero using a user-defined function.

#include <stdio.h>

void check(int);

int main()

{

    int n;

    printf("Enter a number: ");

    scanf("%d", &n);

    check(n);

    return 0;

}

void check(int x)

{

    if (x > 0)

        printf("The number is Positive");

    else if (x < 0)

        printf("The number is Negative");

    else

        printf("The number is Zero");

}

5) Write a C program to greatest number among two using a user-defined function.

#include <stdio.h>

void great(int, int);   

int main()

{

    int a, b;

    printf("Enter first number: ");

    scanf("%d", &a);

    printf("Enter first number: ");

    scanf("%d", &b);

    great(a, b);  

    return 0;

}

void great(int x, int y)    

{

    if (x>y)

        printf("The greatest number is: %d",x);

    else

        printf("The greatest number is: %d",y);

}

PQ) Write a C program to smallest number among three using a user-defined function.

6) Write a program to find the sum of n integer number using function.

#include<stdio.h>

int sum(int);  

int main()

{

int n, s = 0;

printf("Enter number of integers: ");

scanf("%d", &n);

    s = sum(n);  

printf("The sum of integer numbers: %d", s);

return 0;

}

int sum(int x)  

{

int i, num, sm = 0; 

    for(i = 1; i <= x; i++)

{

printf("Enter a number: ");

scanf("%d", &num);

sm = sm + num;

}

return sm;

}


4.2.5 Concept of Recursion: factorial and Fibonacci problems

A recursive function in C is a function that calls itself to solve a problem. Recursion is a programming technique in which a function calls itself to solve a problem. It consists of two main parts: the base case and the recursive case as follows:
1. Base case: The condition that stops further recursive calls.
2. Recursive case: The part of the function where it calls itself.

WAP in C to find Factorial of a given number using recursive function:

#include <stdio.h>

int factorial(int);

int main()

{

    int n, fact;

    printf("Enter a number: ");

    scanf("%d", &n);

    fact = factorial(n);

    printf("The factorial is: %d", fact);

    return 0;

}

int factorial(int n)

{

    if (n == 0 || n == 1)

        return 1;

    else

        return n * factorial(n - 1);

WAP in C to find the nth term of a Fibonacci series using recursive function:

#include <stdio.h>
int fibonacci(int n);
int main() 
{
    int n, result;
    printf("Enter the term number: ");
    scanf("%d", &n);
    result = fibonacci(n);
    printf("The %dth term of the Fibonacci series is %d", n, result);
    return 0;
}

int fibonacci(int n) 
{
    if (n == 0)
        return 0;   
    else if (n == 1)
        return 1;   
    else
        return fibonacci(n - 1) + fibonacci(n - 2);
}


4.3 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 the sum of the sizes of all its members (plus padding if any).

Syntax:

sizeof(struct StructureName)

Example:

printf("Size of Student structure: %d bytes", sizeof(struct Student));


6. Array of Structure

An array of structure is a collection of structure variables of the same type.

Syntax:

struct StructureName arrayName[size];

Example:

struct Student s[3];

Here, 

s[3] is an array that can store 3 student records.
Each array element is a structure variable with members id and marks.


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:

Ø  DefinitionA structure is a user-defined data type that allows storing different types of data together under one name.

Ø  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 to store 10 student records with fields for roll numbers, names, and marks in computer science. Process and display the roll numbers, names, and marks of students.  

Ans:

#include <stdio.h>

struct student

{

    int rn, marks;

    char name[20];

};

int main()

{

    struct student s[10];

    int i;

    for (i = 0; i < 10; i++)

    {

        printf("\nEnter details for Student %d:\n", i + 1);

        printf("Enter Roll Number: ");

        scanf("%d", &s[i].rn);

        printf("Enter Name: ");

        scanf("%s", s[i].name);

        printf("Enter Marks in Computer Science: ");

        scanf("%d", &s[i].marks);

    }

    printf("\nThe Detail of Students in Tabular Form:\n");

    printf("\nROLL NO\tNAME\tMARKS");

    for (i = 0; i < 10; i++)

    {

        printf("\n%d\t%s\t%d", s[i].rn, s[i].name, s[i].marks);

    }

return 0;

}

 

Example Output:

Enter details for Student 1 

Enter Roll Number: 101

Enter Name: Madhav

Enter Marks in Computer Science: 99

.............

Enter Roll Number: 110

Enter Name: Ramesh

Enter Marks in Computer Science: 90

 

The Detail of Students in Tabular Form:



ROLL NO     NAME        MARKS

101              Madhav            99

........           ……..                  …

110              Ramesh             90

PQ) Write a C program that reads the account_number, name and address of ten customers from users and displays the account_number, name and address of these customers using Array and structure.

Q2) Define the structure. 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.   [2+6]

Ans:

#include <stdio.h>

struct staff

{

    int id;

    char name[30];

    float salary;

};

int main()

{

    struct staff s[50];

    int i;

    for(i = 0; i < 50; i++)

    {

        printf("\nEnter details of staff %d\n", i + 1);

        printf("Enter Staff ID: ");

        scanf("%d", &s[i].id);

        printf("Enter Name: ");

        scanf("%s", s[i].name);

        printf("Enter Salary: ");

        scanf("%f", &s[i].salary);

    }

    printf("\nThe Details of Staff with Salary between 25000 and 40000:\n");

    printf("\nID\tNAME\tSALARY");

    for(i = 0; i < 50; i++)

    {

        if(s[i].salary >= 25000 && s[i].salary <= 40000)

        {

            printf("\n%d\t%s\t%.2f", s[i].id, s[i].name, s[i].salary);

        }

    }

    return 0;

} 

 

Example Output:

Enter details of staff 1

Enter Staff ID: 101

Enter Name: Ram

Enter Salary: 30000

..............

Enter details of staff 50

Enter Staff ID: 150

Enter Name: Sita

Enter Salary: 45000

 

The Details of Staff with Salary between 25000 and 40000:

 

ID         NAME        SALARY

101      Ram           30000.00

......      ......            ......

150       Hari           38000.00

PQ1) Create a structure to store the name and salary of 100 employees and display the names of the employee getting salary between 10000 and 25000. 

PQ2) Write a C program using structure that reads the account_number, name and balance of ten customers from users and displays the details of those customers whose account contain more than 1 lakh.

Q3) Develop a program in C using structure to ask the information of any 12 students with roll number, name and marks scored in sub1, sub2, and sub3. Also, display them in proper format along with the calculation of total and percentage. [Note: the full mark of each subject is 100]. 

Ans:

#include <stdio.h>

struct student

{

    int roll;

    char name[30];

    int sub1;

    int sub2;

    int sub3;

    int total;

    float percentage;

};

int main()

{

    struct student s[12];

    int i;

    for(i = 0; i < 12; i++)

    {

        printf("\nEnter details of student %d\n", i + 1);

        printf("Enter Roll Number: ");

        scanf("%d", &s[i].roll);

        printf("Enter Name: ");

        scanf("%s", s[i].name);

        printf("Enter Marks in Subject 1: ");

        scanf("%d", &s[i].sub1);

        printf("Enter Marks in Subject 2: ");

        scanf("%d", &s[i].sub2);

        printf("Enter Marks in Subject 3: ");

        scanf("%d", &s[i].sub3);

        s[i].total = s[i].sub1 + s[i].sub2 + s[i].sub3;

        s[i].percentage = (s[i].total / 300.0) * 100;

    }

    printf("\nThe Details of Students with Total and Percentage:\n");

    printf("\nROLL\tNAME\tSUB1\tSUB2\tSUB3\tTOTAL\tPERCENTAGE");

    for(i = 0; i < 12; i++)

    {

        printf("\n%d\t%s\t%d\t%d\t%d\t%d\t%f",

               s[i].roll,

               s[i].name,

               s[i].sub1,

               s[i].sub2,

               s[i].sub3,

               s[i].total,

               s[i].percentage);

    }

    return 0;

}   

 

Example Output:

Enter details of student 1

Enter Roll Number: 101

Enter Name: Madhav

Enter Marks in Subject 1: 85

Enter Marks in Subject 2: 90

Enter Marks in Subject 3: 80

...............

Enter details of student 12

Enter Roll Number: 112

Enter Name: Ramesh

Enter Marks in Subject 1: 75

Enter Marks in Subject 2: 80

Enter Marks in Subject 3: 85

 

The Details of Students with Total and Percentage:

 

ROLL   NAME          SUB1    SUB2       SUB3        TOTAL   PERCENTAGE

101       Madhav          85              90            80            255              85

......      ......                  ......           .....          ......             ......              .....

112       Ramesh           75             80             85               240             80

PQ) Write a program to enter the roll number, name and five subject marks of student and calculate and display total using structure.


4.4 Pointers

In C programming, a pointer is a variable that stores the memory address of another variable.

Ø  Instead of holding data directly, pointer holds the address of the variable where the data is stored.

Ø  Pointers are widely used in C for dynamic memory allocation, efficient function calls, and working with arrays and strings.

Advantages of using pointers in C programming:

a) Efficient Memory Management: Pointers allow direct access to memory for dynamic allocation and deallocation.

b) Pass-by-Reference: Pointers enable functions to modify the actual values of variables, which improves performance.

c) Dynamic Data Structures: Pointers are essential for creating and managing dynamic data structures such as linked lists and trees.

d) Memory Sharing: Pointers allow different parts of a program to share and manipulate the same data.

e) Faster Data Processing: Pointers provide quick access to arrays and lists, resulting in faster data processing.

f) Direct Hardware Control: Pointers help in interfacing directly with hardware components of the computer.

Key Points about Pointers:

1) Declaration: A pointer is declared by placing an asterisk * before the pointer variable name.

Syntax:

dataType *pointerName;

Example:

int *ptr;

This declares a pointer ptr that can point to an integer variable.

2) Initialization: A pointer is initialized with the address of a variable using the address-of operator “&”.

Example:

int a = 10;

int *ptr = &a;

Here, ptr holds the address of a.

3) Dereferencing: The value at the memory address pointed to by the pointer can be accessed using the dereference (indirection) operator “*”.

Example:

printf("%d", *ptr);                                                             

This prints the value of a, which is 10.

 

Example 1(Sum of two numbers using pointer):

#include <stdio.h>   

int main()

{       

    int a, b, sum;

    int *ptr1 = &a;     // Declaration and Initialization of pointer ptr1

    int *ptr2 = &b;     // Declaration and Initialization of pointer ptr2

    printf("Enter first number: ");

    scanf("%d", ptr1); 

    printf("Enter second number: ");     

    scanf("%d", ptr2);

    sum = *ptr1 + *ptr2;     // Dereferencing pointers to access values and calculate sum

    printf("The sum of two numbers: ", sum);

    return 0;

}

Exampe 2(Check positive, negative or zero using pointer)

#include <stdio.h>   

int main()

{       

    int n;

    int *ptr = &n;          

    printf("Enter a number: ");

    scanf("%d", ptr); 

    if(*ptr>0)

    printf("Positive");

    else if(*ptr<0)

    printf("Negative");

    else

    printf("Zero");

    return 0;

}

Imp Q1) What is a pointer? Write the advantages of a pointer.  

Imp Q2) Write a C program to find the product of two numbers using a pointer. 


4.4.4 Call by value and Call by reference

Call by Value:

Ø Definition: A method of passing arguments to a function where the actual value of the argument is passed to the function's parameter.

Ø Effect: Changes made to the parameter within the function do not affect the original variable.

Ø Usage: Suitable for small or simple data types where modifying the original data is not required.

Example: 

void swap(int a, int b);

swap(a, b);

 

A C program to swap the values of two numbers using a function with call by value is as follows:

#include <stdio.h>

void swap(int, int);    //Function declaration

int main()

{

    int a, b;

    printf("Enter first number: ");

    scanf("%d", &a);

    printf("Enter second number: ");

    scanf("%d", &b);

    swap(a, b);   // Call by value

    return 0;

}

void swap(int x, int y)     //Function definition

{

    int temp;

    temp=x;

    x=y;

    y=temp;

    printf("The value of 1st variable after swap is: %d",x);

    printf("The value of 2nd variable after swap is: %d",y);

}


Call by Reference:

Ø Definition: A method of passing arguments to a function where the reference (address) of the argument is passed to the function's parameter.

Ø Effect: Changes made to the parameter within the function affect the original variable.

Ø Usage: Suitable for large or complex data types where modifying the original data is required.

Example: 

void swap(int *a, int *b);

swap(&a, &b);

 

A C program to swap the values of two numbers using a function with call by reference is as follows:

#include <stdio.h>

void swap(int *, int *);   //Function declaration

int main()

{

    int a, b;

    printf("Enter first number: ");

    scanf("%d", &a);

    printf("Enter second number: ");

    scanf("%d", &b);

    swap(&a, &b);    // Call by reference

    return 0;

}

void swap(int *x, int *y)    //Function definition

{

    int temp;

    temp=*x;

    *x=*y;

    *y=temp;

    printf("The value of 1st variable after swap is: %d",*x);

    printf("The value of 2nd variable after swap is: %d",*y);

}


4.5 Working with File

Concept of Data File:

A data file is defined as the collection of data or information which is permanently stored inside secondary memory as a single unit. We can read, write, append and delete data in data file as per our requirements.

File handling in C refers to the process of creating, reading, writing, and manipulating files on the disk using standard libraries functions.

File Operation Modes:

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 file handling (opening) modes in C, 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 the 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.

Note: IMP for MCQS:

  1. In "w" mode, if the file already exists, its contents are overwritten (content is deleted first and then written). If the file does not exist, a new file is created.
  2. In "r" mode, if the file exists, it loads into memory and sets up a pointer which points to the first character in it. If the file does not exist, it returns Null.
  3. In "a" mode, if the file exists, it loads into memory and sets up a pointer which points to the last character in it. If the file does not exist, a new file is created.

File Pointers Declaration / Opening a data file:
Syntax:
FILE * fptr;
fptr = fopen("file_name", "mode");

Here, 

Ø  FILE is the data structure.

Ø  fopen is a standard library function used to open a file.

Ø  fptr is a file pointer to the type file.

File Manipulation Functions / File handling functions:

1. Writing data to a file:
The file write operations can be performed by following functions:

a) fprintf() : The function fprintf() is a formatted output function which is used to write integers, float, char or string to a file. To use this function the file has to be opened on writing or appending mode.
Syntax:
fprintf(file_pointer, "format_specifiers", variable_list);

Example:
fprintf(fptr, "%d %s", rn, name);

Explanation: 

Above example writes the roll no with format specifier %d and name with format specifier %s into a file.

b) putc(): The function putc() is used to write a character to a file. To use this function the file has to be opened on writing or appending mode.
Syntax:

putc (character, file_pointer);

Example:
putc ('A', fptr);
Explanation:
Above example writes the character 'A' to a file.

c) putw(): The function putw() is used to write an integer in a binary format to a file. To use this function the file has to be opened on writing or appending mode.
Syntax:
putw (integer, file_pointer);

Example:
int n = 123;
putw(n, fptr);

Explanation:
Above example writes the integer 123 to a file in a binary format.

d) fputs() : The function fputs() is used to write a string to a file. To use this function the file has to be opened on writing or appending mode.
Syntax:
fputs(string, file_pointer);

Example:
fputs("Helloworld", fptr);

2. Reading data from a file:
The file read operations can be performed by following functions:

a) fscanf(): The function fscanf() is a formatted input function which is used to read integers, float, chars or strings from a file. To use this function the file has to be opened on reading mode.

Syntax:

fscanf(file_pointer, "format_specifiers", variable_list);

Example:

fscanf(fptr, "%d %s", &rn, name);

Explanation:
Above example reads the roll no with format specifiers %d and name with format specifiers %s from a file.

b) getc(): The function getc() is used to read a character from a file. To use this function the file has to be opened on reading mode.

Syntax:

getc(file_pointer);

Example:

getc(fptr);

c) getw(): The function getw() is used to read an integer in a binary format from a file. To use this function the file has to be opened on reading mode.

Syntax:

getw(file_pointer);

Example:

getw(fptr);

d) fgets(): The function fgets() is used to read a string from a file. To use this function the file has to be opened on reading mode.
Syntax:

fgets(string, n, file_pointer);

Here, n denotes the number of characters in a string.

Example:

fgets(s, 100, fptr);

3. Deleting file and Renaming file:

Ø  remove function is used to delete the file.
Syntax: remove("file_name");

Ø  rename function is used to rename the old file name into the new file name.
Syntax: rename("old_file_name","New_file_name");

Example:

#include<stdio.h>

int main()

{

    char name[20];

    FILE *fptr;

    fptr = fopen("file.txt", "w");

    printf("Enter your name:");

    scanf("%s", name);

    fprintf(fptr, "%s", name);

    fclose(fptr);

    rename("file.txt", "newfile.txt");

    remove("newfile.txt");

    return 0;

}


IMP Note: 

Binary file handling in C refers to reading and writing data in binary format to a file.

This means in binary file handling, the data is stored in the exact byte-for-byte format as it appears in memory, which is different from text file handling where the data is stored as human-readable text.

The primary functions used for binary file handling are:

a) fread()      b) fwrite()       c) putw()       d) getw()     e) fseek()       f) rewind(), etc.

Here's a simple example that demonstrates how to use putw() and getw() for writing and reading integers to and from a binary file:

#include <stdio.h>

int main()

{

    int num, i;

    FILE *fptr;

    fptr = fopen("numbers.bin", "wb");

    for (i = 1; i <= 10; i++)

    {

        putw(i, fptr);

    }

    fclose(fptr);


    fptr = fopen("numbers.bin", "rb");

    printf("Numbers in the file:\n");

    for (i = 0; i < 10; i++)

    {

        num = getw(fptr);

        printf("%d\n", num);

    }

    fclose(fptr);

    return 0;

}


Imp Q) Describe the file handling concept in C. 

Ans:

File handling in C is the process of creating, writing, reading, and manipulating data files on the disk using standard library functions (file manipulation/handling functions).

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);

 

Most Important worked out examples:

Q1) Write a program to create and write(store) data into a file.

                                                                       OR

Write a program to enter name, roll number and age of a student and store them in a data file "student.dat".

Ans: 

#include <stdio.h>

int main()

{

    char name[20];

    int rn, age;

    FILE *fptr;

    fptr = fopen("student.dat", "w");    

    if (fptr == NULL)

    {

        printf("Error opening file!");

        return 1;

    }

    printf("Enter name:");

    scanf("%s", name);

    printf("Enter rollno:");

    scanf("%d", &rn);

    printf("Enter age:");

    scanf("%d", &age);

    // Write data to the file using fprintf. 

    fprintf(fptr, "%s %d %d", name, rn, age);

    fclose(fptr);

    return 0;

}


Q2) Write a program to read and display(print) data from a file.

                                                                                    OR

Write a program to display name, age and roll number of a student reading from a file "student.dat".

Ans:

#include <stdio.h>
int main()
{
    char name[20];
    int rn, age;
    FILE *fptr;
    fptr = fopen("student.dat", "r");
    if (fptr == NULL)
    {
        printf("Error opening file!");
        return 1;
    }
    printf("\nNAME\tROLL NO\tAGE");
    // Read and Display data from the file.
    while (fscanf(fptr, "%s %d %d", name, &rn, &age) != EOF)
    {
        printf("\n%s\t%d\t%d", name, rn, age);
    }
    fclose(fptr);
    return 0;
}


Q3) Write a program to enter name, age and roll number of 10 students and store them in file "student.dat". Read and display the content of the file in an appropriate format.
Ans:
#include <stdio.h>
int main()
{
    char name[20];
    int rn, age, i;
    FILE *fptr;
    fptr = fopen("student.dat", "w");
    if (fptr == NULL)
    {
        printf("Error opening file!");
        return 1;
    }
    for (i = 0; i < 10; i++)
    {
        printf("Enter name:");
        scanf("%s", name);
        printf("Enter roll no:");
        scanf("%d", &rn);
        printf("Enter age:");
        scanf("%d", &age);
        fprintf(fptr, "\n%s\t%d\t%d", name, rn, age);
    }
    fclose(fptr);

    fptr = fopen("student.dat", "r");
    if (fptr == NULL)
    {
        printf("Error opening file!");
        return 1;
    }
    printf("\nNAME\tROLL NO\tAGE");
    while (fscanf(fptr, "%s %d %d", name, &rn, &age) != EOF)
    {
        printf("\n%s\t%d\t%d", name, rn, age);
    }
    fclose(fptr);
    return 0;
}


4) Write a program to enter name, age and roll number of the students (n students) and store them in file "student.dat". Read and display the content of the file in an appropriate format.
Ans:
#include <stdio.h>
int main()
{
    char name[20];
    int rn, age, n, i;
    FILE *fptr;
    fptr = fopen("student.dat", "w");
    if (fptr == NULL)
    {
        printf("Error opening file!");
        return 1;
    }
    printf("Enter number of record: ");
    scanf("%d", &n);
    for (i = 0; i < n; i++)
    {
        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);

    fptr = fopen("student.dat", "r");
    if (fptr == NULL)
    {
        printf("Error opening file!");
        return 1;
    }
    printf("\nNAME\tROLL NO\tAGE");
    while (fscanf(fptr, "%s%d%d", name, &rn, &age) != EOF)
    {
        printf("\n%s\t%d\t%d", name, rn, age);
    }
    fclose(fptr);
    return 0;
}

5) Write a program to enter name, age and roll number of the students and store them in file "student.dat". The program should ask the user to continue or not (until the user say 'NO'). When finished, read and display the content of the file in an appropriate format.
Ans:
#include <stdio.h>
int main()
{
    char name[20], ch;
    int rn, age;
    FILE *fptr;
    fptr = fopen("student.dat", "w");
    if (fptr == NULL)
    {
        printf("Error opening file!");
        return 1;
    }
    do
    {
        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);
        printf("Do you need more record (Y/N)? ");
        scanf(" %c", &ch);  
    } while (ch == 'Y' || ch == 'y');
    fclose(fptr);

    fptr = fopen("student.dat", "r");
    if (fptr == NULL)
    {
        printf("Error opening file!");
        return 1;
    }
    printf("\nNAME\tROLL NO\tAGE");
    while (fscanf(fptr, "%s%d%d", name, &rn, &age) != EOF)
    {
        printf("\n%s\t%d\t%d", name, rn, age);
    }
    fclose(fptr);
    return 0;
}

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.
Ans:
#include<stdio.h>
int main()
{
    char name[50], gender, mobile[15];
    int age, n, i, c = 0;
    FILE *fptr;
    fptr = fopen("ADDRESS.DAT", "w");
    if (fptr == NULL)
    {
        printf("Error opening file!");
        return 1;
    }
    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");
    if (fptr == NULL)
    {
        printf("Error opening file!");
        return 1;
    }
    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);
    return 0;
}


4.5.2 Sequential and Random File:
In C programming, sequential and random access refer to different ways of accessing and manipulating files. 
1. Sequential Access:
Sequential access means reading or writing data in a sequential order from the start to the end of the file. This is useful for situations where the data is processed in the order it appears.
Functions used in sequential file are as follows:
  1. fopen() - Opens the file.
  2. fread() - Reads data from the file in sequence.
  3. fwrite() - Writes data to the file in sequence.
  4. fclose() - Closes the file when done.

2. Random Access:
Random access allows direct access to any part of the file without needing to read through other parts of it. This is helpful when user need to access or modify specific data within a file directly.
Functions used in random file are as follows:
  1. fseek(FILE *file, long offset, int whence) - Moves the file pointer to a specific location.
  2. ftell(FILE *file) - Returns the current position of the file pointer.
  3. rewind(FILE *file) - Resets the file pointer to the beginning of the file.




THE END

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home