Extra Menu

© 2026 Notes Gallery v3.3.1

All rights reserved. Designed for AKTU students.

Saved Bookmarks

Home / BCA / Problem Solving Using C Unit 5 Notes – Searching, Sorting, Dynamic Memory Allocation and File Handling

Problem Solving Using C Unit 5 Notes – Searching, Sorting, Dynamic Memory Allocation and File Handling

BBC103 Problem Solving Using C Unit 5 notes covering searching, sorting, dynamic memory allocation and file handling, with C programs, traces and solved questions.

Course Code: BBC103

Course: AKTU BCA 1st Year, Semester I

Unit: Searching, Sorting, Dynamic Memory Allocation and File Handling

Unit V Overview

Study searching and sorting algorithms, dynamic memory allocation functions, file streams and modes, file operations, command-line arguments and text and binary record input/output.

Topics Covered

Syllabus area Pages
Linear search and analysis 2-3
Binary search and comparison 4-5
Selection and bubble sort 6-9
Dynamic memory allocation functions 9-14
File basics, types, pointer and modes 14-17
File handling functions and positioning 17-21
Command-line arguments and record I/O 21-23
Integrated practice 24
Exam questions with answers 25-27
Quick revision and key formulas 28

Learning Outcomes

  • 1. Trace linear and binary searches.
  • 2. Implement selection and bubble sort.
  • 3. Explain malloc, calloc, realloc and free.
  • 4. Select file modes and perform stream operations.
  • 5. Process filenames through command-line arguments.
  • 6. Read, write and seek through file records.

Included in These Notes

32 study sections; 31 labelled diagrams; 10 colourful context images; explained C programs; worked cases; comparison tables, 24 short answers and 6 structured long answers and quick revision.

Study Approach

Understand. Identify search keys, memory size and file modes.

Compare. Distinguish algorithms, allocation functions and file types.

Apply. Dry-run algorithms and verify outputs from C programs.

Core idea: Search locates data; sorting orders it; dynamic allocation obtains runtime storage; files preserve information.

1. Introduction to searching and sorting

Searching and sorting in everyday problems

Searching retrieves the location of a required item; sorting rearranges a collection according to a chosen order. An examination result system might search for a roll number, then sort results by marks. A library might sort books by accession number to speed up lookup.

Figure 5.1
Unordered keys.

The same keys in ascending order are 9, 15, 24, 32 and 41. Sorting changes their positions, but not the set of stored values. A search returning index 3 refers to the collection’s current arrangement, so indices may change after sorting.

Concept Question answered
Search Where does the key occur?
Sort In what order should items appear?
Key Which value is compared?
Index Which array position is selected?

An algorithm may search for an item in an unsorted set or exploit an ordering already present. Sorting is useful when a collection will be searched repeatedly, displayed in order or processed by rank.

Visual 5.1
Checking keys one by one illustrates sequential search. Illustrative image.

Algorithm requirements and result conventions

Decide how to represent successful and unsuccessful searches. For a zero-based array, a returned integer from 0 through n-1 identifies a valid match, while -1 may indicate that no match was found. When duplicates exist, specify whether to return the first match, any match or all positions.

Performance terminology

Comparison: Testing two keys for order or equality. Swap: Exchanging two values. Pass: One repeated traversal or stage. Auxiliary space: Additional storage used by the algorithm.

Complexity Growth
O(1) Constant
O(log n) Logarithmic
O(n) Linear
O(n squared) Quadratic

These descriptions characterize how work grows as the input length increases, not exact elapsed seconds. Actual time also depends on implementation, hardware and input order. Exam focus: Explain prerequisites, algorithm steps, dry run, C implementation and time complexity for each method.

2. Linear search: logic and flow

Linear search examines array elements sequentially. Start at index 0, compare with the key and move to the next index if it differs. Stop immediately when a match is found, or return -1 after examining the last valid position.

Figure 5.2
Search for 27.

Algorithm

  • 1. Accept an array containing n values and the search key.
  • 2. Initialize i to 0. While i is less than n, compare a[i] with key.
  • 3. If equal, return i; otherwise increase i by one.
  • 4. When the loop finishes, return -1.

int linear(const int a[],int n,
int key){
for(int i=0;i<n;i++)
if(a[i]==key)return i;
return -1;
}

This routine works with both ordered and unordered arrays. Because comparisons begin at the first slot, it returns the first matching index.

Dry run: successful lookup

Given a={14,8,27,5,19}, key=27.

Step Index Value Action
1 0 14 Continue
2 1 8 Continue
3 2 27 Return 2

The result is index 2, corresponding to the third array position. Elements at indices 3 and 4 are not examined. A successful search near the beginning can terminate after very few comparisons.

Unsuccessful lookup

Search the same collection for key=16. Each of the five items differs, so the routine returns -1 after five key comparisons.

Situation Comparisons
Key at first position 1
Key at last position n
Key absent n
Empty collection 0

The array does not need to be rearranged before linear search. This is useful for short lists, frequently changing collections and one-off lookups where sorting overhead may not be justified.

3. Linear search programs and duplicate keys

Program: search user-supplied values

#include <stdio.h>
int main(void){
int a[50],n,key,pos=-1;
if(scanf(“%d”,&n)!=1 ||
n<0 || n>50)return 1;
for(int i=0;i<n;i++)
if(scanf(“%d”,&a[i])!=1)return 1;
if(scanf(“%d”,&key)!=1)return 1;
for(int i=0;i<n;i++){
if(a[i]==key){pos=i;break;}
}
if(pos<0)puts(“Not found”);
else printf(“Index %d”,pos);
return 0;
}

Input: 5 8 2 15 6 9 15. Output: Index 2.

The capacity of a is 50, while n is the logical number of entries. Validation prevents the input loop from exceeding allocated storage.

Why use break?

After discovering the first match, further comparisons are unnecessary. break exits the nearest loop, leaving pos equal to the matching index. If no matching key exists, pos remains at its initial value -1.

Find every occurrence

To report all matching positions, do not return or break at the first equality. Instead, continue scanning and maintain a count.

#include <stdio.h>
int main(void){
int a[]={5,9,5,2,5,7};
int count=0;
for(int i=0;i<6;i++){
if(a[i]==5){
printf(“%d “,i);count++;
}
}
printf(“| Count=%d”,count);
return 0;
}

Output: 0 2 4 | Count=3.

Figure 5.3
Repeated key positions.

The routine visits all six entries, even after the first match. To find the last occurrence instead, either remember the most recent match during a left-to-right scan or begin from the right.

Requirement Strategy
First occurrence Stop at first equality
Last occurrence Scan backward, stop
All occurrences Visit entire array
Count matches Increment a counter

Exam check: Searching {2,4,4,4,6} for 4 with the first-match routine returns 1, not 2 or 3.

Complexity and comparison count

Best case: one comparison. If a match is equally likely at any of n positions, the mean comparison count is (n+1)/2. If it is absent, the scan performs n comparisons. Best time O(1); average and worst time O(n); auxiliary space O(1). An empty array produces no comparisons.

4. Binary search: sorted data and midpoint

Binary search locates a key in a sorted array by repeatedly discarding a portion of the candidate range. It examines the middle item, then decides which half can still contain the target. The standard ascending-order version requires nondecreasing values.

Figure 5.4
Sorted keys.

Let low=0 and high=n-1. Compute mid=low+(high-low)/2 using integer division. If a[mid] equals key, return mid. If a[mid] is smaller, all positions through mid can be discarded. If a[mid] is larger, all positions from mid onward can be discarded.

Why sorting is essential

For unordered values, comparing against the middle element does not prove where the key lies. Consider {30,4,15,2,8}; a target of 30 could be wrongly discarded by the ascending binary-search rule. Establish the input ordering before using the algorithm.

Visual 5.2
Opening a sorted dictionary near its middle illustrates range reduction. Illustrative image.

Iterative program

