You are on page 1of 55

Lab session 3

P2
P2
P3
LAB SESSION 4
1
LAB SESSION 5
LAB SESSION 6
1)Write a C Program to sort an array of integers using pointer.

CODE
#include <stdio.h>

// Function to sort an array of integers using pointers

void sortArray(int *arr, int size) {

int *i, *j, temp;

// Loop through each element of the array

for (i = arr; i < arr + size - 1; i++) {


for (j = i + 1; j < arr + size; j++) {

// Swap elements if they are out of order

if (*i > *j) {

temp = *i;

*i = *j;

*j = temp;

int main() {

int arr[] = {5, 3, 8, 2, 7, 1};

int size = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");

for (int i = 0; i < size; i++) {

printf("%d ", arr[i]);

printf("\n");

// Sort the array using the sortArray function

sortArray(arr, size);

printf("Sorted array: ");

for (int i = 0; i < size; i++) {

printf("%d ", arr[i]);

printf("\n");

return 0;
}

2) Write a program in C to print all permutations of a given


string using pointers.
#include <stdio.h>

// Function to swap characters at two pointers

void swap(char *x, char *y) {

char temp = *x;

*x = *y;

*y = temp;

// Function to calculate the length of a string

int stringLength(char *str) {

int length = 0;

while (*str != '\0') {

length++;

str++;

return length;

// Function to generate permutations of a string

void generatePermutations(char *str, int start, int end) {

if (start == end) {

printf("%s\n", str);

} else {

for (int i = start; i <= end; i++) {

swap((str + start), (str + i));

generatePermutations(str, start + 1, end);

swap((str + start), (str + i)); // backtrack


}

int main() {

char str[100];

printf("Enter a string: ");

scanf("%s", str);

int n = stringLength(str);

printf("All permutations of the string '%s' are:\n", str);

generatePermutations(str, 0, n - 1);

return 0;

2)write C program to find average of numbers using


pointers
Coe
#include <stdio.h>

// Function to swap characters at two pointers

void swap(char *x, char *y) {

char temp = *x;

*x = *y;

*y = temp;

// Function to calculate the length of a string


int stringLength(char *str) {

int length = 0;

while (*str != '\0') {

length++;

str++;

return length;

// Function to generate permutations of a string

void generatePermutations(char *str, int start, int end) {

if (start == end) {

printf("%s\n", str);

} else {

for (int i = start; i <= end; i++) {

swap((str + start), (str + i));

generatePermutations(str, start + 1, end);

swap((str + start), (str + i)); // backtrack

int main() {

char str[100];

printf("Enter a string: ");

scanf("%s", str);

int n = stringLength(str);

printf("All permutations of the string '%s' are:\n", str);

generatePermutations(str, 0, n - 1);
return 0;

3) Write a program in C to remove characters from a


string except alphabets.
#include <stdio.h>

#include <ctype.h>

// Function to remove non-alphabetic characters from a string

void removeNonAlphabetic(char *str) {

int i = 0, j = 0;

while (str[i] != '\0') {

// Check if the character is an alphabet

if (isalpha(str[i])) {

// If it's an alphabet, move it to the beginning of the string

str[j++] = str[i];

i++;

// Add null terminator to indicate end of string

str[j] = '\0';

int main() {

char str[100];

printf("Enter a string: ");


fgets(str, sizeof(str), stdin);

printf("Original string: %s\n", str);

// Remove non-alphabetic characters

removeNonAlphabetic(str);

printf("String after removing non-alphabetic characters: %s\n", str);

return 0;

Lab session 8

Code
#include <stdio.h>

// Function to swap two integers using pointers


void swap(int *x, int *y) {

int temp = *x;

*x = *y;

*y = temp;

// Function to sort numbers in ascending order

void sortAscending(int *arr, int size) {

for (int i = 0; i < size - 1; i++) {

for (int j = 0; j < size - i - 1; j++) {

if (*(arr + j) > *(arr + j + 1)) {

swap(arr + j, arr + j + 1);

// Function to sort numbers in descending order

void sortDescending(int *arr, int size) {

for (int i = 0; i < size - 1; i++) {

for (int j = 0; j < size - i - 1; j++) {

if (*(arr + j) < *(arr + j + 1)) {

swap(arr + j, arr + j + 1);

// Function to print array elements

void printArray(int *arr, int size) {

for (int i = 0; i < size; i++) {


printf("%d ", *(arr + i));

printf("\n");

int main() {

int arr[] = {5, 3, 8, 2, 7, 1};

int size = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");

printArray(arr, size);

// Sort the array in ascending order

sortAscending(arr, size);

printf("Array sorted in ascending order: ");

printArray(arr, size);

// Sort the array in descending order

sortDescending(arr, size);

printf("Array sorted in descending order: ");

printArray(arr, size);

return 0;

}
#include <stdio.h>

// Function to remove duplicates from an array

int removeDuplicates(int *arr, int size) {

int i, j, k;

// Iterate through each element of the array

for (i = 0; i < size; i++) {

// Check if the current element is already seen

for (j = i + 1; j < size;) {

if (*(arr + j) == *(arr + i)) {

// If duplicate found, shift elements to the left

for (k = j; k < size; k++) {

*(arr + k) = *(arr + k + 1);

size--; // Decrease size of array

} else {

j++;

}
return size; // Return the new size of the array

// Function to print array elements

void printArray(int *arr, int size) {

for (int i = 0; i < size; i++) {

printf("%d ", *(arr + i));

printf("\n");

int main() {

int arr[] = {5, 3, 8, 2, 7, 1, 3, 8, 5};

int size = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");

printArray(arr, size);

// Remove duplicates from the array

size = removeDuplicates(arr, size);

printf("Array after removing duplicates: ");

printArray(arr, size);

return 0;

}
#include <stdio.h>

// Function to separate odd and even integers into separate arrays

void separateOddEven(int *arr, int size, int *oddArr, int *evenArr, int *oddSize, int *evenSize) {

for (int i = 0; i < size; i++) {

if (*(arr + i) % 2 == 0) {

// If the number is even, add it to the even array

*(evenArr + (*evenSize)) = *(arr + i);

(*evenSize)++;

} else {

// If the number is odd, add it to the odd array

*(oddArr + (*oddSize)) = *(arr + i);

(*oddSize)++;

// Function to print array elements

void printArray(int *arr, int size) {


for (int i = 0; i < size; i++) {

printf("%d ", *(arr + i));

printf("\n");

int main() {

int arr[] = {5, 3, 8, 2, 7, 1, 4, 6};

int size = sizeof(arr) / sizeof(arr[0]);

int oddArr[size], evenArr[size];

int oddSize = 0, evenSize = 0;

printf("Original array: ");

printArray(arr, size);

// Separate odd and even integers into separate arrays

separateOddEven(arr, size, oddArr, evenArr, &oddSize, &evenSize);

printf("Odd numbers: ");

printArray(oddArr, oddSize);

printf("Even numbers: ");

printArray(evenArr, evenSize);

return 0;

}
#include <stdio.h>

// Function to calculate the Fahrenheit to Celsius conversion

double fahrenheitToCelsius(double x) {

return (5.0 / 9.0) * (x - 32);

// Function to calculate the volume of a sphere

double sphereVolume(double x) {

return (4.0 / 3.0) * 3.14 * x * x * x;

// Function to calculate the value of x*60 when 0 <= x <= 60

double linearFunction(double x) {
if (x >= 0 && x <= 60) {

return x * 60;

} else {

return -1; // Return -1 for out of range values

int main() {

double x;

// Input value for x

printf("Enter a value for x: ");

scanf("%lf", &x);

// Calculate and print the result for each function

printf("f(x) = (5/9) * (x - 32) = %.2f\n", fahrenheitToCelsius(x));

printf("f(x) = 4/3 * 3.14 * x^3 = %.2f\n", sphereVolume(x));

double result = linearFunction(x);

if (result != -1) {

printf("f(x) = x * 60 = %.2f\n", result);

} else {

printf("The value of x is out of range.\n");

return 0;

Lab session 9
#include <stdio.h>

#include <stdlib.h>

// Function to find the largest element

int findLargest(int *arr, int size) {

int largest = *arr; // Initialize largest to the first element

for (int i = 1; i < size; i++) {

if (*(arr + i) > largest) {

largest = *(arr + i); // Update largest if a larger element is found

return largest;

int main() {

int *arr;

int size;

// Input the size of the array

printf("Enter the number of elements: ");


scanf("%d", &size);

// Dynamically allocate memory for the array

arr = (int *)malloc(size * sizeof(int));

if (arr == NULL) {

printf("Memory allocation failed\n");

return 1; // Return with error status

// Input the elements of the array

printf("Enter %d elements:\n", size);

for (int i = 0; i < size; i++) {

scanf("%d", arr + i);

// Find the largest element

int largest = findLargest(arr, size);

// Print the largest element

printf("The largest element is: %d\n", largest);

// Free dynamically allocated memory

free(arr);

return 0;

}
Code

#include <stdio.h>

#include <stdbool.h>

// Function to check if a string is palindrome recursively

bool isPalindrome(char *str, int start, int end) {

// Base case: if start and end pointers cross each other

if (start >= end) {

return true; // String is palindrome

// Check if characters at start and end positions are equal

if (*(str + start) != *(str + end)) {

return false; // Characters don't match, not a palindrome

// Recur for the remaining substring

return isPalindrome(str, start + 1, end - 1);

}
int main() {

char str[100];

printf("Enter a string: ");

scanf("%s", str);

// Calculate the length of the string

int length = 0;

while (str[length] != '\0') {

length++;

// Check if the string is palindrome

if (isPalindrome(str, 0, length - 1)) {

printf("%s is a palindrome.\n", str);

} else {

printf("%s is not a palindrome.\n", str);

return 0;

}
#include <stdio.h>

#include <stdbool.h>

// Function to print the largest and smallest words from a given sentence

void printLargestAndSmallestWord(char *sentence) {

char currentWord[100]; // Assuming max word length is 100

char largestWord[100], smallestWord[100];

int i = 0, j = 0;

int largestLength = 0, smallestLength = 100; // Initializing smallestLength with a large value

// Iterate through the sentence character by character

while (true) {

// Break loop if end of sentence is reached

if (sentence[i] == '\0' || sentence[i] == ' ' || sentence[i] == '\n') {

currentWord[j] = '\0'; // Null terminate the current word

// Update largest and smallest words if necessary

int wordLength = j;

if (wordLength > largestLength) {


largestLength = wordLength;

strcpy(largestWord, currentWord);

if (wordLength < smallestLength && wordLength > 0) {

smallestLength = wordLength;

strcpy(smallestWord, currentWord);

// Reset index for the next word

j = 0;

// Break loop if end of sentence is reached

if (sentence[i] == '\0' || sentence[i] == '\n') {

break;

} else {

// Build the current word character by character

currentWord[j++] = sentence[i];

i++;

// Print the largest and smallest words

printf("Largest word: %s\n", largestWord);

printf("Smallest word: %s\n", smallestWord);

int main() {

char sentence[1000];

printf("Enter a sentence: ");

fgets(sentence, sizeof(sentence), stdin);


// Call the function to print the largest and smallest words

printLargestAndSmallestWord(sentence);

return 0;

#include <stdio.h>

#include <stdlib.h>

int main() {

int size;

// Input the size of the arrays

printf("Enter the size of the arrays: ");

scanf("%d", &size);
// Dynamically allocate memory for arrays A, B, and C

int *A = (int *)malloc(size * sizeof(int));

int *B = (int *)malloc(size * sizeof(int));

int *C = (int *)malloc(size * sizeof(int));

if (A == NULL || B == NULL || C == NULL) {

printf("Memory allocation failed.\n");

return 1;

// Input elements of array A

printf("Enter %d elements for array A:\n", size);

for (int i = 0; i < size; i++) {

scanf("%d", &A[i]);

// Input elements of array B

printf("Enter %d elements for array B:\n", size);

for (int i = 0; i < size; i++) {

scanf("%d", &B[i]);

// Calculate the sum of corresponding elements and store in array C

printf("Result is:\n");

for (int i = 0; i < size; i++) {

C[i] = A[i] + B[i];

printf("%d\n", C[i]);

// Free dynamically allocated memory

free(A);
free(B);

free(C);

return 0;

Lab seeion 10

Code
#include <stdio.h>

// Define the structure Student

struct Student {

char name[50];

int age;

float totalMarks;

};

int main() {

// Declare variables for two students

struct Student student1, student2;


// Input data for student1

printf("Enter name of student 1: ");

scanf("%s", student1.name);

printf("Enter age of student 1: ");

scanf("%d", &student1.age);

printf("Enter total marks of student 1: ");

scanf("%f", &student1.totalMarks);

// Input data for student2

printf("Enter name of student 2: ");

scanf("%s", student2.name);

printf("Enter age of student 2: ");

scanf("%d", &student2.age);

printf("Enter total marks of student 2: ");

scanf("%f", &student2.totalMarks);

// Display information of both students

printf("\nInformation of student 1:\n");

printf("Name: %s\n", student1.name);

printf("Age: %d\n", student1.age);

printf("Total Marks: %.2f\n", student1.totalMarks);

printf("\nInformation of student 2:\n");

printf("Name: %s\n", student2.name);

printf("Age: %d\n", student2.age);

printf("Total Marks: %.2f\n", student2.totalMarks);

// Calculate average total marks

float averageTotalMarks = (student1.totalMarks + student2.totalMarks) / 2.0;

// Display average total marks


printf("\nAverage Total Marks: %.2f\n", averageTotalMarks);

// Display grades based on average total marks

printf("Grades:\n");

if (averageTotalMarks >= 90.0) {

printf("Grade: A\n");

} else if (averageTotalMarks >= 80.0) {

printf("Grade: B\n");

} else if (averageTotalMarks >= 70.0) {

printf("Grade: C\n");

} else if (averageTotalMarks >= 60.0) {

printf("Grade: D\n");

} else {

printf("Grade: F\n");

return 0;

Code
#include <stdio.h>

// Define the structure Date

struct Date {

int day;

int month;

int year;

};

// Function to check if a given year is a leap year

int isLeapYear(int year) {

if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {

return 1; // Leap year

} else {

return 0; // Not a leap year

// Function to find the number of days in a month

int daysInMonth(int month, int year) {

int days[] = {31, 28 + isLeapYear(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

return days[month - 1];

// Function to calculate the difference in days between two dates

int differenceInDays(struct Date d1, struct Date d2) {

int days1 = d1.year * 365 + d1.day; // Convert year and day of d1 into days

for (int i = 0; i < d1.month - 1; i++) {

days1 += daysInMonth(i + 1, d1.year); // Add days for each month of d1

days1 += (d1.year / 4 - d1.year / 100 + d1.year / 400); // Adjust for leap years
int days2 = d2.year * 365 + d2.day; // Convert year and day of d2 into days

for (int i = 0; i < d2.month - 1; i++) {

days2 += daysInMonth(i + 1, d2.year); // Add days for each month of d2

days2 += (d2.year / 4 - d2.year / 100 + d2.year / 400); // Adjust for leap years

// Calculate the difference in days between d1 and d2

return (days2 - days1);

int main() {

struct Date date1, date2;

// Input date 1

printf("Enter date 1 (day month year): ");

scanf("%d %d %d", &date1.day, &date1.month, &date1.year);

// Input date 2

printf("Enter date 2 (day month year): ");

scanf("%d %d %d", &date2.day, &date2.month, &date2.year);

// Calculate difference in days

int difference = differenceInDays(date1, date2);

// Display the difference in days

printf("Difference in days: %d\n", difference);

return 0;

}
#include <stdio.h>

// Define the structure Complex

struct Complex {

float real;

float imag;

};

// Function to add two complex numbers

struct Complex addComplex(struct Complex num1, struct Complex num2) {

struct Complex result;

result.real = num1.real + num2.real;

result.imag = num1.imag + num2.imag;

return result;

// Function to subtract two complex numbers

struct Complex subtractComplex(struct Complex num1, struct Complex num2) {

struct Complex result;

result.real = num1.real - num2.real;

result.imag = num1.imag - num2.imag;

return result;

}
int main() {

struct Complex num1, num2, sum, difference;

// Input the real and imaginary parts of first complex number

printf("Enter real and imaginary parts of first complex number: ");

scanf("%f %f", &num1.real, &num1.imag);

// Input the real and imaginary parts of second complex number

printf("Enter real and imaginary parts of second complex number: ");

scanf("%f %f", &num2.real, &num2.imag);

// Add the complex numbers

sum = addComplex(num1, num2);

// Subtract the complex numbers

difference = subtractComplex(num1, num2);

// Display the results

printf("Sum: %.2f + %.2fi\n", sum.real, sum.imag);

printf("Difference: %.2f + %.2fi\n", difference.real, difference.imag);

return 0;

}
#include <stdio.h>

#include <string.h>

#define MAX_BOOKS 100

// Define the structure Book to represent book information

struct Book {

int accessionNumber;

char author[50];

char title[100];

int isIssued; // 1 if book is issued, 0 if not

};

// Function prototypes

void displayBookInfo(struct Book book);

void displayAllBooks(struct Book books[], int numBooks);

void addNewBook(struct Book books[], int *numBooks);

void displayBooksByAuthor(struct Book books[], int numBooks);


void displayNumBooksByTitle(struct Book books[], int numBooks);

void displayTotalNumBooks(struct Book books[], int numBooks);

void issueBook(struct Book books[], int numBooks);

int main() {

struct Book library[MAX_BOOKS];

int numBooks = 0;

int choice;

do {

// Display menu

printf("\nLibrary Menu\n");

printf("1 - Display book information\n");

printf("2 - Add a new book\n");

printf("3 - Display all books by a particular author\n");

printf("4 - Display the number of books of a particular title\n");

printf("5 - Display the total number of books in the library\n");

printf("6 - Issue a book\n");

printf("0 - Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

if (numBooks > 0) {

displayAllBooks(library, numBooks);

} else {

printf("No books available in the library.\n");

break;

case 2:
addNewBook(library, &numBooks);

break;

case 3:

displayBooksByAuthor(library, numBooks);

break;

case 4:

displayNumBooksByTitle(library, numBooks);

break;

case 5:

displayTotalNumBooks(library, numBooks);

break;

case 6:

issueBook(library, numBooks);

break;

case 0:

printf("Exiting the program.\n");

break;

default:

printf("Invalid choice. Please enter a number between 0 and 6.\n");

} while (choice != 0);

return 0;

// Function to display information of a single book

void displayBookInfo(struct Book book) {

printf("Accession Number: %d\n", book.accessionNumber);

printf("Author: %s\n", book.author);

printf("Title: %s\n", book.title);

printf("Issued: %s\n", book.isIssued ? "Yes" : "No");


printf("\n");

// Function to display information of all books in the library

void displayAllBooks(struct Book books[], int numBooks) {

printf("Library Books:\n");

for (int i = 0; i < numBooks; i++) {

printf("Book %d:\n", i + 1);

displayBookInfo(books[i]);

// Function to add a new book to the library

void addNewBook(struct Book books[], int *numBooks) {

if (*numBooks < MAX_BOOKS) {

struct Book newBook;

printf("Enter book details:\n");

printf("Accession Number: ");

scanf("%d", &newBook.accessionNumber);

printf("Author: ");

scanf("%s", newBook.author);

printf("Title: ");

scanf("%s", newBook.title);

newBook.isIssued = 0; // Set isIssued to 0 since the book is not issued initially

books[*numBooks] = newBook;

(*numBooks)++;

printf("Book added to the library successfully.\n");

} else {

printf("Cannot add more books. Library is full.\n");

}
// Function to display all books by a particular author

void displayBooksByAuthor(struct Book books[], int numBooks) {

char author[50];

int found = 0;

printf("Enter author name: ");

scanf("%s", author);

printf("Books by author '%s':\n", author);

for (int i = 0; i < numBooks; i++) {

if (strcmp(books[i].author, author) == 0) {

displayBookInfo(books[i]);

found = 1;

if (!found) {

printf("No books found by author '%s'.\n", author);

// Function to display the number of books of a particular title

void displayNumBooksByTitle(struct Book books[], int numBooks) {

char title[100];

int count = 0;

printf("Enter title: ");

scanf("%s", title);

for (int i = 0; i < numBooks; i++) {

if (strcmp(books[i].title, title) == 0) {

count++;

printf("Number of books with title '%s': %d\n", title, count);


}

// Function to display the total number of books in the library

void displayTotalNumBooks(struct Book books[], int numBooks) {

printf("Total number of books in the library: %d\n", numBooks);

// Function to issue a book from the library

void issueBook(struct Book books[], int numBooks) {

int accessionNumber;

printf("Enter accession number of the book to issue: ");

scanf("%d", &accessionNumber);

int found = 0;

for (int i = 0; i < numBooks; i++) {

if (books[i].accessionNumber == accessionNumber) {

if (books[i].isIssued) {

printf("Book is already issued.\n");

} else {

books[i].isIssued = 1; // Mark the book as issued

printf("Book issued successfully.\n");

found = 1;

break;

if (!found) {

printf("Book with accession number %d not found.\n", accessionNumber);

}
Code

#include <stdio.h>

#include <string.h>

#define MAX_CUSTOMERS 10

// Structure to store customer information

struct Customer {

char name[50];

int accountNumber;

float balance;

};

// Function to print names of customers with balance less than $200

void printCustomersWithLowBalance(struct Customer customers[], int numCustomers) {

printf("Customers with balance less than $200:\n");

for (int i = 0; i < numCustomers; i++) {

if (customers[i].balance < 200.0) {

printf("%s\n", customers[i].name);
}

// Function to add $100 to the balance of customers with balance more than $1000

void addBalanceForRichCustomers(struct Customer customers[], int numCustomers) {

printf("\nCustomers with balance more than $1000 after incrementing by $100:\n");

for (int i = 0; i < numCustomers; i++) {

if (customers[i].balance > 1000.0) {

customers[i].balance += 100.0;

printf("%s: $%.2f\n", customers[i].name, customers[i].balance);

int main() {

struct Customer customers[MAX_CUSTOMERS] = {

{"Alice", 1001, 150.0},

{"Bob", 1002, 3000.0},

{"Charlie", 1003, 500.0},

{"David", 1004, 1200.0},

{"Eva", 1005, 180.0},

{"Frank", 1006, 800.0},

{"Grace", 1007, 1100.0},

{"Helen", 1008, 700.0},

{"Ian", 1009, 1300.0},

{"Julia", 1010, 1400.0}

};

int numCustomers = MAX_CUSTOMERS;


// Print names of customers with balance less than $200

printCustomersWithLowBalance(customers, numCustomers);

// Add $100 to balance of customers with balance more than $1000 and print incremented
balances

addBalanceForRichCustomers(customers, numCustomers);

return 0;

PATTERN
Write a C Program to print pascal's triangle.

#include <stdio.h>

int main() {
int rows, coef = 1;

printf("Enter the number of rows: ");


scanf("%d", &rows);

for (int i = 0; i < rows; i++) {


for (int space = 1; space <= rows - i; space++) {
printf(" ");
}

for (int j = 0; j <= i; j++) {


if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;

printf("%4d", coef);
}
printf("\n");
}

return 0;
}

Write a C Program to number increasing pyramid.


#include <stdio.h>

int main() {
int rows, num = 1;

printf("Enter the number of rows: ");


scanf("%d", &rows);

for (int i = 1; i <= rows; i++) {


for (int space = 1; space <= rows - i; space++) {
printf(" ");
}
for (int j = 1; j <= i; j++) {
printf("%2d ", num++);
}
printf("\n");
}

return 0;
}

You might also like