C Program - Lab Programs

These are Lab programs

Part A

Program 1: Calculate Straight-Line Distance Between Two Points

A robot needs to find how far it must travel between two points on a 2D plane. The straight-line distance (Euclidean distance) can be calculated using the formula:

distance = √((x₂ - x₁)² + (y₂ - y₁)²)

C Program

#include <stdio.h>
#include <math.h>

int main() {
   double x1, y1, x2, y2, distance;

   // Input coordinates of point 1
   printf("Enter coordinates of point 1 (x1 y1): ");
   scanf("%lf %lf", &x1, &y1);

   // Input coordinates of point 2
   printf("Enter coordinates of point 2 (x2 y2): ");
   scanf("%lf %lf", &x2, &y2);

   // Calculate distance
   distance = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));

   // Display result
   printf("The straight-line distance between the points is: %.4lf\n", distance);

   return 0;
}

there were some issues with sqrt, use the below to compile

cc filename.c -o filename -lm
./filename

Enter coordinates of point 1 (x1 y1): 2 3
Enter coordinates of point 2 (x2 y2): 7 8
The straight-line distance between the points is: 7.0711

Explanation

Program 2: Calculate Grade Based on Marks

Develop a C program that takes a student's marks as input and displays their grade based on the following criteria:

A suitable if-else ladder is used to implement this grading logic efficiently.

C Program

#include <stdio.h>

int main() {
   int marks;
   char grade;

   printf("Enter the student's marks (0-100): ");
   scanf("%d", &marks);

   if (marks < 0 || marks > 100) {
     printf("Invalid marks entered.\n");
     return 1; // Exit for invalid input
   }

   if (marks >= 90) {
     grade = 'A';
   } else if (marks >= 75) {
     grade = 'B';
   } else if (marks >= 60) {
     grade = 'C';
   } else if (marks >= 50) {
     grade = 'D';
   } else {
     grade = 'F';
   }

   printf("Grade: %c\n", grade);
   return 0;
}

Enter the student's marks (0-100): 82
Grade: B

Explanation

Program 3: KYC Verification System

Develop a C program that stores predefined KYC records and allows the user to verify their ID (PAN, AADHAR, APAAR, Driving License, or Passport) against those records. The program uses a switch statement and simple array search logic to determine verification status.

Program Requirements

C Program

#include <stdio.h>

int main() {
  // Predefined KYC records (integer arrays)
  int PAN_Number[5] = {11111, 22222, 33333, 44444, 55555};
  int AADHAR_Number[5] = {121212, 232323, 343434, 454545, 565656};
  int APAAR_Id[5] = {1001, 1002, 1003, 1004, 1005};
  int Driving_License[5] = {2001, 2002, 2003, 2004, 2005};
  int Passport[5] = {3001, 3002, 3003, 3004, 3005};

  int id_type, id_number, i, found = 0;

  printf("KYC Verification System\n");
  printf("Select ID Type to Verify:\n");
  printf("1. PAN Number\n");
  printf("2. AADHAR Number\n");
  printf("3. APAAR ID\n");
  printf("4. Driving License\n");
  printf("5. Passport\n");
  printf("Enter your choice (1-5): ");
  scanf("%d", &id_type);

  printf("Enter your Unique ID Number: ");
  scanf("%d", &id_number);

  switch(id_type) {
    case 1:
      for(i = 0; i < 5; i++) {
        if(id_number == PAN_Number[i]) { found = 1; break; }
      }
      break;

    case 2:
      for(i = 0; i < 5; i++) {
        if(id_number == AADHAR_Number[i]) { found = 1; break; }
      }
      break;

    case 3:
      for(i = 0; i < 5; i++) {
        if(id_number == APAAR_Id[i]) { found = 1; break; }
      }
      break;

    case 4:
      for(i = 0; i < 5; i++) {
        if(id_number == Driving_License[i]) { found = 1; break; }
      }
      break;

    case 5:
      for(i = 0; i < 5; i++) {
        if(id_number == Passport[i]) { found = 1; break; }
      }
      break;

    default:
      printf("Invalid choice! \n");
      return 0;
  }

  if(found)
    printf("Verification Successful: Individual is VERIFIED.\n");
  else
    printf("Verification Failed: Individual NOT found in KYC records.\n");

  return 0;
}

KYC Verification System
Select ID Type to Verify:
1. PAN Number
2. AADHAR Number
3. APAAR ID
4. Driving License
5. Passport

Enter your choice (1-5): 3
Enter your Unique ID Number: 1004
Verification Successful: Individual is VERIFIED.

Explanation

Program 4: Quadratic Equation Roots Calculator

Develop a C program that calculates and displays the roots of a quadratic equation based on user input coefficients. The program determines whether the roots are real and distinct, real and equal, or complex and imaginary based on the discriminant value.

Program Requirements

C Program

Code:

#include <stdio.h>
#include <math.h>
int main() {
  double a, b, c;
  double discriminant, root1, root2, realPart, imagPart;
  printf("Enter coefficients a, b and c: ");
  scanf("%lf %lf %lf", &a, &b, &c);
  if(a == 0) {
    printf("Not a quadratic equation. \n");
    return 0;
  }
  discriminant = b*b - 4*a*c;
  if(discriminant > 0) {
    root1 = (-b + sqrt(discriminant)) / (2*a);
    root2 = (-b - sqrt(discriminant)) / (2*a);
    printf("Roots are real and distinct: \n");
    printf("Root 1 = %.4lf \n", root1);
    printf("Root 2 = %.4lf \n", root2);
  } else if(discriminant == 0) {
    root1 = -b / (2*a);
    printf("Roots are real and equal: \n");
    printf("Root = %.4lf \n", root1);
  } else {
    realPart = -b / (2*a);
    imagPart = sqrt(-discriminant) / (2*a);
    printf("Roots are complex and imaginary: \n");
    printf("Root 1 = %.4lf + %.4lfi \n", realPart, imagPart);
    printf("Root 2 = %.4lf - %.4lfi \n", realPart, imagPart);
  }
  return 0;
}
Enter coefficients a, b and c: 1 -3 2
Roots are real and distinct:
Root 1 = 2.0000
Root 2 = 1.0000

Explanation

Program 5: Sine Approximation for Robotic Arm

Develop a C program to approximate the sine function using Taylor series expansion for real-time angle calculation in robotic arms. This solution avoids using built-in trigonometric functions by implementing power, factorial, and series approximation calculations manually.

Program Requirements

C Program

#include <stdio.h>

double calculatePower(double base, int exponent) {
  double result = 1.0;
  int i;
  for (i = 0; i < exponent; i++) {
    result = result * base;
  }
  return result;
}

unsigned long long calculateFactorial(int number) {
  unsigned long long factorial = 1;
  int i;
  for (i = 2; i <= number; i++) {
    factorial = factorial * i;
  }
  return factorial;
}

// Function to approximate sine using Taylor series
double approximateSine(double angle) {
  double sineValue = 0.0;
  int numberOfTerms = 10;

  int term;
  for (term = 0; term < numberOfTerms; term++) {
    int sign = (term % 2 == 0) ? 1 : -1;

    int exponent = 2 * term + 1;
    unsigned long long fact = calculateFactorial(exponent);
    double currentTerm = sign * calculatePower(angle, exponent) / fact;

    sineValue = sineValue + currentTerm;
  }

  return sineValue;
}

int main() {
  double angleRadians;

  printf("Enter angle in radians: ");
  scanf("%lf", &angleRadians);

  double sineResult = approximateSine(angleRadians);

  printf("Approximate sin(%.4f) = %.6f\n", angleRadians, sineResult);

  return 0;
}

Enter angle in radians: 1.5708
Approximate sin(1.5708) = 1.000000

Enter angle in radians: 0.7854
Approximate sin(0.7854) = 0.707107

Enter angle in radians: 3.1416
Approximate sin(3.1416) = 0.000003

Enter angle in radians: 1.0472
Approximate sin(1.0472) = 0.866025

Explanation

Technical Details

Program 6: Keyword Search in Course Description

Develop a C program that accepts a course description and a keyword from the user. The program searches whether the keyword exists within the course description using string handling functions. Based on the search result, it displays an appropriate message to the user.

Program Requirements

C Program

#include <stdio.h>
#include <string.h>

int main() {
  char courseDesc[500];
  char keyword[100];

  printf("Enter course description: ");
  fgets(courseDesc, sizeof(courseDesc), stdin);

  size_t len = strlen(courseDesc);
  if (len > 0 && courseDesc[len - 1] == '\n') {
    courseDesc[len - 1] = '\0';
  }

  printf("Enter keyword to search: ");
  scanf("%s", keyword);

  if (strstr(courseDesc, keyword) != NULL) {
    printf("Keyword '%s' found in the course description.\n", keyword);
  } else {
    printf("Keyword '%s' not found in the course description.\n", keyword);
  }

  return 0;
}

Enter course description: Introduction to Programming using C
Enter keyword to search: Programming
Keyword 'Programming' found in the course description.

Enter course description: Data Structures and Algorithms
Enter keyword to search: Python
Keyword 'Python' not found in the course description.

Explanation

Technical Details

Program 7: Student Result Check using Function

Develop a C program that takes marks for three subjects as input. The program uses a function to check whether the student has passed with a minimum of 40 marks in each subject. It then calculates the average and displays the result along with pass or fail status.

Program Requirements

C Program

#include <stdio.h>

int checkPass(int m1, int m2, int m3) {
  if (m1 >= 40 && m2 >= 40 && m3 >= 40)
    return 1;
  else
    return 0;
}