#include <stdio.h>
int binary(const int a[],int n,
int key){
int lo=0,hi=n-1;
while(lo<=hi){
int m=lo+(hi-lo)/2;
if(a[m]==key)return m;
if(a[m]<key)lo=m+1;
else hi=m-1;
}
return -1;
}
int main(void){
int a[]={3,8,12,17,25,31,42};
printf(“%d”,binary(a,7,31));
return 0;
}

Output: 5.

Dry run

low high mid Value Action
0 6 3 17 low=4
4 6 5 31 Found

The search uses only two midpoint comparisons for this input. Computing midpoint as low+(high-low)/2 avoids adding two possibly large nonnegative indices directly. The inclusive interval is empty when low exceeds high.

5. Binary search: dry runs and termination

A successful multi-step case

Use sorted values {4,11,18,24,33,40,47,56,72}. Search for key 11. At first mid=4 and value=33, so restrict the candidate range to indices 0 through 3. The next midpoint is 1 and value=11, giving success.

Step low high mid Value
1 0 8 4 33
2 0 3 1 11
Figure 5.5
Left candidate range.

Unsuccessful case

Search for key 35 in the same array. When the range shrinks to an empty interval, the routine returns -1.

low high mid Value
0 8 4 33
5 8 6 47
5 5 5 40
5 4 — Stop

At the third step, 40 is larger than 35, so high becomes 4. Now low=5 > high=4. The key cannot occur in any remaining position.

Loop invariant and termination

At the start of each iteration, if the key exists among still-eligible elements, at least one matching index lies between low and high. A comparison with the middle value either finds an answer or removes a range that cannot contain the target. The remaining interval is shorter.

This invariant explains correctness, while strict movement of a boundary explains termination. Updating low=mid or high=mid can fail to remove the middle position and may create a nonterminating loop. The inclusive-index implementation uses mid+1 or mid-1.

Boundary Meaning
low=high One candidate remains
low>high No candidate remains
mid=low Allowed for a small interval
Found Return current mid

Test cases

Test an empty array, one item that matches, one item that differs, keys smaller than the minimum, larger than the maximum and keys between two adjacent items.

Memory trick: Compare, eliminate, repeat. The interval should shrink on every unsuccessful comparison.

Recursive alternative: Search only the eligible half using the new bounds. Stop when low exceeds high. Recursion uses O(log n) stack space in a straightforward implementation, while iteration uses O(1).

6. Binary search variants and comparison

Duplicate values

The ordinary binary-search routine returns a matching midpoint, not necessarily the earliest one. To find the first match, remember a matching index and continue searching toward smaller indices. For {2,6,6,6,9}, the first matching index is 1. The time remains O(log n).

Figure 5.6
Repeated sorted values.

Linear versus binary search

Criterion Linear Binary
Ordering needed No Yes
Worst time O(n) O(log n)
Method One-by-one Halve range
Auxiliary space iterative O(1) O(1)
Useful when Small unsorted list Sorted indexed list

For n=1024, repeated halving requires at most about 11 midpoint examinations in an unsuccessful worst case using an inclusive interval. Linear search may perform 1024 comparisons. For a single lookup in an unsorted collection, sorting first may cost more than scanning once.

Descending order

The elimination rule must be reversed for nonincreasing values. If the middle value is smaller than the key, a descending collection can contain that larger key on the left. The condition for discarding a side depends on the actual sort order.

Exam question: Why can binary search not be applied directly to every list? Because ordering and efficient access to a midpoint are required for its usual benefit.

7. Selection sort: algorithm

Sorting compares chosen keys and rearranges values in ascending or descending order. Stability preserves relative order of equal-key records; in-place sorting uses a small amount of additional storage. Count comparisons and swaps separately.

Selection sort divides the array into a sorted prefix and an unsorted suffix. Find the smallest value in the suffix, exchange it with the first unsorted item and extend the sorted prefix by one position.

Figure 5.7
Pass 1 input.

Initially the minimum index is 0. Compare the remaining four items and discover that the smallest is 10 at index 1. Swap indices 0 and 1.

Figure 5.8
After first selection.

Algorithm steps

For i from 0 through n-2, set min=i. Examine j from i+1 to n-1, updating min when a smaller value is found. At the end of this inner traversal, if min differs from i, exchange a[i] and a[min]. Repeat until only the final item remains. The selected item is placed at its final sorted position on every completed outer pass.

Visual 5.3
Selecting the smallest rod illustrates choosing an extreme value. Illustrative image.

C implementation

#include <stdio.h>
void selection(int a[],int n){
for(int i=0;i<n-1;i++){
int m=i;
for(int j=i+1;j<n;j++)
if(a[j]<a[m])m=j;
if(m!=i){
int t=a[i];a[i]=a[m];a[m]=t;
}
}
}
int main(void){
int a[]={29,10,14,37,13};
selection(a,5);
for(int i=0;i<5;i++)
printf(“%d “,a[i]);
return 0;
}

Output: 10 13 14 29 37.

Why swap after scanning?

The minimum index can change several times during the inner loop. Selection sort identifies the true minimum of the remaining segment before committing one exchange. Swapping whenever a smaller element is encountered creates a different exchange pattern and loses the usual bounded-swap property.

8. Selection sort: complete trace

Dry run of five values

Starting with {29,10,14,37,13}, process the unsorted range one pass at a time.

Pass Selected minimum Result
1 10 10 29 14 37 13
2 13 10 13 14 37 29
3 14 10 13 14 37 29
4 29 10 13 14 29 37
Figure 5.9
After pass 2.

At pass 3, the minimum is already at the first unsorted location, so no exchange is necessary. The sorted prefix still grows.

Invariant

Before pass i, the first i positions contain the i smallest values in sorted order. Selecting the minimum from the remaining suffix puts the next smallest value into position i. At the final stage, the only remaining item must be the largest.

Comparisons and time complexity

The first pass compares n-1 pairs, the next compares n-2, and the final pass compares one. Their total is n(n-1)/2.

n Comparisons
4 6
5 10
8 28
10 45

Standard selection sort still executes these comparisons for an already sorted array, so best, average and worst time are O(n squared). At most n-1 nontrivial swaps occur, and only a few variables are required.

Stability example

Consider records [2A,2B,1C], with equal numeric keys 2 for A and B. Swapping the minimum 1C with the first item gives [1C,2B,2A]. The equal-key order was reversed. Therefore ordinary selection sort with a direct swap is not stable in general. Exam check: For six items its fixed comparison count is 6×5/2=15. The number of actual swaps can range from zero to five.

9. Bubble sort: adjacent exchange

Bubble sort compares neighboring elements and exchanges them when they are incorrectly ordered. In ascending order, a larger element moves toward the end through successive adjacent exchanges.

Figure 5.10
Before adjacent comparisons.

Compare 7 and 3, swap; compare 7 and 9, leave; compare 9 and 1, swap. The first pass ends with {3,7,1,9}. The largest value 9 is now at the final position.

Figure 5.11
After pass 1.

Algorithm

Run outer passes i from 0 to n-2. On each pass compare a[j] with a[j+1] for j from 0 through n-2-i. Swap when a[j] exceeds a[j+1]. The already finalized suffix is excluded as the pass count grows.

Visual 5.4
Exchanging neighboring cards illustrates adjacent swaps. Illustrative image.

C program

#include <stdio.h>
void bubble(int a[],int n){
for(int i=0;i<n-1;i++){
for(int j=0;j<n-1-i;j++){
if(a[j]>a[j+1]){
int t=a[j];
a[j]=a[j+1];a[j+1]=t;
}
}
}
}
int main(void){
int a[]={7,3,9,1};
bubble(a,4);
for(int i=0;i<4;i++)
printf(“%d “,a[i]);
return 0;
}

Output: 1 3 7 9.

The inner loop condition protects j+1 from exceeding the last unsorted position. Strict comparison using > avoids swapping equal keys, helping maintain their relative order.

The largest remaining element reaches its final position during each completed pass because it keeps moving right whenever it meets a smaller neighbor.

10. Bubble sort: dry run and early termination

Trace every stage

Sort {7,3,9,1} in ascending order.

