0% found this document useful (0 votes)
69 views

Lab Assignment 5-9

The document contains code for various sorting and string manipulation algorithms implemented by Shubhi Shrivastava as part of a lab assignment. The code includes implementations of binary search, bubble sort, selection sort, insertion sort, reversing a string, checking for palindromes, deleting characters from a string, counting character frequencies, and sorting strings alphabetically. Functions are used to modularize the code and handle arguments and return values. Recursive functions are also implemented, such as for generating Fibonacci sequences and calculating greatest common divisors (GCDs).

Uploaded by

Anirudh Achiever
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views

Lab Assignment 5-9

The document contains code for various sorting and string manipulation algorithms implemented by Shubhi Shrivastava as part of a lab assignment. The code includes implementations of binary search, bubble sort, selection sort, insertion sort, reversing a string, checking for palindromes, deleting characters from a string, counting character frequencies, and sorting strings alphabetically. Functions are used to modularize the code and handle arguments and return values. Recursive functions are also implemented, such as for generating Fibonacci sequences and calculating greatest common divisors (GCDs).

Uploaded by

Anirudh Achiever
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Shubhi Shrivastava

B.Arch. 2nd Semester


Department of Architecture and Planning, MNIT Jaipur
2021UAR1195

Lab Assignment 5

1. Write a program to implement binary search on a sorted array of ‘n’ elements.


#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
//implementing binary search
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);
return 0;
}
2.Write a program to implement bubble sort.
/* Bubble sort code */
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < n - 1; c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use '<' instead of '>' */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c < n; c++)
printf("%d\n", array[c]);
return 0;
}
3.Write a program to implement selection sort.
#include <stdio.h>
void selectionSort(int arr[], int size);
void swap(int *a, int *b);
void selectionSort(int arr[], int size)
{
int i, j;
for (i = 0 ; i < size;i++)
{
for (j = i ; j < size; j++)
{
if (arr[i] > arr[j])
swap(&arr[i], &arr[j]);
}
}
}
/* Function to swap two variables */
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int array[10], i, size;
printf("How many numbers you want to sort: ");
scanf("%d", &size);
printf("\nEnter %d numbers\t", size);
printf("\n");
for (i = 0; i < size; i++)
scanf("%d", &array[i]);
selectionSort(array, size);
printf("\nSorted array is ");
for (i = 0; i < size;i++)
printf(" %d ", array[i]);
return 0;
}

4. Write a program to implement insertion sort.


/* C Program to sort an array in ascending order using Insertion Sort */
#include <stdio.h>
int main(void)
{
int n, i, j, temp;
int arr[64];
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
for (i = 1; i < n; i++)
{
j = i;
while (j > 0 && arr[j - 1] > arr[j])
{
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
j--;
}
}
printf("Sorted list in ascending order:\n");
for (i = 0; i < n; i++)
{
printf("%d\n", arr[i]);
}
return 0;
}
Lab Assignment 6

1. Write a program to reverse a given string without using library functions.


#include <stdio.h>
int main()
{
char acData[100]= {0}, Temp = 0;
int iLoop =0, iLen = 0;
printf("\nEnter the string :");
gets(acData);
// calculate length of string
while(acData[iLen++] != '\0');
//Remove the null character
iLen--;
//Array index start from 0 to (length -1)
iLen--;
while (iLoop < iLen)
{
Temp = acData[iLoop];
acData[iLoop] = acData[iLen];
acData[iLen] = Temp;
iLoop++;
iLen--;
}
printf("\n\nReverse string is : %s\n\n",acData);
return 0;
}

2. Write a program to check whether given string is palindrome or not without using library
functions.
#include <stdio.h>
#include <string.h>
void main()
{
char string[25], reverse_string[25] = {'\0'};
int i, length = 0, flag = 0;
printf("Enter a string \n");
gets(string);
for (i = 0; string[i] != '\0'; i++)
{
length++;
}
printf("The length of the string '%s' = %d\n", string, length);
for (i = length - 1; i >= 0 ; i--)
{
reverse_string[length - i - 1] = string[i];
}
for (flag = 1, i = 0; i < length ; i++)
{
if (reverse_string[i] != string[i])
flag = 0;
}
if (flag == 1)
printf ("%s is a palindrome \n", string);
else
printf("%s is not a palindrome \n", string);
}

