Chapter 4
Programming in C
NEB Class 12 past exam questions
Past questions and answers
24 questions set from this chapter. Most repeated first.
- 2083 Baishakh · 1 mark
What does ++X do in a C program?
(a) Returns value then increments
(b) Increments then returns value
(c) Decrement value
(d) Returns original value
Answer
(b) Increments then returns value
++X is the pre-increment operator: it first increases the value of X by 1, and then the incremented value is used in the expression.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 1 MCQ
Loading…
- 2083 Baishakh · 8 marks
(a) [4] Write a C program to input a number and check whether it is positive, negative or zero using a user-defined function.
(b) [4] Write a C program to generate the Fibonacci series of the first two numbers, 7 and 14, up to 10 terms using a user-defined function.
Answer
(a) Check positive, negative or zero using a user-defined function
/* Program to check whether a number is positive, negative or zero
using a user-defined function */
#include <stdio.h>
void check(int n); /* function prototype */
int main()
{
int num;
printf("Enter any number: ");
scanf("%d", &num);
check(num); /* function call */
return 0;
}
/* user-defined function */
void check(int n)
{
if (n > 0)
printf("%d is a positive number.\n", n);
else if (n < 0)
printf("%d is a negative number.\n", n);
else
printf("The number is zero.\n");
}
Output
Enter any number: -5
-5 is a negative number.
(b) Fibonacci series with first two terms 7 and 14, up to 10 terms
The series is: 7, 14, 21, 35, 56, 91, 147, 238, 385, 623
/* Program to generate Fibonacci series of first two terms 7 and 14
up to 10 terms using a user-defined function */
#include <stdio.h>
void fibo(int a, int b, int n); /* function prototype */
int main()
{
printf("Fibonacci series of 10 terms:\n");
fibo(7, 14, 10); /* function call */
return 0;
}
/* user-defined function to generate the series */
void fibo(int a, int b, int n)
{
int i, c;
printf("%d %d ", a, b); /* print first two terms */
for (i = 3; i <= n; i++)
{
c = a + b; /* next term = sum of previous two */
printf("%d ", c);
a = b;
b = c;
}
printf("\n");
}
Output
Fibonacci series of 10 terms:
7 14 21 35 56 91 147 238 385 623
Note: In both programs the actual task is done inside a separate user-defined function (check() and fibo()), while main() only reads the input and calls that function.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2083 Baishakh · 8 marks
Write a C program that reads the student's roll number, name, section and mark of 10 students using an array of structure and display.
Answer
C Program: Array of Structure for 10 Students
/* Program to read and display roll number, name, section and mark
of 10 students using an array of structure */
#include <stdio.h>
#define N 10
struct student
{
int roll;
char name[30];
char section[10];
float mark;
};
int main()
{
struct student s[N];
int i;
/* ---------- Reading the records ---------- */
printf("Enter roll number, name, section and mark of %d students:\n", N);
for (i = 0; i < N; i++)
{
printf("\nStudent %d\n", i + 1);
printf("Roll number : ");
scanf("%d", &s[i].roll);
printf("Name : ");
scanf("%s", s[i].name); /* name without space */
printf("Section : ");
scanf("%s", s[i].section);
printf("Mark : ");
scanf("%f", &s[i].mark);
}
/* ---------- Displaying the records ---------- */
printf("\n\n%-10s %-20s %-10s %-10s\n",
"Roll No", "Name", "Section", "Mark");
printf("------------------------------------------------------\n");
for (i = 0; i < N; i++)
{
printf("%-10d %-20s %-10s %-10.2f\n",
s[i].roll, s[i].name, s[i].section, s[i].mark);
}
return 0;
}
Explanation
-
Structure definition —
struct studentgroups four members of different data types:roll(int),name(string),section(string) andmark(float). This is the key idea of a structure: one variable can hold a complete record. -
Array of structure —
struct student s[N];declares an array of 10 structure variables. Each elements[0],s[1], …s[9]is a full student record. This is exactly what the question asks for. -
Reading data — A
forloop runs 10 times. Inside it,scanf()reads each field using the member operator.(dot operator), e.g.&s[i].rollands[i].name. Note thatnameandsectionare character arrays, so no&is used with them. -
Displaying data — A second
forloop prints all records in a tabular form. The format specifier%-10dmeans "print an integer left-justified in a field of width 10", which keeps the columns aligned.%.2fprints the mark with two decimal places.
Sample Output
Enter roll number, name, section and mark of 10 students:
Student 1
Roll number : 101
Name : Ram
Section : A
Mark : 78.5
...
Student 10
Roll number : 110
Name : Sita
Section : B
Mark : 88
Roll No Name Section Mark
------------------------------------------------------
101 Ram A 78.50
102 Shyam A 65.00
...
110 Sita B 88.00
Note
If a name contains a space (e.g. Ram Bahadur), scanf("%s", ...) stops at the space. To read such names, use scanf(" %[^\n]", s[i].name); or fgets().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 Supplementary · 1 mark
Which of the following is a correct function declaration in C ?
(a) int function (a, b);
(b) void function (int x, int y);
(c) func (int x, y);
(d) int func (int x, int y)
Answer
(b) void function (int x, int y);
It gives the return type (void), the function name, and both parameters with their data types, and ends with a semicolon — so it is a valid function declaration (prototype) in C. Option (d) is missing the semicolon, while (a) and (c) do not specify the data type of every parameter.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 1 MCQ
Loading…
- 2082 Supplementary · 4+4 marks
Write a C program to enter information of 10 clients, including accountNo, accountname, address, and balance, and display the information using a structure.
Answer
C Program: Client Information Using a Structure
(a) Program to enter and display information of 10 clients — 4 marks
#include <stdio.h>
struct client
{
int accountNo;
char accountname[50];
char address[50];
float balance;
};
int main()
{
struct client c[10];
int i;
/* Input section */
printf("Enter information of 10 clients:\n");
for (i = 0; i < 10; i++)
{
printf("\nClient %d\n", i + 1);
printf("Account No: ");
scanf("%d", &c[i].accountNo);
printf("Account Name: ");
scanf("%s", c[i].accountname);
printf("Address: ");
scanf("%s", c[i].address);
printf("Balance: ");
scanf("%f", &c[i].balance);
}
/* Display section */
printf("\n%-12s %-20s %-20s %-10s\n",
"AccountNo", "AccountName", "Address", "Balance");
for (i = 0; i < 10; i++)
{
printf("%-12d %-20s %-20s %-10.2f\n",
c[i].accountNo, c[i].accountname,
c[i].address, c[i].balance);
}
return 0;
}
Explanation of the program
struct clientis declared with four members:accountNo(int),accountname(char array),address(char array) andbalance(float).- Inside
main(), an array of 10 structuresstruct client c[10]is created so that data of 10 clients can be stored. - The first
forloop runs 10 times and reads each field usingscanf(). The dot operator (.) is used to access members, e.g.c[i].accountNo. - The second
forloop runs 10 times and prints the stored records in a tabular form usingprintf()with width specifiers (%-20s,%-10.2f) for neat alignment. %.2fdisplays the balance up to two decimal places.
(b) Output of the program — 4 marks
Enter information of 10 clients:
Client 1
Account No: 101
Account Name: Ram
Address: Kathmandu
Balance: 25000.50
Client 2
Account No: 102
Account Name: Sita
Address: Pokhara
Balance: 18000.75
Client 3
Account No: 103
Account Name: Hari
Address: Lalitpur
Balance: 32000.00
Client 4
Account No: 104
Account Name: Gita
Address: Bhaktapur
Balance: 15500.25
Client 5
Account No: 105
Account Name: Shyam
Address: Chitwan
Balance: 27000.00
Client 6
Account No: 106
Account Name: Ramesh
Address: Butwal
Balance: 21000.40
Client 7
Account No: 107
Account Name: Suman
Address: Dharan
Balance: 19500.60
Client 8
Account No: 108
Account Name: Bina
Address: Biratnagar
Balance: 30500.90
Client 9
Account No: 109
Account Name: Kiran
Address: Nepalgunj
Balance: 12000.00
Client 10
Account No: 110
Account Name: Nisha
Address: Hetauda
Balance: 45000.35
AccountNo AccountName Address Balance
101 Ram Kathmandu 25000.50
102 Sita Pokhara 18000.75
103 Hari Lalitpur 32000.00
104 Gita Bhaktapur 15500.25
105 Shyam Chitwan 27000.00
106 Ramesh Butwal 21000.40
107 Suman Dharan 19500.60
108 Bina Biratnagar 30500.90
109 Kiran Nepalgunj 12000.00
110 Nisha Hetauda 45000.35
Note: The values shown in the output are sample values entered by the user. Since the program reads data at run time, the actual output depends on the values entered. The display section prints the records in the same order in which they were entered.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 Supplementary · 4+4 marks
Describe file handling modes on C. Write a C program to create and write data into a file.
Answer
File Handling Modes in C
A file must be opened with fopen() before use. Its syntax is:
FILE *fp;
fp = fopen("filename", "mode");
The mode string tells the system how the file is to be used. The common modes are:
| Mode | Meaning | If file exists | If file does not exist |
|---|---|---|---|
"r" | Open for reading only | Opens it | Returns NULL |
"w" | Open for writing only | Erases old contents | Creates a new file |
"a" | Open for appending (writing at end) | Adds data at end | Creates a new file |
"r+" | Open for both reading and writing | Opens it | Returns NULL |
"w+" | Open for both reading and writing | Erases old contents | Creates a new file |
"a+" | Open for reading and appending | Adds data at end | Creates a new file |
Binary versions: Adding b (e.g. "rb", "wb", "ab", "rb+") opens the file in binary mode, so bytes are transferred without any text translation. This is used for images, records and other non-text data.
Key points:
"r"and"r+"fail (returnNULL) if the file does not exist."w"and"w+"always destroy the previous contents of the file."a"and"a+"never destroy old data; new data is written after the existing data.- A file opened in a read mode cannot be written to, and vice versa, unless
+is used. - After all operations the file must be closed with
fclose(fp).
C Program to Create and Write Data into a File
/* Program to create a file and write data into it */
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char str[100];
/* Create (or overwrite) the file in write mode */
fp = fopen("data.txt", "w");
if (fp == NULL)
{
printf("Error: File could not be created.\n");
exit(1);
}
printf("Enter text to write into the file: ");
fgets(str, sizeof(str), stdin); /* read a line from keyboard */
fputs(str, fp); /* write the line into the file */
fclose(fp); /* close the file */
printf("Data written to data.txt successfully.\n");
return 0;
}
Output (sample):
Enter text to write into the file: I am a student of Class 12.
Data written to data.txt successfully.
Explanation:
fopen("data.txt", "w")creates a new file nameddata.txt(or clears it if it already exists) and returns a file pointer.- The
if (fp == NULL)check handles the case where the file cannot be opened. fgets()reads a line of text from the user, andfputs()writes that text into the file.fclose(fp)flushes the buffer and closes the file so the data is safely saved on disk.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 Baishakh · 1 mark
The statement int number (int a); is a ...
(a) function call
(b) function definition
(c) function declaration
(d) function execution
Answer
(c) function declaration
It ends with a semicolon and has no body, so it only tells the compiler the function's name, return type and parameter type — that is a function prototype (declaration). A definition would have a body { ... }, a call would be number(x);, and execution happens only when the call is made.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 1 MCQ
Loading…
- 2082 Baishakh · 8 marks
Write a C program to read account number, name and address of ten customers and display them using array and structure.
Answer
C Program: Ten Customers Using Array of Structures
/* Program to read and display account number, name and address
of ten customers using an array of structures */
#include <stdio.h>
struct customer
{
int acc_no;
char name[30];
char address[50];
};
int main()
{
struct customer c[10]; /* array of 10 structures */
int i;
/* Reading records */
printf("Enter account number, name and address of 10 customers:\n");
for (i = 0; i < 10; i++)
{
printf("\nCustomer %d\n", i + 1);
printf("Account Number: ");
scanf("%d", &c[i].acc_no);
printf("Name: ");
scanf("%s", c[i].name);
printf("Address: ");
scanf("%s", c[i].address);
}
/* Displaying records */
printf("\n%-15s %-20s %-25s\n", "Account No", "Name", "Address");
printf("--------------------------------------------------------\n");
for (i = 0; i < 10; i++)
{
printf("%-15d %-20s %-25s\n", c[i].acc_no, c[i].name, c[i].address);
}
return 0;
}
Explanation
Structure definition: struct customer groups three members of different data types — acc_no (int), name (char array) and address (char array) — into a single user-defined data type.
Array of structures: struct customer c[10]; declares an array that can hold the records of ten customers. Each element c[i] is a complete structure, so all three fields of one customer are stored together.
Accessing members: The dot operator (.) is used with the array subscript, as in c[i].acc_no, c[i].name and c[i].address. The address-of operator & is used with scanf() for acc_no, while the array names name and address already represent addresses, so & is not needed for them.
Reading loop: The first for loop runs from i = 0 to i = 9, reading the three fields of each customer one by one.
Displaying loop: The second for loop prints the stored records in a tabular form. The format specifier %-15s left-aligns the text within a field of width 15, which keeps the columns neat.
Note: Since name and address are read with %s, they cannot contain spaces. If full names or addresses with spaces are required, scanf("%[^\n]", c[i].name); or fgets() should be used instead.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 Baishakh · 8 marks
What are the components of a function in C? Describe Call-by-value and Call-by-reference.
Answer
Components of a Function in C
A function in C has three main components:
1. Function Declaration (Prototype) Also called the function prototype, it tells the compiler the function's name, return type, and the number and types of its parameters before the function is actually used. It ends with a semicolon.
int sum(int a, int b);
2. Function Definition This is the actual body of the function where the statements that perform the task are written. It consists of:
- Return type – the data type of the value the function returns (e.g.,
int,float,void). - Function name – a valid identifier used to call the function.
- Parameter list – variables in parentheses that receive values from the caller.
- Function body – the block of statements enclosed in
{ }.
int sum(int a, int b)
{
return a + b;
}
3. Function Call The statement that invokes the function and passes arguments to it.
result = sum(5, 3);
So, in short, the components are: return type, function name, parameter list, function body, along with the declaration and the call.
Call-by-Value
In call-by-value, a copy of the actual argument's value is passed to the formal parameter. The function works on this copy, so any change made inside the function does not affect the original variable in the calling function.
Example:
#include <stdio.h>
void swap(int x, int y)
{
int t = x;
x = y;
y = t;
}
int main()
{
int a = 10, b = 20;
swap(a, b);
printf("a = %d, b = %d", a, b); /* a = 10, b = 20 */
return 0;
}
Here the values of a and b remain unchanged because only their copies were swapped.
Call-by-Reference
In call-by-reference, the address of the actual argument is passed to the formal parameter (using pointers). The function accesses the original memory location, so any change made inside the function does affect the original variable.
Example:
#include <stdio.h>
void swap(int *x, int *y)
{
int t = *x;
*x = *y;
*y = t;
}
int main()
{
int a = 10, b = 20;
swap(&a, &b);
printf("a = %d, b = %d", a, b); /* a = 20, b = 10 */
return 0;
}
Here the values of a and b are actually interchanged because their addresses were passed.
Difference between Call-by-value and Call-by-reference
| Call-by-value | Call-by-reference |
|---|---|
| A copy of the value is passed. | The address of the variable is passed. |
| Changes do not affect the original variable. | Changes affect the original variable. |
| Formal parameters are ordinary variables. | Formal parameters are pointer variables. |
| More memory is used (copies are made). | Less memory is used (only addresses are passed). |
| Safer, as original data cannot be altered accidentally. | Less safe, as original data may be altered. |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 Baishakh · 1 mark
What is the correct syntax to declare a structure in C?
(a) struct { }
(b) define struct { }
(c) struct [ ]
(d) struct <name> { }
Answer
(d) struct <name> { }
The general form of a structure declaration in C is struct tag { member declarations };, where the tag (name) identifies the structure type — for example:
struct student {
int roll;
char name[20];
};
Option (a) is only an anonymous structure (no tag), and options (b) and (c) are not valid C syntax.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 1 MCQ
Loading…
- 2081 Baishakh · 1 mark
In C, which operator is used to get the address of a variable?
(a) *
(b) &
(c) ->
(d) .
Answer
(b) &
The & (ampersand) is the address-of operator — it returns the memory address of a variable, as in &x. The * is the dereference operator (gives the value at an address), while -> and . are member-access operators for structures.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 1 MCQ
Loading…
- 2081 Baishakh · 8 marks
Write a C program that uses structures to represent details of five books (title, author, publisher and price) and prints them out.
Answer
A structure groups related data of different types under one name. Here we declare a struct book with four members, read the details of five books into an array of structures, and then print them in a table.
#include <stdio.h>
struct book
{
char title[50];
char author[50];
char publisher[50];
float price;
};
int main()
{
struct book b[5];
int i;
/* Reading details of five books */
printf("Enter details of five books:\n");
for (i = 0; i < 5; i++)
{
printf("\nBook %d\n", i + 1);
printf("Title: ");
scanf(" %[^\n]", b[i].title);
printf("Author: ");
scanf(" %[^\n]", b[i].author);
printf("Publisher: ");
scanf(" %[^\n]", b[i].publisher);
printf("Price: ");
scanf("%f", &b[i].price);
}
/* Printing the details in tabular form */
printf("\n%-25s %-20s %-20s %s\n", "Title", "Author", "Publisher", "Price");
printf("----------------------------------------------------------------------\n");
for (i = 0; i < 5; i++)
{
printf("%-25s %-20s %-20s %.2f\n",
b[i].title, b[i].author, b[i].publisher, b[i].price);
}
return 0;
}
Explanation of the key points
struct bookis the structure template;b[5]is an array of five such structures, so each elementb[i]holds one complete book record.- Members are accessed with the dot operator, e.g.
b[i].title,b[i].price. scanf(" %[^\n]", ...)reads a string containing spaces (the leading space skips the leftover newline);%salone would stop at the first space, which is wrong for titles and author names.- The
%-25sand%-20sformat specifiers left-align the text in fixed-width columns so the output appears as a neat table.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 Baishakh · 8 marks
Discuss the concept of binary file handling in C programming and explain how fwrite() and getw() functions facilitate binary input/output operations. Give examples.
Answer
Binary file handling in C
A binary file stores data in the same raw byte form in which it is held in memory, with no conversion to readable characters. An int takes 4 bytes in the file, not one character per digit. A binary file is opened by adding b to the mode: "rb", "wb", "ab", "rb+", "wb+".
| Text file | Binary file |
|---|---|
| Data stored as characters (human readable) | Data stored as raw bytes (not readable) |
| Newline translation may occur | No translation |
Uses fprintf(), fscanf(), fputs(), fgets() | Uses fwrite(), fread(), putw(), getw() |
| Larger and slower for numeric data | Compact, faster, preserves exact values |
Binary files are suited to storing records (structures), arrays and numbers, because a whole block can be moved in one call.
fwrite()
size_t fwrite(const void *ptr, size_t size, size_t n, FILE *fp);
It writes n items, each size bytes long, from the memory at ptr into the file fp. It returns the number of items actually written, which equals n if there is no error. Its counterpart is fread(), which reads blocks back.
#include <stdio.h>
struct student { int roll; char name[20]; float marks; };
int main()
{
FILE *fp;
struct student s = {1, "Sita", 85.5};
int arr[5] = {10, 20, 30, 40, 50};
fp = fopen("data.bin", "wb");
if (fp == NULL) { printf("Cannot open file"); return 1; }
fwrite(&s, sizeof(s), 1, fp); /* one structure record */
fwrite(arr, sizeof(int), 5, fp); /* whole array in one call */
fclose(fp);
return 0;
}
getw() (and putw())
int getw(FILE *fp);
int putw(int n, FILE *fp);
putw() writes one integer (sizeof(int) bytes) to a binary file. getw() reads the next integer from the file and returns it. At the end of the file or on error it returns EOF, so feof(fp) should be used to check the end of file.
#include <stdio.h>
int main()
{
FILE *fp;
int i, n;
fp = fopen("num.bin", "wb");
for (i = 1; i <= 5; i++)
putw(i * 10, fp); /* writes 10 20 30 40 50 */
fclose(fp);
fp = fopen("num.bin", "rb");
while ((n = getw(fp)), !feof(fp))
printf("%d ", n); /* reads integers one by one */
fclose(fp);
return 0;
}
Output: 10 20 30 40 50
Reading back with fread()
struct student t;
fp = fopen("data.bin", "rb");
fread(&t, sizeof(t), 1, fp);
printf("%d %s %.1f", t.roll, t.name, t.marks); /* 1 Sita 85.5 */
fclose(fp);
Conclusion
fwrite() and fread() transfer whole blocks (arrays and structures) in a single call, while putw() and getw() transfer one integer at a time. Both avoid text conversion, so data is stored compactly and read back exactly as written.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 Supplementary · 1 mark
What will be the output of the program code?
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "Hello";
char str2[] = "world";
strcat(str1, str2);
puts(str1);
return 0;
}
(a) Hello
(b) World
(c) Helloworld
(d) WorldHello
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "Hello";
char str2[] = "world";
strcat(str1, str2);
puts(str1);
return 0;
}
Answer
(c) Helloworld
strcat(str1, str2) appends the string str2 ("world") to the end of str1 ("Hello"), overwriting the null terminator of str1. The combined string "Helloworld" (10 characters) easily fits in the 20-byte array str1, so puts(str1) prints Helloworld.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 1 MCQ
Loading…
- 2080 Supplementary · 8 marks
What is structure? Write a program to store five students’ information (ID, Name, DOB and phone) and display them using structure.
Answer
Structure
A structure is a user-defined data type in C that groups together variables of different data types under a single name. Each variable inside the structure is called a member (or field). Unlike an array, which can hold only elements of the same type, a structure allows related but dissimilar data to be stored as one unit — for example, a student's ID (int), name (string), DOB (string) and phone (string) can all be kept together in one structure variable.
Structures are declared with the struct keyword and members are accessed using the dot operator (.).
Program
#include <stdio.h>
struct student
{
int id;
char name[30];
char dob[15];
char phone[15];
};
int main()
{
struct student s[5];
int i;
/* Input */
for (i = 0; i < 5; i++)
{
printf("Enter details of student %d\n", i + 1);
printf("ID: ");
scanf("%d", &s[i].id);
printf("Name: ");
scanf("%s", s[i].name);
printf("DOB (dd/mm/yyyy): ");
scanf("%s", s[i].dob);
printf("Phone: ");
scanf("%s", s[i].phone);
}
/* Output */
printf("\nID\tName\t\tDOB\t\tPhone\n");
for (i = 0; i < 5; i++)
{
printf("%d\t%s\t\t%s\t%s\n",
s[i].id, s[i].name, s[i].dob, s[i].phone);
}
return 0;
}
Sample output
Enter details of student 1
ID: 101
Name: Ram
DOB (dd/mm/yyyy): 12/05/2005
Phone: 9801234567
...
ID Name DOB Phone
101 Ram 12/05/2005 9801234567
102 Sita 03/08/2004 9812345678
103 Hari 21/01/2005 9845678123
104 Gita 15/11/2004 9856781234
105 Ramesh 09/03/2005 9867812345
Explanation: An array of five struct student variables is declared. A loop reads the four members of each student using scanf with the dot operator. A second loop prints all five records in tabular form.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 Supplementary · 8 marks
What is Pointer? Write a program to read and write data from a file using file handling functions.
Answer
Pointer
A pointer is a variable that stores the memory address of another variable. Instead of holding a data value directly, it holds the location in memory where that value is kept. Pointers allow a program to access and manipulate data indirectly, and they are used for dynamic memory allocation, passing arguments by reference, and building data structures like linked lists.
In C, a pointer is declared using the * operator, and the address of a variable is obtained using the & operator.
int a = 10;
int *p; /* p is a pointer to int */
p = &a; /* p now holds the address of a */
printf("%d", *p); /* prints 10, *p dereferences the pointer */
Here p is a pointer, &a gives the address of a, and *p gives the value stored at that address.
Program to read and write data from a file using file handling functions
The program below uses the standard C file handling functions fopen(), fprintf()/fputs(), fscanf()/fgets(), and fclose() to write data into a file and then read it back.
/* Program to write data to a file and read it back */
#include <stdio.h>
#include <conio.h>
int main()
{
FILE *fp;
char name[30];
int age;
/* ---------- Writing data to the file ---------- */
fp = fopen("student.txt", "w"); /* open file in write mode */
if (fp == NULL)
{
printf("Error: Cannot open file for writing.\n");
return 1;
}
printf("Enter name and age of student: ");
scanf("%s %d", name, &age);
fprintf(fp, "%s %d\n", name, age); /* write formatted data */
fclose(fp); /* close the file */
/* ---------- Reading data from the file ---------- */
fp = fopen("student.txt", "r"); /* open file in read mode */
if (fp == NULL)
{
printf("Error: Cannot open file for reading.\n");
return 1;
}
fscanf(fp, "%s %d", name, &age); /* read formatted data */
printf("Data read from file: %s %d\n", name, age);
fclose(fp); /* close the file */
getch();
return 0;
}
Output (sample):
Enter name and age of student: Ram 18
Data read from file: Ram 18
File handling functions used
| Function | Purpose |
|---|---|
fopen() | Opens a file and returns a file pointer; mode "w" for writing, "r" for reading |
fprintf() | Writes formatted data to a file |
fscanf() | Reads formatted data from a file |
fclose() | Closes the file and releases the file pointer |
The same task can also be done with character-based functions fputc()/fputs() for writing and fgetc()/fgets() for reading.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 Baishakh · 1 mark
Which of the following is true about FILE *pt?
(a) FILE is a keyword in c for representing files and fpt is a variable of FILE type
(b) FILE is a buffered Stream
(c) FILE is a Stream
(d) FILE is a structure and fpt is a pointer to the structure of FILE type
Answer
(d) FILE is a structure and fpt is a pointer to the structure of FILE type
FILE is not a keyword but a structure type defined in the header file stdio.h that holds information about a stream (buffer address, file descriptor, position pointer, error flags, etc.). So FILE *pt; declares pt as a pointer to such a structure, and this pointer is what all file-handling functions like fopen(), fclose() and fprintf() use to refer to a file.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 1 MCQ
Loading…
- 2080 Baishakh · 3+5 marks
Write the advantage of pointer. Write a C-program to enter the radius of a football and find the area of football by using user defined function.
Answer
Advantages of Pointer (3 marks)
- Direct memory access: A pointer stores the address of a variable, so data can be read or modified directly in memory without copying it.
- Dynamic memory allocation: Pointers allow memory to be allocated and freed at run time using
malloc(),calloc(),realloc()andfree(), so memory is used only when needed. - Pass by reference: By passing pointers to a function, the function can change the original values in the calling function and can also return more than one value.
- Efficient handling of arrays, strings and data structures: Pointers make traversal and manipulation of arrays, strings, linked lists, trees and graphs faster and use less memory than copying whole structures.
C Program (5 marks)
Algorithm
- Start.
- Read the radius
rof the football. - Call the user-defined function
area(r). - Inside the function compute area = 4πr² (surface area of a sphere).
- Print the area and stop.
Program
/* Program to find the surface area of a football using a user defined function */
#include <stdio.h>
#define PI 3.14159
float area(float r); /* function prototype */
int main()
{
float r, a;
printf("Enter the radius of the football: ");
scanf("%f", &r);
a = area(r); /* function call */
printf("Area of the football = %.2f sq. units", a);
return 0;
}
/* user defined function */
float area(float r)
{
return 4 * PI * r * r; /* area of sphere = 4*pi*r*r */
}
Output
Enter the radius of the football: 7
Area of the football = 615.75 sq. units
Note: A football is a sphere, so its surface area is 4πr². If only the area of its circular cross-section is asked, use PI * r * r in the function.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 Baishakh · 2+6 marks
Define the structure. Write a C-program using structure to input staff id, name and the salary of 50 staffs. Display staff id, name and salary of those staff whose salary range from 25 thousand to 40 thousand.
Answer
1. Definition of Structure (2 marks)
A structure is a user-defined data type in C that groups together variables of different data types under a single name. Each variable inside a structure is called a member (or field), and the members are accessed using the dot operator (.). It is used to represent a record, such as a staff record containing an id, name and salary.
struct staff {
int id;
char name[30];
float salary;
};
2. C-Program (6 marks)
/* Program to input staff id, name and salary of 50 staffs
and display those whose salary is between 25,000 and 40,000 */
#include <stdio.h>
struct staff {
int id;
char name[30];
float salary;
};
int main() {
struct staff s[50];
int i, n;
printf("How many staffs? ");
scanf("%d", &n);
/* Input section */
for (i = 0; i < n; i++) {
printf("\nStaff %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);
}
/* Display section */
printf("\nStaffs whose salary is between Rs 25000 and Rs 40000:\n");
printf("ID\tName\tSalary\n");
for (i = 0; i < n; i++) {
if (s[i].salary >= 25000 && s[i].salary <= 40000) {
printf("%d\t%s\t%.2f\n", s[i].id, s[i].name, s[i].salary);
}
}
return 0;
}
Output (sample):
How many staffs? 3
Staff 1
Enter staff id: 101
Enter name: Ram
Enter salary: 30000
Staff 2
Enter staff id: 102
Enter name: Sita
Enter salary: 45000
Staff 3
Enter staff id: 103
Enter name: Hari
Enter salary: 38000
Staffs whose salary is between Rs 25000 and Rs 40000:
ID Name Salary
101 Ram 30000.00
103 Hari 38000.00
Explanation: An array of 50 structures s[50] is declared to hold the records. The for loop reads the id, name and salary of each staff using s[i].id, s[i].name and s[i].salary. A second for loop checks the condition salary >= 25000 && salary <= 40000 and prints only those staff records that satisfy the given salary range.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 Jestha · 1 mark
What is the output of C program?
void main(){
int b = 25;
// b memory location = 1234;
int *p; p = &b; printf("%d %d", &b, p);
}
(a) 25 25
(b) 1234 1234
(c) 25
(d) 1234 25
void main(){
int b = 25;
// b memory location = 1234;
int *p; p = &b; printf("%d %d", &b, p);
}
Answer
(b) 1234 1234
p = &b makes p store the address of b. Since the address of b is given as 1234, both &b and p print the same value: 1234 1234.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 1 MCQ
Loading…
- 2079 Jestha · 2+6 marks
What is structure? Write a program to input roll, name and age of 5 students and display them properly using structure.
Answer
Structure is a user-defined data type in C that groups variables of different data types under a single name. Each variable inside a structure is called a member, and the structure lets us treat related data (such as a student's roll, name and age) as one unit.
Program:
#include <stdio.h>
struct student
{
int roll;
char name[30];
int age;
};
int main()
{
struct student s[5];
int i;
/* Input */
for (i = 0; i < 5; i++)
{
printf("Enter roll, name and age of student %d: ", i + 1);
scanf("%d %s %d", &s[i].roll, s[i].name, &s[i].age);
}
/* Display */
printf("\nRoll\tName\tAge\n");
for (i = 0; i < 5; i++)
{
printf("%d\t%s\t%d\n", s[i].roll, s[i].name, s[i].age);
}
return 0;
}
Output (sample):
Enter roll, name and age of student 1: 1 Ram 15
Enter roll, name and age of student 2: 2 Sita 16
Enter roll, name and age of student 3: 3 Hari 14
Enter roll, name and age of student 4: 4 Gita 15
Enter roll, name and age of student 5: 5 Nita 17
Roll Name Age
1 Ram 15
2 Sita 16
3 Hari 14
4 Gita 15
5 Nita 17
Explanation: An array of structure s[5] is declared so that each element holds one student's record. The dot operator (.) accesses each member, e.g. s[i].roll. The first loop reads the data for all five students and the second loop prints them in a tabular form.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 Jestha · 8 marks
Write a C program to enter ID, employee name and post of the employee and store them in a data file "emp.txt". Display each record on the screen in an appropriate format.
Answer
A structure groups the three fields of one employee, and fwrite/fread handle the whole structure in one go.
/* Store employee records in "emp.txt" and display them */
#include <stdio.h>
#include <stdlib.h>
struct employee
{
int id;
char name[30];
char post[20];
};
int main()
{
FILE *fp;
struct employee e;
int n, i;
/* ---------- Writing records to the file ---------- */
fp = fopen("emp.txt", "wb");
if (fp == NULL)
{
printf("Error: cannot open file for writing.\n");
exit(1);
}
printf("How many employees? ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("\nEmployee %d\n", i + 1);
printf("Enter ID : ");
scanf("%d", &e.id);
printf("Enter Name : ");
scanf("%s", e.name);
printf("Enter Post : ");
scanf("%s", e.post);
fwrite(&e, sizeof(struct employee), 1, fp);
}
fclose(fp);
/* ---------- Reading records back and displaying ---------- */
fp = fopen("emp.txt", "rb");
if (fp == NULL)
{
printf("Error: cannot open file for reading.\n");
exit(1);
}
printf("\n%-10s %-20s %-20s\n", "ID", "NAME", "POST");
printf("------------------------------------------------------\n");
while (fread(&e, sizeof(struct employee), 1, fp) == 1)
printf("%-10d %-20s %-20s\n", e.id, e.name, e.post);
fclose(fp);
return 0;
}
How it works
struct employeedeclares the three fields —id(int),nameandpost(strings).- The file is opened in binary write mode
"wb"so that the structure is written exactly as it is stored in memory.fwrite(&e, sizeof(struct employee), 1, fp)writes one complete record at a time. - After
fclose, the same file is reopened in binary read mode"rb". freadreturns the number of items read; the loopwhile (fread(...) == 1)therefore stops automatically at end-of-file, printing each record in a tabular format using%-10dand%-20sfield widths.exit(1)from<stdlib.h>terminates the program if the file cannot be opened.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- NEB Class 12 Computer Science · 8 marks
Write a C program using structures to record the roll number, name and marks in three subjects (each out of 100) of 12 students. Display the total and percentage of each student.
Answer
#include <stdio.h>
struct student {
int roll;
char name[30];
float marks[3];
float total;
float percentage;
};
int main() {
struct student s[12];
int i, j;
for (i = 0; i < 12; i++) {
printf("Enter details of student %d\n", i + 1);
printf("Roll number: ");
scanf("%d", &s[i].roll);
printf("Name: ");
scanf(" %[^\n]", s[i].name);
s[i].total = 0;
for (j = 0; j < 3; j++) {
printf("Marks in subject %d: ", j + 1);
scanf("%f", &s[i].marks[j]);
s[i].total += s[i].marks[j];
}
s[i].percentage = s[i].total / 3; /* 3 subjects, each out of 100 */
}
printf("\nRoll\tName\t\tTotal\tPercentage\n");
for (i = 0; i < 12; i++) {
printf("%d\t%-15s\t%.2f\t%.2f%%\n",
s[i].roll, s[i].name, s[i].total, s[i].percentage);
}
return 0;
}
Total marks is , so the percentage is , which is what the program computes.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- NEB Class 12 Computer Science · 8 marks
Write a C program that creates a data file named score.dat storing the registration number, name, gender and address of students. Ask the user whether to continue entering records, and at the end display all the records.
Answer
#include <stdio.h>
struct student {
int regno;
char name[30];
char gender;
char address[30];
};
int main() {
FILE *fp;
struct student s;
char choice;
fp = fopen("score.dat", "wb");
if (fp == NULL) {
printf("File cannot be opened.\n");
return 1;
}
do {
printf("Registration number: ");
scanf("%d", &s.regno);
printf("Name: ");
scanf(" %[^\n]", s.name);
printf("Gender (M/F/O): ");
scanf(" %c", &s.gender);
printf("Address: ");
scanf(" %[^\n]", s.address);
fwrite(&s, sizeof(s), 1, fp);
printf("Do you want to continue? (y/n): ");
scanf(" %c", &choice);
} while (choice == 'y' || choice == 'Y');
fclose(fp);
/* display all records */
fp = fopen("score.dat", "rb");
if (fp == NULL) {
printf("File cannot be opened.\n");
return 1;
}
printf("\nRegNo\tName\t\tGender\tAddress\n");
while (fread(&s, sizeof(s), 1, fp) == 1) {
printf("%d\t%-15s\t%c\t%s\n", s.regno, s.name, s.gender, s.address);
}
fclose(fp);
return 0;
}
The file is first opened in wb mode to write records until the user answers anything other than y, then reopened in rb mode and read with fread until no more records remain.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
Questions from NEB Class 12 2083 Computer Science (Board exam, Baishakh 2083; typed transcription), NEB Class 12 2082 Supplementary Computer Science (Supplementary exam 2082; set B; scanned images), NEB Class 12 2082 Computer Science (Board exam, Baishakh 2082; set D; typed transcription), NEB Class 12 2081 Computer Science (Board exam, Baishakh 2081; typed transcription), NEB Class 12 2080 Supplementary Computer Science (Supplementary/grade-increment exam 2080; set B; typed transcription), NEB Class 12 2080 Computer Science (Board exam, Baishakh 2080; typed text (solved)), NEB Class 12 2079 Computer Science (Board exam, Jestha 2079; set A; typed transcription) and NEB Class 12 Computer Science (4281) Model Question (NEB model question set, 50 marks, 2 hours; questions only (answers not taken). Wording of some questions reconstructed from a page summary, so check against the paper.). Answers are written for this site; check them against your class notes.
Chapter titles and hours from the official syllabus ↗