Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

A

LAB REPORT
ON
ARTIFICIAL INTELLIGENCE (CACS410)
“LAB I”
Faculty of Humanities & Social Science
Department of Computer Application
In partial fulfillment of the requirements for the
Course Artificial Intelligence

Submitted by: Submitted to:


BCA 7th Semester
LAB SHEET I
FACTS, RULES AND QUERIES
Theory:
Facts: In Prolog, facts are fundamental building blocks that represent assertions about
relationships between entities in the domain. They are typically written as predicates, where
each predicate asserts a truth about a particular relationship. Facts provide the base level of
knowledge upon which Prolog programs operate. For instance, in a family tree application,
facts might be used to represent relationships such as parentage or siblinghood, like
parent(john, jack) or sibling(jack, mary).

Rules: Rules in Prolog are logical statements that allow for the definition of complex
relationships based on simpler ones. A rule consists of a head and a body, where the head
represents what can be inferred and the body specifies the conditions under which the
inference is valid. Through rules, Prolog can derive new information or make logical
deductions. For example, a rule might define an ancestor relationship by stating that X is an
ancestor of Y if X is a parent of Y, or if X is a parent of some Z and Z is an ancestor of Y.

Queries: Queries are the mechanism by which users interact with Prolog programs. They are
questions or goals posed to the Prolog system, asking it to find solutions or proofs based on
the facts and rules provided. Prolog attempts to satisfy queries by searching for matches in its
knowledge base and applying rules as necessary. Users can pose queries to retrieve
information or test relationships within the domain. For instance, a query might ask whether
John is the father of Jack, prompting Prolog to search for a matching fact father(john, jack) in
its database and return true or false accordingly.
Objective:
The targets of Prolog as a rationale programming language include:

1. Declarative Programming: Prolog means to give a revelatory programming worldview,


where clients indicate what they need to accomplish instead of how to accomplish it. This
works with composing programs at a more elevated level of deliberation, permitting
designers to zero in on the issue space as opposed to low-even out execution subtleties.

2. Logical Inference: Prolog is intended to help legitimate derivation, empowering the


portrayal and control of intelligent connections and allowances. By characterizing realities
and rules, Prolog projects can make legitimate deductions and get new information from
existing data.

3. Pattern Coordinating and Backtracking: Prolog utilizes design coordinating and


backtracking as central components for search and deduction. It efficiently investigates
potential answers for inquiries by matching them against realities and rules and backtracking
when important to track down elective arrangements.

4. Scalability and Modularity: Prolog means to help the improvement of versatile and
particular projects. It considers the decay of complicated issues into more modest, more
sensible units using predicates and modules, advancing code reuse and viability.

5. Integration with Other Paradigms: Prolog is much of the time utilized related to other
programming standards, for example, utilitarian programming or article situated
programming. It furnishes offices for communicating with outside code written in different
dialects, considering consistent reconciliation inside bigger programming frameworks.

6. AI and Master Systems: Prolog has been generally utilized in man-made brainpower
(simulated intelligence) and master frameworks applications because of its capacity to
address and reason about complex information and connections. It gives a characteristic
structure to communicating master information and carrying out thinking systems.

Generally, Prolog expects to give a flexible and expressive programming language for
tackling many issues, especially those including emblematic calculation, sensible induction,
and information portrayal.
1. Develop rules for the following: Jealousy between two persons if they love the same
person of opposite gender. Experiment with different forms of queries.
Source Code:

Output:
2. Develop rules for brother-in-law and sister-in-law and experiment with different
forms of queries.
Source Code:

Output:
3. Develop friendship relationship in prolog using recursive function and experiment
with different forms of queries.
Source Code:

Output:
5. Implementation of for loop in prolog and using that print multiplication table of n.
Source Code:

Output:
6. Find factorial in prolog using recursion.
Source Code:

Output:
7. Print Fibonacci series in prolog upto n terms.
Source Code:

Output:

Conclusion:
Through the exploration of various Prolog concepts and techniques, including rule-based
inference, recursion, and iterative constructs, a diverse range of problems has been
successfully addressed. The development of rules for jealousy, brother-in-law and sister-in-
law relationships, and friendship illustrates Prolog's ability to represent complex relationships
and derive logical conclusions. Additionally, the implementation of for loops facilitated tasks
like printing multiplication tables and calculating factorials, demonstrating Prolog's
versatility in handling iterative computations. Furthermore, the generation of the Fibonacci
series showcases Prolog's capability for recursive problem-solving. Overall, these exercises
highlight the effectiveness of Prolog in tackling diverse problem domains through its unique
logic-based approach.
A
LAB REPORT
ON
ARTIFICIAL INTELLIGENCE (CACS410)
“LAB II”
Faculty of Humanities & Social Science
Department of Computer Application
“KATHMANDU NATIONAL COLLEGE”
In partial fulfillment of the requirements for the
Course Artificial Intelligence

Submitted by: Sabina Ghimire Submitted to: Er. Ashish Kumar


Jha
BCA 7th Semester
LAB SHEET II
ARITIFICIAL INTELLIGENCE

Theory:
Artificial Intelligence (AI) encompasses a diverse set of objectives aimed at creating
intelligent systems that can revolutionize technology and society. At its core, AI seeks to
automate tasks and enhance human capabilities by developing systems that can understand
and reason with complex data, learn and adapt over time, process natural language, perceive
the environment, and operate autonomously. Through automation, AI frees humans from
mundane and repetitive tasks, allowing them to focus on more creative and complex
endeavors. By augmenting human capabilities, AI enables individuals and organizations to
achieve higher levels of productivity and efficiency in various domains. AI also aims to
enable machines to learn from data and experience, continuously improving their
performance and adaptability. Natural Language Processing (NLP) technologies empower AI
systems to understand and generate human language, facilitating seamless communication
between humans and machines. Additionally, AI seeks to equip machines with perception
capabilities, enabling them to interpret and interact with the physical world autonomously.
Ultimately, AI's objectives converge to drive innovation, efficiency, and progress, shaping a
future where intelligent systems work in harmony with humans to solve complex problems
and enhance the quality of life for individuals and society as a whole.

Objective:
The objective of Artificial Intelligence (AI) is twofold: to create intelligent systems that can
automate tasks, enhance human capabilities, understand and reason with data, learn and adapt
over time, process natural language, perceive the environment, and operate autonomously. By
achieving these goals, AI aims to improve efficiency, solve complex problems, and ultimately
enhance the quality of life for individuals and society as a whole.
1. Write a program in C to implement DFS/BFS on water jug problem Given a 4-liter
jug filled with water & an empty 3-liter jug, how can one obtain exactly 2 liters in 4
liters jug. There is no measuring mark on any of them.

Source Code:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define MAX_QUEUE_SIZE 100
typedef struct
{
int j1;
int j2;
} Pair;
// Queue implementation for BFS
typedef struct
{
Pair data[MAX_QUEUE_SIZE];
int front;
int rear;
} Queue;

void initializeQueue(Queue *q)