3. Develop a program to delete ‘n’ characters in the string from a particular position.
#include <stdio.h>
void del_str(char [],int, int);
main(){
int n,p;
char str[30];
printf("\n Enter the String:");
gets(str);
fflush(stdin);
printf("\n Enter the position from where the characters are to be deleted:");
scanf("%d",&p);
printf("\n Enter Number of characters to be deleted:");
scanf("%d",&n);
del_str(str,p,n);
}
void del_str(char str[],int p, int n){
int i,j;
for(i=0,j=0;str[i]!='\0';i++,j++){
if(i==(p-1)){
i=i+n;
}
str[j]=str[i];
}
str[j]='\0';
puts(" The string after deletion of characters:");
puts(str);
}

4. Write a program to find the number of occurrences of each alphabet in a given string without
using library functions. Assume that the string contains only alphabets.
#include <stdio.h>
int main() {
char str[1000], ch;
int count = 0;

printf("Enter a string: ");


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

printf("Enter a character to find its frequency: ");


scanf("%c", &ch);

for (int i = 0; str[i] != '\0'; ++i) {


if (ch == str[i])
++count;
}

printf("Frequency of %c = %d", ch, count);


return 0;
}
5. Write a program to read a string and rewrite it in the alphabetical order of the string by
ASCII values. For example the word STRING should be written as GINRST.

#include <stdio.h>
#include <string.h>
int main ()
{
char string[100];
printf("\n\t Enter the string : ");
scanf("%s", string);
char temp;
int i, j;
int n = strlen(string);
for (i = 0; i < n-1; i++) {
for (j = i+1; j < n; j++) {
if (string[i] > string[j]) {
temp = string[i];
string[i] = string[j];
string[j] = temp;
}
}
}
printf("The sorted string is : %s”, string);
return 0;
}
Lab Assignment 7
1. Write a program with functions –
•Without Arguments &amp; without Return Value
•With Arguments &amp; without Return Value
•With Arguments &amp; with Return Value
for the sum of digits of a given number.

/* Function to get sum of digits */


//Without Arguments &amp; without Return Value
#include <stdio.h>
int n = 0;
int sum = 0;
int getSum()
{
while (n != 0) {
sum = sum + n % 10;
n = n / 10;
}
return;
}
int main()
{
n=1835;
getSum();
printf(" %d ", (sum));
sum = 0;
return 0;
}

//With Arguments &amp; without Return Value


#include <stdio.h>
int sum = 0;
int getSum(int n)
{
while (n != 0) {
sum = sum + n % 10;
n = n / 10;
}
return;
}
int main()
{
int n = 687;
getSum(n);
printf(" %d ", (sum));
sum = 0;
return 0;
}

//With Arguments &amp; with Return Value


#include <stdio.h>
int getSum(int n)
{ int sum = 0;
while (n != 0) {
sum = sum + n % 10;
n = n / 10;
}
return sum;
}

// Driver code
int main()
{
int n = 2816;
printf(" %d ", (getSum(n)));
return 0;
}

2. Write a program with Recursive Function for Generation of Fibonacci series.


#include<stdio.h>
int main()
{
int first=0, second=1, i, n, sum=0;
printf("Enter the number of terms: ");
scanf("%d",&n);
//accepting the terms
printf("Fibonacci Series:");
for(i=0 ; i<n ; i++)
{
if(i <= 1)
{
sum=i;
}
//to print 0 and 1
else
{
sum=first + second;
first=second;
second=sum;
}
printf(" %d",sum);
}
return 0;
}

3. Write a program to convert a binary number to octal and vice-versa using Functions.
#include <stdio.h>
int main()
{
long int binarynum, octalnum = 0, j = 1, remainder;
printf("Enter the value for binary number: ");
scanf("%ld", &binarynum);
while (binarynum != 0)
{
remainder = binarynum % 10;
octalnum = octalnum + remainder * j;
j = j * 2;
binarynum = binarynum / 10;
}
printf("Equivalent octal value: %lo", octalnum);
return 0;
}

4. Write a program to check whether a number can be expressed as the sum of two prime
numbers.
#include <stdio.h>
int checkPrime(int n);
int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 2; i <= n / 2; ++i) {
// condition for i to be a prime number
if (checkPrime(i) == 1) {
// condition for n-i to be a prime number
if (checkPrime(n - i) == 1) {
printf("%d = %d + %d\n", n, i, n - i);
flag = 1;
}
}
}