Pass Adjacent pair Array after comparison
1 7,3 3 7 9 1
1 7,9 3 7 9 1
1 9,1 3 7 1 9
2 3,7 3 7 1 9
2 7,1 3 1 7 9
3 3,1 1 3 7 9
Figure 5.12
After pass 2.

The trailing suffix containing 7 and 9 is finalized after pass two. The third pass needs just one comparison.

Early termination

If an entire pass completes without exchanges, every adjacent pair in the unsorted region is in order. Combined with the finalized suffix, the collection is already sorted. Set a swapped flag to zero at the beginning of each pass and to one whenever an exchange occurs.

Optimized bubble implementation

void bubble(int a[],int n){
for(int i=0;i<n-1;i++){
int swapped=0;
for(int j=0;j<n-1-i;j++){
if(a[j]>a[j+1]){
int t=a[j];
a[j]=a[j+1];a[j+1]=t;
swapped=1;
}
}
if(!swapped)break;
}
}

For an already sorted array of n items, the first pass carries out n-1 comparisons and zero exchanges. The flag remains zero and the outer loop exits.

Input pattern Optimized behavior
Already sorted One pass
Nearly sorted May terminate early
Reverse order All required passes
All equal No swaps, one pass

With strict greater-than swaps, bubble sort is stable. It uses constant auxiliary space. The optimized best-case time is O(n); average and worst-case time are O(n squared). Without the flag, the basic nested-loop version uses quadratic comparisons even for sorted input.

11. Sorting comparison and exam numericals

Property Selection sort Bubble sort
Method Choose extreme Swap adjacent
Finalized part Prefix Suffix
Best time standard O(n squared) O(n squared)
Best optimized O(n squared) O(n)
Worst time O(n squared) O(n squared)
Swaps worst n-1 n(n-1)/2
Stable typical No Yes
Extra space O(1) O(1)

Numerical: reversed order

For {5,4,3,2,1}, standard bubble sort uses 10 comparisons and 10 swaps. Every pair is initially inverted. Selection sort uses 10 comparisons but only two swaps with the conditional-exchange implementation: swap 5 with 1, then 4 with 2. Remaining values already fit.

Pass Selection result
1 1 4 3 2 5
2 1 2 3 4 5
3 1 2 3 4 5
4 1 2 3 4 5

Moving a complete record can be expensive; fewer swaps may be beneficial. Stability may be more important when sorting existing groups of equal keys.

Descending order

For selection sort, choose the largest remaining key and move it to the front. For bubble sort, swap neighbors when the left value is smaller than the right. Changing the comparison changes the direction without changing the overall loop structure.

/* Selection: */
if(a[j]>a[m])m=j;
/* Bubble: */
if(a[j]<a[j+1]){
int t=a[j];a[j]=a[j+1];a[j+1]=t;
}

Worked strategy selection

Assume a store has 12 unordered items and someone asks for one product ID. Linear search avoids sorting entirely. If the same list will be searched many times and can be maintained in order, sort once and use binary search for later queries.

Revision formula: For n items, a simple quadratic pass schedule has n(n-1)/2 comparisons. For binary search, the range length decreases roughly by a factor of two on each unsuccessful step.

Write exact array contents after every requested pass; do not jump directly to the final sorted result.

12. Dynamic memory allocation: introduction

A program may not know how many values it must store until input is received. Dynamic allocation requests a region of storage during execution. Its lifetime extends until it is explicitly released, rather than necessarily ending with an enclosing block.

Figure 5.13
Runtime storage flow.

For example, a program reads the number of examination scores, then obtains enough storage for exactly that many integers. The returned address is held in a pointer variable.

Important distinction

An ordinary local array declared with a fixed bound has automatic storage duration. Allocated storage has a lifetime controlled by the allocation and deallocation functions. The local pointer variable and the allocated region are different objects.

Header: stdlib.h declares malloc, calloc, realloc and free. These library functions are central to the syllabus.

Visual 5.5
A newly fitted storage compartment illustrates requesting capacity. Illustrative image.

Fixed arrays versus dynamic allocation

Feature Fixed local array Allocated storage
Size Declared bound Requested at runtime
Lifetime Usually block execution Until released
Access Array expression Through returned pointer
Resize Not automatic Request with realloc
Cleanup Automatic for local array Explicit free

Memory allocation can fail. A correct program checks the result before accessing it, and avoids requesting an invalid or unrepresentable size.

Calculating requested bytes

For n integers, request nsizeof(int) bytes. A convenient expression is nsizeof *p, which derives the element size from p’s pointed-to type. If an int has four bytes and n=25, the request is 100 bytes.

The exact size of a fundamental type is implementation-dependent. sizeof expresses the requirement without assuming a particular number of bytes on every compiler.

Rule: Know the element count, requested capacity, initialized range and responsibility for releasing the storage.

13. malloc: allocating uninitialized storage

The malloc function requests a block containing a specified number of bytes. On success its returned void pointer can be converted to a pointer to a suitable object type. On failure it returns a null pointer.

#include <stdlib.h>
int *p=malloc(5*sizeof *p);
if(p==NULL){
/* allocation failed */
}

Figure 5.14
Allocated five slots.

The contents of newly allocated storage are indeterminate. Assign a usable value to each element before reading it. malloc does not automatically initialize the allocated bytes to zero.

Syntax

void *malloc(size_t size);

In standard C, no explicit cast is required when assigning void * to an object pointer. Include stdlib.h so the correct function declaration is visible.

If p is valid, p[i] can access element i within the requested array region after suitable initialization.

Program: allocate and fill an array

#include <stdio.h>
#include <stdlib.h>
int main(void){
size_t n=5;
int *p=malloc(n*sizeof *p);
if(!p)return 1;
for(size_t i=0;i<n;i++)
p[i]=(int)(i+1)*10;
for(size_t i=0;i<n;i++)
printf(“%d “,p[i]);
free(p);
return 0;
}

Output: 10 20 30 40 50.

Figure 5.15
Initialized slots.

The first loop assigns all five integer values; the second reads them. free releases the allocated region once it is no longer needed.

Allocation request calculation

For 8 doubles assuming sizeof(double)=8, request 64 bytes. Writing p[8] in an eight-element region would be outside the valid index range of 0 through 7. The allocation provides capacity but does not enforce indexing automatically.

14. calloc: zero-initialized storage

calloc requests storage for a given number of elements of a given size. Its initialization sets all bytes in the allocated region to zero. For ordinary integer arrays, this produces zero-valued elements.

int *p=calloc(6,sizeof *p);

Figure 5.16
Zero-initialized integers.

Syntax

void *calloc(size_t count,
size_t size);

Both count and element size are expressed in size_t. When allocating a nonzero required quantity, check the returned address before using it. Do not generalize byte-zero initialization to every conceivable object representation: portable C does not guarantee that all-bits-zero is a null pointer or floating-point zero. The examples here use integer counters. calloc is useful when every counter must begin at zero.

Visual 5.6
Uniform empty compartments illustrate freshly initialized storage. Illustrative image.

Program: dynamically allocated frequency counters

#include <stdio.h>
#include <stdlib.h>
int main(void){
int key[]={3,1,3,0,1};
int *count=calloc(4,sizeof *count);
if(!count)return 1;
for(int i=0;i<5;i++)
count[key[i]]++;
for(int i=0;i<4;i++)
printf(“%d “,count[i]);
free(count);
return 0;
}

Output: 1 2 0 2.

Counter 0 1 2 3
Before 0 0 0 0
After 1 2 0 2

Every key in this sample is in the permitted range 0 through 3. For general user input, validate that range before using a key as an index.

malloc versus calloc

Criterion malloc calloc
Arguments Byte count Count and size
Initial bytes Indeterminate Zero
Typical use Values written soon Counters begin at zero
Failure Null Null

Both require cleanup using free after successful allocation. Choose the function that suits the initialization requirements.

15. realloc: resizing allocated storage

realloc changes the size of a previously allocated region. It may extend the existing region or allocate a new region and move preserved contents. It returns an address for the resized allocation on success.

int *temp=realloc(p,8*sizeof *p);
if(temp!=NULL)p=temp;

Figure 5.17
Example resize from 3 to 5.

