Tribhuvan University
Faculty of Management
Office of the Dean
2023 AD / Regular Examination
Time: 3 Hrs. | Full Marks: 60 | Pass Marks: 30
Subjective Questions
- [2]
Define object code.
View model solution
Definition of Object Code
Object code is the low-level, machine-readable binary representation (sequence of instructions in 0s and 1s) produced by a language translator—such as a C compiler or assembler—from high-level human-readable source code.
Key Aspects:
- In C, compilation generates an intermediate object file with extension
.obj(on Windows) or.o(on UNIX/Linux). - Object code is not yet fully executable on its own because external library function references (e.g.,
printf,sqrt) remain unresolved until the linker links it with runtime libraries to produce the final executable (.exe).
- In C, compilation generates an intermediate object file with extension
- [2]
Write the rule to define a variable.
View model solution
Rules to Define a Variable Name in C
An identifier or variable name in C must adhere to the following naming conventions:
- Permitted Characters: Can consist solely of letters (
A-Z,a-z), digits (0-9), and the underscore (_) character. - First Character Rule: Must begin with an alphabetical letter or an underscore. It cannot begin with a digit (e.g.,
1countis invalid;count1is valid). - No Special Symbols: Spaces and special characters (
@,$,#,-,%) are strictly disallowed. - Keywords Reserved: Cannot be any of C’s 32 reserved keywords (e.g.,
int,while,returncannot be variable names). - Case Sensitivity: C is case-sensitive (
total,Total, andTOTALdenote three distinct variables).
- Permitted Characters: Can consist solely of letters (
- [2]
Is printf() formatted or unformatted I/O? Justify.
View model solution
Is printf() Formatted or Unformatted I/O? Justification
printf()is a formatted I/O function.Justification:
- Format Specifiers:
printf()accepts a formatting string containing conversion specifications (e.g.,%d,%f,%s,%c,%x). It actively parses these specifiers and converts internal binary data representations into human-readable formatted character strings. - Layout Control: It supports field widths, precision specifiers, padding zeroes, and alignment flags (e.g.,
printf("%10.2f", num)). - Contrast with Unformatted I/O: Unformatted functions (such as
putchar(),puts(), andwrite()) simply transmit raw, uninterpreted byte sequences without conversion or string formatting.
- Format Specifiers:
- [2]
What do you mean by implicit type conversion?
View model solution
Implicit Type Conversion in C
Implicit type conversion (also termed type coercion or automatic type conversion) is the automatic conversion of a variable of one data type into another data type performed directly by the C compiler without explicit programmer intervention.
Rules & Promotion Hierarchy:
The compiler converts lower-rank types into higher-rank types in expressions to prevent loss of precision:
Example:
int a = 5; float b = 2.5; float result = a + b; // 'a' is automatically converted to float 5.0; result is 7.5 - [2]
Why do we need exit function?
View model solution
Purpose of the exit() Function in C
The
exit()function, declared in<stdlib.h>, is used to immediately terminate the execution of the entire calling process/program from any point, returning control back to the operating system.Key Functions:
- Immediate Termination: Bypasses remaining code and returns immediately, even from deeply nested functions.
- Resource Cleanup: Flushes all unwritten buffered output streams, closes all open file pointers, and removes temporary files created by
tmpfile(). - Exit Status Code: Returns a status code to the operating system:
exit(0)orexit(EXIT_SUCCESS): Normal successful program termination.exit(1)orexit(EXIT_FAILURE): Abnormal termination due to an error (e.g., file not found, out of memory).
- [2]
Define Null character.
View model solution
Definition of Null Character in C
The null character is an escape sequence denoted by
'\0'in C, having an ASCII numerical value of0.Significance:
- String Delimiter: Serves as the universal sentinel marker denoting the end of a character sequence (string) in memory.
- Buffer Traversal: Enables functions like
printf("%s"),strlen(), andstrcpy()to loop through memory until*ptr == '\0'without needing to pass an explicit array length. - Distinction: Differs fundamentally from the character digit
'0'(ASCII 48) and theNULLpointer((void*)0).
- [2]
How does complier determine the life time of a variable?
View model solution
How Compiler Determines the Lifetime of a Variable
The C compiler determines the lifetime (duration of memory retention) of a variable based on its storage class and the scope of its declaration:
- Automatic Storage Class (
auto):- Default for variables declared inside a block or function.
- Lifetime: Allocated on the call stack when the block is entered, and automatically deallocated when the block exits.
- Static Storage Class (
static):- Variables declared with the
statickeyword or declared globally outside functions. - Lifetime: Allocated in the data segment at program startup and persists throughout the entire program execution.
- Variables declared with the
- Dynamic Storage (Heap Allocation):
- Memory allocated via
malloc(),calloc(), orrealloc(). - Lifetime: Managed dynamically by the programmer; persists until explicitly released via
free()or program exit.
- Memory allocated via
- Automatic Storage Class (
- [2]
List any one advantage and disadvantage of pointer.
View model solution
Advantages and Disadvantages of Pointers in C
One Major Advantage:
- Dynamic Memory Management & Pass by Reference: Pointers enable dynamic runtime memory allocation on the heap (
malloc) and allow functions to directly modify the caller’s variables through pass-by-reference without the overhead of copying large arrays or structures.
One Major Disadvantage:
- Risk of Memory Corruption & Bugs: Improper pointer manipulation can lead to severe runtime faults including segmentation faults, dangling pointers (pointing to freed memory), wild pointers (uninitialized), and memory leaks.
- Dynamic Memory Management & Pass by Reference: Pointers enable dynamic runtime memory allocation on the heap (
- [2]
When do we prefer union rather than structure? Give an example.
View model solution
When to Prefer Union Over Structure
A union is preferred over a structure when a program requires a variable that can hold different data types at different times, but only one member will ever be stored at any given moment, thereby drastically conserving memory.
Explanation:
- A structure allocates separate memory for each member (total size = sum of member sizes + padding).
- A union allocates a single shared memory block equal to the size of its largest member; all members share the exact same starting address.
Example:
union HardwareValue { int intVal; // 4 bytes float floatVal; // 4 bytes char charVal; // 1 byte }; // Size of union is 4 bytes, compared to 9+ bytes in a struct. - [2]
What is the difference between append mode and write mode in file handling?
View model solution
Difference Between Append Mode (“a”) and Write Mode (“w”) in File Handling
Feature Write Mode ( "w")Append Mode ( "a")Existing File Handling Completely truncates (overwrites) the existing file, erasing all previous data. Preserves all existing content intact. File Pointer Position Positioned at the beginning of the file (offset 0). Positioned at the end of file (EOF). Non-existent File Creates a new file. Creates a new file. Primary Use Case When generating a fresh report or overwriting previous output. When appending transaction logs, audit trails, or adding records. - [5]
Draw a flowchart to find the smallest among three given integer.
View model solution
Flowchart to Find the Smallest Among Three Integers
[ START ] | v [ Input A, B, C ] | v / \ / A < B ? \ / \ (YES) (NO) / \ v v / \ / \ / A < C ? \ / B < C ? \ (YES) (NO) (YES) (NO) | | | | v v v v [Print A] [Print C] [Print B] [Print C] \ / \ / \ / \ / +--------+---------------+--------+ | v [ STOP ]Logic:
- Compare (A) with (B). If (A < B), compare (A) with (C); if (A < C), (A) is smallest; otherwise (C) is smallest.
- If (A \ge B), compare (B) with (C); if (B < C), (B) is smallest; otherwise (C) is smallest.
- [5]
What are the different data types in C programming and how are they used?
View model solution
Data Types in C Programming and Their Usage
C provides a rich type system categorized into three main families:
1. Fundamental (Primitive) Data Types:
int(Integer): Stores whole numbers without fractional parts (e.g.,int age = 21;, typically 4 bytes, range (-2^{31}) to (2^{31}-1)).float(Floating-Point): Stores single-precision real numbers with decimals (e.g.,float gpa = 3.75f;, 4 bytes, ~6-7 decimal digits precision).double(Double Precision): Stores high-precision floating numbers (e.g.,double pi = 3.1415926535;, 8 bytes, ~15 decimal digits precision).char(Character): Stores single ASCII characters enclosed in single quotes (e.g.,char grade = 'A';, 1 byte, range -128 to 127).void(Empty Type): Denotes the absence of a value or generic untyped pointer (void*).
2. Derived Data Types:
- Arrays: Collections of homogeneous elements (e.g.,
int marks[5];). - Pointers: Variables that hold memory addresses (e.g.,
int *ptr;). - Functions: Subroutines with specific return types and parameter lists.
3. User-Defined Data Types:
struct: Heterogeneous grouping of related attributes.union: Memory-sharing type for mutually exclusive fields.enum: Enumerated named integer constants.
- [5]
Describe the significance of escape sequence and delimiter with example.
View model solution
Escape Sequences and Delimiters in C
1. Escape Sequences:
An escape sequence is a character combination consisting of a backslash (
\) followed by a letter or digits. It represents non-printable, control, or special characters in character/string literals.- Significance: Allows programmers to format terminal output, control cursor movement, and include quotation marks within strings.
- Common Examples:
\n: Newline (moves cursor to next line).\t: Horizontal tab (indents by tab stops).\\: Backslash literal.\": Double quotation mark literal within a string.
printf("Paper Khoj:\tArchiving Past Papers\nPrice:\t\"Rs. 0 (Free)\"\n");
2. Delimiters:
A delimiter is a character or sequence of characters that separates independent lexical tokens (words, statements, expressions, data values).
- Significance: The compiler and runtime scanners use delimiters to parse statements and separate distinct fields in input streams.
- Common Examples in C:
- Semicolon (
;): Statement delimiter / terminator. - Comma (
,): Separates arguments, variable declarations, and array elements. - Braces (
{and}): Delimits functional and structural code blocks. - Whitespace (Space, Tab, Newline): Separates adjacent tokens in C and values in
scanf("%d %d", &a, &b).
- Semicolon (
- [5]
How pointer is used in arithmetic operation? Illustrate with an example.
View model solution
Pointer Arithmetic in C with Example
In C, arithmetic operations on pointers do not behave like standard integer addition. Instead, pointer arithmetic is scaled automatically by the size of the data type to which the pointer points.
Allowed Operations:
- Adding an integer to a pointer (
ptr + nadvances by (n \times \text{sizeof}(*\text{ptr})) bytes). - Subtracting an integer from a pointer (
ptr - n). - Subtracting two pointers of the same type (
ptr2 - ptr1yields the number of elements between them). - Increment (
ptr++) and Decrement (ptr--).
Illustrative Program:
#include <stdio.h> int main() { int arr[] = {10, 20, 30, 40, 50}; int *ptr = arr; // points to arr[0] printf("=== Pointer Arithmetic Demonstration ===\n"); printf("Initial Address of ptr (&arr[0]) : %p | Value: %d\n", (void*)ptr, *ptr); // Increment pointer ptr++; // advances by sizeof(int) = 4 bytes printf("After ptr++ (&arr[1]) : %p | Value: %d\n", (void*)ptr, *ptr); // Adding integer offset ptr = ptr + 2; // points to arr[3] printf("After ptr + 2 (&arr[3]) : %p | Value: %d\n", (void*)ptr, *ptr); return 0; } - Adding an integer to a pointer (
- [5]
Create a structure “mobile” with data member model and price and display the model of mobile having price more than Rs 10,000.
View model solution
Program: Structure “mobile” and Price Filter (> 10,000)
#include <stdio.h> #include <string.h> // Define structure Mobile struct mobile { char model[50]; float price; }; int main() { int n, i; printf("=== Mobile Phones Directory ===\n"); printf("Enter number of mobiles: "); if (scanf("%d", &n) != 1 || n <= 0) { printf("Invalid input count!\n"); return 1; } struct mobile m[n]; for (i = 0; i < n; i++) { printf("\nEnter details for Mobile #%d:\n", i + 1); printf(" Model Name: "); scanf("%s", m[i].model); printf(" Price (Rs.): "); scanf("%f", &m[i].price); } printf("\n===========================================\n"); printf("Mobiles with Price > Rs. 10,000:\n"); printf("===========================================\n"); int found = 0; for (i = 0; i < n; i++) { if (m[i].price > 10000.0f) { printf("Model: %-20s | Price: Rs. %.2f\n", m[i].model, m[i].price); found = 1; } } if (!found) { printf("No mobiles found with price exceeding Rs. 10,000.\n"); } printf("===========================================\n"); return 0; } - [5]
Write a program to copy the contain of one file to another file.
View model solution
Program: Copy Contents of One File to Another File
#include <stdio.h> #include <stdlib.h> int main() { char sourceFile[100], destFile[100]; FILE *fSource, *fDest; int ch; printf("=== File Copy Utility in C ===\n"); printf("Enter source filename: "); scanf("%s", sourceFile); printf("Enter destination filename: "); scanf("%s", destFile); // Open source file in read mode fSource = fopen(sourceFile, "r"); if (fSource == NULL) { printf("Error: Could not open source file '%s'!\n", sourceFile); return 1; } // Open destination file in write mode fDest = fopen(destFile, "w"); if (fDest == NULL) { printf("Error: Could not create destination file '%s'!\n", destFile); fclose(fSource); return 1; } // Read character-by-character until EOF and write to destination while ((ch = fgetc(fSource)) != EOF) { fputc(ch, fDest); } printf("\nSuccessfully copied content from '%s' to '%s'.\n", sourceFile, destFile); fclose(fSource); fclose(fDest); return 0; }Key Steps:
fgetc(fSource)reads bytes sequentially untilEOF.fputc(ch, fDest)writes each character into the destination file.fclose()commits data and flushes buffers.
- [5]
Write a program to find the sum of digits of given integer using recursion. (eg: input = 123, output = 1+2+3=6)
View model solution
Program: Sum of Digits of an Integer Using Recursion
#include <stdio.h> // Recursive function to calculate sum of digits int sumOfDigits(int n) { // Base case: when number reduces to 0 if (n == 0) { return 0; } // Recursive case: last digit (n % 10) + sum of remaining digits (n / 10) return (n % 10) + sumOfDigits(n / 10); } int main() { int num, result; printf("=== Sum of Digits (Recursive) ===\n"); printf("Enter an integer: "); if (scanf("%d", &num) != 1) { printf("Invalid input!\n"); return 1; } // Handle negative integers by taking absolute value int temp = (num < 0) ? -num : num; result = sumOfDigits(temp); printf("Input: %d -> Sum of Digits: %d\n", num, result); return 0; }Execution Trace for
input = 123:sumOfDigits(123)= (123 % 10) +sumOfDigits(12)= (3) +sumOfDigits(12)sumOfDigits(12)= (12 % 10) +sumOfDigits(1)= (2) +sumOfDigits(1)sumOfDigits(1)= (1 % 10) +sumOfDigits(0)= (1) + (0) = (1)- Total unwind: (1 + 2 + 3 = 6).
- [5]
How do you draw a rectangle in Graphics in C? Write the codes.
View model solution
Drawing a Rectangle in C Graphics
In C graphics (
<graphics.h>), a rectangle is drawn using therectangle()function.Syntax:
void rectangle(int left, int top, int right, int bottom);left: X-coordinate of top-left corner.top: Y-coordinate of top-left corner.right: X-coordinate of bottom-right corner.bottom: Y-coordinate of bottom-right corner.
Complete Program:
#include <graphics.h> #include <conio.h> #include <stdio.h> int main() { int gd = DETECT, gm; // Initialize graphics mode initgraph(&gd, &gm, "C:\\Turboc3\\BGI"); // Optional styling setcolor(YELLOW); // Draw rectangle from (100, 100) to (400, 250) rectangle(100, 100, 400, 250); outtextxy(120, 120, "Tribhuvan University - BITM Graphics"); getch(); // Wait for user keystroke closegraph(); // Deallocate graphics screen memory return 0; } - [5]
Describe any four storage classes in C with example.
View model solution
Four Storage Classes in C with Examples
A storage class defines the scope, visibility, initial value, and lifetime of a variable:
Storage Class Keyword Storage Location Default Value Scope Lifetime Automatic autoStack memory Garbage Local block Exists within block Register registerCPU register Garbage Local block Exists within block Static staticData segment Zero ( 0)Local/File Entire program External externData segment Zero ( 0)Global / All files Entire program Code Demonstrations:
#include <stdio.h> // 1. External (Global) int globalCount = 100; void demo() { // 2. Automatic (local stack) auto int a = 10; // 3. Static (retains value across calls) static int s = 0; s++; // 4. Register (hint to CPU for fast loop index) register int i; printf("a = %d, static s = %d\n", a, s); } int main() { demo(); // a = 10, s = 1 demo(); // a = 10, s = 2 return 0; } - [5]
Display the following pattern using loop. BIMMIB IMMI MM
View model solution
Program: Symmetrical Word Pattern Printing
Pattern to display:
BIMMIB IMMI MM#include <stdio.h> #include <string.h> int main() { char word[] = "BIM"; int len = strlen(word); // len = 3 int i, j; printf("=== Symmetrical Word Pattern ===\n"); // Loop through 3 rows for (i = 0; i < len; i++) { // Left side: print letters from index i to len - 1 for (j = i; j < len; j++) { putchar(word[j]); } // Right side (mirror): print letters from index len - 1 down to i for (j = len - 1; j >= i; j--) { putchar(word[j]); } printf("\n"); } return 0; }Step-by-Step Logic:
- Row 0 (
i=0): Left printsword[0..2]("BIM"), Right printsword[2..0]("MIB") (\rightarrow)BIMMIB. - Row 1 (
i=1): Left printsword[1..2]("IM"), Right printsword[2..1]("MI") (\rightarrow)IMMI. - Row 2 (
i=2): Left printsword[2..2]("M"), Right printsword[2..2]("M") (\rightarrow)MM.
- Row 0 (
- [10]
Discuss some commonly used string library functions in C programming. Provide examples of each function.
View model solution
Common String Library Functions in C (
<string.h>)The C standard library provides functions declared in
<string.h>to manipulate null-terminated character strings:1.
strlen()— String Length- Returns the number of characters in the string, excluding
'\0'. - Example:
strlen("Tribhuvan")returns9.
2.
strcpy()— String Copy- Copies the source string into the destination buffer (including
'\0'). - Example:
strcpy(dest, "BITM");
3.
strcat()— String Concatenation- Appends the source string to the end of the destination string.
- Example:
strcat(dest, " Nepal");
4.
strcmp()— String Comparison- Lexicographically compares two strings:
- Returns
0if identical. - Returns (< 0) if str1 is lexicographically smaller than str2.
- Returns (> 0) if str1 is greater than str2.
- Returns
5.
strrev()— String Reverse (or manual reversal)- Reverses the string in place.
Comprehensive Demonstration Program:
#include <stdio.h> #include <string.h> int main() { char s1[50] = "Tribhuvan"; char s2[50] = "University"; char s3[100]; printf("=== String Library Functions Demonstration ===\n\n"); // 1. strlen printf("1. Length of '%s': %zu\n", s1, strlen(s1)); // 2. strcpy strcpy(s3, s1); printf("2. Copied s1 to s3: '%s'\n", s3); // 3. strcat strcat(s3, " "); strcat(s3, s2); printf("3. Concatenated s3: '%s'\n", s3); // 4. strcmp int cmp = strcmp(s1, s2); if (cmp == 0) { printf("4. s1 and s2 are equal.\n"); } else if (cmp < 0) { printf("4. '%s' precedes '%s' alphabetically.\n", s1, s2); } else { printf("4. '%s' follows '%s' alphabetically.\n", s1, s2); } return 0; } - Returns the number of characters in the string, excluding
- [10]
Compare and contrast passing arguments by value and passing arguments by address in C programming. Provide examples.
View model solution
Passing Arguments by Value vs Passing Arguments by Address in C
1. Comparison & Contrast:
Parameter Passing by Value Passing by Address (Reference) Mechanism Copies the actual argument’s data value into the function’s formal parameter variable. Passes the memory address of the actual argument to a pointer parameter. Memory Allocation Formal parameter resides in a separate stack frame location. Formal parameter is a pointer variable referencing the caller’s memory. Side Effects Changes made to the parameter inside the function do not affect the caller’s variable. Modifying the dereferenced pointer ( *ptr) directly mutates the caller’s variable.Return Capability Can return at most one value via the returnstatement.Can update multiple values simultaneously across variables in caller. Performance Can be slow if copying large structures or objects. High performance; passes only an address (typically 4 or 8 bytes).
2. Side-by-Side Code Demonstration:
#include <stdio.h> // A. Pass by Value: original variable remains unchanged void modifyByValue(int x) { x = x + 100; printf(" Inside modifyByValue: x = %d\n", x); } // B. Pass by Address: original variable is mutated void modifyByAddress(int *ptr) { *ptr = *ptr + 100; printf(" Inside modifyByAddress: *ptr = %d\n", *ptr); } int main() { int num1 = 50; int num2 = 50; printf("=== Demonstration of Argument Passing Modes ===\n\n"); // Case 1: Pass by Value printf("Case 1: Passing by Value\n"); printf(" Before function call: num1 = %d\n", num1); modifyByValue(num1); printf(" After function call : num1 = %d (UNCHANGED)\n\n", num1); // Case 2: Pass by Address printf("Case 2: Passing by Address\n"); printf(" Before function call: num2 = %d\n", num2); modifyByAddress(&num2); // pass address using & printf(" After function call : num2 = %d (MUTATED)\n", num2); return 0; }