Saturday, March 8, 2025

4. Programming in C [Most Important Questions and Solutions]

[Structure]

2082 Q. No. 16 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.

#include <stdio.h>

struct customer

{

    int account_number;

    char name[30];

    char address[50];

};

int main()

{

    struct customer c[10];

    int i;

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

    {

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

        printf("Enter Account Number: ");

        scanf("%d", &c[i].account_number);

        printf("Enter Name: ");

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

        printf("Enter Address: ");

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

    }

    printf("\nThe Details of Customers in Tabular Form:\n");

    printf("\nACCOUNTNO.\tNAME\tADDRESS");

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

    {

        printf("\n%d\t%s\t%s", c[i].account_number, c[i].name, c[i].address);

    }

    return 0;

}

 

Example Output:

Enter details of customer 1

Enter Account Number: 101

Enter Name: Ram

Enter Address: Kathmandu

……………………

Enter details of customer 10

Enter Account Number: 102

Enter Name: Sita

Enter Address: Pokhara

 

The Details of Customers in Tabular Form:

 

ACCOUNTNO.        NAME        ADDRESS

101                            Ram            Kathmandu

…..                            …….           ………

102                            Sita              Pokhara

2082 GIE Set B Q. No. 16 Write a C program to enter information of 10 clients, including account ID, account name, address, and balance, and display the information using a structure. 

Ans:

#include <stdio.h>

struct client

{

    int accid;

    char name[30];

    char address[50];

    float balance;

};

int main()

{

    struct client c[10];

    int i;

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

    {

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

        printf("Enter Account ID: ");

        scanf("%d", &c[i].accid);

        printf("Enter Account Name: ");

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

        printf("Enter Address: ");

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

        printf("Enter Balance: ");

        scanf("%f", &c[i].balance);

    }

    printf("\nThe Details of Clients in Tabular Form:\n");

    printf("\nACCOUNTID\tNAME\tADDRESS\tBALANCE");

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

    {

        printf("\n%d\t%s\t%s\t%f", c[i].accid, c[i].name, c[i].address, c[i].balance);

    }

    return 0;

}

 

Example Output:

Enter details of client 1

Account ID: 101

Account Name: Ram

Address: Kathmandu

Balance: 5000

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

Enter details of client 10

Account ID: 110

Account Name: Sita

Address: Pokhara

Balance: 7500

 

The Details of Clients in Tabular Form:

 

ACCOUNTID        NAME           ADDRESS        BALANCE

101                          Ram              Kathmandu         5000.000000

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

110                          Sita                Pokhara            7500.000000

 

2081 GIE Set A Q. No. 16 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


2081 HISSAN) Write a C program to enter roll, name, school name and district of 15 students and display the information in proper format using structure. Ans: Do yourself

2081 GIE Set B Q. No. 16 Create a structure named "player" to store details pname, game, age, and salary. Write a C program to input details for five players and display their information in proper format.

Ans:

#include <stdio.h>

struct player

{

    char pname[30];

    char game[30];

    int age;

    float salary;

};

int main()

{

    struct player p[5];

    int i;

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

    {

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

        printf("Enter Player Name: ");

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

        printf("Enter Game: ");

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

        printf("Enter Age: ");

        scanf("%d", &p[i].age);

        printf("Enter Salary: ");

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

    }

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

    printf("\nNAME\tGAME\tAGE\tSALARY");

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

    {

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

               p[i].pname,

               p[i].game,

               p[i].age,

               p[i].salary);

    }

    return 0;

 

Example Output:

Enter details of player 1

Enter Name: John

Enter Game: Cricket

Enter Age: 25

Enter Salary: 50000

………

Enter details of player 5

Enter Name: David

Enter Game: Football

Enter Age: 24

Enter Salary: 55000

 

The Detail of Students in Tabular Form: 

 

NAME    GAME          AGE     SALARY

John       Cricket         25        50000.000000

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

David     Football       24        55000.000000