if (flag == 0)
printf("%d cannot be expressed as the sum of two prime numbers.", n);

return 0;
}

// function to check prime number


int checkPrime(int n) {
int i, isPrime = 1;

// 0 and 1 are not prime numbers


if (n == 0 || n == 1) {
isPrime = 0;
}
else {
for(i = 2; i <= n/2; ++i) {
if(n % i == 0) {
isPrime = 0;
break;
}
}
}

return isPrime;
}
5. Write a program to find G.C.D. using recursion.
#include <stdio.h>
int hcf(int n1, int n2);
int main() {
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1, n2));
return 0;
}
int hcf(int n1, int n2) {
if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1;
}
Lab Assignment 8

1. Write a program to swap two numbers using pointers.


#include <stdio.h>
void swap(int *x,int *y)
{
int t;
t = *x;
*x = *y;
*y = t;
}
int main()
{
int num1,num2;
printf("Enter value of num1: ");
scanf("%d",&num1);
printf("Enter value of num2: ");
scanf("%d",&num2);
printf("Before Swapping: num1 is: %d, num2 is: %d\n",num1,num2);
swap(&num1,&num2);
printf("After Swapping: num1 is: %d, num2 is: %d\n",num1,num2);
return 0;
}

2. Write a program to copy one array to another using pointers.


#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
/* Function declaration to print array */
void printArray(int arr[], int size);
int main()
{
int source_arr[MAX_SIZE], dest_arr[MAX_SIZE];
int size, i;

int *source_ptr = source_arr; // Pointer to source_arr


int *dest_ptr = dest_arr; // Pointer to dest_arr
int *end_ptr;
printf("Enter size of array: ");
scanf("%d", &size);
printf("Enter elements in array: ");
for (i = 0; i < size; i++)
{
scanf("%d", (source_ptr + i));
}
// Pointer to last element of source_arr
end_ptr = &source_arr[size - 1];
/* Print source and destination array before copying */
printf("\nSource array before copying: ");
printArray(source_arr, size);
printf("\nDestination array before copying: ");
printArray(dest_arr, size);
while(source_ptr <= end_ptr)
{
*dest_ptr = *source_ptr;
source_ptr++;
dest_ptr++;
}
/* Print source and destination array after copying */
printf("\n\nSource array after copying: ");
printArray(source_arr, size);
printf("\nDestination array after copying: ");
printArray(dest_arr, size);
return 0;
}

/**
* Function to print array elements.
*
* @arr Integer array to print.
* @size Size of array.
*/
void printArray(int *arr, int size)
{
int i;

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


{
printf("%d, ", *(arr + i));
}
}
3. Write a program to reverse a string using pointers.
#include<stdio.h>
int string_length(char*);
void reverse(char*);
main()
{
char string[100];
printf("Enter a string\n");
gets(string);
reverse(string);
printf("Reverse of entered string is \"%s\".\n", string);
return 0;
}
void reverse(char *string)
{
int length, c;
char *begin, *end, temp;
length = string_length(string);
begin = string;
end = string;
for ( c = 0 ; c < ( length - 1 ) ; c++ )
end++;
for ( c = 0 ; c < length/2 ; c++ )
{
temp = *end;
*end = *begin;
*begin = temp;
begin++;
end--;
}
}
int string_length(char *pointer)
{
int c = 0;
while( *(pointer+c) != '\0' )
c++;
return c;
}

