NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

1.1.
OBJECTIVE: TO IMPLEMENT CONJUNCTION, DISJUNCTION AND NEGATION.
THEORY:
Conjunction, typically represented as "∧" or "AND" in logic, is a fundamental logical operation that involves combining two individual propositions or statements. It yields a true result if and only if both of the input propositions are true simultaneously. In essence, conjunction represents a logical "and" relationship, ensuring that both conditions must be met for the combined statement to be considered true.


Disjunction, often symbolized as "∨" or "OR," is another fundamental operation in logic where two propositions are combined. Unlike conjunction, disjunction results in a true value if at least one of the input propositions is true. In other words, it represents a logical "or" relationship, indicating that the combined statement is true if either or both of the conditions are satisfied.


Negation, represented as "¬" or "NOT," is a unary operation that operates on a single proposition. It essentially reverses the truth value of the input proposition, turning true into false and false into true. Negation is a straightforward way to express the negation or denial of a statement, providing a means to represent the opposite or contradictory condition to the original proposition.


SOURCE CODE:
#include <stdio.h>
int main() {
int p, q;
// Print header for the truth table
printf("ptqt p ^ qt p V qt -pn");
printf("_______________________________________ n");

// Loop through all possible values of p and q (0 for false, 1 for true)
for (p = 0; p <= 1; p++) {
for (q = 0; q <= 1; q++) {
// Calculate the results of logical operations
int andResult = p && q; // Conjunction (AND)
int orResult = p || q; // Disjunction (OR)
int notPResult = !p; // Negation (NOT)

// Convert integer results into 'T' for true and 'F' for false
char andChar = (andResult) ? 'T' : 'F';
char orChar = (orResult) ? 'T' : 'F';
char notPChar = (notPResult) ? 'T' : 'F';

// Print the values and results in the truth table
printf("%ct%ct %ct %ct %cn", (p == 1) ? 'T' : 'F', (q == 1) ? 'T' : 'F', andChar, orChar, notPChar);
}
}

return 0;
}

OUTPUT AND DISCUSSION:


This program generates a truth table for the logical operations AND, OR, and NOT. It iterates through all possible combinations of two binary variables, p and q(F or T), and displays the results of these operations in a neatly formatted table with headers. This table helps illustrate how these fundamental logical operations behave for different input values, facilitating comprehension of Boolean logic principles.

CONCLUSION:
Hence, in this way we can implement conjunction, disjunction and negation.





1.2.
OBJECTIVE: TO IMPLEMENT IMPLICATION AND BICONDITIONAL.
THEORY:
Implication, often denoted as "→" or expressed as "if...then," is a fundamental logical operation in which the truth of one proposition (the antecedent) implies the truth of another proposition (the consequent). In an implication, if the antecedent is true, the consequent must also be true for the entire statement to be true. However, if the antecedent is false, the statement is considered true regardless of the truth value of the consequent. This relationship is a fundamental concept in logic and is used extensively in mathematics, philosophy, and computer science for conditional reasoning.
Truth Table:
p q p →q
T T T
T F F
F T T
F F T

Biconditional, denoted as "↔" or expressed as "if and only if," is another important logical operation that signifies that two propositions are both true or both false, creating a bidirectional relationship between them. In a biconditional statement, if one proposition is true, the other must also be true, and if one is false, the other must be false. It asserts that the two propositions have the same truth value and are inherently connected, providing a means to express equivalence or mutual exclusivity between statements. The biconditional is commonly used in mathematics and formal logic to establish logical equivalences and define necessary and sufficient conditions.
p q p ↔ q
T T T
T F F
F T F
F F T
Truth Table:





SOURCE CODE:
#include <stdio.h>
int main() {
int p, q;

// Print headers for the truth tables
printf("ptqt p -> qt p <-> qn");
printf("__________________________________n");
// Loop through all possible values of p and q (0 for false, 1 for true)
for (p = 0; p <= 1; p++) {
for (q = 0; q <= 1; q++) {
// Calculate the results of logical operations
int implicationResult = !p || q; // Implication (p -> q)
int biconditionalResult = (!p || q) && (!q || p); // Biconditional (p <-> q)

// Convert integer results into 'T' for true and 'F' for false
char implicationChar = (implicationResult) ? 'T' : 'F';
char biconditionalChar = (biconditionalResult) ? 'T' : 'F';

// Print the values and results in the truth tables
printf("%ct%ct %ct %cn", (p == 1) ? 'T' : 'F', (q == 1) ? 'T' : 'F', implicationChar, biconditionalChar);
}
}

return 0;
}

OUTPUT AND DISCUSSION:



In this program, we calculated the truth values for implication (p → q) and biconditional (p ↔ q) based on the values of p and q. We used nested loops to iterate through all possible combinations of p and q, where both variables can be either F(false) or T(true). The truth tables are displayed with proper headers and formatting.

CONCLUSION:
Hence, in this way we can implement implication and biconditional.





1.3.
OBJECTIVE: TO GENERATE THE TRUTH TABLE OF GIVEN PREPOSITIONS.
i) [ ( p→ q) ∧(q→ r) ] → (p→ r)
ii) (p→ r) ∨ (q→ r)
THEORY: In the above given prepositions, AND(∧) , OR (V) & IMPLICATION (→) are used.
AND (Conjunction): "AND" requires all conditions to be true simultaneously.
OR (Disjunction): "OR" necessitates at least one condition to be true.
IMPLICATION (Conditional): "IMPLICATION" asserts that one statement guarantees another under specific conditions.
SOURCE CODE:
// For [ ( p→ q) ∧(q→ r) ] → (p→ r)
#include<stdio.h>
#include <stdio.h>

int main() {
int p, q, r;
printf("ptqtrtp->qtq->rtp->rt(p->q)^(q->r)t[(p->q)^(q->r)]->(p->r)n");
printf("__________________________________________________________________________n");
// Loop through all possible values of p, q, and r (0 for false, 1 for true)
for (p = 0; p <= 1; p++) {
for (q = 0; q <= 1; q++) {
for (r = 0; r <= 1; r++) {

// Calculate the results of logical operations
int implicationResultpq = !p || q; // Implication (p -> q)
int implicationResultqr = !q || r; // Implication (q -> r)
int implicationResultpr = !p || r; // Implication (p -> r)
int andresultpqr = implicationResultpq && implicationResultqr; // Conjunction (AND)
int implicationpqr = andresultpqr <= implicationResultpr; // Main implication (->)

// Convert integer results into 'F' for false and 'T' for true
char implicationResultpqChar = (implicationResultpq) ? 'T' : 'F';
char implicationResultqrChar = (implicationResultqr) ? 'T' : 'F';
char implicationResultprChar = (implicationResultpr) ? 'T' : 'F';
char andresultpqrChar = (andresultpqr) ? 'T' : 'F';
char implicationpqrChar = (implicationpqr) ? 'T' : 'F';

// Print the values and results in the table
printf("%ct%ct%ct %ct %ct %ct %cttt %cn",
(p == 1) ? 'T' : 'F',
(q == 1) ? 'T' : 'F',
(r == 1) ? 'T' : 'F',
implicationResultpqChar,
implicationResultqrChar,
implicationResultprChar,
andresultpqrChar,
implicationpqrChar);
}
}
}
return 0;
}

// For (p->r) V (q->r)

#include <stdio.h>

