🏛️ UPSC Advanced Examination Practice

Computing with C and R — Model Solutions (2025)

Language Constraint

A comprehensive, manually-coded approach to solving high-level statistical computing problems.

📌 Q13 (a) Bitwise Operators and Bitwise Shift Operators in C

📖 Introduction

Bitwise operators are special operators in the C programming language that operate directly on the binary representation of integers. Instead of working with decimal values, these operators manipulate individual bits (0 or 1) of a number.

Bitwise operations are widely used in low-level programming, system software, device drivers, cryptography, and applications where efficient memory and performance optimization are required.

⚙️ Types of Bitwise Operators

The commonly used bitwise operators in C are:

Operator Name Description
&Bitwise ANDReturns 1 if both bits are 1
|Bitwise ORReturns 1 if at least one bit is 1
^Bitwise XORReturns 1 if bits are different
~Bitwise NOTInverts all bits

1. Bitwise AND (&)

The bitwise AND operator compares each bit of two numbers. The result bit is 1 only when both corresponding bits are 1.

$$5 = 0101$$ $$3 = 0011$$ $$5 \ \& \ 3 = 0001 = 1$$
Bit of 5Bit of 3Result
000
100
010
111

Thus, the result of the AND operation is 1.

2. Bitwise OR (|)

The bitwise OR operator compares each bit of two numbers. The result bit is 1 if at least one of the corresponding bits is 1.

$$5 = 0101$$ $$3 = 0011$$ $$5 \ | \ 3 = 0111 = 7$$

Thus, the OR operation produces the value 7.

3. Bitwise XOR (^)

The bitwise XOR (exclusive OR) operator returns 1 when the corresponding bits of two numbers are different and returns 0 when they are the same.

$$5 = 0101$$ $$3 = 0011$$ $$5 \ \oplus \ 3 = 0110 = 6$$

Hence the result is 6.

4. Bitwise NOT (~)

The bitwise NOT operator inverts all bits of a number. Every 0 becomes 1 and every 1 becomes 0.

$$5 = 00000101$$ $$\sim 5 = 11111010$$

In most systems using two's complement representation, this corresponds to the value: $\sim 5 = -6$

🔄 Bitwise Shift Operators

Operator Name Description
<<Left ShiftShifts bits to the left
>>Right ShiftShifts bits to the right

1. Left Shift Operator (<<)

Each bit shifts one position to the left and a 0 is inserted at the rightmost position. Thus, left shift is equivalent to multiplying the number by $2^n$.

$$5 \ll 1 = 00001010 = 10$$

2. Right Shift Operator (>>)

Each bit moves one position to the right. Thus, right shift is equivalent to dividing the number by $2^n$.

$$8 \gg 1 = 00000100 = 4$$
Conclusion: Bitwise operators allow direct manipulation of binary data and provide efficient computation at the hardware level. They are widely used in system programming, embedded systems, network protocols, and performance-critical applications.

📌 Q13 (b) C Program to Check Whether a Given Year is a Leap Year

📝 Problem Statement

Write a C program to determine whether a given year is a leap year or not.

📖 Introduction

A leap year is a year that contains 366 days instead of 365 days. The extra day is added to the month of February.

A year is considered a leap year if it satisfies the following conditions:

Examples: 2000 is a leap year. 1900 is not a leap year. 2024 is a leap year.

⚙️ Algorithm

  1. Start the program.
  2. Read the input year from the user.
  3. Check if the year is divisible by 400. If true, it is a leap year.
  4. Otherwise check if the year is divisible by 4 but not by 100. If true, it is a leap year.
  5. Otherwise the year is not a leap year.
  6. Display the result.
  7. Stop the program.

💻 C Program

#include <stdio.h>