4. Write a program to find length of a string using pointers.


#include<stdio.h>
int stringLengthUsingPointer(char*);
int main() {
char str[100];
int len;
printf("\nEnter string : ");
gets(str);
len = stringLengthUsingPointer(str);
printf("The length of the string %s is : %d", str, len);
return 0;
}
int stringLengthUsingPointer(char*p) /* p=&str[0] */
{
int count = 0;
while (*p != '\0') {
count++;
p++;
}
return count;
}
Lab Assignment 9

1. Write a program to store information of a Student using Structure.


#include <stdio.h>
struct student {
char firstName[50];
int roll;
float marks;
} s[5];
int main() {
int i;
printf("Enter information of students:\n");
// storing information
for (i = 0; i < 5; ++i) {
s[i].roll = i + 1;
printf("\nFor roll number%d,\n", s[i].roll);
printf("Enter first name: ");
scanf("%s", s[i].firstName);
printf("Enter marks: ");
scanf("%f", &s[i].marks);
}
printf("Displaying Information:\n\n");
// displaying information
for (i = 0; i < 5; ++i) {
printf("\nRoll number: %d\n", i + 1);
printf("First name: ");
puts(s[i].firstName);
printf("Marks: %.1f", s[i].marks);
printf("\n");
}
return 0;
}
2. Write a program to add Two Complex Numbers by Passing Structure to a Function.
#include<stdio.h>
/* Declaring Structure */
struct complex
{
float real;
float imaginary;
};
int main()
{
/* Declaring structure variable using struct complex */
struct complex cnum1, cnum2, sum;
printf("Enter real and imaginary part of first complex number:\n");
scanf("%f%f", &cnum1.real, &cnum1.imaginary);
printf("Enter real and imaginary part of second complex number:\n");
scanf("%f%f", &cnum2.real, &cnum2.imaginary);
sum.real = cnum1.real + cnum2.real;
sum.imaginary = cnum1.imaginary + cnum2.imaginary;
printf("SUM = %0.2f + %0.2f i", sum.real, sum.imaginary);
return 0;
}
3. Write a program to find total and average of sales of all employees using array of
structure.
#include <stdio.h>
#include <stdlib.h>
typedef struct{
char name[30];
int sales;
} Employee;
int main()
{
//number of employees
int n=3, sum=0, avg;
//array to store structure values of all employees
Employee employees[n];
//Taking each employee detail as input
printf("Enter %d Employee Details \n \n",n);
for(int i=0; i<n; i++){
printf("Employee %d:- \n",i+1);
//Name
printf("Name: ");
scanf("%[^\n]s",employees[i].name);
//Salary
printf("Sales: ");
scanf("%d",&employees[i].sales);
sum=sum+employees[i].sales;
//to consume extra '\n' input
char ch = getchar();
printf("\n");
}
//Displaying Employee details
printf("-------------- All Employees Details ---------------\n");
for(int i=0; i<n; i++){
printf("Name \t: ");
printf("%s \n",employees[i].name);
printf("Sales \t: ");
printf("%d \n",employees[i].sales);
printf("\n");
}
printf("total=%d",sum);
printf("\n");
avg=sum/n;
printf("average=%d",avg);
return 0;
}
4. Write a program to compare two structure variables.

#include<stdio.h>
struct class
{
int number; char name[20];
float marks;
};
main()
{
int x;
//Declaring and initializing structures of 'class' type
struct class student2 = {2, "Shubhi", 78.00};
struct class student3;
student3 = student2; // Copying student2 to student3
if ((student3.number = student2.number) && (student3.marks = student2.marks)) // verifying results of copy
{
printf("\n student2 and student3 are equal");
printf("%d %s %f\n", student3.number, student3.name, student3.marks);
}
else
printf("\n student2 and student3 are different");
}

You might also like