The original bytes are preserved up to the smaller of old and new sizes. When growing a block, the additional bytes have indeterminate values. Initialize the added elements explicitly before reading them.

Important failure behavior

For a nonzero request, if realloc fails, the original allocation remains valid. Using a temporary pointer protects its address. Writing p=realloc(p,new_size) directly may lose the original pointer if the request fails. On success, use the new returned pointer. Do not continue using old pointer values or old aliases to the previous object.

Visual 5.7
A larger tray illustrates reserving space for more elements. Illustrative image.

Program: extend from three to five values

#include <stdio.h>
#include <stdlib.h>
int main(void){
int *p=malloc(3*sizeof *p);
if(!p)return 1;
p[0]=4;p[1]=8;p[2]=12;
int *q=realloc(p,5*sizeof *p);
if(!q){free(p);return 1;}
p=q;
p[3]=16;p[4]=20;
for(int i=0;i<5;i++)
printf(“%d “,p[i]);
free(p);
return 0;
}

Output: 4 8 12 16 20.

Stage Capacity Initialized count
Before 3 3
Resize success 5 3
Fill extension 5 5

The two newly added elements must be assigned before display. Shrinking storage discards bytes beyond the new size, so adjust the logical length if it exceeds the new capacity.

Avoid zero-sized realloc requests in introductory portable programs because language-version rules differ. Explicitly free the allocation when no elements are needed.

16. free and allocation lifecycle

The free function releases storage obtained from an allocation function. It neither returns the original contents nor automatically sets the caller’s pointer variable to null.

free(p);
p=NULL;

After free, do not access the former allocation or retain aliases for later access. Assigning NULL to the owner pointer can help make ownership state explicit, but it does not change other pointer variables pointing to the old storage.

Figure 5.18
Lifetime sequence.

Basic conditions

free(NULL) performs no action. Otherwise pass the address returned by a compatible allocation function that has not yet been released. Do not free an ordinary local array, an interior element address, or a pointer that does not represent a current allocation.

Use the allocated region only within its valid lifetime.

Program: one owner and cleanup

#include <stdlib.h>
#include <stdio.h>
int main(void){
int *data=malloc(4*sizeof *data);
if(!data)return 1;
for(int i=0;i<4;i++)data[i]=i*i;
printf(“%d”,data[3]);
free(data);
data=NULL;
return 0;
}

Output: 9.

Error Prevention
Leak Release each owned allocation
Invalid access Use only within valid region
Repeated release One release per allocation
Lost owner Keep valid base pointer
Forgotten failure Check result before access

If a function receives a pointer merely to read values, it should not unexpectedly release storage owned by the caller. Define which routine is responsible for free. If ownership is transferred, make the transfer clear. Exam tip: Distinguish the pointer’s scope from the allocated storage’s lifetime. They are not necessarily the same. Remember: malloc requests bytes, calloc initializes bytes to zero, realloc resizes, and free releases a live allocation. When pointers share one allocation, release it only once.

17. Allocation size, capacity and safe input

Validate the requested quantity

The program should reject negative input counts and requests too large for its intended limits before converting them into a byte count. Multiplying a very large element count by element size may exceed the range of size_t.

#include <stdint.h>
#include <stdlib.h>
int *p=NULL;
size_t n=100;
if(n>SIZE_MAX/sizeof *p)
return 1;
p=malloc(n*sizeof *p);

This is a general check for an array-size multiplication. The example assumes the code is inside an int-returning function. Handle allocation failure separately.

Logical length and capacity

Capacity is the number of slots that can be stored. Length is the portion currently occupied with meaningful values. A dynamically allocated region can have greater capacity than length.

Figure 5.19
Capacity 6, length 4.

Only initialized logical elements should participate in calculations.

Program: allocate after validated input

#include <stdio.h>
#include <stdlib.h>
int main(void){
int n;
if(scanf(“%d”,&n)!=1 ||
n<1 || n>1000)return 1;
int *a=malloc((size_t)n*sizeof *a);
if(!a)return 1;
long sum=0;
for(int i=0;i<n;i++){
if(scanf(“%d”,&a[i])!=1){
free(a);return 1;
}
sum+=a[i];
}
printf(“%.2f”,(double)sum/n);
free(a);
return 0;
}

Input: 4 10 20 30 40. Output: 25.00.

The program releases its allocation even when later input fails. It ensures a positive count before dividing.

Stage Check
Read count Conversion succeeds
Range 1 through 1000
Allocation Address not null
Read data Every value supplied
Finish Release storage

This pattern is preferable to allocating an unchecked amount or neglecting cleanup on an early return.

Growth strategy: Keep separate length and capacity values. When full, request a larger valid capacity through realloc and append only after success. A geometric growth strategy can reduce repeated resize calls.

18. File handling: basics and persistent storage

A file stores information outside the immediate execution of a program. While values in ordinary working memory generally disappear when execution ends, data written to a file can be read in a later run.

Figure 5.20
File processing cycle.

The C standard input/output library supplies a stream abstraction, allowing a program to read and write data without handling all storage-device details. A named file may be associated with a stream when it is opened.

Need for files

Student reports, attendance sheets, sales records and configuration data often need to survive program termination. Files allow storage, later retrieval, modification, reporting and exchange between programs.

Header: stdio.h declares FILE, fopen, fclose and the standard file input/output functions.

Visual 5.8
A records archive illustrates lasting information storage. Illustrative image.

Basic operations

Operation Purpose
Create Start a new file
Open Associate a stream
Read Obtain stored data
Write Produce output data
Append Add data at the end
Seek Change stream position
Close Finish using stream

The program chooses an appropriate opening mode before performing an operation. Access rights, an invalid path or unavailable storage can prevent opening. Check the return value and respond to failure.

Stream examples

The predefined stdin, stdout and stderr are streams for standard input, standard output and standard diagnostic output respectively. A file opened by fopen provides another stream that can be passed to suitable file functions. The same formatting concept used by printf can be applied to a file through fprintf. The stream argument identifies where the characters should go.

19. Text files and binary files

A text stream represents data as characters and lines. Numeric values can be converted to printable characters when written and parsed again when read. A binary stream transfers data as sequences of bytes with fewer text-mode transformations.

Feature Text file Binary file
Representation Characters Bytes
Human readability Often readable Usually needs interpretation
Numeric I/O Formatted conversion Raw representation
Modes r, w, a rb, wb, ab

For the integer 125, formatted output may write the printable characters ‘1’, ‘2’ and ‘5’. Raw binary output instead represents the bytes of the integer object, whose size and encoding depend on the implementation.

Text mode

Text streams may translate line endings or apply other implementation-specific transformations. Binary mode is useful when exact byte sequences should be preserved.

Choosing a format

Text is convenient for log messages, reports and simple portable data interchange. Binary files may store dense representations and support record-sized access, but direct dumps of C objects are generally not portable across implementations.

Figure 5.21
Representations.
Example Recommended type
Plain report Text
CSV-like rows Text
Raw image bytes Binary
Same-system record storage Binary with defined assumptions

Do not assume that all binary files are smaller or faster than all text files. The result depends on the format, conversion cost, compression and required operations.

Record portability

When data must move between systems, define numeric representation, field sizes and text encoding explicitly or use a documented text format. A raw structure file may contain padding and implementation-dependent member representations.

Exam check: A file extension such as .txt or .dat does not itself guarantee the format; the program’s chosen representation determines how data is interpreted.

20. File pointer and opening a file

A file pointer is an object pointer of type FILE * that refers to a library-managed stream object. It is a handle used by file operations, not a pointer to an ordinary array of stored file contents.

FILE *fp=fopen(“marks.txt”,”r”);
if(fp==NULL){
/* file could not be opened */
}

Figure 5.22
Stream relationship.

The stream holds information required for buffering, positioning, input and output state. Its internal representation is managed by the library. Programs normally use the public functions rather than attempting to inspect FILE members.

Syntax

FILE *fopen(const char *filename,
const char *mode);

The filename identifies the intended file, often relative to the program’s working directory. The mode states which operations are permitted.

Open, check and close

