Semester
Subject
Year
Tribhuwan University
2079
Bachelor Level / First Year / First Semester / Science
(C Programming)
Full Marks: 60
Pass Marks: 24
Time: 3 Hours
Candidates are required to give their answers in their own words as for as practicable.
The figures in the margin indicate full marks.
Long Answers Questions
A global variable is a variable declared outside all functions, accessible from any function throughout the program.
Advantages:
Disadvantages:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *f1, *f2, *f3;
int a[100], b[100], c[200];
int i = 0, j = 0, k = 0, n1 = 0, n2 = 0, temp;
// Read integers from num1.txt
f1 = fopen("num1.txt", "r");
if (f1 == NULL) {
printf("Cannot open num1.txt\n");
exit(1);
}
while (fscanf(f1, "%d", &a[n1]) != EOF) {
n1++;
}
fclose(f1);
// Read integers from num2.txt
f2 = fopen("num2.txt", "r");
if (f2 == NULL) {
printf("Cannot open num2.txt\n");
exit(1);
}
while (fscanf(f2, "%d", &b[n2]) != EOF) {
n2++;
}
fclose(f2);
// Copy all elements into array c
for (i = 0; i < n1; i++)
c[k++] = a[i];
for (j = 0; j < n2; j++)
c[k++] = b[j];
// Sort array c using Bubble Sort
for (i = 0; i < k - 1; i++) {
for (j = 0; j < k - i - 1; j++) {
if (c[j] > c[j + 1]) {
temp = c[j];
c[j] = c[j + 1];
c[j + 1] = temp;
}
}
}
// Write sorted integers to file3.txt
f3 = fopen("file3.txt", "w");
if (f3 == NULL) {
printf("Cannot open file3.txt\n");
exit(1);
}
for (i = 0; i < k; i++) {
fprintf(f3, "%d\n", c[i]);
}
fclose(f3);
printf("Files merged and sorted successfully into file3.txt\n");
return 0;
}
Logic Explanation:
fprintf().Conclusion: Global variables offer easy data sharing but compromise modularity and security. The file merging program demonstrates file handling with fopen(), fscanf(), fprintf(), and fclose() along with sorting logic to produce a sorted output file.
Short Answers Questions