{
q->front = -1;
q->rear = -1;
}
bool isEmpty(Queue *q)
{
return (q->front == -1 && q->rear == -1);
}
void enqueue(Queue *q, Pair state)
{
if ((q->rear + 1) % MAX_QUEUE_SIZE == q->front)
{
printf("Queue is full.\n");
return;
}
if (isEmpty(q))
{
q->front = 0;
q->rear = 0;
}
else
{
q->rear = (q->rear + 1) % MAX_QUEUE_SIZE;
}
q->data[q->rear] = state;
}
Pair dequeue(Queue *q)
{
if (isEmpty(q))
{
printf("Queue is empty.\n");
exit(EXIT_FAILURE);
}
Pair temp = q->data[q->front];
if (q->front == q->rear)
{
q->front = -1;
q->rear = -1;
}
else
{
q->front = (q->front + 1) % MAX_QUEUE_SIZE;
}
return temp;
}
bool isVisited(bool visited[][4], int j1, int j2)
{
return visited[j1][j2];
}
void solveWaterJugBFS(int jug1, int jug2, int target)
{
bool visited[jug1 + 1][jug2 + 1];
for (int i = 0; i <= jug1; ++i)
{
for (int j = 0; j <= jug2; ++j)
{
visited[i][j] = false;
}
}
Queue queue;
initializeQueue(&queue);
Pair initialState = {0, 0};
enqueue(&queue, initialState);
while (!isEmpty(&queue))
{
Pair curr = dequeue(&queue);
if (isVisited(visited, curr.j1, curr.j2))
continue;
visited[curr.j1][curr.j2] = true;
if (curr.j1 == target || curr.j2 == target)
{
printf("Path of states of jugs followed is :\n");
printf("%d , %d\n", curr.j1, curr.j2);
return;
}
enqueue(&queue, (Pair){jug1, curr.j2});
enqueue(&queue, (Pair){curr.j1, jug2});
enqueue(&queue, (Pair){jug1, curr.j2});
enqueue(&queue, (Pair){curr.j1, jug2});
enqueue(&queue, (Pair){0, curr.j2});
enqueue(&queue, (Pair){curr.j1, 0});
int emptyJug = jug2 - curr.j2;
int amountTransferred = (curr.j1 < emptyJug) ? curr.j1 : emptyJug;
enqueue(&queue, (Pair){curr.j1 - amountTransferred, curr.j2 + amountTransferred});
emptyJug = jug2 - curr.j2;
amountTransferred = (curr.j1 < emptyJug) ? curr.j1 : emptyJug;
enqueue(&queue, (Pair){curr.j1 - amountTransferred, curr.j2 + amountTransferred});
}
printf("Not Possible to obtain target.\n");
}
int main()
{
int jug1 = 5;
int jug2 = 3;
int target = 4;
solveWaterJugBFS(jug1, jug2, target);
return 0;
}

Output:
2. Write a program in C to calculate the heuristic value of the states for Blocks
World Problem as follows:

Global heuristic: e(p) is calculated as


 For each block that has the correct support structure: +1 to every block in the
support structure.
 For each bock that has a wrong support structure: -1 to every block in the
support structure.
Source Code:
#include <stdio.h>
#include <stdbool.h>

#define MAX_BLOCKS 100

typedef struct
{
int id;
int support; // ID of the block this block is supported by
} Block;

Block blocks[MAX_BLOCKS];
int numBlocks;

int calculateHeuristic()
{
int heuristic = 0;
for (int i = 0; i < numBlocks; i++)
{
int correctSupport = (blocks[i].id - 1 + numBlocks) % numBlocks; //
Expected ID of supported block

// Special case: block supports the base


if (blocks[i].support == -1 && blocks[i].id == numBlocks - 1)
{
heuristic++;
continue; // Move to the next iteration
}

// Check if the block has correct support


if (blocks[blocks[i].support].id == correctSupport)
{
heuristic++;
}
else
{
heuristic--;
}
}
return heuristic;
}

int main()
{
// Initialize blocks with initial placement
numBlocks = 4;
blocks[0].id = 0;
blocks[0].support = 3; // Block b on the base
blocks[1].id = 1;
blocks[1].support = 0; // Block c on block b
blocks[2].id = 2;
blocks[2].support = 0; // Block d on block b
blocks[3].id = 3;
blocks[3].support = -1; // Block a on the base

// Calculate and print the heuristic value


int heuristic = calculateHeuristic();
printf("Heuristic value: %d\n", heuristic);

return 0;
}