#include <stdio.h>
int main(void){
FILE *f=fopen(“report.txt”,”w”);
if(!f){
perror(“report.txt”);
return 1;
}
if(fputs(“BCA report\n”,f)==EOF){
fclose(f);return 1;
}
if(fclose(f)==EOF)return 1;
return 0;
}

The program creates or truncates report.txt and writes one line. If fopen fails, it reports the problem and never passes a null file pointer to an output function.

fclose returns zero if closing succeeds, or EOF on failure. Checking close is especially important for output files because buffered data may be written at that stage.

File-pointer state

Before open, the stream is not available. After a successful open, the handle is valid for its permitted operations. After closing, it must not be used again unless a fresh successful fopen supplies another stream.

One successful open should have a corresponding close operation.

21. File opening modes in detail

Mode Purpose If file absent
r Read Fails
w Write, truncate Creates
a Append output Creates
r+ Read and write Fails
w+ Read and write, truncate Creates
a+ Read and append Creates

The w and w+ modes discard existing contents when opening succeeds. The a and a+ modes cause output to be written at the end of the file. They are appropriate for logs that preserve earlier entries.

For binary streams add b, for example rb, wb, ab, rb+, wb+ and ab+ (r+b etc. are also recognized forms).

Figure 5.23
Append concept.

Choose carefully

To inspect a report, use r. To generate a replacement report, use w. To add a new entry without destroying prior data, use a. Open for update only when both reading and writing are necessary.

Visual 5.9
Adding a ledger entry illustrates retaining earlier data in append mode. Illustrative image.

Practical scenarios

Task Mode
Read existing marks r
Create new daily report w
Add expense line a
Read/update existing record file r+b
Create new binary record file wb
Read binary data rb

Opening a file with w is a deliberate replacement of any existing content. When the goal is to add lines, select append rather than write mode.

Update streams

For a stream opened with +, switch from writing to reading only after a flushing or positioning operation. Switch from reading to writing only after a positioning operation unless the read encountered end-of-file. This rule applies to update streams in standard C.

For introductory tasks, close and reopen with a new mode when that expresses the operation more clearly.

Exam trick: r needs an existing file; w creates or clears; a preserves and adds. The + permits reading and writing; b requests binary mode.

22. Character input and output functions

The fgetc function reads the next character from an input stream, returning its unsigned-char value converted to int, or EOF if the read fails or end-of-file is reached. Store the result in int so every possible character value and EOF can be distinguished.

int ch;
while((ch=fgetc(fp))!=EOF)
putchar(ch);

The fputc function writes one character to a stream. It returns the written character on success or EOF on failure.

fputc(‘A’,fp);
fputc(‘\n’,fp);

Figure 5.24
Character stream.

The position advances as characters are processed. These functions are useful for copying files, counting character categories or scanning text one character at a time.

Program: write then read characters

#include <stdio.h>
int main(void){
FILE *f=fopen(“demo.txt”,”w”);
if(!f)return 1;
fputc(‘C’,f);fputc(‘5’,f);
if(fclose(f)==EOF)return 1;
f=fopen(“demo.txt”,”r”);
if(!f)return 1;
int c;
while((c=fgetc(f))!=EOF)
putchar(c);
int err=ferror(f);
fclose(f);
return err?1:0;
}

Output: C5.

After writing, close and reopen for reading. The read loop checks the returned character before processing it.

Important end-of-file distinction

EOF is a sentinel return value, not a character that the program writes into a normal text file to mark its end. An end-of-file indicator is set when input attempts to read beyond available data. ferror can distinguish a read error from normal end-of-file.

23. Line input and output: fgets and fputs

The fgets function reads a bounded sequence of characters from a stream. With a positive buffer size greater than one, it reads at most size-1 characters, stops after a newline if encountered, and adds a null terminator on successful input.

char line[100];
while(fgets(line,sizeof line,fp))
fputs(line,stdout);

fputs writes the string’s characters to the chosen stream without writing its terminating null. It does not automatically append a newline. Supply one explicitly if a new line is desired.

fputs(“First record\n”,fp);

Line processing

One fgets call may return only part of a long line if the buffer is too small. Process chunks or use a larger validated buffer when the task requires complete lines.

Function Use
fgetc One character
fputc One character output
fgets Bounded text chunk
fputs String output

Program: read text lines

#include <stdio.h>
int main(void){
FILE *f=fopen(“lines.txt”,”w”);
if(!f)return 1;
fputs(“Alpha\nBeta\n”,f);
if(fclose(f)==EOF)return 1;
f=fopen(“lines.txt”,”r”);
if(!f)return 1;
char line[64];
while(fgets(line,sizeof line,f))
fputs(line,stdout);
int err=ferror(f);
fclose(f);
return err?1:0;
}

Output: Alpha and Beta, each on its own line. The returned pointer from fgets indicates successful input. Do not process the buffer after an unsuccessful return without a separate reason to know its contents are valid.

Count lines carefully

Counting successful fgets calls gives the number of chunks, not necessarily logical lines. Counting newline characters gives the number of newline-terminated lines; if the final file segment does not end with a newline, decide whether to count that segment as a line too.

24. Formatted file input and output

fprintf writes formatted output to a specified stream. Its format string follows the conversion rules used by printf. The return value is the number of characters written on success or a negative value on output error.

fprintf(fp,”%d %.2f\n”,101,87.5);

fscanf reads formatted input from a stream. It returns the number of successfully matched and assigned conversions, or EOF if an input failure happens before the first conversion.

int roll;double marks;
while(fscanf(fp,”%d %lf”,
&roll,&marks)==2){
printf(“%d %.2f\n”,roll,marks);
}

The number 2 indicates both required conversions succeeded. If conversion stops because of malformed input, blindly repeating the same scan may not make progress.

Function Direction
fprintf Formatted writing
fscanf Formatted reading
printf Formatted standard output
scanf Formatted standard input

Program: store and retrieve scores

#include <stdio.h>
int main(void){
FILE *f=fopen(“marks.txt”,”w”);
if(!f)return 1;
fprintf(f,”%d %.1f\n”,7,92.5);
fprintf(f,”%d %.1f\n”,9,81.0);
if(fclose(f)==EOF)return 1;
f=fopen(“marks.txt”,”r”);
if(!f)return 1;
int id;double m;
while(fscanf(f,”%d %lf”,&id,&m)==2)
printf(“%d %.1f\n”,id,m);
fclose(f);
return 0;
}

Output: 7 92.5, then 9 81.0 on the next line.

Handling formatted records

Whitespace in a scan format can match a sequence of whitespace characters. A conversion such as %19s reads one word into a sufficiently large character array, not an entire name containing spaces. For more complex records, prefer an explicit line-based format with controlled parsing.

Always use the correct conversion specifier for the actual object type.

25. Append operations and file copy

Append record to an existing log

#include <stdio.h>
int main(void){
FILE *f=fopen(“daily.txt”,”w”);
if(!f)return 1;
fputs(“Day 1: Present\n”,f);
if(fclose(f)==EOF)return 1;
f=fopen(“daily.txt”,”a”);
if(!f)return 1;
fputs(“Day 2: Present\n”,f);
return fclose(f)==EOF?1:0;
}

After the second successful close, the file retains its first line and contains the appended second line. The a mode positions all output at the end.

Figure 5.25
Log after append.

Why close after writing?

Closing flushes pending stream output and frees resources associated with that stream. A program that continues processing other files should close each stream after use rather than retaining handles indefinitely.

Copying a file

Open distinct source and destination streams using suitable modes. Read each character with fgetc and write it with fputc only after successful input. Check output results, read errors and close both streams. For arbitrary bytes, use rb and wb. Block-oriented copying with fread and fwrite is described next.

Stage Action
Open Check both streams
Transfer Read and write
Check Detect short/error results
Close Release both streams

If the second open fails, close the first stream before leaving the routine.

26. Binary input and output: fread and fwrite

fwrite writes a specified number of elements, each with a specified byte width, to a stream. fread reads elements in the same general manner.

size_t fwrite(const void *ptr,
size_t size,size_t count,FILE *f);
size_t fread(void *ptr,
size_t size,size_t count,FILE *f);