int main() {
int p, q, r;
printf("ptqtrtp->rtq->rt(p->r) V (q->r)n");
printf("__________________________________________________________n");

// Loop through all possible values of p, q, and r (0 for false, 1 for true)
for (p = 0; p <= 1; p++) {
for (q = 0; q <= 1; q++) {
for (r = 0; r <= 1; r++) {
// Calculate the results of logical operations
int implicationResultpr = !p || r; // Implication (p -> r)
int implicationResultqr = !q || r; // Implication (q -> r)
int orresultpqr = implicationResultpr || implicationResultqr; // Disjunction (OR)

// Convert integer results into 'F' for false and 'T' for true
char implicationResultprChar = (implicationResultpr) ? 'T' : 'F';
char implicationResultqrChar = (implicationResultqr) ? 'T' : 'F';
char orresultpqrChar = (orresultpqr) ? 'T' : 'F';

// Print the values and results in the table
printf("%ct%ct%ct %ct %ct %cn",
(p == 1) ? 'T' : 'F',
(q == 1) ? 'T' : 'F',
(r == 1) ? 'T' : 'F',
implicationResultprChar,
implicationResultqrChar,
orresultpqrChar);
}
}
}
return 0;
}

OUTPUT AND DISCUSSION:



The first program is designed to evaluate and print the truth values of the logical expression [(p → q) ∧ (q → r)] → (p → r). It does so by iterating through all possible combinations of truth values for p, q, and r, calculating the intermediate results of implication and conjunction, and finally, determining the overall result of the implication. The program provides a clear table showing the values and results for each combination, which helps in understanding the behavior of the given logical expression.The second program, on the other hand, evaluates and prints the truth values of the logical expression (p → r) ∨ (q → r). Similar to the first program, it iterates through all possible combinations of truth values for p, q, and r, calculates the intermediate results of implication, and then computes the overall result using logical disjunction (OR). The program presents the results in a table, allowing for a straightforward analysis of the given logical expression.
In summary, both programs provide a systematic approach to assess and visualize the truth values of complex logical expressions, making it easier to comprehend the logic and outcomes associated with different truth value combinations of the variables involved.

CONCLUSION:
Hence, In this way, we can calculate the truth values of different given prepositions.
1.4.
OBJECTIVE: TO CHECK WHETHER THE GIVEN PREPOSITION IS TAUTOLOGY, CONTRADICTION OR CONTINGENCY.
THEORY:
Tautology is a statement that is always true, regardless of the circumstances. In other words, it is a statement that cannot be false. An example of a tautology is "A bachelor is an unmarried man." This statement is inherently true because the definition of a bachelor includes being unmarried. Tautologies are often used in logic and mathematics to establish certain truths or as a basis for reasoning.

Contradiction, on the other hand, is a statement that is always false, regardless of the circumstances. It is a statement that cannot be true. An example of a contradiction is "A married man is not married." This statement is inherently false because it directly contradicts itself. Contradictions are important in logic as they help identify flawed arguments or inconsistent beliefs.

Contingency is a statement that is neither a tautology nor a contradiction; its truth value depends on specific conditions or circumstances. For instance, the statement "It will rain tomorrow" is contingent because its truth depends on the actual weather conditions that occur tomorrow. Contingent statements are common in everyday life and are the focus of much empirical investigation and prediction in various fields, such as meteorology, economics, and science, where outcomes are uncertain and dependent on multiple factors.
SOURCE CODE:
#include <stdio.h>
void display(bool q) {
if (q == true)
printf("Tt");
else
printf("Ft");
}
bool isTautology(bool expr[]){
for(int i=0; i<8; i++){
if(!expr[i])
return false;
}
return true;
}

// Checks if expression is contradiction
bool isContradiction(bool expr[]){
for(int i=0; i<8; i++){
if(expr[i])
return false;
}
return true;
}

