QUESTION 01 · Array Basics
What is an array?
2 marksAnswer
An array is a fixed-length sequence of elements of one type, stored contiguously.
- Each element is selected using an index.
- For an array of length n, valid indices are 0 through n - 1.

AR25 · I Year I Semester · 2025–2026 · Unit IV: Arrays, Searching and Sorting
QUESTION 01 · Array Basics
An array is a fixed-length sequence of elements of one type, stored contiguously.
QUESTION 02 · Array Basics
An array stores several values of one element type under one name. An index identifies each element.
int marks[3] = {70, 80, 90}; creates three int elements. Their names are marks[0], marks[1] and marks[2]. The number in brackets in a declaration gives the element count, not the last index. All elements belong to the same array and occupy contiguous storage.
Arrays are useful for marks, measurements and sorted lists. A direct valid element access takes O(1) time in the usual random-access model. Processing all n elements takes O(n). Storing n elements requires O(n) space, while a fixed number of counters adds O(1) auxiliary space. A single indexed access does not sort or search the whole array.
An array of length 3 has no element at index 3. Access outside its bounds has undefined behaviour; it is not guaranteed to display zero or a predictable extra value.
Related questions in the arrays category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Write an algorithm to sum all elements in an array and find its time complexity.
Paper P02 · page 2What is an array? Describe declaration and initialisation of one- and two-dimensional arrays.
Paper P03 · page 1QUESTION 03 · Array Basics
The values are 2, 4, 0, 0 and 0.
QUESTION 04 · Array Basics
An array declaration specifies its element type, name and size. Initialisation supplies starting values when the object is created.
int marks[4];
int scores[4] = {60, 70, 80, 90};
int values[] = {2, 4, 6};
int zeroes[4] = {0};marks has space for four integers. An ordinary automatic marks array without an initialiser does not have useful guaranteed starting values. scores receives all four listed values. The length of values is inferred as three from its initialisers. In zeroes, the first element is explicitly zero and the remaining elements are also zero-initialised.
int a[5] = {2, 4}; stores 2 and 4 in the first two positions and zero in the rest. Do not confuse this with int a[5]; at block scope, which does not initialise the ordinary automatic elements. Objects with static storage duration have their own default initialisation rules.
Assign individual elements using a valid index, such as a[2] = 9;. Ordinary C arrays cannot be assigned as a whole using a = b. To copy elements between separate arrays, use a suitable loop or an appropriate library operation with correct bounds.
Where the actual array declaration is visible, sizeof a / sizeof a[0] gives its element count for this ordinary array. It does not work as an array-length calculation on an adjusted array parameter. Initialising or copying n elements involves O(n) element work; one element assignment is O(1).
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int a[5] = {2, 4};
for (int i = 0; i < 5; ++i) { printf("%d\n", a[i]); }
return 0;
}This example uses values already written in the program.
2
4
0
0
0Related questions in the arrays category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Write an algorithm to sum all elements in an array and find its time complexity.
Paper P02 · page 2What is an array? Describe declaration and initialisation of one- and two-dimensional arrays.
Paper P03 · page 1QUESTION 05 · Array Basics
The valid indices are 0 through 9.
QUESTION 06 · Array Basics
A subscript is the integer expression inside brackets that selects an array element. Valid indices must remain within the array’s bounds.
For int a[4] = {10, 20, 30, 40};, a[0] is 10, a[2] is 30 and a[3] is 40. An index can be a variable or expression, such as a[i] or a[i + 1], when its resulting value is valid.
for (int i = 0; i < n; ++i) {
printf("%d\n", a[i]);
}Using i <= n instead of i < n reaches a[n] when n is the array’s logical length and capacity. That extra iteration is invalid for an array with exactly n elements. A one-based position shown to a student is different from a zero-based index: position 1 corresponds to index 0.
C does not promise a runtime error message for an invalid subscript. Reading or writing outside bounds has undefined behaviour and can corrupt unrelated data. A pointer may be formed one past an array in certain permitted operations, but it must not be dereferenced there. In this unit, simply restrict element access to valid indices.
A valid direct access uses O(1) time in the usual array model. Checking a fixed set of bounds also uses O(1); it does not require traversing the array.
Related questions in the arrays category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Write an algorithm to sum all elements in an array and find its time complexity.
Paper P02 · page 2What is an array? Describe declaration and initialisation of one- and two-dimensional arrays.
Paper P03 · page 1QUESTION 07 · Array Basics
It must fit the array’s capacity so that input does not write outside the array.
QUESTION 08 · Array Basics
A loop can read each array element using its address and then display each stored value using the same valid index range.
scanf("%d", &a[i]) supplies the address of the selected int element so that scanf can store its value. printf("%d", a[i]) supplies the stored value for output. The address is needed for this input conversion; it is not the value to display.
For count 3 and elements 8, -2 and 5, the first loop fills a[0], a[1] and a[2]. The second loop displays 8 -2 5 in the same order. No sorting takes place. A space is printed before every value after the first, followed by one newline at the end.
This complete example accepts values between -10000 and 10000. Input tokens must fit int. It rejects a bad count, a failed conversion or a value outside the chosen range. The fixed capacity is 20, while n describes how many positions currently contain the list.
Reading n values requires n input operations and displaying them requires n output operations. The total work is proportional to 2n, giving O(n) time. The list storage is O(n) in a general-size version; counters add O(1) auxiliary space. This sample reserves a fixed array of 20 elements.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int n, a[20];
if (scanf("%d", &n) != 1 || n < 1 || n > 20) {
puts("Unsupported input"); return 1;
}
for (int i = 0; i < n; ++i) {
if (scanf("%d", &a[i]) != 1 || a[i] < -10000 || a[i] > 10000) {
puts("Unsupported input"); return 1;
}
}
for (int i = 0; i < n; ++i) {
if (i > 0) { putchar(' '); }
printf("%d", a[i]);
}
putchar('\n');
return 0;
}3
8 -2 58 -2 5Related questions in the arrays category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Write an algorithm to sum all elements in an array and find its time complexity.
Paper P02 · page 2What is an array? Describe declaration and initialisation of one- and two-dimensional arrays.
Paper P03 · page 1QUESTION 09 · Array Basics
Traversal visits the array elements in a chosen order to perform an operation on each.
QUESTION 10 · Array Basics
Array traversal visits elements one by one. The same loop pattern can display values, calculate a sum or count values satisfying a condition.
For the list 4, -1 and 7, sum starts at 0. After index 0 it is 4. After index 1 it is 3. After index 2 it is 10. The loop finishes after every valid element has contributed exactly once.
Starting at index 1 would omit the first element. Using i <= n would attempt an extra access. The loop condition i < n covers exactly n elements when i starts at zero and increases by one. The list need not be sorted for a sum.
The sample uses long long for sum and %lld to print it. With at most 20 inputs of magnitude at most 10000, the total fits that type’s guaranteed range. A general implementation must choose a type and supported bounds suitable for its largest possible total.
The loop performs one addition for every element, so n elements give O(n) time. Input reading is also O(n), leaving the total linear. Apart from the array, only a count, counter and accumulator are needed: O(1) auxiliary space. Traversal is not a separate copy of the array.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int n, a[20];
if (scanf("%d", &n) != 1 || n < 1 || n > 20) {
puts("Unsupported input"); return 1;
}
for (int i = 0; i < n; ++i) {
if (scanf("%d", &a[i]) != 1 || a[i] < -10000 || a[i] > 10000) {
puts("Unsupported input"); return 1;
}
}
long long sum = 0;
for (int i = 0; i < n; ++i) { sum += a[i]; }
printf("Sum = %lld\n", sum);
return 0;
}3
4 -1 7Sum = 10Related questions in the arrays category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Write an algorithm to sum all elements in an array and find its time complexity.
Paper P02 · page 2What is an array? Describe declaration and initialisation of one- and two-dimensional arrays.
Paper P03 · page 1QUESTION 11 · Array Basics
The first element is an actual value in a non-empty list and is a valid starting candidate.
QUESTION 12 · Array Basics
The minimum and maximum can be updated while traversing an array. The average is the total divided by the number of elements.
For 4, -2 and 7, both extremes start at 4 and sum starts at 4. Reading -2 changes minimum to -2 and sum to 2. Reading 7 changes maximum to 7 and sum to 9. Average is 9.0 / 3 = 3.0.
A single-element list has the same minimum, maximum and average value. Repeated equal values need no special replacement. The list can contain negative values and need not be sorted. An empty list is rejected because this method needs a first element and the average must not divide by zero.
Casting sum to double before division allows a fractional average. Casting after integer division would not restore a discarded fraction. long long stores the bounded sample’s total safely, and the result is displayed with two decimal places.
One scan examines each value once. A fixed number of comparisons and an addition are performed per element, giving O(n) time. minimum, maximum, sum and average occupy fixed extra storage, so auxiliary space is O(1), excluding the input array.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int n, a[20];
if (scanf("%d", &n) != 1 || n < 1 || n > 20) {
puts("Unsupported input"); return 1;
}
for (int i = 0; i < n; ++i) {
if (scanf("%d", &a[i]) != 1 || a[i] < -10000 || a[i] > 10000) {
puts("Unsupported input"); return 1;
}
}
int minimum = a[0], maximum = a[0];
long long sum = a[0];
for (int i = 1; i < n; ++i) {
if (a[i] < minimum) { minimum = a[i]; }
if (a[i] > maximum) { maximum = a[i]; }
sum += a[i];
}
printf("Minimum = %d, maximum = %d, average = %.2f\n",
minimum, maximum, (double)sum / n);
return 0;
}3
4 -2 7Minimum = -2, maximum = 7, average = 3.00Related questions in the arrays category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Write an algorithm to sum all elements in an array and find its time complexity.
Paper P02 · page 2What is an array? Describe declaration and initialisation of one- and two-dimensional arrays.
Paper P03 · page 1QUESTION 13 · Arrays and Functions
No. An expression such as a[1] supplies an int value to an int parameter.
QUESTION 14 · Arrays and Functions
An individual array element can be passed to a function in the same way as another value of its element type.
In show(a[1]), a[1] selects one element and its value is passed to the parameter. For an int parameter, that parameter is a separate object. Assigning to it does not assign to the original array element. This follows C’s pass-by-value rule.
The sample starts with a[1] equal to 20. change(a[1]) gives the function’s parameter n the value 20. The function assigns n = 99 and prints it. When it returns, a[1] still contains 20. The two printed values demonstrate that only a value was supplied.
A call such as change_at(&a[1]) could pass the address to an int * parameter. Assigning through that valid pointer could change the selected element. The pointer value is still passed by value; the object reached through it is shared. Detailed pointer operations belong to Unit V.
Selecting and passing one fixed-width element takes constant work in the usual model. The function’s own processing determines any additional complexity. The example uses O(1) time and O(1) extra space.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
void change(int n)
{
n = 99;
printf("Parameter = %d\n", n);
}
int main(void)
{
int a[3] = {10, 20, 30};
change(a[1]);
printf("Element = %d\n", a[1]);
return 0;
}This example uses values already written in the program.
Parameter = 99
Element = 20Related questions in the array function arguments category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Illustrate passing arrays to functions with a relevant example program.
Paper P04 · page 1Explain passing an entire array as an argument to a function, with an example.
Paper P10 · page 2QUESTION 15 · Arrays and Functions
A parameter written as int a[] is adjusted to an int * parameter and does not carry the array’s element count.
QUESTION 16 · Arrays and Functions
A function can process an array when it receives access to its elements and enough information to keep its accesses within bounds.
long long total(const int a[], int n);In a parameter declaration, const int a[] is adjusted to const int *a. The function receives a pointer value identifying the first element. The array contents are not automatically copied. n states how many elements the function is allowed to read. const prevents modification through this parameter’s element access.
main holds 4, 5 and 6 and calls total(a, 3). The function visits a[0], a[1] and a[2], adding them to its local accumulator. It returns 15. main prints the result. The array remains unchanged because this function only reads it.
The function reads n elements once, giving O(n) time. It does not build a second array; only a sum and counter are added, giving O(1) auxiliary space. Copying a pointer argument does not mean copying n elements.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
long long total(const int a[], int n)
{
long long sum = 0;
for (int i = 0; i < n; ++i) { sum += a[i]; }
return sum;
}
int main(void)
{
int a[3] = {4, 5, 6};
printf("Total = %lld\n", total(a, 3));
return 0;
}This example uses values already written in the program.
Total = 15Related questions in the array function arguments category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Illustrate passing arrays to functions with a relevant example program.
Paper P04 · page 1Explain passing an entire array as an argument to a function, with an example.
Paper P10 · page 2QUESTION 17 · Searching
It compares the key with successive elements until a match is found or the list ends.
QUESTION 18 · Searching
Linear search checks elements one by one for a required key. It works on both sorted and unsorted arrays.
For 8, 3 and 5 with key 3, index 0 does not match. Index 1 matches, so the function returns 1. The displayed result is an index, not a one-based position. If the key were 7, all three comparisons would fail and -1 would be returned.
Returning immediately at a match produces the first matching index. A one-element list is checked once. A generic linear-search function can also handle a length of zero by skipping its loop, although this interactive sample requires at least one input element.
The best case is a match at index 0, requiring one comparison: O(1). In the worst case, the key is absent or appears only at the last element, requiring n comparisons: O(n). Under a usual equally-likely-position model, successful average search also grows linearly. The input-reading part of the complete program is O(n) regardless of where a match occurs.
The non-recursive search stores only an index and fixed parameters, so auxiliary space is O(1). It neither sorts nor copies the input array.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int linear_search(const int a[], int n, int key)
{
for (int i = 0; i < n; ++i) {
if (a[i] == key) { return i; }
}
return -1;
}
int main(void)
{
int n, a[20];
if (scanf("%d", &n) != 1 || n < 1 || n > 20) {
puts("Unsupported input"); return 1;
}
for (int i = 0; i < n; ++i) {
if (scanf("%d", &a[i]) != 1 || a[i] < -10000 || a[i] > 10000) {
puts("Unsupported input"); return 1;
}
}
int key;
if (scanf("%d", &key) != 1) { puts("Unsupported input"); return 1; }
printf("Index = %d\n", linear_search(a, n, key));
return 0;
}3
8 3 5
3Index = 1Related questions in the linear search category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Describe linear search with an example and give its time complexity in all cases.
Paper P02 · page 2Write the linear-search algorithm and explain with an example.
Paper P05 · page 2QUESTION 19 · Searching
The array must be sorted in ascending order.
QUESTION 20 · Searching
Binary search finds a key in a sorted array by repeatedly reducing a search interval to one half.
For 2, 4, 6, 8 and 10 with key 8, mid is initially 2 and a[2] is 6. Since 8 is larger, low becomes 3. The next midpoint is 3, whose value is 8, so index 3 is returned.
The sample checks ascending order before calling the search function. Equal adjacent values are allowed. With duplicates, this version returns a matching index, which is not necessarily the first or last occurrence. Searching an unsorted array this way can miss a present key.
Each unsuccessful step roughly halves the candidate count: n, n/2, n/4 and so on. After about log2 n steps, at most one candidate remains. Thus worst-case search time is O(log n), while a first-midpoint match is O(1). Reading and checking the complete input is O(n), so the full interactive program has O(n) total work before and including one search.
This iterative function stores low, high and mid without recursive calls or another array, giving O(1) auxiliary space. The midpoint form avoids adding low and high directly.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int binary_search(const int a[], int n, int key)
{
int low = 0, high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (a[mid] == key) { return mid; }
if (a[mid] < key) { low = mid + 1; }
else { high = mid - 1; }
}
return -1;
}
int main(void)
{
int n, a[20];
if (scanf("%d", &n) != 1 || n < 1 || n > 20) {
puts("Unsupported input"); return 1;
}
for (int i = 0; i < n; ++i) {
if (scanf("%d", &a[i]) != 1 || a[i] < -10000 || a[i] > 10000) {
puts("Unsupported input"); return 1;
}
}
for (int i = 1; i < n; ++i) {
if (a[i] < a[i - 1]) { puts("Array must be sorted"); return 1; }
}
int key;
if (scanf("%d", &key) != 1) { puts("Unsupported input"); return 1; }
printf("Index = %d\n", binary_search(a, n, key));
return 0;
}5
2 4 6 8 10
8Index = 3Take the sorted array 3, 8, 12, 17, 21, 29, 34 and search for 20. Indexes begin at zero. Count one visit each time the algorithm examines a midpoint element; a visit can include more than one C comparison.
| Visit | low | high | mid | Element | Next step |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 17 | 20 is larger: low becomes 4 |
| 2 | 4 | 6 | 5 | 29 | 20 is smaller: high becomes 4 |
| 3 | 4 | 4 | 4 | 21 | 20 is smaller: high becomes 3 |
Now low = 4 and high = 3. No candidate remains, so the function returns -1. It examined only three midpoint elements. The key need not lie outside the array’s smallest and largest values to be absent.
Suppose the only remaining element is 21 and the key is 20. Setting high = mid leaves the same interval unchanged. The next iteration can examine 21 again forever. Use high = mid - 1, because the midpoint has already been ruled out. The same reasoning gives low = mid + 1 for the other branch.
n = 0 and return -1 without reading an element. The interactive driver on this page deliberately accepts only 1–20 elements.4, 4, 4, the current function can return index 1. It does not promise the first occurrence.Related questions in the binary search category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Discuss binary search with an example.
Paper P02 · page 2Write the time complexity of binary search.
Paper P05 · page 1QUESTION 21 · Searching
Linear search can be used directly.
QUESTION 22 · Searching
Linear search examines successive elements. Binary search uses sorted order to discard half of the remaining interval at each step.
It can start immediately on an unsorted array. It compares the key with each element until it finds a match or reaches the end. A first-element match is O(1), while the worst case is O(n). A simple first-match version returns the first occurrence when duplicates exist.
It requires sorted input. It compares the key with a midpoint and retains only the possible half. A midpoint match is O(1), and the worst case is O(log n) for indexed arrays. A basic version does not guarantee the first duplicate. The iterative version needs O(1) auxiliary space.
For a small unsorted list and one search, linear search is simple and avoids a preliminary sort. If an array is already sorted or will support many searches, binary search can reduce work per query. Sorting and later maintaining sorted order have costs of their own.
For five unsorted marks, scanning directly may be the appropriate task. For thousands of already sorted roll numbers, repeatedly halving the interval is useful. The correct choice depends on input order, the number of searches and the representation.
The complexity of the search function differs from the total cost of reading, sorting or validating its input. A binary-search sample that checks every adjacent pair first spends O(n) on that validation, even though the actual search remains O(log n).
| Feature | Linear | Binary |
|---|---|---|
| Input order | Any | Ascending for shown version |
| Best search time | O(1) | O(1) |
| Worst search time | O(n) | O(log n) |
| Auxiliary space | O(1) | O(1) |
| Duplicate result | First in shown version | Any match in shown version |
Related questions in the linear search category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Describe linear search with an example and give its time complexity in all cases.
Paper P02 · page 2Write the linear-search algorithm and explain with an example.
Paper P05 · page 2QUESTION 23 · Sorting
It moves the largest value in the current unsorted part to its final rightmost position.
QUESTION 24 · Sorting
Bubble sort repeatedly compares adjacent values and swaps them when they are in the wrong order.
For 5, 1 and 4, compare 5 with 1 and swap, giving 1, 5, 4. Compare 5 with 4 and swap, giving 1, 4, 5. The largest value 5 is now fixed. The next pass compares 1 with 4 and makes no swap, so the algorithm stops.
Each adjacent comparison moves the larger of the pair one position right. Across a pass, the largest remaining value keeps moving until it reaches the final unsorted position. Repeating this step fixes one more position each time.
In reverse order, the comparisons can total (n - 1) + (n - 2) + ... + 1 = n(n - 1)/2, giving O(n²) time. With the swapped flag, already sorted input needs only one pass of n - 1 comparisons, giving O(n) best-case time. Average performance is also quadratic under usual input models.
Only a few counters, a flag and a temporary value are added, so auxiliary space is O(1). This version swaps only when the left value is strictly larger. Equal values do not cross through a swap, so it is stable. The input array itself is rearranged.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
void sort(int a[], int n)
{
for (int pass = 0; pass < n - 1; ++pass) {
int swapped = 0;
for (int j = 0; j < n - 1 - pass; ++j) {
if (a[j] > a[j + 1]) {
int temporary = a[j]; a[j] = a[j + 1]; a[j + 1] = temporary;
swapped = 1;
}
}
if (!swapped) { break; }
}
}
int main(void)
{
int n, a[20];
if (scanf("%d", &n) != 1 || n < 1 || n > 20) {
puts("Unsupported input"); return 1;
}
for (int i = 0; i < n; ++i) {
if (scanf("%d", &a[i]) != 1 || a[i] < -10000 || a[i] > 10000) {
puts("Unsupported input"); return 1;
}
}
sort(a, n);
for (int i = 0; i < n; ++i) {
if (i > 0) { putchar(' '); }
printf("%d", a[i]);
}
putchar('\n');
return 0;
}3
5 1 41 4 5Related questions in the bubble sort category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Explain bubble sort with an example.
Paper P01 · page 1Explain bubble sort and mention its time complexity.
Paper P04 · page 1QUESTION 25 · Sorting
The minimum value in the remaining unsorted part.
QUESTION 26 · Sorting
Selection sort repeatedly chooses the smallest remaining value and places it at the beginning of the unsorted part.
For 5, 1 and 4, the first scan finds 1 at index 1. Swapping it with index 0 gives 1, 5, 4. The next scan finds 4 as the minimum of the remaining two values. The result becomes 1, 4, 5.
Each completed pass fixes the next smallest value in the next leftmost position. The values before i are already in their correct sorted places, so the scan only examines the remaining part.
The first pass makes n - 1 comparisons, the next n - 2, and so on. The total is n(n - 1)/2, giving O(n²) comparisons in best, average and worst cases for this version. Already sorted input still requires those scans. At most n - 1 swaps are needed.
The algorithm uses O(1) auxiliary space. The usual distant-swap implementation is not stable. For labelled equal values 2A, 2B, 1, swapping the final 1 with 2A produces 1, 2B, 2A; the equal 2s have changed relative order. To sort descending instead, select the largest remaining value with a suitable comparison.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
void sort(int a[], int n)
{
for (int i = 0; i < n - 1; ++i) {
int smallest = i;
for (int j = i + 1; j < n; ++j) {
if (a[j] < a[smallest]) { smallest = j; }
}
if (smallest != i) {
int temporary = a[i]; a[i] = a[smallest]; a[smallest] = temporary;
}
}
}
int main(void)
{
int n, a[20];
if (scanf("%d", &n) != 1 || n < 1 || n > 20) {
puts("Unsupported input"); return 1;
}
for (int i = 0; i < n; ++i) {
if (scanf("%d", &a[i]) != 1 || a[i] < -10000 || a[i] > 10000) {
puts("Unsupported input"); return 1;
}
}
sort(a, n);
for (int i = 0; i < n; ++i) {
if (i > 0) { putchar(' '); }
printf("%d", a[i]);
}
putchar('\n');
return 0;
}3
5 1 41 4 5Related questions in the selection sort category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Write a C program for selection sort.
Paper P03 · page 1What is sorting? Explain selection sort with an example.
Paper P05 · page 2QUESTION 27 · Sorting
It takes the next key, shifts larger preceding values right and inserts the key into the gap.
QUESTION 28 · Sorting
Insertion sort builds a sorted prefix by inserting each next value into its correct position among the values already processed.
For 5, 1 and 4, key 1 is saved first. Since 5 is larger, shift it right and insert 1 at index 0, giving 1, 5, 4. Next save key 4. Shift 5 right, stop at 1 and insert 4 between them. The result is 1, 4, 5.
Shifting overwrites array positions. Saving the selected value in a separate variable prevents it from being lost before the gap is ready. The condition j >= 0 && a[j] > key checks the boundary first, so short-circuit evaluation avoids reading a[-1].
For already sorted input, each key needs only a small comparison and no shifting, giving O(n) best-case time. For reverse order, the shifts total 1 + 2 + ... + (n - 1), giving O(n²) worst-case time. The usual average case is quadratic too. It can be useful for small or nearly sorted arrays.
Only a key and counters are added, giving O(1) auxiliary space. Shifting only strictly larger values keeps equal values in their prior relative order, so this version is stable.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
void sort(int a[], int n)
{
for (int i = 1; i < n; ++i) {
int key = a[i], j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j]; --j;
}
a[j + 1] = key;
}
}
int main(void)
{
int n, a[20];
if (scanf("%d", &n) != 1 || n < 1 || n > 20) {
puts("Unsupported input"); return 1;
}
for (int i = 0; i < n; ++i) {
if (scanf("%d", &a[i]) != 1 || a[i] < -10000 || a[i] > 10000) {
puts("Unsupported input"); return 1;
}
}
sort(a, n);
for (int i = 0; i < n; ++i) {
if (i > 0) { putchar(' '); }
printf("%d", a[i]);
}
putchar('\n');
return 0;
}3
5 1 41 4 5Related questions in the insertion sort category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Give a brief note on insertion sort.
Paper P01 · page 1Explain insertion sort using an example array.
Paper P02 · page 2QUESTION 29 · Sorting
It preserves the original relative order of items with equal keys.
QUESTION 30 · Sorting
The three methods all sort by comparisons, but differ in how values are moved and how they behave on nearly sorted input.
Adjacent values are compared and swapped when out of order. Each pass fixes a rightmost value. With the early-stop flag used here, sorted input takes O(n); average and worst cases take O(n²). Strictly-greater adjacent swaps preserve equal-value order.
Each pass scans for the minimum remaining value and swaps it into the next leftmost position. The scan count remains quadratic even on sorted input: O(n²). It uses relatively few swaps, at most n - 1, but a distant swap can reverse equal keys, so the usual version is not stable.
Each next key is inserted into a sorted prefix by shifting larger values. It takes O(n) on already sorted input and O(n²) in the worst case. The strict comparison used here preserves equal-key order. It is often useful for small or nearly sorted lists.
All three shown implementations sort within the input array and use only a fixed number of extra variables. Their auxiliary space is O(1). This does not mean the input array takes no space; it means no extra storage proportional to n is needed.
Look at input size, order, required stability and the cost of moving a record. A comparison of only worst-case Big-O values misses practical differences. For much larger lists, other algorithms may be preferable, but they are outside these three basic syllabus methods.
| Method | Best time | Worst time | Extra space | Stable |
|---|---|---|---|---|
| Optimised bubble | O(n) | O(n²) | O(1) | Yes |
| Selection | O(n²) | O(n²) | O(1) | No |
| Insertion | O(n) | O(n²) | O(1) | Yes |
Related questions in the bubble sort category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Explain bubble sort with an example.
Paper P01 · page 1Explain bubble sort and mention its time complexity.
Paper P04 · page 1QUESTION 31 · Matrices and Dimensions
Use a[row][col], with row in 0..1 and col in 0..2.
QUESTION 32 · Matrices and Dimensions
A two-dimensional array is an array whose elements are themselves arrays. It naturally represents a table of rows and columns.
int a[2][3] = {
{1, 2, 3},
{4, 5, 6}
};a[0][0] is 1, a[0][2] is 3 and a[1][1] is 5. The first index selects a row array; the second selects an element within that row. Neither index may leave its own array bounds. a[0][3] is invalid even though another row follows in storage.
C stores each row contiguously, followed by the next row. The example’s element order is 1, 2, 3, 4, 5, 6. This is called row-major order. A two-dimensional array is not the same type as a pointer to pointer.
Use an outer loop for rows and an inner loop for columns. Print a newline after the inner loop to end each row. The program displays the two rows exactly as a table.
For r rows and c columns, there are r × c elements. Visiting every element once takes O(rc) time. The array occupies r × c × sizeof(element) C bytes; only loop counters add O(1) auxiliary space. A direct valid access uses O(1) time in the usual model.
When passing such an array to a function, the row width must be described correctly so that indexing advances by a complete row. The final topic of this unit explains the fixed-width function form.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int row = 0; row < 2; ++row) {
for (int col = 0; col < 3; ++col) {
if (col > 0) { putchar(' '); }
printf("%d", a[row][col]);
}
putchar('\n');
}
return 0;
}This example uses values already written in the program.
1 2 3
4 5 6Related questions in the multidimensional arrays category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Using a two-dimensional array, write a C program to transpose a 2 × 2 matrix.
Paper P04 · page 1What is a two-dimensional array?
Paper P06 · page 1QUESTION 33 · Matrices and Dimensions
They must have the same number of rows and the same number of columns.
QUESTION 34 · Matrices and Dimensions
Matrix addition adds corresponding elements of two matrices with identical dimensions: C[i][j] = A[i][j] + B[i][j].
For A rows [1, 2] and [3, 4], and B rows [5, 6] and [7, 8], the result rows are [6, 8] and [10, 12]. Each result position uses only the two elements at that same position.
The add function receives both input arrays, the output array and the active dimensions. All row widths are MAX because the actual objects are declared with that width. The function writes its results into C. Reading and validation are separated from the calculation.
The sample accepts 1 through 5 rows and columns, with element values between -1000 and 1000. These bounds keep each sum within the minimum guaranteed range of int. A failed input read stops the program before calculation.
There are r × c output elements, and each requires one addition. Thus the addition routine takes O(rc) time. Reading and printing all elements have the same growth rate.
The separate result contains rc elements, so output storage is O(rc). Apart from that output, the addition uses O(1) auxiliary space for counters. This sample allocates fixed MAX-by-MAX arrays; the dimension-based description applies to the active matrix problem.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#define MAX 5
int read_matrix(int a[][MAX], int rows, int cols)
{
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (scanf("%d", &a[i][j]) != 1 || a[i][j] < -1000 || a[i][j] > 1000) {
return 0;
}
}
}
return 1;
}
void add(int a[][MAX], int b[][MAX], int c[][MAX], int rows, int cols)
{
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) { c[i][j] = a[i][j] + b[i][j]; }
}
}
int main(void)
{
int rows, cols, a[MAX][MAX], b[MAX][MAX], c[MAX][MAX];
if (scanf("%d%d", &rows, &cols) != 2 || rows < 1 || rows > MAX || cols < 1 || cols > MAX) {
puts("Unsupported dimensions"); return 1;
}
if (!read_matrix(a, rows, cols) || !read_matrix(b, rows, cols)) {
puts("Unsupported input"); return 1;
}
add(a, b, c, rows, cols);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (j > 0) { putchar(' '); }
printf("%d", c[i][j]);
}
putchar('\n');
}
return 0;
}2 2
1 2 3 4
5 6 7 86 8
10 12Related questions in the multidimensional arrays category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Using a two-dimensional array, write a C program to transpose a 2 × 2 matrix.
Paper P04 · page 1What is a two-dimensional array?
Paper P06 · page 1QUESTION 35 · Matrices and Dimensions
If A is r × k and B is k × c, the result is r × c.
QUESTION 36 · Matrices and Dimensions
Matrix multiplication combines each row of A with each column of B. It is not element-by-element multiplication.
C[i][j] = sum of A[i][t] * B[t][j]
for t = 0 through inner - 1For A = [[1, 2], [3, 4]] and B = [[5, 6], [7, 8]], C[0][0] is 1×5 + 2×7 = 19. C[0][1] is 1×6 + 2×8 = 22. The second row is 43, 50. Each result is a dot product of one complete row and one complete column.
Set every result accumulator to zero before its inner loop. Otherwise a result might include an old or invalid value. The sample uses long long for the result and 1LL * a[i][t] * b[t][j] to perform the product in that type. Inputs are limited to magnitude 1000 and dimensions at most 5.
For r result rows and c result columns, each position requires k products and additions. The total is r × c × k, giving O(rkc) time. For square n × n matrices this becomes O(n³) for this basic method.
The output contains rc long long values. Output storage is O(rc), while the counters add O(1) auxiliary space beyond the inputs and output. Matrix multiplication is generally not commutative: reversing A and B may change the answer or make the dimensions incompatible.
| Operation | Input sizes | Requirement | Output size |
|---|---|---|---|
| Addition | r × c and r × c | Both dimensions equal | r × c |
| Multiplication | r × k and k × c | Inner dimensions equal | r × c |
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#define MAX 5
int read_matrix(int a[][MAX], int rows, int cols)
{
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (scanf("%d", &a[i][j]) != 1 || a[i][j] < -1000 || a[i][j] > 1000) {
return 0;
}
}
}
return 1;
}
void multiply(int a[][MAX], int b[][MAX], long long c[][MAX],
int rows, int inner, int cols)
{
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
c[i][j] = 0;
for (int t = 0; t < inner; ++t) {
c[i][j] += 1LL * a[i][t] * b[t][j];
}
}
}
}
int main(void)
{
int ra, ca, rb, cb, a[MAX][MAX], b[MAX][MAX];
long long c[MAX][MAX];
if (scanf("%d%d%d%d", &ra, &ca, &rb, &cb) != 4 ||
ra < 1 || ra > MAX || ca < 1 || ca > MAX ||
rb < 1 || rb > MAX || cb < 1 || cb > MAX) {
puts("Unsupported dimensions"); return 1;
}
if (ca != rb) { puts("Incompatible dimensions"); return 1; }
if (!read_matrix(a, ra, ca) || !read_matrix(b, rb, cb)) {
puts("Unsupported input"); return 1;
}
multiply(a, b, c, ra, ca, cb);
for (int i = 0; i < ra; ++i) {
for (int j = 0; j < cb; ++j) {
if (j > 0) { putchar(' '); }
printf("%lld", c[i][j]);
}
putchar('\n');
}
return 0;
}2 2 2 2
1 2 3 4
5 6 7 819 22
43 50Related questions in the matrix multiplication category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
What is an array? Write a C program for matrix multiplication.
Paper P01 · page 1Write a program to multiply two matrices of size 2 × 2.
Paper P02 · page 1QUESTION 37 · Matrices and Dimensions
There are 2 × 3 × 4 = 24 int elements.
QUESTION 38 · Matrices and Dimensions
A multidimensional array has more than one level of array nesting. A three-dimensional array can represent groups of row-and-column tables.
int a[2][3][4] = {0};
a[1][2][3] = 7;The declaration creates two elements at the first level. Each is an array of three row arrays, and each row holds four integers. The valid index ranges are 0..1, 0..2 and 0..3. The assignment changes one selected int to 7. The {0} initialiser gives all elements zero before that assignment.
C arrays are nested contiguous arrays. The last subscript changes fastest through the element storage order. For dimensions x, y and z, the total element count is x × y × z, and storage is that product times sizeof(element). Every individual index must remain within its corresponding bound.
Three nested loops can visit a three-dimensional array. The outer loop selects a group, the next selects a row and the inner selects an element. A direct selected access still has constant work in the usual model; visiting every position has work proportional to the total element count.
A full traversal takes O(xyz) time. If all dimensions equal n, it takes O(n³). Loop counters use O(1) auxiliary space when the number of dimensions is fixed. Such arrays can model several matrices, time-based tables or small grids. Choose dimensions carefully: increasing each dimension multiplies storage rather than merely adding a few elements.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int a[2][3][4] = {0};
a[1][2][3] = 7;
printf("Selected = %d\n", a[1][2][3]);
printf("Elements = %zu\n", sizeof a / sizeof a[0][0][0]);
return 0;
}This example uses values already written in the program.
Selected = 7
Elements = 24Related questions in the multidimensional arrays category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Using a two-dimensional array, write a C program to transpose a 2 × 2 matrix.
Paper P04 · page 1What is a two-dimensional array?
Paper P06 · page 1QUESTION 39 · Matrices and Dimensions
The function needs that width to advance correctly from one row to the next.
QUESTION 40 · Matrices and Dimensions
A two-dimensional array argument normally supplies a pointer to its first row. The function must use the correct row type and valid active dimensions.
void show(int a[][3], int rows);
/* equivalent parameter type: int (*a)[3] */The actual array has rows containing three ints. In the parameter, the outer array form adjusts to a pointer to one such row. The first bound may be omitted because the function receives a pointer, but the row width 3 describes the row type and the step used by a[i]. It must match the caller’s actual object.
main holds a 2-by-3 matrix and calls show(a, 2). The function visits two rows and three columns. The example prints the same matrix without copying the whole object. Since its parameter is not const-qualified, the function could modify elements, although this show function only reads them.
In the matrix calculation programs, actual arrays have MAX columns even when only some columns are active. Their parameters therefore also use MAX as the row width. Passing cols as a logical count does not change the actual row width. C also supports other suitable dimension-aware forms, but this unit uses fixed-width parameters for clarity.
Do not cast an incompatible matrix to int ** or use a wrong row width. Pass and validate the row count separately. A display function for r rows and a fixed c-column width takes O(rc) time and O(1) auxiliary space beyond the input array.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
void show(int a[][3], int rows)
{
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < 3; ++j) {
if (j > 0) { putchar(' '); }
printf("%d", a[i][j]);
}
putchar('\n');
}
}
int main(void)
{
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
show(a, 2);
return 0;
}This example uses values already written in the program.
1 2 3
4 5 6Related questions in the multidimensional arrays category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Using a two-dimensional array, write a C program to transpose a 2 × 2 matrix.
Paper P04 · page 1What is a two-dimensional array?
Paper P06 · page 1