2081 Q. No. 16 Write a C program that uses structures to represent details of five books (title, author, publisher, and price) and prints them out. [8]

Ans:

#include <stdio.h>

struct book

{

    char title[50];

    char author[50];

    char publisher[50];

    float price;

};

int main()

{

    struct book b[5];

    int i;

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

    {

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

        printf("Enter Title: ");

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

        printf("Enter Author: ");

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

        printf("Enter Publisher: ");

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

        printf("Enter Price: ");

        scanf("%f", &b[i].price);

    }

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

    printf("\nTITLE\tAUTHOR\tPUBLISHER\tPRICE");

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

    {

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

               b[i].title,

               b[i].author,

               b[i].publisher,

               b[i].price);

    }

    return 0;

}

 

Example Output:

Enter details of book 1

Enter Title: Computer

Enter Author: Madhav

Enter Publisher: Heritage

Enter Price: 450

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

Enter details of book 5

Enter Title: English

Enter Author: Suman

Enter Publisher: Asmita

Enter Price: 650

 

The Detail of Books in Tabular Form:

 

TITLE              AUTHOR          PUBLISHER        PRICE

Computer    Madhav           Heritage               450.000000

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

English          Suman            Asmita                   650.000000

 

2080 GIE Set A Q. No. 16 What is a structure? Write a program to store five students' information (ID, Name, DOB, and phone) and display them using structure. [2+6]

Ans:

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;

 

A program to store five students' information (ID, Name, DOB, and phone) and display them using structure is as follows:

#include <stdio.h>

struct student

{

    int id;

    char name[30];

    char dob[15];

    char phone[15];

};

int main()

{

    struct student s[5];

    int i;

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

    {

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

        printf("Enter ID: ");

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

        printf("Enter Name: ");

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

        printf("Enter Date of Birth: ");

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

        printf("Enter Phone Number: ");

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

    }

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

    printf("\nID\tNAME\tDOB\tPHONE");

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

    {

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

               s[i].id,

               s[i].name,

               s[i].dob,

               s[i].phone);

    }

    return 0;

 

Example Output:

Enter details of student 1

Enter ID: 101

Enter Name: Madhav

Enter Date of Birth: 2005-05-10

Enter Phone Number: 9801234567

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

Enter details of student 5

Enter ID: 105

Enter Name: Ramesh

Enter Date of Birth: 2005-12-20

Enter Phone Number: 9812345678

 

The Details of Students in Tabular Form:

 

ID         NAME             DOB                   PHONE

101      Madhav         2005-05-10     9801234567

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

105      Ramesh        2005-12-20      9812345678

2080 GIE Set B Q. No. 16 Write a program to store five employees' records (EID, Name, Post, and Department) and display them using structure. [8]

Ans:

#include <stdio.h>

struct employee

{

    int eid;

    char name[30];

    char post[30];

    char department[30];

};

int main()

{

    struct employee e[5];

    int i;

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

    {

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

        printf("Enter Employee ID: ");

        scanf("%d", &e[i].eid);

        printf("Enter Name: ");

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

        printf("Enter Post: ");

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

        printf("Enter Department: ");

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

    }

    printf("\nThe Details of Employees in Tabular Form:\n");

    printf("\nEID\tNAME\tPOST\tDEPARTMENT");

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

    {

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

               e[i].eid,

               e[i].name,

               e[i].post,

               e[i].department);

    }

    return 0;

} 

 

Example Output:

Enter details of employee 1

Enter Employee ID: 201

Enter Name: Ram

Enter Post: Manager

Enter Department: Sales

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

Enter details of employee 5

Enter Employee ID: 205

Enter Name: Sita

Enter Post: Accountant

Enter Department: Finance

 

The Details of Employees in Tabular Form:

 

EID     NAME       POST            DEPARTMENT

201     Ram         Manager      Sales

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

205      Sita         Accountant   Finance

 

2080 Q. No. 16 OR 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: For definition of structure look on 2080 GIE Set A Q. No. 16 