// Checks if expression is contingency
bool isContingency(bool expr[]){
int trueCount = 0, falseCount = 0;
for(int i=0; i<8; i++){
if(expr[i])
trueCount++;
else
falseCount++;
}

return (trueCount != 0 && falseCount != 0);
}
int main() {
bool exp1[8], exp3[8];
bool p[] = { true, true, true, true, false, false, false, false };
bool q[] = { true, true, false, false, true, true, false, false };
bool r[] = { true, false, true, false, true, false, true, false };
bool x;
int i;
printf("npt qt rt p->qt q->rt (p->q)^(q->r)t p->rt ((p->q)^(q->r))->(p->r)t(p->r)v(q->r)n");
printf("______________________________________________________________n");
for (i = 0; i < 8; i++) {
display(p[i]);
display(q[i]);
display(r[i]);
display((!p[i] || q[i]));
display((!q[i] || r[i]));
printf("t");
display((!p[i] || q[i]) && (!q[i] || r[i]));
display(!p[i] || r[i]);
x = (!p[i] || q[i] && (!q[i] || r[i]));
printf("t");
display(!x || (!p[i] || r[i]));
printf("ttt");
display((!p[i] || r[i]) || (!q[i] || r[i]));
exp1[i] = (!x || (!p[i] || r[i]));
exp3[i] = ((!p[i] || r[i]) || (!q[i] || r[i]));
printf("n");
}
if (isTautology(exp1))
{
printf("Tautology : ((p->q)^(q->r)->(p->r))n");
}
if (isContingency(exp3))
{
printf("Contingency : (p->r) v (q->r) ");
}
return 0;
}

OUTPUT AND DISCUSSION:


This program effectively analyzes logical expressions involving three boolean variables (p, q, and r), computes their truth values, and determines whether the expression ((p->q)^(q->r)->(p->r)) is a tautology and whether (p->r) v (q->r) is a contingency. It showcases the versatility of boolean logic and highlights the tautological nature of the first expression, always true, and the contingency of the second expression, varying between true and false depending on input values.

CONCLUSION:
Hence, in this way we can check whether the given preposition is either tautology, contradiction or contingency.











2.1.
OBJECTIVE: TO IMPLEMENT EUCLIDEAN ALGORITHM.
THEORY: The Euclidean Algorithm is a method for finding the greatest common divisor (GCD) of two integers. The GCD of two numbers is the largest positive integer that divides both of them without leaving a remainder. The Euclidean Algorithm is one of the oldest and most efficient algorithms for this purpose.
The Euclidean Algorithm is efficient because it reduces the problem of finding the GCD of two large numbers to a series of much smaller divisions, which can be computed relatively quickly. It has numerous applications in number theory, cryptography, and various areas of computer science and mathematics.

SOURCE CODE:
#include<stdio.h>
int main()
{
int a,b,r;
printf("Enter two numbers:n");
scanf("%d%d",&a,&b);
while(b>0){
r=a % b;
a=b;
b=r;
}
printf("The GCD is: %d",a);
return 0;
}


OUTPUT AND DISCUSSION:


This code efficiently calculates and displays the greatest common divisor (GCD) of two input numbers using the Euclidean Algorithm.

CONCLUSION:
In this way, we can calculate the GCD of any two numbers using Euclidean Algorithm.






2.2.
OBJECTIVE: TO IMPLEMENT EXTENDED EUCLIDEAN ALGORITHM.
THEORY:
The Extended Euclidean Algorithm is an extension of the Euclidean Algorithm that not only finds the greatest common divisor (GCD) of two integers but also computes two additional integers, often denoted as x and y, such that ax + by = GCD (a, b).It works by iteratively applying the Euclidean Algorithm while maintaining two sets of coefficients (x and y) and updating them in each step until the GCD becomes 1. The coefficients x and y can then be used to solve various diophantine equations and modular arithmetic problems.
SOURCE CODE:
#include <stdio.h>

int main()
{
int a, b, x, y, x1 = 0, y1 = 1, x2 = 1, y2 = 0, q, r;
printf("Enter two numbers: n");
scanf("%d %d", &a, &b);
if (b == 0)
printf("GCD is %d, x is 1, and y is 0n", a);
else {
while (b > 0) {
q = a / b;
r = a - q * b;
x = x2 - q * x1;
y = y2 - q * y1;
a = b;
b = r;
x2 = x1;
y2 = y1;
x1 = x;
y1 = y;
}
printf("GCD is %d, while x is %d and y is %d.n", a, x2, y2);
}

return 0;
}






OUTPUT AND DISCUSSION:


This program efficiently calculates the greatest common divisor (GCD) of two input numbers using the Extended Euclidean Algorithm. It also provides values for ‘x’ and ‘y’ that satisfy the equation ax + by = GCD(a, b). The program also handles cases where the second input (b) is zero, ensuring a clear output for such situations.