int main() {
  int marks1, marks2, marks3;
  float average;

  printf("Enter marks for subject 1: ");
  scanf("%d", &marks1);
  printf("Enter marks for subject 2: ");
  scanf("%d", &marks2);
  printf("Enter marks for subject 3: ");
  scanf("%d", &marks3);

  average = (marks1 + marks2 + marks3) / 3.0;

  int result = checkPass(marks1, marks2, marks3);

  printf("\nAverage marks: %.2f\n", average);
  if (result)
    printf("Status: Passed\n");
  else
    printf("Status: Failed\n");
  return 0;
}

Enter marks for subject 1: 45
Enter marks for subject 2: 55
Enter marks for subject 3: 35
Average marks: 45.00
Status: Failed

Explanation

Technical Details

Program 8: ATM Account Balance Swap using Pointers

Develop a C program where two account balances are temporarily swapped for validation. This program accepts two balances, uses a function with pointers to swap their values, and displays the balances before and after the swap operation.

Program Requirements

C Program

#include <stdio.h>

// Function to swap two balances using pointers
void swapBalances(float *a, float *b) {
  float temp = *a;
  *a = *b;
  *b = temp;
}

int main() {
  float balance1, balance2;

  // Input balances
  printf("Enter balance of Account 1: ");
  scanf("%f", &balance1);
  printf("Enter balance of Account 2: ");
  scanf("%f", &balance2);

  // Display before swapping
  printf("\nBefore swapping:\n");
  printf("Account 1 balance: %.2f\n", balance1);
  printf("Account 2 balance: %.2f\n", balance2);

  // Swap balances
  swapBalances(&balance1, &balance2);

  // Display after swapping
  printf("\nAfter swapping:\n");
  printf("Account 1 balance: %.2f\n", balance1);
  printf("Account 2 balance: %.2f\n", balance2);

  return 0;
}

Enter balance of Account 1: 1500.75
Enter balance of Account 2: 2450.50
Before swapping:
Account 1 balance: 1500.75
Account 2 balance: 2450.50
After swapping:
Account 1 balance: 2450.50
Account 2 balance: 1500.75

Explanation

Technical Details

Part B

Program 1: Book Search in Digital Library using Binary Search

A college library uses a digital bookshelf system where books are stored in ascending order of Book IDs. To quickly check if a particular Book ID exists, the program uses Binary Search which reduces search time by repeatedly dividing the collection into halves.

Program Requirements

C Program

#include <stdio.h>

int binarySearch(int arr[], int size, int key) {
  int low = 0;
  int high = size - 1;

  while (low <= high) {
    int mid = low + (high - low) / 2;

    if (arr[mid] == key)
      return mid; // Found the book
    else if (arr[mid] < key)
      low = mid + 1; // Search right half
    else
      high = mid - 1; // Search left half
  }
  return -1; // Book not found
}

int main() {
  int n, key, result, i;

  printf("Enter number of books in shelf: ");
  scanf("%d", &n);

  int bookIDs[n];
  printf("Enter Book IDs in ascending order:\n");
  for (i = 0; i < n; i++) {
    scanf("%d", &bookIDs[i]);
  }

  printf("Enter Book ID to search: ");
  scanf("%d", &key);

  result = binarySearch(bookIDs, n, key);

  if (result != -1)
    printf("Book with ID %d is available at position %d.\n", key, result + 1);
  else
    printf("Book with ID %d is not available in the shelf.\n", key);

  return 0;
}

Enter number of books in shelf: 6
Enter Book IDs in ascending order:
101 203 305 410 512 678
Enter Book ID to search: 410
Book with ID 410 is available at position 4.

Explanation

Technical Details

Program 2: Sorting Race Scores in Descending Order

A sports teacher needs to prepare a result sheet for a 100-meter race. The recorded scores must be arranged from highest to lowest. This program takes student scores as input and sorts them in descending order using Bubble Sort.

Program Requirements

C Program

#include <stdio.h>

int main() {
  int n, i, j, temp;

  printf("Enter number of students: ");
  scanf("%d", &n);

  int scores[n];
  printf("Enter the scores:\\n");
  for (i = 0; i < n; i++) {
    scanf("%d", &scores[i]);
  }

  // Sort in descending order using Bubble Sort
  for (i = 0; i < n - 1; i++) {
    for (j = 0; j < n - 1 - i; j++) {
      if (scores[j] < scores[j + 1]) {
        temp = scores[j];
        scores[j] = scores[j + 1];
        scores[j + 1] = temp;
      }
    }
  }

  printf("\\nScores in descending order:\\n");
  for (i = 0; i < n; i++) {
    printf("%d\\n", scores[i]);
  }

  return 0;
}

Enter number of students: 5
Enter the scores:
12
10
15
9
14

Scores in descending order:
15
14
12
10
9

How This Works