#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%f", 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.000000

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

150       Hari           38000.000000

PABSON 2081) 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. 

Ans: Do yourself by looking on 2080 Q. No. 16 OR 

2079 GIE Set A Q. No. Write a C program to enter name, grade, age, and address of 10 students in a structure and display the information.

Ans:

#include <stdio.h>

struct student

{

    char name[30];

    char grade[5];

    int age;

    char address[50];

};

int main()

{

    struct student s[10];

    int i;

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

    {

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

        printf("Enter Name: ");

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

        printf("Enter Grade: ");

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

        printf("Enter Age: ");

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

        printf("Enter Address: ");

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

    }

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

    printf("\nNAME\tGRADE\tAGE\tADDRESS");

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

    {

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

               s[i].name,

               s[i].grade,

               s[i].age,

               s[i].address);

    }

    return 0;

} 

 

Example Output:

Enter details of student 1

Enter Name: Madhav

Enter Grade: A

Enter Age: 18

Enter Address: Kathmandu

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

Enter details of student 10

Enter Name: Ramesh

Enter Grade: B

Enter Age: 19

Enter Address: Pokhara

 

The Details of Students in Tabular Form:

 

NAME         GRADE    AGE     ADDRESS

Madhav      A               18         Kathmandu

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

Ramesh      B             19           Pokhara

 

2079 Set A Q.No. 16 What is structure? Write a program to input roll, name and age of 5 students and display them properly using structure.   [2+6=8]

Ans:

#include <stdio.h>

struct student

{

    int roll;

    char name[30];

    int age;

};

int main()

{

    struct student s[5];

    int i;

    for(i = 0; i < 5; 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 Age: ");

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

    }

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

    printf("\nROLL\tNAME\tAGE");

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

    {

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

    }

    return 0;

 

Example Output:

Enter details of student 1

Enter Roll Number: 101

Enter Name: Madhav

Enter Age: 18

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

Enter details of student 5

Enter Roll Number: 105

Enter Name: Ramesh

Enter Age: 19

 

The Details of Students in Tabular Form:

 

ROLL                  NAME                AGE

101                     Madhav            18

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

105                     Ramesh            19

 

2079 NEB Model Q. No. 16 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]. [8]

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


Heritage Model Set III) Create a structure employee with members id, name, post and salary with appropriate data type. Write a main program to read records of 50 employee using and display the record of those employee whose post is Accountant.

Ans:

#include <stdio.h>

#include <string.h>

struct employee

{

    int id;

    char name[50];

    char post[30];  

    float salary;   

};

int main()

{

    struct employee e[50];

    int i;

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

    {

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

        printf("Enter ID: ");

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

        printf("Enter Name: ");

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

        printf("Enter Post: ");

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

        printf("Enter Salary: ");

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

    }

    printf("\nThe Details of Employees with Post Accountant:\n");

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

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

    {

        if(strcmp(e[i].post, "Accountant") == 0) 

        {

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

        }

    }

    return 0;

}

 

Heritage Model Set II) Design a structure student with members roll, name, gender and marks in computer. Write a main program to read details of 20 students using structure and then display detail of those students whose gender is male.

Ans: Do yourself Looking on Heritage Model Set III)


[Functions]

2080 Q. No. 16 Write a C program to enter the radius of a football and find the area of the football by using a user-defined function.  [5]

Ans:

#include<stdio.h>

#include<conio.h>

float area(int);

void main()

{

    int r;

    float a;

    clrscr();

    printf("Enter radius:");

    scanf("%d", &r);

    a = area(r);

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

    getch();

}

float area(int x)

{

    float ar;

    ar = 4 * 3.14 * x * x;

    return ar;

}

 

Example Output:

Enter radius: 7

The area of a ball is 615.44

 

2079 GIE Set B Q. No. 16 Define function. Write a program to generate the factorial of a given number using a recursive function in C programming. [3+5] 

Ans:

A function in C is a self-contained block of statements that performs a specific task. A function is executed when it is called in the program. Some advantages of functions are as follows:

  1. Reusability: Use the same code multiple times.
  2. Modularity: Break the program into smaller parts.
  3. Easy Maintenance: Fix or update one function without affecting others.
  4. Clear and Readable: Makes the program easy to understand.

Different types of functions are as follows:

  1. Predefined (Library) Functions: Functions provided by C standard libraries (e.g., printf, scanf, sqrt).
  2. User-Defined Functions: Functions created by the programmer 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

b)      Functions with No Arguments but Return a Value

c)       Functions with Arguments but No Return Value

d)      Functions with Arguments and Return Value

A program to generate the factorial of a given number using a recursive function in C programming is as follows:

#include <stdio.h>

#include <conio.h>

int factorial(int n);

void main()

{

    int n, fact;

    clrscr();

    printf("Enter a number:");

    scanf("%d", &n);

    fact = factorial(n);

    printf("Factorial of %d is %d", n, fact);

    getch();

}

int factorial(int n)

{

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

    {

        return 1;

    }

    else

    {

        return n * factorial(n - 1);

    }

}

 

Example Output:

Enter a number: 5

Factorial of 5 is 120

 


 

[Working with File]

2079 GIE Set A Q. No. 16 OR Describe the file handling concept in C. Write a C program to enter names and addresses of the students and store them in a data file "student.dat". [3+5]

Ans:

File handling in C refers to 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);

 

A C program to enter names and addresses of the students and store them in a data file "student.dat" is as follows:

#include <stdio.h>

int main()

{

    char name[50], address[100];

    int n, i;

    FILE *fptr;

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

    if (fptr == NULL)

    {

        printf("Error opening file!");

        return 1;

    }

    printf("Enter number of records:");

    scanf("%d", &n);

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

    {

        printf("Enter name:");

        scanf("%s", name);

        printf("Enter address:");

        scanf("%s", address);

        fprintf(fptr, "\n%s\t%s", name, address);

    }

    fclose(fptr);

 

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

    if (fptr == NULL)

    {

        printf("Error opening file!");

        return 1;

    }

    printf("\nNAME\tADDRESS");

    while (fscanf(fptr, "%s %s", name, address) != EOF)

    {

        printf("\n%s\t%s", name, address);

    }

    fclose(fptr);

    return 0;

}

 

2082 GIE Set B Q. No. 16 OR /2080 GIE Set B Q. No. 16 OR Describe file handling modes in C. Write a C program to create and write data into a file.  [4+4]

Ans:

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.

 

A C program to create and write data into a file “student.dat” is as follows:

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

  // Write data to the file using fprintf.

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

  fclose(fptr);

  return 0;

}


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

Ans: A program to read and display(print) data from a file “student.dat” is as follows:

#include <stdio.h>
int main()
{
    char name[20];
    int rn, age;
    FILE *fptr;
    fptr = fopen("student.dat", "r");
    printf("\nNAME\tROLL NO\tAGE");
    // Read and Display data from a 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;
}

2080 GIE Set A Q. No. 16 OR Write a program to read and write data from a file using file handling functions. [8]

2066 GIE Write a program to show data writing and reading operation to/from a data file.

2081 GIE Set B Q. No. 16 OR/ 2072 Set C Write a C program that illustrates the use of fprintf() and fscanf() functions of file handling.  [8]

Ans: 

fprintf() and fscanf() are popular file handling functions in C.

The function fprintf() is a formatted output function which is used to write integer, float, char, or string to a file.

Ø  Syntax: fprintf(file_pointer, "format_specifiers", list_of_variables);

Ø  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.

The function fscanf() is a formatted input function which is used to read integer, float, char, or string from a file.

Ø  Syntax: fscanf(file_pointer, "format_specifiers", variable_list);

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

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

A program to read and write data from a file using file handling functions (fscanf and fprintf) is as follows:

(A C program that illustrates the use of fprintf() and fscanf() functions of file handling is as follows:)