CONCLUSION:
So, in this way, we can find GCD of any two numbers using the Extended Euclidean Algorithm technique.














2.3.
OBJECTIVE: TO IMPLEMENT ADDITION AND MULTIPLICATION ALGORITHM FOR TWO BINARY NUMBERS.
THEORY:
Binary numbers are a foundational concept in the realm of digital computing, serving as the fundamental language of computers and electronic devices. Unlike our familiar decimal system, which employs ten digits (0-9), binary operates with just two digits, 0 and 1. This simplicity belies its crucial role, as binary code represents the basis for encoding and processing all data in the digital world. Understanding binary numbers is essential for grasping how computers store and manipulate information, making it an indispensable concept in the modern age of technology.

SOURCE CODE:
#include <stdio.h>
int conveterBD(int n) {
int decimal = 0;
int base = 1;
while (n > 0) {
int lastDigit = n % 10;
n = n / 10;
decimal += lastDigit * base;
base = base * 2;
}
return decimal;
}
// Function to add two binary numbers
int addBinary(int a, int b){
int sum = conveterBD(a) + conveterBD(b);
return sum;
}
// Function for binary multiplication
int multiplyBinary(int a, int b){
int product = conveterBD(a) * conveterBD(b);
return product;
}
int bin(int n){
int binary[32];
int i = 0;
while (n > 0) {
binary[i] = n % 2;
n = n / 2;
i++;
}
for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]);
}
}
int main() {
int a,b,add,mul;
printf("Enter two number in binaryn");
scanf("%d %d",&a,&b);
add=addBinary(a,b);
mul=multiplyBinary(a,b);
printf("Addition in dec:t %d n", add);
printf("Multiplication in dec: t %d", mul);
printf("n");
printf("binary addition:");
bin(add);
printf(" binary multiplication:");
bin(mul);
return 0;
}
OUTPUT AND DISCUSSION:

This C program provides a straightforward binary addition and multiplication calculator, allowing users to input binary numbers and obtain their respective decimal results along with binary representations, demonstrating a basic understanding of binary arithmetic. It serves as a practical tool for binary operations while emphasizing the importance of conversion between binary and decimal number systems.

CONCLUSION:
In this way, we can implement addition and binary algorithm for two binary numbers.











2.4.
OBJECTIVE: TO FIND BOOLEAN JOIN AND MULTIPLICATION OF BOOLEAN MATRICES.
THEORY:
Boolean join (also known as Boolean OR operation) and Boolean multiplication (also known as Boolean AND operation) of Boolean matrices are fundamental operations in Boolean algebra and are often used in various computer science and logic applications:
Boolean Join, also referred to as the union operation, involves merging two matrices through the logical OR operation (A ∨ B). This operation results in a fresh matrix where each element is determined by applying the OR operation to the corresponding elements of the input matrices.
On the other hand, Boolean Multiplication, often termed the intersection operation, combines two matrices using the logical AND operation (A ∧ B). This operation produces a new matrix where each element is computed by applying the AND operation to the corresponding elements of the input matrices.


SOURCE CODE:
#include <stdio.h>
#include <stdbool.h>
#define RC 3

// Function for Boolean join of two matrices
bool join[RC][RC];

void boolJoin(bool A[RC][RC], bool B[RC][RC])
{
for(int i=0; i<RC; i++)
{
for(int j=0; j<RC; j++)
{
join[i][j] = A[i][j] || B[i][j];
printf("%d", join[i][j]);
}
printf("n");
}
}

void displayMatrix(bool a[RC][RC])
{
for(int i=0; i<RC; i++)
{
for(int j=0; j<RC; j++)
{
printf("%d", a[i][j]);
}
printf("n");
}
}

// Function for Boolean multiplication of two matrices
bool prod[RC][RC];