The returned value is the number of complete elements transferred, not directly the number of bytes (unless size is 1). A short count may indicate end-of-file or an error.

Figure 5.26
Binary transfer.

Write an integer array

int a[]={7,14,21};
size_t written=fwrite(a,sizeof a[0],
3,fp);

On success, written equals 3. The file receives the three objects’ binary representations. This representation is suitable for reading back on a compatible implementation, but is not a universal interchange format.

Program: write and read a binary array

#include <stdio.h>
int main(void){
int a[]={2,4,8,16},b[4];
FILE *f=fopen(“vals.dat”,”wb”);
if(!f)return 1;
size_t n=fwrite(a,sizeof *a,4,f);
int closed=fclose(f);
if(n!=4||closed==EOF)return 1;
f=fopen(“vals.dat”,”rb”);
if(!f)return 1;
n=fread(b,sizeof *b,4,f);
fclose(f);
for(size_t i=0;i<n;i++)
printf(“%d “,b[i]);
return n==4?0:1;
}

Output: 2 4 8 16. The loop reads only elements reported as fully transferred. If the record count is shorter than requested, handle the problem instead of using unwritten slots.

Term Example
Element size sizeof(int)
Count requested 4
Possible full count 4
Total bytes if int=4 16

Use binary modes to avoid text transformations. In a byte-oriented copy, size=1 allows the returned count to represent the number of bytes directly.

27. File positioning: fseek, ftell, rewind

A stream has a file position indicator. Sequential operations advance it. Positioning functions can move the indicator when the stream supports seeking.

Function Purpose
fseek Move to specified position
ftell Obtain current position
rewind Return to beginning
SEEK_SET Relative to beginning
SEEK_CUR Relative to current position
SEEK_END Relative to end

if(fseek(fp,0L,SEEK_SET)==0){
long pos=ftell(fp);
}

fseek returns zero on success. ftell returns a long value representing the position, or -1L on failure. rewind returns no value and resets the position to the beginning, clearing error and end-of-file indicators.

Figure 5.27
Binary file positions.

For a fixed-width binary record of size S, the offset of record k is k×S from the beginning. Validate multiplication and conversion to the positioning function’s required type.

Random access demonstration

#include <stdio.h>
int main(void){
int a[]={10,20,30};
FILE *f=fopen(“pos.dat”,”wb”);
if(!f)return 1;
size_t n=fwrite(a,sizeof *a,3,f);
int c=fclose(f);
if(n!=3||c==EOF)return 1;
f=fopen(“pos.dat”,”rb”);
if(!f)return 1;
int v;
if(fseek(f,2L*sizeof(int),
SEEK_SET)!=0 ||
fread(&v,sizeof v,1,f)!=1){
fclose(f);return 1;
}
printf(“%d”,v);
fclose(f);return 0;
}

Output: 30.

This binary example selects zero-based index 2. Text stream position values have more restrictive portability rules; do not assume arbitrary byte-offset arithmetic in text mode.

Not every stream supports seeking (for example, some input streams may be sequential only). Check positioning results before reading or writing at a requested location.

28. End-of-file and error handling

The feof function reports whether the end-of-file indicator is set for a stream. ferror reports its error indicator. The indicators describe previous operations, so test the input function’s result first.

int c;
while((c=fgetc(f))!=EOF){
/* process c */
}
if(ferror(f)){
/* input error */
}

Do not write while(!feof(f)) followed by an unconditional processing step. The EOF indicator is set only after a read attempt establishes the end condition. This flawed pattern can process stale or invalid data once after the final valid element.

Function Purpose
feof Test end-of-file indicator
ferror Test error indicator
clearerr Clear both indicators
perror Print diagnostic using errno
fclose Close stream and report failure

clearerr does not fix the underlying problem or necessarily change the file position. It simply clears the indicators.

Correct record-reading pattern

int id;float m;
int status;
while((status=fscanf(f,”%d %f”,
&id,&m))==2){
printf(“%d %.1f\n”,id,m);
}

After the loop, status==EOF may indicate end-of-file or an input error, whereas status 0 or 1 indicates an incomplete or malformed record. Inspect ferror and handle incomplete data according to the file format.

Output and close checks

Writing may fail because the stream cannot accept more data; a close operation may also report a buffered-write failure. A successful fopen does not guarantee all later operations succeed.

Stage Typical validation
fopen Check non-null
fread/fwrite Compare element count
fscanf Compare conversion count
fseek Check zero return
fclose Check EOF failure

Revision: Process a read result only after confirming that it contains the expected complete data.

29. File handling through command-line arguments

Command-line arguments allow the user to provide filenames or options when starting a C program. A common main form is:

int main(int argc,char *argv[])

argc represents the number of argument strings. argv contains pointers to the strings. When present, argv[0] conventionally gives the program invocation name, while later entries contain user-supplied arguments.

Figure 5.28
Example argument vector.

Suppose a program is invoked as viewer report.txt. In a typical hosted environment, argc is 2. The filename is argv[1]; verify that the argument exists before referencing it.

Advantages

The same executable can process many different files without changing its source code. Arguments may specify input or output filenames, numeric choices or operation modes.

Visual 5.10
A supplied filename and record ledger illustrate command-line file I/O. Illustrative image.

Program: display named text file

#include <stdio.h>
int main(int argc,char *argv[]){
if(argc!=2){
puts(“Usage: viewer filename”);
return 1;
}
FILE *f=fopen(argv[1],”r”);
if(!f){perror(argv[1]);return 1;}
int c;
while((c=fgetc(f))!=EOF)
putchar(c);
int bad=ferror(f);
fclose(f);
return bad?1:0;
}

Example: If the provided file contains the text Hello, successful execution displays Hello. If the argument is missing, the program prints its usage message.

Argument check Meaning
argc==1 No filename supplied
argc==2 One filename supplied
argc>2 Extra arguments
argv[argc] Null pointer marker

The arguments are strings. A numeric argument should be parsed and validated before using it as an element count or choice. Do not treat argv[1] as a filename when argc is too small.

Two filenames: Require argc==3 before accessing argv[1] and argv[2]. Open the stated source and destination separately, use distinct files, and check transfer and close results.

30. Record I/O in files: text records

A record is a group of fields representing one entity. For example, a sales record contains an item code and quantity. Record I/O writes or reads these fields together according to a defined file format.

Figure 5.29
Record fields.

For a simple text representation, store one record per line with whitespace-separated numeric fields. Use fprintf for writing and fscanf for reading. A fixed format makes later parsing predictable.

fprintf(f,”%d %d %.2f\n”,
item.code,item.qty,item.price);

The text characters are independent of the structure’s in-memory padding. The parser must nevertheless follow the agreed field sequence and types.

Benefits

Text records can be inspected or edited with ordinary text tools. Data should still be validated, because manually edited records may have missing fields, unexpected characters or out-of-range values.

Program: write and read records

#include <stdio.h>
struct Item{int id,qty;};
int main(void){
struct Item a[]={{11,3},{12,7}};
FILE *f=fopen(“items.txt”,”w”);
if(!f)return 1;
for(int i=0;i<2;i++)
fprintf(f,”%d %d\n”,a[i].id,a[i].qty);
if(fclose(f)==EOF)return 1;
f=fopen(“items.txt”,”r”);
if(!f)return 1;
struct Item x;
while(fscanf(f,”%d %d”,
&x.id,&x.qty)==2)
printf(“%d:%d “,x.id,x.qty);
fclose(f);return 0;
}

Output: 11:3 12:7. Each successful read assigns both fields of x; a subsequent read overwrites x with the next record.

Records with text names

If names may contain spaces or delimiters, choose an unambiguous encoding. A simple %s conversion cannot recover an arbitrary multiword name. A line-based format can use an explicit separator with appropriate parsing and escaping.

31. Record I/O: binary structure records

A fixed-size structure can be stored using fwrite and retrieved using fread on the same compatible implementation. Each complete structure corresponds to one binary record.

struct Item{int id,qty;};
struct Item x={23,8};
fwrite(&x,sizeof x,1,fp);