#include <stdio.h>

int main()

{

    char name[20];

    int rn, age, i;

    FILE *fptr;

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

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

    {

        printf("Enter name: ");

        scanf("%s", name);

        printf("Enter roll no: ");

        scanf("%d", &rn);

        printf("Enter age: ");

        scanf("%d", &age);

        // Write data to the file using fprintf.

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

    }

    fclose(fptr);

 

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

    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;

}

 

2079 Set A Q. No. 16 OR 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");

    if (fptr == NULL)

    {

        printf("Error opening file!");

        return 1;

    }

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

    if (fptr == NULL)

    {

        printf("Error opening file!");

        return 1;

    }

    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;

}

 

2081 Q. No. 16 OR Discuss the concept of binary file handling in C programming and explain how putw() and getw() functions facilitate binary input/output operations. Give examples. [8]

Ans:

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;

}

This C program writes numbers 1 to 10 into a binary file using putw() and then reads them back using getw().

 

2079 NEB Model Q. No. 16 OR 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");

    if (fptr == NULL)

    {

        printf("Error opening file!");

        return 1;

    }

    do

    {

        printf("Enter Registration Number: ");

        scanf("%d", &reg_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");

    if (fptr == NULL)

    {

        printf("Error opening file!");

        return 1;

    }

    printf("\nREG NO\tNAME\tGENDER\tADDRESS");

    while (fscanf(fptr, "%d%s%s%s", &reg_no, name, gender, address) != EOF)

    {

        printf("\n%d\t%s\t%s\t%s", reg_no, name, gender, address);

    }

    fclose(fptr);

    return 0;

}

 

2068 Cancelled / Asmita Sample Model Q. No. 16 OR 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.

Ans:

#include <stdio.h>

int main()

{

    char name[50], address[100], phone[15], ch;

    int roll_no;

    FILE *fptr;

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

    if (fptr == NULL)

    {

        printf("Error opening file!");

        return 1;

    }

    do

    {

        printf("Enter Roll Number: ");

        scanf("%d", &roll_no);

        printf("Enter Name: ");

        scanf("%s", name);

        printf("Enter Address: ");

        scanf("%s", address);

        printf("Enter Phone Number: ");

        scanf("%s", phone);

        fprintf(fptr, "\n%d\t%s\t%s\t%s", roll_no, name, address, phone);

        printf("Do you want to enter more records (Y/N)? ");

        scanf(" %c",&ch);

    } while (ch == 'Y' || ch == 'y');

    fclose(fptr);

 

    fptr = fopen("students.dat", "r");

    if (fptr == NULL)

    {

        printf("Error opening file!");

        return 1;

    }

    printf("\nROLL NO\tNAME\tADDRESS\tPHONE");

    while (fscanf(fptr, "%d%s%s%s", &roll_no, name, address, phone) != EOF)

    {

        printf("\n%d\t%s\t%s\t%s", roll_no, name, address, phone);

    }

    fclose(fptr);

    return 0;

}

2081 Pre-Board KMC 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, 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);

                  }

                  if (gender == 'F' || gender == 'f')

                 {

                  c=c+1;

                  }

    }

    printf("Total number of Female students: %d", c);

    fclose(fptr);

    return 0;

}


2071 Set C Describe any five-file handling function with examples.  [8]

Ans: Any five file handling function with examples are as follows:

1) 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", list_of_variables);

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.

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

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

4) 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 without format specifiers %s from a file.

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

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


2071 GIE /2072 Set D Describe fprintf and fscanf file handling functions. Write a program which writes "Welcome to Nepal" in a file.

Ans: 

1) 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", list_of_variables);

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.

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

A program which writes "Welcome to Nepal" in a file is as follows:

#include <stdio.h>

int main()

{

    FILE *fptr;

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

    if (fptr == NULL)

    {

        printf("Error opening file!");

        return 1;

    }

    fprintf(fptr, "Welcome to Nepal");

    fclose(fptr);

    return 0;

}