Output:
3. Write a program in C to implement steepest ascent hill climbing for 8-puzzle
problem. Develop appropriate heuristic function.
Source Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

// Heuristic function: Number of misplaced tiles


int misplaced_tiles(int state[3][3], int goal_state[3][3])
{
int misplaced = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (state[i][j] != goal_state[i][j])
{
misplaced++;
}
}
}
return misplaced;
}

// Function to find possible moves


void possible_moves(int state[3][3], int moves[4][3][3])
{
int empty_i, empty_j;
// Find the position of the empty tile (0)
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (state[i][j] == 0)
{
empty_i = i;
empty_j = j;
break;
}
}
}
// Generate possible moves
int k = 0;
// Move up
if (empty_i > 0)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
moves[k][i][j] = state[i][j];
}
}
moves[k][empty_i][empty_j] = moves[k][empty_i - 1][empty_j];
moves[k][empty_i - 1][empty_j] = 0;
k++;
}
// Move down
if (empty_i < 2)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
moves[k][i][j] = state[i][j];
}
}
moves[k][empty_i][empty_j] = moves[k][empty_i + 1][empty_j];
moves[k][empty_i + 1][empty_j] = 0;
k++;
}
// Move left
if (empty_j > 0)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
moves[k][i][j] = state[i][j];
}
}
moves[k][empty_i][empty_j] = moves[k][empty_i][empty_j - 1];
moves[k][empty_i][empty_j - 1] = 0;
k++;
}
// Move right
if (empty_j < 2)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
moves[k][i][j] = state[i][j];
}
}
moves[k][empty_i][empty_j] = moves[k][empty_i][empty_j + 1];
moves[k][empty_i][empty_j + 1] = 0;
k++;
}
}

// Function to display the state of the puzzle


void display_state(int state[3][3], int empty_i, int empty_j)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf("+---");
}
printf("+\n");
for (int j = 0; j < 3; j++)
{
if (state[i][j] == 0)
{
printf("| ");
}
else
{
if (i == empty_i && j == empty_j)
{
printf("| *%d", state[i][j]);
}
else
{
printf("| %2d", state[i][j]);
}
}
}
printf("|\n");
}
for (int j = 0; j < 3; j++)
{
printf("+---");
}
printf("+\n");
}

// Steepest ascent hill climbing algorithm


void steepest_ascent_hill_climbing(int initial_state[3][3], int goal_state[3][3])
{
int current_state[3][3];
int best_h, h;
int moves[4][3][3];
int step = 1;

printf("Step %d:\n", step);


display_state(initial_state, -1, -1);
printf("\n");
while (true)
{
best_h = misplaced_tiles(initial_state, goal_state);
possible_moves(initial_state, moves);
int found_better = 0;
for (int k = 0; k < 4; k++)
{
h = misplaced_tiles(moves[k], goal_state);
if (h < best_h)
{
best_h = h;
found_better = 1;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
current_state[i][j] = moves[k][i][j];
}
}
}
}
if (!found_better)
{
break;
}
printf("Step %d:\n", ++step);
display_state(current_state, -1, -1);
printf("\n");
// Update initial state
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
initial_state[i][j] = current_state[i][j];
}
}
}
}

int main()
{
int initial_state[3][3] = {
{1, 2, 3},
{0, 4, 6},
{7, 5, 8}};

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

steepest_ascent_hill_climbing(initial_state, goal_state);

return 0;
}
Output:
4. Write a C program to calculate the heuristic value of the states for Tic-Tac-Toe
as follows:

Heuristic Function:
e(p)= No. of complete rows, columns or diagonals are still open for player) – (No.
of complete rows, columns or diagonals are still open for opponent)

Source Code:

#include <stdio.h>

// Function to calculate the heuristic value for Tic-Tac-Toe