void boolMultiply(bool A[RC][RC], bool B[RC][RC])
{
for(int i=0; i<RC; i++)
{
for(int j=0; j<RC; j++)
{
prod[i][j] = false;
for(int k=0; k<RC; k++)
{
prod[i][j] = (prod[i][j] || (A[i][k] && B[k][j]));
}
printf("%d", prod[i][j]);
}
printf("n");
}
}

int main()
{
// Initialize sample 3x3 Boolean matrices with different values
bool A[RC][RC] = {{true, true, true}, {false, false, true}, {true, false, true}};
bool B[RC][RC] = {{false, true, false}, {false, true, false}, {true,true, true}};

printf("Matrix A :n");
displayMatrix(A);
printf("Matrix B :n");
displayMatrix(B);
printf("Bool Join:n");
boolJoin(A, B);
printf("Bool Product:n");
boolMultiply(A, B);

return 0;
}










OUTPUT AND DISCUSSION:


This C program demonstrates Boolean matrix operations, specifically Boolean join (union) and Boolean multiplication (intersection). It defines functions to perform these operations on two 3x3 Boolean matrices with different values. The ‘boolJoin’ function computes the union of the input matrices, printing the result, while the ‘boolMultiply’ function calculates the intersection and also displays the outcome. The program showcases how Boolean algebra can be applied to manipulate and analyze binary data, making it a valuable tool for logical and set-based operations.

CONCLUSION:
In this way, we can find Boolean join and multiplication of Boolean matrices.






3.1.
TO SOLVE THE RECURSIVE PROBLEMS.
OBJECTIVES:
3.1.1. TO FIND THE SUM OF FIRST N NAURAL NUMBERS.
3.1.2. TO FIND THE VALUE OF n! .
3.1.3. TO FIND THE nth FIBONACCI NUMBER.
3.1.4. TO FIND THE VALUE OF 12+22+32+42+…….+n2.
3.1.5. TO FIND POWER(a,b).
THEORY:
A recursive function is a function that calls itself to solve a problem by breaking it down into smaller, similar subproblems until a base case is reached, at which point the recursion stops. Recursive function consists of two primary components: the base case, which defines when the recursion terminates and returns a specific result, and the recursive case, where the function calls itself with modified arguments to solve subproblems. Recursive functions are widely used in C to solve problems with repetitive or hierarchical structures, such as factorial calculation, traversing linked lists or trees, and implementing various algorithms like quicksort and recursive descent parsing. Care must be taken to ensure that recursive functions have a proper termination condition to avoid infinite recursion.

3.1.1.
SOURCE CODE:
//program to find the sum of first n natural numbers
#include<stdio.h>
int sum(int n){
if(n==0)
return 0;
else
return n+sum(n-1);
}
int main(){
int n;
printf("Enter the number:");
scanf("%d",&n);
printf(" The Sum of first %d natural numbers is %dn",n,sum(n));
}


OUTPUT:



3.1.2.
SOURCE CODE:
//program to find the value of n!
#include<stdio.h>
int fact(int n){
if(n==0 || n==1)
return 1;
else
return n*fact(n-1);
}
int main()
{
int n;
printf("Enter the number:");
scanf("%d",&n);
printf("The factorial of %d is %dn",n,fact(n));
}

OUTPUT:





3.1.3.
SOURCE CODE:
//program to find the nth value of Fibonacci number
#include<stdio.h>
int fibo(int n){
if(n<=1)
return n;
else
return fibo(n-1)+fibo(n-2);
}

int main()
{
int n;
printf("Enter the number:");
scanf("%d",&n);
printf("The %dth term of fibonacci number is %d.n",n,fibo(n));
}
OUTPUT:


3.1.4.
SOURCE CODE:
//program to find the sum of square of n natural numbers
#include<stdio.h>
int sumsq(int n){
if(n==1)
return 1;
else
return n*n+sumsq(n-1);
}
int main()
{
int n;
printf("Enter the number:");
scanf("%d",&n);
printf("The sum of square of the first %d natural numbers is %d.n",n,sumsq(n));
}


OUTPUT:


3.1.5.
SOURCE CODE:
//program to find the power of a,b.
#include<stdio.h>
int pow(int a, int b){
if(b==0)
return 1;
else
return a*pow(a,b-1);
}
int main()
{
int a,b;
printf("Enter the base and power number:");
scanf("%d%d",&a,&b);
printf("%d to the power %d is %d.n",a,b,pow(a,b));
return 0;
}
OUTPUT:


CONCLUSION:
So, in this way , we can use the recursive function to solve different recursive problems.




3.2.
OBJECTIVE: TO SOLVE TOWER OF HANOI (TOH) PROBLEM.
THEORY:
The Tower of Hanoi is a classic mathematical puzzle where you have three rods and a stack of disks on one rod. The goal is to move all the disks from one rod to another while following rules: you can only move one disk at a time, and you cannot place a larger disk on top of a smaller one. It's a popular problem for teaching recursion and problem-solving and has a minimum of 2^n - 1 moves to solve with n disks.

SOURCE CODE:
// Function to solve Tower of Hanoi using recursion
#include <stdio.h>

void towerOfHanoi(int n, char source, char auxiliary, char destination)
{
if (n == 1)
{
printf("Move disk 1 from %c to %cn", source, destination);
return;
}

towerOfHanoi(n - 1, source, destination, auxiliary);
printf("Move disk %d from %c to %cn", n, source, destination);

towerOfHanoi(n - 1, auxiliary, source, destination);
}

int main()
{
int n;

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

printf("Steps to solve the Tower of Hanoi with %d disks:n", n);
towerOfHanoi(n, 'A', 'B', 'C');

return 0;
}



OUTPUT AND DISCUSSION:


This program defines a towerOfHanoi function that uses recursion to solve the Tower of Hanoi problem for a given number of disks. In the main function, you can enter the number of disks you want to use for the puzzle, and it will print the steps to solve it. The source, auxiliary, and destination represent the three rods (A, B, and C) in the problem.

CONCLUSION:
Hence, in this way, we can use the recursive function to solve the Tower Of Hanoi(TOH) problem.








3.3.
OBJECTIVE: TO IMPLEMENT MERGE SORT ALGORITHM.
THEORY:
Merge sort is a highly efficient and widely used sorting algorithm that operates on the divide-and-conquer principle. It works by repeatedly dividing the unsorted list into smaller sublists until each sublist consists of just one element, which is inherently sorted. Then, it merges these sublists back together in a sorted manner, combining them into larger sorted sublists until the entire list is sorted. Merge sort is known for its stability and consistent performance, making it a preferred choice for sorting large datasets in various programming applications.

SOURCE CODE:
#include <stdio.h>

// Function to merge two subarrays arr[l..m] and arr[m+1..r]
void merge(int arr[], int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

// Create temporary arrays
int L[n1], R[n2];

// Copy data to temporary arrays L[] and R[]
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

// Merge the two sorted arrays back into arr[l..r]
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

// Copy the remaining elements of L[], if any
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}

// Copy the remaining elements of R[], if any
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

// Recursive function to perform Merge Sort
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = l + (r - l) / 2;

// Recursively sort the first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

// Merge the sorted halves
merge(arr, l, m, r);
}
}

int main()
{
int arr[] = {38, 27, 43, 3, 9, 82, 10};
int arr_size = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");
for (int i = 0; i < arr_size; i++)
printf("%d ", arr[i]);

mergeSort(arr, 0, arr_size - 1);

printf("nSorted array: ");
for (int i = 0; i < arr_size; i++)
printf("%d ", arr[i]);

return 0;
}


OUTPUT AND DISCUSSION:

This program uses the Merge Sort algorithm to sort an array of integers in ascending order. It divides the array into smaller subarrays, recursively sorts them, and then merges them back together while maintaining the sorted order. The result is a sorted array displayed alongside the original unsorted array. Merge Sort is known for its efficiency and stability with a time complexity of O(n log n), making it a reliable choice for sorting tasks.

CONCLUSION:
So, in this way, we can implement the merge sort algorithm.
     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.