2067 Write a program to delete and rename the data file.  
Ans:

#include<stdio.h>

int main()

{

    char name[20];

    FILE *fptr;

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

    if (fptr == NULL)

    {

        printf("Error opening file!");

        return 1;

    }

    printf("Enter your name:");

    scanf("%s", name);

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

    fclose(fptr);

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

    remove("newfile.txt");

    return 0;

}

[Pointer]

2080 GIE Set A OR) What is a pointer?   [3]

2077 Set D) Describe the pointer with example.  [4]

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

Ø  Instead of holding data directly, it 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.

Example of Pointer:

int a = 10;

int *ptr = &a;

Explanation:

Ø ptr holds the address of a.

Ø &a: The address-of operator. It gives the memory address of the variable a.

Ø *ptr: The dereference (indirection) operator. It accesses the value stored at the memory address that ptr is pointing to.

Here’s a complete C program to find the sum of two numbers using pointers:

#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 %d and %d is: %d\n", *ptr1, *ptr2, sum);

    return 0;

}

 

2080 / 2078 Set C / 2071 Set D What is pointer? Write the advantages(benefits) of a pointer.          [4]

Ans: For definition of pointer look on 2080 GIE Set A OR) 

Advantages of using pointers in C programming are as follows:

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

b) Pass-by-Reference: Enables functions to modify actual variable values, improving performance.

c) Dynamic Data Structures: Essential for creating and managing structures like linked lists and trees.

d) Memory Sharing: Allows multiple parts of a program to share and manipulate the same data.

e) Faster data processing: Quick access to lists and arrays.

f) Direct hardware control: Interface with computer components.

 

2081 GIE Set A Q. No. 16.b Write a C program to find the product of two numbers using a pointer.  [4]

#include <stdio.h>    

int main() 

{        

    int a, b, product;      

    int *ptr1 = &a;         

    int *ptr2 = &b;           

    printf("Enter first number: "); 

    scanf("%d", ptr1);     

    printf("Enter second number: ");      

    scanf("%d", ptr2);     

    product = (*ptr1) * (*ptr2); 

    printf("The product of %d and %d is: %d\n", *ptr1, *ptr2, product);

    return 0;

}

 

2082 OR) What are the components of a function of C? Describe the Call – by – value and Call – by – reference and passing the function parameters. [4+4]

Ans: A function in C is a self-contained block of statements that performs a specific task. A function is executed when it is called in the program. 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);

 

Passing Function Parameters in C:

C supports two ways of passing arguments to functions as follows:

1) Call by Value:

Ø Definition: A method of passing arguments to a function where the actual value of the argument is copied 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);

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

 

 

 

Out Of Syllabus 2078 NEB Model Q 1) Write a program to enter ten integer numbers into an array, sort and display them in ascending order.   [Only for A+ Students]

Ans:

#include <stdio.h>

int main()

{

    int arr[10], i, j, temp;

    printf("Enter 10 integers:\n");

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

        scanf("%d", &arr[i]);

    }

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

    {

        for (j = 0; j < 9 - i; j++)

        {

            if (arr[j] > arr[j + 1])

            {

                temp = arr[j];

                arr[j] = arr[j + 1];

                arr[j + 1] = temp;

            }

        }

    }

    printf("Sorted numbers in ascending order:\n");

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

        printf("%d ", arr[i]);

    }

  return 0;

}

 

Out Of Syllabus 2078 NEB Model Q 2) Write a program to read the marks of any 5 students in a subject and count how many students are pass and fail.   [Only for A+ Students]

Ans:

#include <stdio.h>

int main()

{

    int marks[5], i, pass = 0, fail = 0;

    printf("Enter the marks of 5 students:\n");

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

    {

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

        if (marks[i] >= 40)

        {

            pass=pass+1;

        } else {

            fail=fail+1;

        }

    }

    printf("Number of students who passed: %d", pass);

    printf("Number of students who failed: %d", fail);

    return 0;

}

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home