int calculate_heuristic(char board[3][3], char player)
{
int player_count = 0;
int opponent_count = 0;

// Check rows and columns


for (int i = 0; i < 3; i++)
{
if ((board[i][0] == player && board[i][1] == player && board[i][2] == player) ||
(board[0][i] == player && board[1][i] == player && board[2][i] == player))
{
player_count++;
}
else if ((board[i][0] != player && board[i][1] != player && board[i][2] != player) ||
(board[0][i] != player && board[1][i] != player && board[2][i] != player))
{
opponent_count++;
}
}

// Check diagonals
if ((board[0][0] == player && board[1][1] == player && board[2][2] == player) ||
(board[0][2] == player && board[1][1] == player && board[2][0] == player))
{
player_count++;
}
else if ((board[0][0] != player && board[1][1] != player && board[2][2] != player) ||
(board[0][2] != player && board[1][1] != player && board[2][0] != player))
{
opponent_count++;
}

return player_count - opponent_count;


}

int main()
{
char board[3][3] = {
{'X', ' ', 'O'},
{'O', 'X', ' '},
{'O', ' ', 'X'}};
char player = 'X'; // Assuming 'X' is the player symbol

int heuristic_value = calculate_heuristic(board, player);


printf("Heuristic value: %d\n", heuristic_value);

return 0;
}

Output:

5. Solve the 8 puzzle problem-using A* algorithm in Prolog.


Source Code:
Solve the 8 puzzle problem using A* algorithm in prolog.
Program:
test(Plan):-
write('Initial state:'),nl,
Init= [at(tile4,1), at(tile3,2), at(tile8,3), at(empty,4), at(tile2,5), at(tile6,6), at(tile5,7),
at(tile1,8), at(tile7,9)],
write_sol(Init),
Goal= [at(tile1,1), at(tile2,2), at(tile3,3), at(tile4,4), at(empty,5), at(tile5,6), at(tile6,7),
at(tile7,8), at(tile8,9)],
nl,write('Goal state:'),nl,
write(Goal),nl,nl,
solve(Init,Goal,Plan).
solve(State, Goal, Plan):-
solve(State, Goal, [], Plan).
%Determines whether Current and Destination tiles are a valid move.
is_movable(X1,Y1) :- (1 is X1 - Y1) ; (-1 is X1 - Y1) ; (3 is X1 - Y1) ; (-3 is X1 - Y1).
% This predicate produces the plan. Once the Goal list is a subset
% of the current State the plan is complete and it is written to
% the screen using write_sol/1.
solve(State, Goal, Plan, Plan):-
is_subset(Goal, State), nl,
write_sol(Plan).
solve(State, Goal, Sofar, Plan):-
act(Action, Preconditions, Delete, Add),
is_subset(Preconditions, State),
\+ member(Action, Sofar),
delete_list(Delete, State, Remainder),
append(Add, Remainder, NewState),
solve(NewState, Goal, [Action|Sofar], Plan).
% The problem has three operators.
% 1st arg = name
% 2nd arg = preconditions
% 3rd arg = delete list
% 4th arg = add list.
% Tile can move to new position only if destination tile is empty & Manhattan distance =
1
act(move(X,Y,Z),
[at(X,Y), at(empty,Z), is_movable(Y,Z)],
[at(X,Y), at(empty,Z)],
[at(X,Z), at(empty,Y)]).
% Utility predicates.
% Check is first list is a subset of the second
is_subset([H|T], Set):-
member(H, Set),
is_subset(T, Set).
is_subset([], _).
% Remove all elements of 1st list from second to create third.
delete_list([H|T], Curstate, Newstate):-
remove(H, Curstate, Remainder),
delete_list(T, Remainder, Newstate).
delete_list([], Curstate, Curstate).
remove(X, [X|T], T).
remove(X, [H|T], [H|R]):-
remove(X, T, R).
write_sol([]).
write_sol([H|T]):-
write_sol(T),
write(H), nl.
append([H|T], L1, [H|L2]):-
append(T, L1, L2).
append([], L, L).
member(X, [X|_]).
member(X, [_|T]):-
member(X, T).