int main()
{
    int year;

    printf("Enter a year: ");
    scanf("%d", &year);

    if((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
        printf("The year is a Leap Year");
    else
        printf("The year is Not a Leap Year");

    return 0;
}

📊 Meaning of Variables Used

Conclusion: The program checks divisibility conditions to determine whether the given year satisfies the leap year rule and prints the result accordingly.

📌 Q13 (c) C Program to Calculate the Sum of the Expression

📝 Problem Statement

Write a C program to calculate the sum of the following series:

$$ \frac{1}{2} + \frac{5}{6} + \frac{9}{10} + ... + \frac{99}{100} $$

📖 Introduction

The given series follows a specific arithmetic pattern where:

The last term of the series is $\frac{99}{100}$. The program calculates the cumulative sum using a single loop, ensuring proper typecasting to handle floating-point division.

⚙️ Algorithm

  1. Start the program.
  2. Initialize the sum variable to zero (as a float).
  3. Use a for loop initializing i = 1 and j = 2.
  4. For each step, calculate the fraction: divide i by j.
  5. Add the calculated value to the sum.
  6. Increment both i and j by 4.
  7. Continue the loop until the numerator i exceeds 99.
  8. Display the final sum.
  9. Stop the program.

💻 C Program

#include <stdio.h>

int main()
{
    int i, j;
    float sum = 0;

    /* Loop steps numerator and denominator by 4 simultaneously */
    for(i = 1, j = 2; i <= 99; i = i + 4, j = j + 4)
    {
        /* Explicitly cast 'i' to float to prevent integer division */
        sum = sum + (float)i / j;
    }

    printf("Sum of the series = %f", sum);

    return 0;
}

📊 Meaning of Variables Used

Conclusion: The program generates the given mathematical series using precise loop control. By incrementing multiple variables within a single for loop and utilizing explicit typecasting, it calculates the final sum efficiently.

📌 Q13 (d) Explain Any Five File Operations in C

📖 Introduction

File handling in C allows programs to store data permanently in external files. This enables data to be saved, processed, and retrieved even after the program's execution is completed.

Instead of storing data temporarily in RAM (which is volatile), file operations allow direct interaction with the hard drive. The C standard library provides several functions to perform these critical operations.

⚙️ Important File Operations

1. fopen() - Open a File

This function is used to open an existing file or create a new one. It returns a file pointer that is used to access the file in subsequent operations.

FILE *fp;
fp = fopen("data.txt", "r");

2. fclose() - Close a File

Once all operations are completed, it is mandatory to close the file to free up memory resources and ensure all buffers are flushed to the disk.

fclose(fp);

3. fprintf() - Write Formatted Data

Similar to printf(), but instead of writing to the console screen, it writes formatted text directly into the specified file.

fprintf(fp, "Student Name: %s, Marks: %d", name, marks);

4. fscanf() - Read Formatted Data

Similar to scanf(), it reads formatted data from the file instead of the standard input (keyboard).

int num;
fscanf(fp, "%d", &num);

5. fgetc() and fputc() - Character I/O

These functions are used to read (fgetc) and write (fputc) a single character from or to a file. They are often used in loops to process files character by character.

char ch;
/* Read a character */
ch = fgetc(fp);

/* Write a character */
fputc(ch, fp);
Conclusion: File operations form the foundation of persistent data storage in C. By mastering fopen, fclose, and various read/write commands, programs can handle large-scale data processing applications and robust database systems efficiently.

📌 Q13 (e) R Code for Vector and Matrix Operations

📝 Problem Statement

Write a set of R codes to perform the following operations:

  1. Read a vector of values.
  2. Create a matrix of dimensions $r_1 \times c_1$.
  3. Compute the MinMax and MaxMin values.
  4. Print whether these two values are equal or not.

📖 Introduction

In matrix theory, two highly important values can be computed from a matrix to determine optimal strategies or saddle points:

If these two values are equal, that specific value is called the saddle point of the matrix.

To demonstrate computational proficiency, this program constructs the matrix from a given vector and computes the MinMax and MaxMin values manually using nested loops, entirely avoiding R's built-in min() and max() functions.

💻 R Program (100% Manual Implementation)

# Step 1: Input vector
v <- c(4, 7, 2, 9, 5, 6)

# Step 2: Matrix dimensions
r1 <- 2
c1 <- 3

# Step 3: Create matrix manually
m <- matrix(0, r1, c1)
k <- 1

for(i in 1:r1) {
  for(j in 1:c1) {
    m[i,j] <- v[k]
    k <- k + 1
  }
}

cat("Matrix is:\n")
print(m)

# Step 4: Compute row minimums
row_min <- numeric(r1)

for(i in 1:r1) {
  min_val <- m[i,1]
  
  for(j in 2:c1) {
    if(m[i,j] < min_val) {
      min_val <- m[i,j]
    }
  }
  row_min[i] <- min_val
}

# Step 5: Compute column maximums
col_max <- numeric(c1)

for(j in 1:c1) {
  max_val <- m[1,j]
  
  for(i in 2:r1) {
    if(m[i,j] > max_val) {
      max_val <- m[i,j]
    }
  }
  col_max[j] <- max_val
}

# Step 6: Find MinMax (Minimum of column maximums)
minmax <- col_max[1]

for(j in 2:c1) {
  if(col_max[j] < minmax) {
    minmax <- col_max[j]
  }
}

# Step 7: Find MaxMin (Maximum of row minimums)
maxmin <- row_min[1]

for(i in 2:r1) {
  if(row_min[i] > maxmin) {
    maxmin <- row_min[i]
  }
}

cat("MinMax =", minmax, "\n")
cat("MaxMin =", maxmin, "\n")

# Step 8: Check equality
if(minmax == maxmin) {
  cat("MinMax and MaxMin are Equal (Saddle Point Exists)\n")
} else {
  cat("MinMax and MaxMin are Not Equal\n")
}

📊 Meaning of Variables Used

Conclusion: The program dynamically constructs a matrix from a raw vector and computes the MinMax and MaxMin values using strict manual comparisons. By comparing these values at the end, it correctly evaluates the presence of a saddle point.

📚 Paper Summary & Key Focus Areas

🎯 Core Concepts Tested in This Paper

Based on the questions in this year's examination, aspirants should heavily focus on the following domains:

📌 Points to Remember

🎯 Try These: Practice Questions

To solidify the concepts learned in this paper, attempt the following questions using the exact same constraints (manual logic, no built-in functions):

📝 Practice Question 1 (C Programming)

Write a C program to check if a given positive integer is a power of 2 using only bitwise operators (no loops or division).

💡 Hint & Approach:
Think about the binary representation of a power of 2 (e.g., 4 is $0100$, 8 is $1000$). Notice that a power of 2 has exactly one '1' bit.
Now look at the number just before it (e.g., 3 is $0011$, 7 is $0111$).
If you perform a Bitwise AND between a power of 2 ($n$) and ($n-1$), what is the result? The condition (n & (n - 1)) == 0 is the key.

📝 Practice Question 2 (R Programming)

Write an R script to compute the transpose of a given $m \times n$ matrix. You must create an empty matrix of dimensions $n \times m$ and use nested loops to populate it. Do not use the t() function.

💡 Hint & Approach:
First, determine the dimensions of the original matrix $A$ using manual iteration or nrow() / ncol(). Initialize a new matrix $B$ filled with zeros, where the rows of $B$ equal the columns of $A$, and the columns of $B$ equal the rows of $A$. Use two nested loops for (i in 1:m) and for (j in 1:n), and assign the values using the logic: B[j, i] <- A[i, j].