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

algo lab

This document contains a collection of C programming code snippets that demonstrate various algorithms and functions, including generating Fibonacci numbers, reversing numbers, converting binary to decimal, calculating trigonometric functions without built-in functions, and more. Each code snippet is accompanied by a description of its functionality and example output. The document serves as a practical guide for implementing common programming tasks and algorithms in C.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

algo lab

This document contains a collection of C programming code snippets that demonstrate various algorithms and functions, including generating Fibonacci numbers, reversing numbers, converting binary to decimal, calculating trigonometric functions without built-in functions, and more. Each code snippet is accompanied by a description of its functionality and example output. The document serves as a practical guide for implementing common programming tasks and algorithms in C.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

1.

Generate Nth Fibonacci Number

#include <stdio.h>
int fibonacci(int n)
{
if (n <= 1)
return n;
int a = 0, b = 1, c;
for (int i = 2; i <= n; i++)
{ c = a + b; a = b; b = c;
}
return b;
} int main()
{
int n;
printf("Enter the position of Fibonacci number: ");
scanf("%d", &n);
printf("Fibonacci number at position %d is %d\n", n, fibonacci(n));
return 0;
}

Output

Enter the position of Fibonacci number: 312


Fibonacci number at position 312 is 1911599776`

Algorithm to Generate Nth Fibonacci Number

1. Input: Read an integer NNN (the position of the Fibonacci number).


2. Initialization:
o Set a=0a = 0a=0 (first Fibonacci number).
o Set b=1b = 1b=1 (second Fibonacci number).
o If N=0N = 0N=0, return aaa.
o If N=1N = 1N=1, return bbb.
3. Loop: For iii from 2 to NNN:
o Calculate c=a+bc = a + bc=a+b (next Fibonacci number).
o Update a=ba = ba=b (previous number becomes the current).
o Update b=cb = cb=c (current becomes the next).
4. Output: Return bbb (Nth Fibonacci number)
+-------------------+
| Start |
+-------------------+
|
v
+-------------------+
| Input N |
+-------------------+
|
v
+-------------------+
| a = 0, b = 1 |
+-------------------+
|
v
+-------------------+
| Is N == 0? |
+-------------------+
| |
Yes No
| |
v |
+-------------------+
| Output a (0) |
+-------------------+
|
v
+-------------------+
| Is N == 1? |
+-------------------+`
| |
Yes No
| |`
v |
+-------------------+
| Output b (1) |
+-------------------+
|
v
+-------------------+
| Loop i from 2 to N|
+-------------------+
|
v
+-------------------+
|c=a+b |
+-------------------+
|
v
+-------------------+
|a=b |
+-------------------+
|
v
+-------------------+
|b=c |
+-------------------+
|
v
+-------------------+
| Output b |
+-------------------+
|
v
+-------------------+
| End |``
+-------------------+

2. Reverse the Given Decimal Number

#include <stdio.h>

int reverseNumber(int n) {
int reversed = 0;
while (n != 0) {
reversed = reversed * 10 + n % 10;
n /= 10;
}
return reversed;
}
int main() {
int n;
printf("Enter a decimal number: ");
scanf("%d", &n);
printf("Reversed number: %d\n", reverseNumber(n));
return 0;
}

Output
Enter a decimal number: 12345
Reversed number: 54321

3.Convert Binary Number to Decimal Number

#include <stdio.h>

int binaryToDecimal(int binary)

int decimal = 0, base = 1;

while (binary > 0) {

decimal += (binary % 10) * base;

binary /= 10;

base *= 2;

return decimal;

}
int main() {

int binary;

printf("Enter a binary number: ");

scanf("%d", &binary);

printf("Decimal equivalent: %d\n", binaryToDecimal(binary));

return 0;

Output
Enter a binary number: 1234
Decimal equivalent: 26

4.Calculate Sin(x) Value Without Using In-Built Function

#include <stdio.h>

double factorial(int n) {

double result = 1;

for (int i = 1; i <= n; i++)

result *= i;

return result;

double sinx(double x) {

double result = 0;

for (int n = 0; n < 10; n++) {


double term = (n % 2 == 0 ? 1 : -1) * (pow(x, 2 * n + 1) / factorial(2 * n + 1));

result += term;

return result;

int main() {

double x;

printf("Enter angle in radians: ");

scanf("%lf", &x);

printf("sin(%lf) = %lf\n", x, sinx(x));

return 0;

output

Enter angle in radians: 5


sin(5.000000) = -0.958933

5. Calculate Cos(x) Value Without Using In-Built Function

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void main()
{
int n, x1;
float accuracy, term, denominator, x, cosx, cosval;
printf("Enter the value of x (in degrees) \n");
scanf("%f", &x);
x1 = x;
/* Converting degrees to radians */
x = x * (3.142 / 180.0);
cosval = cos(x);
printf("Enter the accuracy for the result \n");
scanf("%f", &accuracy);
term = 1;
cosx = term;
n = 1;
do
{
denominator = 2 * n * (2 * n - 1);
term = -term * x * x / denominator;
cosx = cosx + term;
n = n + 1;
} while (accuracy <= fabs(cosval - cosx));
printf("Sum of the cosine series = %f\n", cosx);
printf("Using Library function cos(%d) = %f\n", x1, cos(x));
}

Output
Enter the value of x (in degrees)
60
Enter the accuracy for the result
0.86602
Sum of the cosine series = 0.451546
Using Library function cos(60) = 0.499882

6. Calculate Tan(x) Value Without Using In-Built Function

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

int main()
{
// 30 degrees in radians
double a = M_PI / 6;
// 45 degrees in radians
double b = M_PI / 4;
// 60 degrees in radians
double c = M_PI / 3;
// 90 degrees in radians
double d = M_PI / 2;
// Variable to store the results
double res;

res = tan(a);
printf("The tangent of %.3lf radians (30 degrees) is "
"%.3lf\n",
a, res);

res = tan(b);
printf("The tangent of %.3lf radians (45 degrees) is "
"%.3lf\n",
b, res);

res = tan(c);
printf("The tangent of %.3lf radians (60 degrees) is "
"%.3lf\n",
c, res);

res = tan(d);
printf("The tangent of %.3lf radians (90 degrees) is "
"%.3lf\n",
d, res);

return 0;
}
output
The tangent of 0.524 radians (30 degrees) is 0.577
The tangent of 0.785 radians (45 degrees) is 1.000
The tangent of 1.047 radians (60 degrees) is 1.732
The tangent of 1.571 radians (90 degrees) is 16331239353195370.000
7. Calculate GCD of Two Numbers
#include <stdio.h>

int gcd(int a, int b) {


while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}

int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("GCD of %d and %d is %d\n", a, b, gcd(a, b));
return 0;
}

Output
Enter two numbers: 2 5
GCD of 2 and 5 is 1

8.Generate Prime Numbers

#include <stdio.h>

void generatePrimes(int n) {
for (int num = 2; num <= n; num++) {
int isPrime = 1;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
isPrime = 0;
break;
}
}
if (isPrime) {
printf("%d ", num);
}
}
printf("\n");
}

int main() {
int n;
printf("Enter the range to generate prime numbers: ");
scanf("%d", &n);
printf("Prime numbers up to %d are: ", n);
generatePrimes(n);
return 0;
}

output
Enter the range to generate prime numbers: 100
Prime numbers up to 100 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61
67 71 73 79 83 89 97

9. Find Square Root of a Number Without Using In-Built Function

#include <stdio.h>

double squareRoot(double n) {
double low = 0, high = n, mid;
double epsilon = 0.00001;
while (high - low > epsilon) {
mid = (low + high) / 2;
if (mid * mid < n) {
low = mid;
} else {
high = mid;
}
}
return mid;
}

int main() {
double n;
printf("Enter a number: ");
scanf("%lf", &n);
printf("Square root of %lf is approximately %lf\n", n, squareRoot(n));
return 0;
}

output
Enter a number: 32
Square root of 32.000000 is approximately 5.65685

10. Convert Character to ASCII Code

#include <stdio.h>
int main() {
char c;
printf("Enter a character: ");
scanf(" %c", &c);
printf("ASCII value of '%c' is %d\n", c, (int)c);
return 0;
}

output
Enter a character: a
ASCII value of 'a' is 97

11. Partition an Array

#include <stdio.h>

void partition(int arr[], int n, int pivot) {


int i = 0, j = 0;
while (i < n) {
if (arr[i] < pivot) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
j++;
}
i++;
}
}

int main() {
int arr[] = {5, 3, 8, 4, 2};
int n = sizeof(arr) / sizeof(arr[0]);
int pivot = 4;
partition(arr, n, pivot);
printf("Partitioned array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}

output
Partitioned array: 3 2 8 4 5

12. Remove Duplicate Elements from an Array

#include <stdio.h>
void removeDuplicates(int arr[], int* n) {
int temp[*n];
int j = 0;

for (int i = 0; i < *n; i++) {


int found = 0;
for (int k = 0; k < j; k++) {
if (arr[i] == temp[k]) {
found = 1;
break;
}
}
if (!found) {
temp[j++] = arr[i];
}
}

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


arr[i] = temp[i];
}
*n = j;
}

int main() {
int arr[] = {1, 2, 3, 2, 1, 4};
int n = sizeof(arr) / sizeof(arr[0]);
removeDuplicates(arr, &n);
printf("Array after removing duplicates: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}

Output
Array after removing duplicates: 1 2 3 4

13. Count Duplicate Elements from an Array

#include <stdio.h>
void countDuplicates(int arr[], int n) {
int count[n];
for (int i = 0; i < n; i++) {
count[i] = 1; // Initialize counts
}

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


for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
count[i]++;
count[j] = -1; // Mark as counted
}
}
}
printf("Duplicate elements and their counts:\n");
for (int i = 0; i < n; i++) {
if (count[i] > 1) {
printf("%d occurs %d times\n", arr[i], count[i]);
}
}
}

int main() {
int arr[] = {1, 2, 3, 2, 1, 4, 1};
int n = sizeof(arr) / sizeof(arr[0]);
countDuplicates(arr, n);
return 0;
}

Output

Duplicate elements and their counts:


1 occurs 3 times
2 occurs 2 times

14. Calculate Prime Factors of a Number

#include <stdio.h>
void primeFactors(int n) {
printf("Prime factors of %d are: ", n);
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
printf("%d ", i);
n /= i;
}
}
printf("\n");
}

int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
primeFactors(n);
return 0;
}

Output
Enter a number: 45
Prime factors of 45 are: 3 3 5

15. Reverse an Array

#include <stdio.h>
void reverseArray(int arr[], int n) {
int start = 0, end = n - 1;
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
reverseArray(arr, n);
printf("Reversed array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}

output

Reversed array: 5 4 3 2 1
16. Calculate kth Smallest Number in an Array

#include <stdio.h>
#include <limits.h>

int kthSmallest(int arr[], int n, int k) {


for (int i = 0; i < k; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
return arr[k - 1];
}

int main() {
int arr[] = {7, 10, 4, 3, 20, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3; // Find 3rd smallest
printf("The %dth smallest element is %d\n", k, kthSmallest(arr, n, k));
return 0;
}

Output

The 3th smallest element is 7

17. Implement Merge Sort

#include <stdio.h>
void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;

int L[n1], R[n2];


for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];

i = 0;
j = 0;
k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k++] = L[i++];
} else {
arr[k++] = R[j++];
}
}
while (i < n1) arr[k++] = L[i++];
while (j < n2) arr[k++] = R[j++];
}

void mergeSort(int arr[], int left, int right) {


if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}

int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, n - 1);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
output

Sorted array: 5 6 7 11 12 13

18. Find Minimum and Maximum Among Given Set

#include <stdio.h>
#include <limits.h>

void findMinMax(int arr[], int n, int* min, int* max) {


*min = INT_MAX;
*max = INT_MIN;
for (int i = 0; i < n; i++) {
if (arr[i] < *min) *min = arr[i];
if (arr[i] > *max) *max = arr[i];
}
}

int main() {
int arr[] = {12, 3, 5, 7, 19};
int n = sizeof(arr) / sizeof(arr[0]);
int min, max;
findMinMax(arr, n, &min, &max);
printf("Minimum: %d, Maximum: %d\n", min, max);
return 0;
}

output
Minimum: 3, Maximum: 19
19. Perform Quick Sort

#include <stdio.h>
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return (i + 1);
}

void quickSort(int arr[], int low, int high) {


if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}

output

Sorted array: 1 5 7 8 9 10

20. Array Counting Using Histogram

#include <stdio.h>

void histogram(int arr[], int n, int range) {


int hist[range + 1];
for (int i = 0; i <= range; i++) hist[i] = 0;

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


hist[arr[i]]++;
}

printf("Value\tCount\n");
for (int i = 0; i <= range; i++) {
if (hist[i] > 0) {
printf("%d\t%d\n", i, hist[i]);
}
}
}

int main() {
int arr[] = {1, 2, 2, 3, 1, 4, 5, 4};
int n = sizeof(arr) / sizeof(arr[0]);
int range = 5; // Max value in arr
histogram(arr, n, range);
return 0;
}

output

Value Count
1 2
2 2
3 1
4 2
5 1

You might also like