Output:
Conclusion:

Through the exploration of various problem-solving techniques in C programming and


Prolog, including depth-first search (DFS), breadth-first search (BFS), heuristic value
calculation for the Blocks World Problem, steepest ascent hill climbing for the 8-puzzle
problem, and heuristic evaluation for Tic-Tac-Toe, a diverse range of challenges has been
successfully addressed. These programs demonstrate the versatility and effectiveness of both
C and Prolog in tackling complex problem domains through their unique approaches to
algorithm design, logic representation, and search strategies. Additionally, the
implementation of the A* algorithm in Prolog for solving the 8-puzzle problem further
underscores the capability of logic-based programming languages in handling heuristic search
algorithms efficiently. Overall, these exercises showcase the power and flexibility of C and
Prolog in solving diverse computational problems, ranging from classic puzzles to real-world
optimization tasks.
A
LAB REPORT
ON
ARTIFICIAL INTELLIGENCE (CACS410)
“LAB III”
Faculty of Humanities & Social Science
Department of Computer Application
“KATHMANDU NATIONAL COLLEGE”
In partial fulfillment of the requirements for the
Course Artificial Intelligence

Submitted by: Sabina Ghimire Submitted to: Er. Ashish Kumar


Jha
BCA 7th Semester
LAB SHEET III
ML and Neural Network

Theory:
Machine Learning (ML):
Machine Learning is a field of artificial intelligence (AI) that focuses on developing
algorithms and techniques to enable computers to learn from data and improve
performance on specific tasks without being explicitly programmed. ML algorithms can
be broadly categorized into supervised learning, unsupervised learning, and reinforcement
learning. In supervised learning, algorithms learn from labeled data to make predictions
or classify new data points. Unsupervised learning algorithms identify patterns and
structures in unlabeled data, while reinforcement learning algorithms learn to make
decisions by interacting with an environment and receiving feedback in the form of
rewards or penalties.
Neural Networks (NNs):
Neural Networks are a class of machine learning models inspired by the structure and
function of the human brain. They consist of interconnected nodes organized into layers,
including an input layer, one or more hidden layers, and an output layer. Each node, or
neuron, applies a mathematical operation to its input and passes the result through an
activation function to produce an output. Through a process called backpropagation,
neural networks adjust the weights of connections between neurons during training to
minimize the difference between predicted and actual outputs. This enables neural
networks to learn complex patterns and relationships in data, making them effective for
tasks such as image recognition, natural language processing, and predictive modeling.

Objective:
Machine Learning (ML) and Neural Networks aim to develop algorithms and models that
learn from data to:
 Predict future outcomes and classify data accurately.
 Recognize patterns and structures in data for decision-making and insight generation.
 Optimize model parameters to minimize errors or maximize performance.
 Automate tasks and decision-making processes based on learned patterns.
 Extract meaningful features from raw data and learn representations at multiple levels
of abstraction.
 Approximate complex functions and adaptively improve performance over time.
 Generalize well to unseen data and solve tasks efficiently in dynamic environments.
1. Write a program in C to Implement AND Gate.

Source Code:
#include <stdio.h>

// Function to simulate an AND gate


int and_gate(int input1, int input2)
{
if (input1 == 1 && input2 == 1)
{
return 1; // Output is true (1) only when both inputs are true (1)
}
else
{
return 0; // Otherwise, output is false (0)
}
}

int main()
{
int input1, input2;

// Input from the user


printf("Enter input 1 (0 or 1): ");
scanf("%d", &input1);

// Validate input1
if (input1 != 0 && input1 != 1)
{
printf("Invalid input. Please enter 0 or 1.\n");
return 1; // Exit with error
}

printf("Enter input 2 (0 or 1): ");


scanf("%d", &input2);

// Validate input2
if (input2 != 0 && input2 != 1)
{
printf("Invalid input. Please enter 0 or 1.\n");
return 1; // Exit with error
}

// Calculate the output of the AND gate


int output = and_gate(input1, input2);

// Display the output1


return 0;
}