Figure 5.30
Binary record layout.

The function transfers sizeof x bytes, including any padding within the representation. Do not serialize pointer members as meaningful cross-run references; stored address values are not valid links to newly created objects in a later execution.

When portability matters, encode individual fields in a specified representation instead of dumping a raw structure.

Method Characteristics
Text fields Readable and explicit
Raw binary records Fixed record size on same layout
Portable encoding Specified field representation

Always check the number of records successfully transferred.

Complete binary record program

#include <stdio.h>
struct R{int id,qty;};
int main(void){
struct R a[]={{1,4},{2,9},{3,6}};
FILE *f=fopen(“records.dat”,”wb”);
if(!f)return 1;
size_t n=fwrite(a,sizeof *a,3,f);
int rc=fclose(f);
if(n!=3||rc==EOF)return 1;
f=fopen(“records.dat”,”rb”);
if(!f)return 1;
struct R r;
while(fread(&r,sizeof r,1,f)==1)
printf(“%d:%d “,r.id,r.qty);
int err=ferror(f);
fclose(f);return err?1:0;
}

Output: 1:4 2:9 3:6.

The loop processes only full records. A file with unexpected trailing bytes may contain an incomplete final record; a robust format should validate record boundaries and expected counts.

Size numerical

If the actual sizeof(struct R) is 8 bytes, three records occupy 24 bytes in this format. If sizeof differs on another implementation, the raw file layout is correspondingly different.

Updating a fixed-width record

For records of size S, record k starts at offset k×S. Open an existing binary file with r+b; position with fseek, read and modify the record, position again at its starting offset, then write and check the result. With 16-byte records, index 4 begins at offset 64. Sequential record search reads complete records and compares their keys.

32. Integrated practice: runtime data and file report

Problem statement

Read a bounded number of values, allocate an array at runtime, place its values in ascending order using selection sort and write the sorted sequence to a text report.

Figure 5.31
Workflow.

After reading the count, request enough bytes for that many integers. Handle a failed allocation before accepting the elements. Sort the logical values, not unused capacity. Then open a report stream and write its contents.

The combination uses all three main syllabus areas: a sorting routine, dynamic memory allocation and file handling. Each step has a separate responsibility and should check its own result.

Algorithm

Validate count; allocate; initialize from input; sort; open intended report; write sorted items; close report; release storage. Failure at an intermediate point should trigger cleanup of resources already acquired.

Compact complete implementation

#include <stdio.h>
#include <stdlib.h>
int main(void){
int n;
if(scanf(“%d”,&n)!=1||n<1||n>100)
return 1;
int *a=malloc(n*sizeof *a);
if(!a)return 1;
for(int i=0;i<n;i++)
if(scanf(“%d”,&a[i])!=1){
free(a);return 1;
}
for(int i=0;i<n-1;i++){
int m=i;
for(int j=i+1;j<n;j++)
if(a[j]<a[m])m=j;
int t=a[i];a[i]=a[m];a[m]=t;
}
FILE *f=fopen(“sorted.txt”,”w”);
if(!f){free(a);return 1;}
int ok=1;
for(int i=0;i<n;i++)
if(fprintf(f,”%d\n”,a[i])<0)ok=0;
if(fclose(f)==EOF)ok=0;
free(a);return ok?0:1;
}

For input 5 9 4 2 8 6, sorted.txt stores 2, 4, 6, 8 and 9 on separate lines. The routine intentionally creates or replaces the report.

Program: copy a named text file

The following illustration takes source and destination names as arguments. Use distinct files; the destination is deliberately created or replaced. Open input successfully before opening the destination.

#include <stdio.h>
int main(int argc,char **argv){
if(argc!=3)return 1;
FILE *in=fopen(argv[1],”r”);
if(!in)return 1;
FILE *out=fopen(argv[2],”w”);
if(!out){fclose(in);return 1;}
int c,ok=1;
while((c=fgetc(in))!=EOF){
if(fputc(c,out)==EOF){ok=0;break;}
}
if(ferror(in))ok=0;
if(fclose(out)==EOF)ok=0;
fclose(in);
return ok?0:1;
}

The program reads one character at a time until input ends or an output problem occurs. Its status reports success only when the checked transfer and destination close succeed.

EXAM QUESTIONS WITH ANSWERS

Practice questions covering the definitions, comparisons and applications in Unit V.

Short-answer practice

Q1. Define searching.

Answer. Searching is the process of finding whether a required key occurs in a collection and, if so, identifying its location according to the chosen result convention.

Q2. Define sorting.

Answer. Sorting rearranges a collection according to an ordering rule, such as ascending numeric keys, without losing the association between each record and its fields.

Q3. What is linear search?

Answer. It compares the key with each item sequentially until a matching item is reached or the collection ends. It can operate on unordered data.

Q4. State linear search complexity.

Answer. Its best case uses constant time, while average and worst time grow linearly with item count. An iterative scan requires only constant auxiliary space.

Q5. What is binary search?

Answer. A search of an ordered indexed collection that compares the middle item and eliminates the half that cannot contain the target, repeating until success or exhaustion.

Q6. Why must binary search use sorted data?

Answer. The ordering justifies eliminating an entire candidate range after a midpoint comparison. With unordered keys, the discarded region could contain the target.

Q7. How is midpoint calculated safely?

Answer. For a nonempty inclusive range use low+(high-low)/2. This avoids directly adding the two nonnegative endpoint indices, provided the bounds are valid.

Q8. State binary search complexity.

Answer. Repeated range halving gives logarithmic worst-case comparisons. An iterative implementation uses constant auxiliary space; straightforward recursion can use logarithmic stack space.

Q9. What is selection sort?

Answer. Repeatedly identify the smallest remaining key and place it at the beginning of the unsorted portion until the array is fully ordered.

Q10. How many comparisons does selection sort make?

Answer. The standard implementation compares n-1, n-2, down to 1 pairs, giving n(n-1)/2 comparisons regardless of the initial input ordering.

Q11. What is bubble sort?

Answer. It repeatedly compares adjacent elements and exchanges inverted neighbors. After each ascending pass, the largest remaining value reaches its final position.

Q12. What is a stable sorting algorithm?

Answer. A stable algorithm keeps the original relative order of records having equal comparison keys. Strict adjacent-exchange bubble sort is stable under its usual implementation.

Q13. What does a swapped flag do?

Answer. It records whether an exchange happened during a bubble-sort pass. If none occurred, the list is already sorted and further passes may be omitted.

Q14. Define dynamic memory allocation.

Answer. Obtaining storage during program execution using library allocation functions. The allocated region can remain available until it is released explicitly.

Q15. How do malloc and calloc differ?

Answer. malloc takes a requested byte count and leaves initial contents indeterminate. calloc takes a count and element width and initializes the allocated bytes to zero.

Q16. What is realloc used for?

Answer. It requests resizing of a previous allocation, preserving bytes up to the smaller old and new sizes on success. A failed nonzero request leaves the old allocation intact.

Q17. What does free do?

Answer. It releases a current allocated region. A null argument performs no action. It does not automatically erase or reset the caller’s pointer variable.

Q18. What is a FILE pointer?

Answer. FILE * is a handle referring to a library-managed stream object. Pass it to appropriate standard I/O functions after confirming that opening succeeded.

Q19. Differentiate text and binary files.

Answer. Text streams represent character data and may perform text transformations. Binary streams support byte-level transfers, but raw object representations can depend on the implementation.

Q20. Differentiate r, w and a modes.

Answer. r opens existing data for input; w creates or truncates for output; a creates if necessary and places output at the end.

Q21. What are fread and fwrite used for?

Answer. They transfer a requested number of elements of specified byte width and report the number of complete elements successfully read or written.

Q22. What are fseek and ftell?

Answer. fseek requests a new file position and returns zero on success. ftell reports the current position or -1L if the operation fails.

Q23. What are argc and argv?

Answer. argc identifies the argument count, while argv provides pointers to argument strings. Check the count before accessing a supplied filename.

Q24. What is record input/output?