Output:
2. Write a program in C to implement OR Gate.

Source Code:
#include <stdio.h>

// Function to simulate an OR gate


int or_gate(int input1, int input2)
{
if (input1 == 1 || input2 == 1)
{
return 1; // Output is true (1) if either input1 or input2 is true (1)
}
else
{
return 0; // Otherwise, output is false (0)
}
}

int main()
{
int input1, input2;

// Input from the user


printf("Enter input 1 (0 or 1): ");
scanf("%d", &input1);

// Validate input1
if (input1 != 0 && input1 != 1)
{
printf("Invalid input. Please enter 0 or 1.\n");
return 1; // Exit with error
}

printf("Enter input 2 (0 or 1): ");


scanf("%d", &input2);

// Validate input2
if (input2 != 0 && input2 != 1)
{
printf("Invalid input. Please enter 0 or 1.\n");
return 1; // Exit with error
}

// Calculate the output of the OR gate


int output = or_gate(input1, input2);

// Display the output


printf("\nOutput of the OR gate: %d\n", output);
return 0;
}

Output:

3. Write a program in C to implement EX-OR Gate.


Source Code:
#include <stdio.h>

// Function to simulate an XOR gate


int xor_gate(int input1, int input2)
{
if ((input1 == 1 && input2 == 0) || (input1 == 0 && input2 == 1))
{
return 1; // Output is true (1) if inputs are different
}
else
{
return 0; // Otherwise, output is false (0)
}
}

int main()
{
int input1, input2;

// Input from the user


printf("Enter input 1 (0 or 1): ");
scanf("%d", &input1);

// Validate input1
if (input1 != 0 && input1 != 1)
{
printf("Invalid input. Please enter 0 or 1.\n");
return 1; // Exit with error
}

printf("Enter input 2 (0 or 1): ");


scanf("%d", &input2);

// Validate input2
if (input2 != 0 && input2 != 1)
{
printf("Invalid input. Please enter 0 or 1.\n");
return 1; // Exit with error
}

// Calculate the output of the XOR gate


int output = xor_gate(input1, input2);

// Display the output


printf("\nnOutput of the XOR gate: %d\n", output);

return 0;}
Output:
4. Write a program in C to implement NOT Gate.
Source code:
#include <stdio.h>

// Function to simulate a NOT gate


int not_gate(int input)
{
return !input; // Return the opposite of the input (0 becomes 1, and 1 becomes 0)
}

int main()
{
int input;

// Input from the user


printf("Enter input (0 or 1): ");
scanf("%d", &input);

// Validate input
if (input != 0 && input != 1)
{
printf("Invalid input. Please enter 0 or 1.\n");
return 1; // Exit with error
}

// Calculate the output of the NOT gate


int output = not_gate(input);

// Display the output


printf("Output of the NOT gate: %d\n", output);

return 0;
}

Output:
Conclusion:

Through the exploration of various concepts and techniques in C programming, including


logical operations, bitwise manipulation, and control structures, a diverse range of
problems has been successfully addressed. The development of programs for
implementing logical gates such as AND, OR, EX-OR, and NOT showcases C's ability to
represent and manipulate binary logic efficiently. Additionally, the utilization of loops and
conditional statements facilitated tasks like printing multiplication tables and calculating
factorials, demonstrating C's versatility in handling iterative computations. Furthermore,
the implementation of iterative constructs allowed for the generation of sequences like the
Fibonacci series, showcasing C's capability for recursive problem-solving when
necessary. Overall, these exercises highlight the effectiveness of C in tackling diverse
problem domains through its powerful and flexible syntax, making it a valuable tool for
both low-level system programming and high-level application development.

You might also like