Answer. Reading or writing a defined group of fields as one record, using formatted text or a specified binary representation. Transfer counts and record boundaries must be checked.

Structured long-answer practice

Use a clear definition, numbered explanation, examples and relevant comparisons. Adjust the depth of your answer to the marks and question.

Long question 1. Explain linear search and binary search with algorithms and comparison.

Answer

  • 1. Linear search. Begin at the first valid index; compare each value with the key, returning the matching position or continuing to the next. If the entire range is examined without success, return a failure sentinel.

  • 2. Binary search. For an ascending sorted array, maintain inclusive lower and upper indices. Calculate the midpoint, return it on equality, or discard the lower or upper portion justified by ordering.

  • 3. Example. For {3,8,12,17,25,31,42}, searching for 31 by binary search first compares 17 at index 3, then 31 at index 5. Linear search would examine six entries.

  • 4. Comparison. Linear search needs no ordering, has O(n) worst-case time and constant iterative auxiliary space. Binary search requires efficient indexed access and sorted keys, yielding O(log n) worst-case comparisons.

  • 5. Correctness. Test boundary cases and distinguish an absent key from a valid zero index. Move binary-search endpoints beyond the examined midpoint to ensure the remaining range shrinks.

Long question 2. Explain selection sort and bubble sort using working principles and dry runs.

Answer

  • 1. Selection method. Maintain an ordered prefix and an unordered suffix. Find the minimum in the suffix, exchange it with the first unsorted element and extend the prefix by one position.

  • 2. Trace. For {29,10,14,37,13}, the first selection yields {10,29,14,37,13}; the next yields {10,13,14,37,29}. Subsequent passes place 14 and 29 correctly.

  • 3. Bubble method. Compare adjacent values and exchange those in the wrong order. In ascending mode the maximum remaining value reaches the last eligible position on each pass, shrinking the unsorted suffix.

  • 4. Trace and optimization. For {7,3,9,1}, bubble passes produce {3,7,1,9}, then {3,1,7,9}, then {1,3,7,9}. If a full pass has no exchanges, terminate immediately.

  • 5. Comparison. Selection performs n(n-1)/2 comparisons and at most n-1 actual exchanges; ordinary selection is not stable. Strict adjacent bubble sort is stable, has quadratic worst time and an optimized linear best case.

Long question 3. Explain dynamic memory allocation and all four standard functions.

Answer

  • 1. Need and header. Runtime allocation supports storage requests whose size is selected during execution. stdlib.h declares malloc, calloc, realloc and free. A pointer provides access to the live allocated region.

  • 2. malloc. Request a byte count, typically n*sizeof *p for n suitably typed elements. The resulting storage has indeterminate initial contents; check for failure and write valid values before reading.

  • 3. calloc. Supply element count and width separately. The returned region’s bytes are initially zero, making it useful for integer frequency counters. A failed nonzero allocation returns null.

  • 4. realloc. Resize an existing allocation through a temporary pointer. A successful request preserves the smaller old/new byte extent; added bytes require initialization. A failed nonzero request leaves the old region available.

  • 5. free and lifecycle. Release each owned region once when use is complete. Check sizes, allocation results and valid access limits. Do not continue using a released allocation; ensure cleanup also occurs on an early failure path.

Long question 4. Discuss file handling basics, file types, stream pointers and modes.

Answer

  • 1. Purpose. Files allow information to persist after program execution. The stdio library manages streams so programs can open, process and close named files using standard interfaces.

  • 2. Types. Text represents characters and formatted fields, often with implementation-specific line transformations. Binary mode supports byte transfers; raw C object layout is not automatically a portable file format.

  • 3. Stream handle. fopen returns a FILE * on success or null on failure. The pointer refers to the library-managed stream and is passed to subsequent input, output and positioning operations.

  • 4. Opening modes. r reads an existing file, w creates or truncates for output, and a preserves earlier data while adding output at the end. Add + for update access and b for binary mode.

  • 5. Closing and errors. Check every opening, choose modes deliberately and inspect input/output return values. fclose releases the stream and can report an output error caused during flushing.

Long question 5. Explain important file-handling functions and positioning operations.

Answer

  • 1. Character I/O. fgetc obtains the next character as an int or reports EOF. fputc writes a character. Store the return value in int so character values are distinguished from the sentinel.

  • 2. Line and formatted I/O. fgets reads a bounded text chunk, and fputs writes a string. fprintf converts values into formatted output; fscanf parses input and reports successful assignments.

  • 3. Binary transfers. fread and fwrite receive a buffer, element width, count and stream. Their returns count fully transferred elements. Process only valid complete data and detect short transfers.

  • 4. Positioning. fseek changes the file-position indicator using an offset and origin, while ftell reports the position. rewind returns to the start. For fixed binary records, the starting offset is index multiplied by record width.

  • 5. Reliability. Loop on the result of the actual read operation, not on an unchecked feof condition. Inspect ferror when reading stops, and test output and closing results to detect communication or storage errors.

Long question 6. Explain file handling through command-line arguments and record input/output.

Answer

  • 1. Command-line interface. Use main(int argc,char *argv[]) in a hosted program. argc counts argument strings and argv provides their addresses; confirm required filename arguments exist before accessing them.

  • 2. Opening by argument. A viewer can require two arguments, then use fopen(argv[1],”r”). Check the returned handle and report an error if the selected file cannot be opened.

  • 3. Text records. Define a field order such as product ID and quantity. Write each record with fprintf and read it with fscanf while every required conversion succeeds. Validate fields in the expected format.

  • 4. Binary records. A fixed-size structure can be written with fwrite and read with fread on a compatible implementation. Check complete-record counts; for cross-system interchange, choose an explicit portable encoding.

  • 5. Retrieval and updating. Search sequentially by reading complete records and comparing keys. For compatible fixed-width records, seek to index×record_size to locate a slot. When updating, position correctly and check the write and close results.

QUICK REVISION AND COMPARISON

Algorithm Recall
Linear search Ordered or unordered scan
Binary search Sorted range halving
Selection sort Select minimum in suffix
Bubble sort Exchange adjacent pairs
Method Worst time
Linear O(n)
Binary O(log n)
Selection O(n squared)
Bubble O(n squared)

Selection uses n(n-1)/2 comparisons; optimized bubble terminates after a pass without swaps.

Allocation functions

Function Use
malloc Request byte count
calloc Allocate zeroed bytes
realloc Resize and preserve old part
free Release live allocation

For 16 elements of width 8, request 128 bytes. Resize to 24 elements by requesting 192 bytes. Initialize the newly available slots.

File modes

Mode Purpose
r Read existing
w Create or truncate
a Append
rb Read binary
r+b Update existing binary

Use + for update, b for binary. Check every stream opening and close result.

Solved algorithm traces

  • 1. Binary search: Search {5,12,19,26,33,40,47} for 40. Check index 3 (26), then index 5 (40). Result: 5.

  • 2. Selection: {18,6,12,3} becomes {3,6,12,18} after one swap. Six comparisons in total.

  • 3. Bubble: {4,1,3,2} becomes {1,3,2,4}, then {1,2,3,4}. Six comparisons and four swaps for the standard pass schedule.

File functions

Function Remember
fopen Open stream
fgetc / fputc Character I/O
fgets / fputs Text chunk / string
fprintf / fscanf Formatted I/O
fread / fwrite Complete element count
fseek / ftell Position and query
fclose Close stream

Record-size numerical

If each binary record has 24 bytes, record index 6 starts at offset 144. Ten records require 240 bytes without a header.

Command-line reminder

Check argc before reading argv[1]. Pass the verified filename to fopen and report failure if the stream is unavailable.

Final checklist: Trace searches and sorting passes, validate allocation requests, choose file modes deliberately, check transfer results, close streams and release owned storage.

←
Previous Story

Problem Solving Using C Unit 4 Notes – Structures, Unions, Enum and Storage Classes

Leave a Reply

Your email address will not be published. Required fields are marked *

Schedule Appointment

Fill out the form below, and we will be in touch shortly.
Contact Information
Vehicle Information
Preferred Date and Time Selection