formatting source-code for 5bba04b671

This commit is contained in:
github-actions 2020-06-28 15:25:37 +00:00
parent 5bba04b671
commit 6f98288110
134 changed files with 440 additions and 623 deletions

View File

@ -30,7 +30,7 @@ int main()
memset(&cliaddr, 0, sizeof(cliaddr)); memset(&cliaddr, 0, sizeof(cliaddr));
// Filling server information // Filling server information
servaddr.sin_family = AF_INET; // IPv4 servaddr.sin_family = AF_INET; // IPv4
servaddr.sin_addr.s_addr = INADDR_ANY; servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT); servaddr.sin_port = htons(PORT);

View File

@ -7,7 +7,6 @@
int main() int main()
{ {
int remainder, number = 0, decimal_number = 0, temp = 1; int remainder, number = 0, decimal_number = 0, temp = 1;
printf("/n Enter any binary number= "); printf("/n Enter any binary number= ");
scanf("%d", &number); scanf("%d", &number);
@ -15,11 +14,10 @@ int main()
// Iterate over the number until the end. // Iterate over the number until the end.
while (number > 0) while (number > 0)
{ {
remainder = number % 10; remainder = number % 10;
number = number / 10; number = number / 10;
decimal_number += remainder * temp; decimal_number += remainder * temp;
temp = temp * 2; // used as power of 2 temp = temp * 2; // used as power of 2
} }
printf("%d\n", decimal_number); printf("%d\n", decimal_number);

View File

@ -26,7 +26,7 @@ int main(void)
while (binary_num > 0) while (binary_num > 0)
{ {
if (binary_num > if (binary_num >
111) // Checking if binary number is greater than three digits 111) // Checking if binary number is greater than three digits
td = three_digits(binary_num); td = three_digits(binary_num);
else else
@ -45,7 +45,7 @@ int main(void)
base *= 2; base *= 2;
} }
res += d * ord; // Calculating the octal value res += d * ord; // Calculating the octal value
ord *= 10; ord *= 10;
} }

View File

@ -5,7 +5,6 @@
int main() int main()
{ {
// input of the user // input of the user
int inputNumber; int inputNumber;
@ -35,7 +34,6 @@ int main()
// actual processing // actual processing
while (inputNumber > 0) while (inputNumber > 0)
{ {
// computes the remainder by modulo 2 // computes the remainder by modulo 2
re = inputNumber % 2; re = inputNumber % 2;

View File

@ -4,7 +4,6 @@ void decimal2Hexadecimal(long num);
int main() int main()
{ {
long decimalnum; long decimalnum;
printf("Enter decimal number: "); printf("Enter decimal number: ");
@ -19,7 +18,6 @@ int main()
* number****************/ * number****************/
void decimal2Hexadecimal(long num) void decimal2Hexadecimal(long num)
{ {
long decimalnum = num; long decimalnum = num;
long quotient, remainder; long quotient, remainder;
int i, j = 0; int i, j = 0;
@ -29,7 +27,6 @@ void decimal2Hexadecimal(long num)
while (quotient != 0) while (quotient != 0)
{ {
remainder = quotient % 16; remainder = quotient % 16;
if (remainder < 10) if (remainder < 10)
hexadecimalnum[j++] = 48 + remainder; hexadecimalnum[j++] = 48 + remainder;

View File

@ -4,7 +4,6 @@ void decimal2Octal(long decimalnum);
int main() int main()
{ {
long decimalnum; long decimalnum;
printf("Enter the decimal number: "); printf("Enter the decimal number: ");
@ -30,9 +29,7 @@ void decimal2Octal(long decimalnum)
quotient = quotient / 8; quotient = quotient / 8;
} }
for (j = i - 1; j > 0; j--) for (j = i - 1; j > 0; j--) printf("%d", octalNumber[j]);
printf("%d", octalNumber[j]);
printf("\n"); printf("\n");
} }

View File

@ -6,12 +6,10 @@ int convertValue(int num, int i) { return num * pow(8, i); }
long long toDecimal(int octal_value) long long toDecimal(int octal_value)
{ {
int decimal_value = 0, i = 0; int decimal_value = 0, i = 0;
while (octal_value) while (octal_value)
{ {
// Extracts right-most digit and then multiplies by 8^i // Extracts right-most digit and then multiplies by 8^i
decimal_value += convertValue(octal_value % 10, i++); decimal_value += convertValue(octal_value % 10, i++);
@ -24,7 +22,6 @@ long long toDecimal(int octal_value)
int main() int main()
{ {
printf("Enter octal value: "); printf("Enter octal value: ");
int octal_value; int octal_value;

View File

@ -13,10 +13,10 @@
* *
*/ */
#include "CArray.h"
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
#include "CArray.h"
int CArrayTests() int CArrayTests()
{ {
@ -37,7 +37,7 @@ int CArrayTests()
} }
printf("Entered array is:\n"); printf("Entered array is:\n");
displayCArray(array); displayCArray(array);
printf("\nCode: %d\n", pushValueCArray(array, 11)); // 5 printf("\nCode: %d\n", pushValueCArray(array, 11)); // 5
for (i = 0; i < array->size; i++) for (i = 0; i < array->size; i++)
{ {
@ -46,8 +46,8 @@ int CArrayTests()
displayCArray(array); displayCArray(array);
printf("\nCode: %d", removeValueCArray(array, -1)); // 1 printf("\nCode: %d", removeValueCArray(array, -1)); // 1
printf("\nCode: %d\n", insertValueCArray(array, -1, 1)); // 1 printf("\nCode: %d\n", insertValueCArray(array, -1, 1)); // 1
// Erase // Erase
for (i = 0; i < array->size; i++) for (i = 0; i < array->size; i++)
@ -55,7 +55,7 @@ int CArrayTests()
insertValueCArray(array, i, i + 1); insertValueCArray(array, i, i + 1);
} }
eraseCArray(array); eraseCArray(array);
displayCArray(array); // Should give all 0s displayCArray(array); // Should give all 0s
// Switching // Switching
CArray *arr = getCArray(13); CArray *arr = getCArray(13);

View File

@ -50,8 +50,7 @@ avlNode *minNode(avlNode *node)
{ {
avlNode *temp = node; avlNode *temp = node;
while (temp->left != NULL) while (temp->left != NULL) temp = temp->left;
temp = temp->left;
return temp; return temp;
} }
@ -64,8 +63,7 @@ void printAVL(avlNode *node, int level)
printAVL(node->right, level + 1); printAVL(node->right, level + 1);
printf("\n\n"); printf("\n\n");
for (i = 0; i < level; i++) for (i = 0; i < level; i++) printf("\t");
printf("\t");
printf("%d", node->key); printf("%d", node->key);
@ -117,7 +115,6 @@ avlNode *RightLeftRotate(avlNode *z)
avlNode *insert(avlNode *node, int key) avlNode *insert(avlNode *node, int key)
{ {
if (node == NULL) if (node == NULL)
return (newNode(key)); return (newNode(key));
@ -310,7 +307,6 @@ int main()
case 1: case 1:
{ {
printf("\n\tEnter the Number to insert: "); printf("\n\tEnter the Number to insert: ");
scanf("%d", &insertNum); scanf("%d", &insertNum);

View File

@ -12,7 +12,6 @@
// Node, the basic data structure in the tree // Node, the basic data structure in the tree
typedef struct node typedef struct node
{ {
// left child // left child
struct node *left; struct node *left;
@ -27,7 +26,6 @@ typedef struct node
// pointer // pointer
node *newNode(int data) node *newNode(int data)
{ {
// creates a slug // creates a slug
node *tmp = (node *)malloc(sizeof(node)); node *tmp = (node *)malloc(sizeof(node));
@ -110,7 +108,6 @@ node *delete (node *root, int data)
// subtree and switch with the root's // subtree and switch with the root's
else else
{ {
// finds the biggest node in the left branch. // finds the biggest node in the left branch.
node *tmp = getMax(root->left); node *tmp = getMax(root->left);
@ -190,7 +187,6 @@ void inOrder(node *root)
void main() void main()
{ {
// this reference don't change. // this reference don't change.
// only the tree changes. // only the tree changes.
node *root = NULL; node *root = NULL;
@ -200,9 +196,10 @@ void main()
// event-loop. // event-loop.
while (opt != 0) while (opt != 0)
{ {
printf("\n\n[1] Insert Node\n[2] Delete Node\n[3] Find a Node\n[4] Get " printf(
"current Height\n[5] Print Tree in Crescent Order\n[0] Quit\n"); "\n\n[1] Insert Node\n[2] Delete Node\n[3] Find a Node\n[4] Get "
scanf("%d", &opt); // reads the choice of the user "current Height\n[5] Print Tree in Crescent Order\n[0] Quit\n");
scanf("%d", &opt); // reads the choice of the user
// processes the choice // processes the choice
switch (opt) switch (opt)

View File

@ -7,7 +7,7 @@
void inOrderTraversal(struct node *node) void inOrderTraversal(struct node *node)
{ {
if (node == NULL) // if tree is empty if (node == NULL) // if tree is empty
return; return;
inOrderTraversal(node->leftNode); inOrderTraversal(node->leftNode);
@ -17,7 +17,7 @@ void inOrderTraversal(struct node *node)
void preOrderTraversal(struct node *node) void preOrderTraversal(struct node *node)
{ {
if (node == NULL) // if tree is empty if (node == NULL) // if tree is empty
return; return;
printf("\t%d\t", node->data); printf("\t%d\t", node->data);
@ -27,7 +27,7 @@ void preOrderTraversal(struct node *node)
void postOrderTraversal(struct node *node) void postOrderTraversal(struct node *node)
{ {
if (node == NULL) // if tree is empty if (node == NULL) // if tree is empty
return; return;
postOrderTraversal(node->leftNode); postOrderTraversal(node->leftNode);

View File

@ -91,7 +91,6 @@ Node *rightRotate(Node *node)
// Check the node after the insertion step // Check the node after the insertion step
void checkNode(Node *node) void checkNode(Node *node)
{ {
// If the node is the root // If the node is the root
if (node == NULL || node->par == NULL) if (node == NULL || node->par == NULL)
{ {
@ -166,7 +165,7 @@ void checkNode(Node *node)
grandParent->color = 1; grandParent->color = 1;
} }
else else
{ // Right Left Case { // Right Left Case
// First step -> Parent Child Rotation // First step -> Parent Child Rotation
parent->left = child->right; parent->left = child->right;
if (child->right != NULL) if (child->right != NULL)
@ -206,7 +205,7 @@ void checkNode(Node *node)
} }
} }
else else
{ // Left Case { // Left Case
// Left Left Case // Left Left Case
if (parent->left == node) if (parent->left == node)
{ {
@ -238,7 +237,7 @@ void checkNode(Node *node)
grandParent->color = 1; grandParent->color = 1;
} }
else else
{ // Left Right Case { // Left Right Case
// First step -> Parent Child Rotation // First step -> Parent Child Rotation
parent->right = child->left; parent->right = child->left;
@ -307,7 +306,6 @@ void insertNode(int val, Node **root)
} }
else else
{ {
// Go right // Go right
if (buffRoot->right != NULL) if (buffRoot->right != NULL)
{ {
@ -344,7 +342,6 @@ void insertNode(int val, Node **root)
void checkForCase2(Node *toDelete, int delete, int fromDirection, Node **root) void checkForCase2(Node *toDelete, int delete, int fromDirection, Node **root)
{ {
if (toDelete == (*root)) if (toDelete == (*root))
{ {
(*root)->color = 0; (*root)->color = 0;
@ -374,7 +371,7 @@ void checkForCase2(Node *toDelete, int delete, int fromDirection, Node **root)
// Get the sibling for further inspection // Get the sibling for further inspection
Node *sibling; Node *sibling;
Node *parent = toDelete->par; Node *parent = toDelete->par;
int locateChild = 0; // 0 if toDeleted is left of its parent else 1 int locateChild = 0; // 0 if toDeleted is left of its parent else 1
if (parent->right == toDelete) if (parent->right == toDelete)
{ {
sibling = parent->left; sibling = parent->left;
@ -391,11 +388,9 @@ void checkForCase2(Node *toDelete, int delete, int fromDirection, Node **root)
{ {
if (sibling->right != NULL && sibling->right->color == 1) if (sibling->right != NULL && sibling->right->color == 1)
{ {
// Sibling is left and child is right. i.e. LEFT RIGHT ROTATION // Sibling is left and child is right. i.e. LEFT RIGHT ROTATION
if (locateChild == 1) if (locateChild == 1)
{ {
int parColor = parent->color; int parColor = parent->color;
// Step 1: Left rotate sibling // Step 1: Left rotate sibling
@ -427,8 +422,8 @@ void checkForCase2(Node *toDelete, int delete, int fromDirection, Node **root)
} }
} }
else else
{ // Sibling is right and child is also right. i.e. LEFT LEFT { // Sibling is right and child is also right. i.e. LEFT LEFT
// ROTATION // ROTATION
int parColor = parent->color; int parColor = parent->color;
@ -460,11 +455,9 @@ void checkForCase2(Node *toDelete, int delete, int fromDirection, Node **root)
} }
else else
{ {
// Sibling is right and child is left. i.e. RIGHT LEFT ROTATION // Sibling is right and child is left. i.e. RIGHT LEFT ROTATION
if (locateChild == 0) if (locateChild == 0)
{ {
int parColor = parent->color; int parColor = parent->color;
// Step 1: Right rotate sibling // Step 1: Right rotate sibling
@ -499,8 +492,8 @@ void checkForCase2(Node *toDelete, int delete, int fromDirection, Node **root)
} }
} }
else else
{ // Sibling is left and child is also left. i.e. RIGHT RIGHT { // Sibling is left and child is also left. i.e. RIGHT RIGHT
// ROTATION // ROTATION
int parColor = parent->color; int parColor = parent->color;
@ -532,7 +525,7 @@ void checkForCase2(Node *toDelete, int delete, int fromDirection, Node **root)
} }
} }
else if (sibling->color == 0) else if (sibling->color == 0)
{ // Make the sibling red and recur for its parent { // Make the sibling red and recur for its parent
// Recolor the sibling // Recolor the sibling
sibling->color = 1; sibling->color = 1;
@ -561,9 +554,9 @@ void checkForCase2(Node *toDelete, int delete, int fromDirection, Node **root)
checkForCase2(parent, 0, locateChild, root); checkForCase2(parent, 0, locateChild, root);
} }
else else
{ // Bring the sibling on top and apply 2.1 or 2.2 accordingly { // Bring the sibling on top and apply 2.1 or 2.2 accordingly
if (locateChild) if (locateChild)
{ // Right Rotate { // Right Rotate
toDelete->par->right = toDelete->left; toDelete->par->right = toDelete->left;
if (toDelete->left != NULL) if (toDelete->left != NULL)
@ -584,7 +577,7 @@ void checkForCase2(Node *toDelete, int delete, int fromDirection, Node **root)
checkForCase2(parent->right, 0, 1, root); checkForCase2(parent->right, 0, 1, root);
} }
else else
{ // Left Rotate { // Left Rotate
toDelete->par->left = toDelete->right; toDelete->par->left = toDelete->right;
if (toDelete->right != NULL) if (toDelete->right != NULL)
@ -616,7 +609,6 @@ void deleteNode(int val, Node **root)
// Search for the element in the tree // Search for the element in the tree
while (1) while (1)
{ {
if (val == buffRoot->val) if (val == buffRoot->val)
{ {
// Node Found // Node Found
@ -684,7 +676,6 @@ void deleteNode(int val, Node **root)
(toDelete->left != NULL && toDelete->left->color == 1) || (toDelete->left != NULL && toDelete->left->color == 1) ||
(toDelete->right != NULL && toDelete->right->color == 1)) (toDelete->right != NULL && toDelete->right->color == 1))
{ {
// if it is a leaf // if it is a leaf
if (toDelete->left == NULL && toDelete->right == NULL) if (toDelete->left == NULL && toDelete->right == NULL)
{ {
@ -699,7 +690,7 @@ void deleteNode(int val, Node **root)
} }
} }
else else
{ // else its child should be red { // else its child should be red
// Check for the exitstence of left node // Check for the exitstence of left node
if (toDelete->left != NULL) if (toDelete->left != NULL)
@ -710,7 +701,7 @@ void deleteNode(int val, Node **root)
toDelete->left->color = 1; toDelete->left->color = 1;
} }
else else
{ // else the right node should be red { // else the right node should be red
toDelete->par->left = toDelete->right; toDelete->par->left = toDelete->right;
toDelete->right->par = toDelete->par; toDelete->right->par = toDelete->par;
toDelete->right->color = 1; toDelete->right->color = 1;
@ -721,7 +712,7 @@ void deleteNode(int val, Node **root)
free(toDelete); free(toDelete);
} }
else else
{ // Case 2 { // Case 2
checkForCase2(toDelete, 1, ((toDelete->par->right == toDelete)), root); checkForCase2(toDelete, 1, ((toDelete->par->right == toDelete)), root);
} }
} }
@ -755,8 +746,9 @@ int main()
{ {
Node *root = NULL; Node *root = NULL;
int scanValue, choice = 1; int scanValue, choice = 1;
printf("1 - Input\n2 - Delete\n3 - Inorder Traversel\n0 - Quit\n\nPlease " printf(
"Enter the Choice - "); "1 - Input\n2 - Delete\n3 - Inorder Traversel\n0 - Quit\n\nPlease "
"Enter the Choice - ");
scanf("%d", &choice); scanf("%d", &choice);
while (choice) while (choice)
{ {
@ -795,8 +787,9 @@ int main()
printf("Root - %d\n", root->val); printf("Root - %d\n", root->val);
} }
} }
printf("1 - Input\n2 - Delete\n3 - Inorder Traversel\n0 - " printf(
"Quit\n\nPlease Enter the Choice - "); "1 - Input\n2 - Delete\n3 - Inorder Traversel\n0 - "
"Quit\n\nPlease Enter the Choice - ");
scanf("%d", &choice); scanf("%d", &choice);
} }
} }

View File

@ -51,8 +51,8 @@ node *create_node(int data)
void insert_bt(node **root, int data) void insert_bt(node **root, int data)
{ {
node *new_node = create_node(data); node *new_node = create_node(data);
node *temp; // to be deleted node *temp; // to be deleted
node *prev; // keeps track of the parent of the element deleted node *prev; // keeps track of the parent of the element deleted
if (*root == NULL) if (*root == NULL)
{ {
*root = new_node; *root = new_node;
@ -204,7 +204,7 @@ void delete_bt(node **root, int ele)
return; return;
else else
{ {
node *replacement; // deleted node's replacement node *replacement; // deleted node's replacement
node *t; node *t;
if (temp->llink == NULL && temp->rlink == NULL) if (temp->llink == NULL && temp->rlink == NULL)
{ {
@ -220,15 +220,15 @@ void delete_bt(node **root, int ele)
} }
else else
{ {
replacement = temp->rlink; // replaced with inorder successor replacement = temp->rlink; // replaced with inorder successor
t = replacement; t = replacement;
while (t->llink != NULL) while (t->llink != NULL)
{ {
t = t->llink; t = t->llink;
} }
t->llink = t->llink =
temp->llink; // leftmost node of the replacement is linked to temp->llink; // leftmost node of the replacement is linked to
// the left child of the deleted node // the left child of the deleted node
} }
if (temp == *root) if (temp == *root)

View File

@ -1,6 +1,6 @@
#include "dynamic_array.h"
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include "dynamic_array.h"
int main() int main()
{ {

View File

@ -74,8 +74,7 @@ void BellmanFord(struct Graph *graph, int src)
// Initialize distances array as INF for all except source // Initialize distances array as INF for all except source
// Intialize source as zero // Intialize source as zero
for (int i = 0; i < V; i++) for (int i = 0; i < V; i++) dist[i] = INT_MAX;
dist[i] = INT_MAX;
dist[src] = 0; dist[src] = 0;
// Calculate shortest path distance from source to all edges // Calculate shortest path distance from source to all edges
@ -100,8 +99,9 @@ void BellmanFord(struct Graph *graph, int src)
if (dist[u] != INT_MAX && dist[u] + w < dist[v]) if (dist[u] != INT_MAX && dist[u] + w < dist[v])
{ {
printf("Graph contains negative weight cycle. Hence, shortest " printf(
"distance not guaranteed."); "Graph contains negative weight cycle. Hence, shortest "
"distance not guaranteed.");
return; return;
} }
} }

View File

@ -1,18 +1,17 @@
#include "Graph.h"
#include "queue.h"
#include <stdbool.h> #include <stdbool.h>
#include <stdio.h> #include <stdio.h>
#include "Graph.h"
#include "queue.h"
#define MAX_NODES 1000 #define MAX_NODES 1000
int visited[MAX_NODES]; // array to store visiting order int visited[MAX_NODES]; // array to store visiting order
// indexed by vertex 0..nV-1 // indexed by vertex 0..nV-1
bool findPathBFS(Graph g, int nV, Vertex src, Vertex dest) bool findPathBFS(Graph g, int nV, Vertex src, Vertex dest)
{ {
Vertex v; Vertex v;
for (v = 0; v < nV; v++) for (v = 0; v < nV; v++) visited[v] = -1;
visited[v] = -1;
visited[src] = src; visited[src] = src;
queue Q = newQueue(); queue Q = newQueue();

View File

@ -14,8 +14,8 @@ struct Graph
int numVertices; int numVertices;
int *visited; int *visited;
struct node * struct node *
*adjLists; // we need int** to store a two dimensional array. Similary, *adjLists; // we need int** to store a two dimensional array. Similary,
// we need struct node** to store an array of Linked lists // we need struct node** to store an array of Linked lists
}; };
struct Graph *createGraph(int); struct Graph *createGraph(int);
void addEdge(struct Graph *, int, int); void addEdge(struct Graph *, int, int);

View File

@ -1,11 +1,11 @@
#include "Graph.h"
#include <stdbool.h> #include <stdbool.h>
#include <stdio.h> #include <stdio.h>
#include "Graph.h"
#define MAX_NODES 1000 #define MAX_NODES 1000
int visited[MAX_NODES]; // array to store visiting order int visited[MAX_NODES]; // array to store visiting order
// indexed by vertex 0..nV-1 // indexed by vertex 0..nV-1
bool dfsPathCheck(Graph g, int nV, Vertex v, Vertex dest) bool dfsPathCheck(Graph g, int nV, Vertex v, Vertex dest)
{ {
@ -25,8 +25,7 @@ bool dfsPathCheck(Graph g, int nV, Vertex v, Vertex dest)
bool findPathDFS(Graph g, int nV, Vertex src, Vertex dest) bool findPathDFS(Graph g, int nV, Vertex src, Vertex dest)
{ {
Vertex v; Vertex v;
for (v = 0; v < nV; v++) for (v = 0; v < nV; v++) visited[v] = -1;
visited[v] = -1;
visited[src] = src; visited[src] = src;
return dfsPathCheck(g, nV, src, dest); return dfsPathCheck(g, nV, src, dest);
} }

View File

@ -18,8 +18,7 @@ void createGraph(struct Graph *G, int V)
for (int i = 0; i < V; i++) for (int i = 0; i < V; i++)
{ {
G->edges[i] = (int *)malloc(V * sizeof(int)); G->edges[i] = (int *)malloc(V * sizeof(int));
for (int j = 0; j < V; j++) for (int j = 0; j < V; j++) G->edges[i][j] = INT_MAX;
G->edges[i][j] = INT_MAX;
G->edges[i][i] = 0; G->edges[i][i] = 0;
} }
} }
@ -63,13 +62,12 @@ void print(int dist[], int V)
void Dijkstra(struct Graph *graph, int src) void Dijkstra(struct Graph *graph, int src)
{ {
int V = graph->vertexNum; int V = graph->vertexNum;
int mdist[V]; // Stores updated distances to vertex int mdist[V]; // Stores updated distances to vertex
int vset[V]; // vset[i] is true if the vertex i included int vset[V]; // vset[i] is true if the vertex i included
// in the shortest path tree // in the shortest path tree
// Initialise mdist and vset. Set distance of source as zero // Initialise mdist and vset. Set distance of source as zero
for (int i = 0; i < V; i++) for (int i = 0; i < V; i++) mdist[i] = INT_MAX, vset[i] = 0;
mdist[i] = INT_MAX, vset[i] = 0;
mdist[src] = 0; mdist[src] = 0;

View File

@ -1,6 +1,6 @@
#include "Graph.h"
#include <stdbool.h> #include <stdbool.h>
#include <stdio.h> #include <stdio.h>
#include "Graph.h"
// Return the number of vertices that v is // Return the number of vertices that v is
// connected to // connected to

View File

@ -18,8 +18,7 @@ void createGraph(struct Graph *G, int V)
for (int i = 0; i < V; i++) for (int i = 0; i < V; i++)
{ {
G->edges[i] = (int *)malloc(V * sizeof(int)); G->edges[i] = (int *)malloc(V * sizeof(int));
for (int j = 0; j < V; j++) for (int j = 0; j < V; j++) G->edges[i][j] = INT_MAX;
G->edges[i][j] = INT_MAX;
G->edges[i][i] = 0; G->edges[i][i] = 0;
} }
} }
@ -38,7 +37,6 @@ void print(int dist[], int V)
{ {
for (int j = 0; j < V; j++) for (int j = 0; j < V; j++)
{ {
if (dist[i * V + j] != INT_MAX) if (dist[i * V + j] != INT_MAX)
printf("%d\t", dist[i * V + j]); printf("%d\t", dist[i * V + j]);
else else
@ -57,8 +55,7 @@ void FloydWarshall(struct Graph *graph)
// Initialise distance array // Initialise distance array
for (int i = 0; i < V; i++) for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++) for (int j = 0; j < V; j++) dist[i][j] = graph->edges[i][j];
dist[i][j] = graph->edges[i][j];
// Calculate distances // Calculate distances
for (int k = 0; k < V; k++) for (int k = 0; k < V; k++)
@ -79,8 +76,7 @@ void FloydWarshall(struct Graph *graph)
// Convert 2d array to 1d array for print // Convert 2d array to 1d array for print
int dist1d[V * V]; int dist1d[V * V];
for (int i = 0; i < V; i++) for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++) for (int j = 0; j < V; j++) dist1d[i * V + j] = dist[i][j];
dist1d[i * V + j] = dist[i][j];
print(dist1d, V); print(dist1d, V);
} }

View File

@ -7,9 +7,9 @@
typedef struct GraphRep typedef struct GraphRep
{ {
int **edges; // adjacency matrix int **edges; // adjacency matrix
int nV; // #vertices int nV; // #vertices
int nE; // #edges int nE; // #edges
} GraphRep; } GraphRep;
Graph newGraph(int V) Graph newGraph(int V)
@ -43,7 +43,7 @@ void insertEdge(Graph g, Edge e)
assert(g != NULL && validV(g, e.v) && validV(g, e.w)); assert(g != NULL && validV(g, e.v) && validV(g, e.w));
if (!g->edges[e.v][e.w]) if (!g->edges[e.v][e.w])
{ // edge e not in graph { // edge e not in graph
g->edges[e.v][e.w] = 1; g->edges[e.v][e.w] = 1;
g->edges[e.w][e.v] = 1; g->edges[e.w][e.v] = 1;
g->nE++; g->nE++;
@ -55,7 +55,7 @@ void removeEdge(Graph g, Edge e)
assert(g != NULL && validV(g, e.v) && validV(g, e.w)); assert(g != NULL && validV(g, e.v) && validV(g, e.w));
if (g->edges[e.v][e.w]) if (g->edges[e.v][e.w])
{ // edge e in graph { // edge e in graph
g->edges[e.v][e.w] = 0; g->edges[e.v][e.w] = 0;
g->edges[e.w][e.v] = 0; g->edges[e.w][e.v] = 0;
g->nE--; g->nE--;
@ -87,8 +87,7 @@ void freeGraph(Graph g)
assert(g != NULL); assert(g != NULL);
int i; int i;
for (i = 0; i < g->nV; i++) for (i = 0; i < g->nV; i++) free(g->edges[i]);
free(g->edges[i]);
free(g->edges); free(g->edges);
free(g); free(g);
} }

View File

@ -1,6 +1,6 @@
#include "Graph.h"
#include <stdbool.h> #include <stdbool.h>
#include <stdio.h> #include <stdio.h>
#include "Graph.h"
#define MAX_NODES 1000 #define MAX_NODES 1000
@ -38,8 +38,7 @@ bool hamiltonR(Graph g, int nV, Vertex v, Vertex dest, int d)
bool hasHamiltonianPath(Graph g, int nV, Vertex src, Vertex dest) bool hasHamiltonianPath(Graph g, int nV, Vertex src, Vertex dest)
{ {
Vertex v; Vertex v;
for (v = 0; v < nV; v++) for (v = 0; v < nV; v++) visited[v] = false;
visited[v] = false;
return hamiltonR(g, nV, src, dest, nV - 1); return hamiltonR(g, nV, src, dest, nV - 1);
} }

View File

@ -91,9 +91,9 @@ int myComp(const void *a, const void *b)
void KruskalMST(struct Graph *graph) void KruskalMST(struct Graph *graph)
{ {
int V = graph->V; int V = graph->V;
struct Edge result[V]; // Tnis will store the resultant MST struct Edge result[V]; // Tnis will store the resultant MST
int e = 0; // An index variable, used for result[] int e = 0; // An index variable, used for result[]
int i = 0; // An index variable, used for sorted edges int i = 0; // An index variable, used for sorted edges
// Step 1: Sort all the edges in non-decreasing // Step 1: Sort all the edges in non-decreasing
// order of their weight. If we are not allowed to // order of their weight. If we are not allowed to
@ -152,8 +152,8 @@ int main()
| \ | | \ |
2--------3 2--------3
4 */ 4 */
int V = 4; // Number of vertices in graph int V = 4; // Number of vertices in graph
int E = 5; // Number of edges in graph int E = 5; // Number of edges in graph
struct Graph *graph = createGraph(V, E); struct Graph *graph = createGraph(V, E);
// add edge 0-1 // add edge 0-1

View File

@ -2,11 +2,11 @@
typedef struct QueueRep *queue; typedef struct QueueRep *queue;
queue newQueue(); // set up empty queue queue newQueue(); // set up empty queue
void dropQueue(queue); // remove unwanted queue void dropQueue(queue); // remove unwanted queue
int QueueIsEmpty(queue); // check whether queue is empty int QueueIsEmpty(queue); // check whether queue is empty
void QueueEnqueue(queue, int); // insert an int at end of queue void QueueEnqueue(queue, int); // insert an int at end of queue
int QueueDequeue(queue); // remove int from front of queue int QueueDequeue(queue); // remove int from front of queue
// By // By
// .----------------. .----------------. .----------------. // .----------------. .----------------. .----------------.

View File

@ -1,6 +1,6 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#define MAX_SIZE 40 // Assume 40 nodes at max in graph #define MAX_SIZE 40 // Assume 40 nodes at max in graph
#define INT_MIN 0 #define INT_MIN 0
// A vertex of the graph // A vertex of the graph
struct node struct node
@ -15,8 +15,8 @@ struct Graph
int numVertices; int numVertices;
int *visited; int *visited;
struct node * struct node *
*adjLists; // we need int** to store a two dimensional array. Similary, *adjLists; // we need int** to store a two dimensional array. Similary,
// we need struct node** to store an array of Linked lists // we need struct node** to store an array of Linked lists
}; };
// Structure to create a stack, necessary for topological sorting // Structure to create a stack, necessary for topological sorting
struct Stack struct Stack
@ -89,14 +89,14 @@ void fillOrder(int vertex, struct Graph *graph, struct Stack *stack)
struct Graph *transpose(struct Graph *g) struct Graph *transpose(struct Graph *g)
{ {
struct Graph *graph = struct Graph *graph =
createGraph(g->numVertices); // Number of vertices is same createGraph(g->numVertices); // Number of vertices is same
int i = 0; int i = 0;
for (i = 0; i < g->numVertices; i++) for (i = 0; i < g->numVertices; i++)
{ {
struct node *temp = g->adjLists[i]; struct node *temp = g->adjLists[i];
while (temp != NULL) while (temp != NULL)
{ {
addEdge(graph, temp->vertex, i); // Reverse all edges addEdge(graph, temp->vertex, i); // Reverse all edges
temp = temp->next; temp = temp->next;
} }
} }
@ -211,7 +211,7 @@ struct Stack *createStack()
void push(struct Stack *stack, int element) void push(struct Stack *stack, int element)
{ {
stack->arr[++stack->top] = stack->arr[++stack->top] =
element; // Increment then add, as we start from -1 element; // Increment then add, as we start from -1
} }
// Removes element from stack, or returns INT_MIN if stack empty // Removes element from stack, or returns INT_MIN if stack empty
int pop(struct Stack *stack) int pop(struct Stack *stack)

View File

@ -1,6 +1,6 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#define MAX_SIZE 40 // Assume 40 nodes at max in graph #define MAX_SIZE 40 // Assume 40 nodes at max in graph
#define INT_MIN 0 #define INT_MIN 0
// A vertex of the graph // A vertex of the graph
struct node struct node
@ -15,8 +15,8 @@ struct Graph
int numVertices; int numVertices;
int *visited; int *visited;
struct node * struct node *
*adjLists; // we need int** to store a two dimensional array. Similary, *adjLists; // we need int** to store a two dimensional array. Similary,
// we need struct node** to store an array of Linked lists // we need struct node** to store an array of Linked lists
}; };
// Structure to create a stack, necessary for topological sorting // Structure to create a stack, necessary for topological sorting
struct Stack struct Stack
@ -97,8 +97,7 @@ void topologicalSort(struct Graph *graph)
topologicalSortHelper(i, graph, stack); topologicalSortHelper(i, graph, stack);
} }
} }
while (stack->top != -1) while (stack->top != -1) printf("%d ", pop(stack));
printf("%d ", pop(stack));
} }
// Allocate memory for a node // Allocate memory for a node
struct node *createNode(int v) struct node *createNode(int v)
@ -159,7 +158,7 @@ struct Stack *createStack()
void push(struct Stack *stack, int element) void push(struct Stack *stack, int element)
{ {
stack->arr[++stack->top] = stack->arr[++stack->top] =
element; // Increment then add, as we start from -1 element; // Increment then add, as we start from -1
} }
// Removes element from stack, or returns INT_MIN if stack empty // Removes element from stack, or returns INT_MIN if stack empty
int pop(struct Stack *stack) int pop(struct Stack *stack)

View File

@ -11,8 +11,7 @@ void warshall()
{ {
int i, s, t; int i, s, t;
for (s = 0; s < NODES; s++) for (s = 0; s < NODES; s++)
for (t = 0; t < NODES; t++) for (t = 0; t < NODES; t++) tc[s][t] = digraph[s][t];
tc[s][t] = digraph[s][t];
for (i = 0; i < NODES; i++) for (i = 0; i < NODES; i++)
for (s = 0; s < NODES; s++) for (s = 0; s < NODES; s++)

View File

@ -105,7 +105,7 @@ int main()
merge(); merge();
printf("\nMerged Linked List: "); printf("\nMerged Linked List: ");
printlist(head1); // list one has been modified printlist(head1); // list one has been modified
return 0; return 0;
} }

View File

@ -11,14 +11,14 @@ struct node
}; };
struct node *start = NULL; struct node *start = NULL;
/////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////
struct node *createnode() // function to create node struct node *createnode() // function to create node
{ {
struct node *t; struct node *t;
t = (struct node *)malloc(sizeof(struct node)); t = (struct node *)malloc(sizeof(struct node));
return (t); return (t);
} }
//////////////////////////////////////////////////////// ////////////////////////////////////////////////////////
void insert() // function to insert at first location void insert() // function to insert at first location
{ {
struct node *p; struct node *p;
p = createnode(); p = createnode();
@ -36,7 +36,7 @@ void insert() // function to insert at first location
} }
} }
/////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////
void deletion() // function to delete from first position void deletion() // function to delete from first position
{ {
struct node *t; struct node *t;
if (start == NULL) if (start == NULL)
@ -52,7 +52,7 @@ void deletion() // function to delete from first position
} }
} }
/////////////////////////////////////////////////////// ///////////////////////////////////////////////////////
void viewlist() // function to display values void viewlist() // function to display values
{ {
struct node *p; struct node *p;
if (start == NULL) if (start == NULL)

View File

@ -69,7 +69,6 @@ void pop(struct node *p)
void display(struct node *p) void display(struct node *p)
{ {
if (top == NULL) if (top == NULL)
printf("stack is empty\n"); printf("stack is empty\n");
else else

View File

@ -29,8 +29,7 @@ L List_push(L list, void *val)
int List_length(L list) int List_length(L list)
{ {
int n; int n;
for (n = 0; list; list = list->next) for (n = 0; list; list = list->next) n++;
n++;
return n; return n;
} }

View File

@ -1,14 +1,13 @@
#include "list.h"
#include <assert.h> #include <assert.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include "list.h"
void print_list(char **array) void print_list(char **array)
{ {
int i; int i;
for (i = 0; array[i]; i++) for (i = 0; array[i]; i++) printf("%s", array[i]);
printf("%s", array[i]);
printf("\n"); printf("\n");
} }

View File

@ -33,7 +33,6 @@ int isEmpty();
int main(int argc, char const *argv[]) int main(int argc, char const *argv[])
{ {
create(); create();
enque(5); enque(5);

View File

@ -38,7 +38,6 @@ int isEmpty();
int main(int argc, char const *argv[]) int main(int argc, char const *argv[])
{ {
int x, y, z; int x, y, z;
create(); create();
@ -54,7 +53,7 @@ int main(int argc, char const *argv[])
y = pop(); y = pop();
// 3, 2. Count: 1. Empty: 0; // 3, 2. Count: 1. Empty: 0;
printf("%d, %d.\t\tCount: %d.\tEmpty: %d.\n", x, y, size(), isEmpty()); printf("%d, %d.\t\tCount: %d.\tEmpty: %d.\n", x, y, size(), isEmpty());
pop(); // Empty the stack. pop(); // Empty the stack.
push(5); push(5);
push(6); push(6);

View File

@ -11,7 +11,6 @@ int a[100], top = -1;
int main() int main()
{ {
int x; int x;
while (1) while (1)
{ {

View File

@ -11,16 +11,16 @@ struct node
struct node *link; struct node *link;
}; };
int c = 0; // c used as counter to check if stack is empty or not int c = 0; // c used as counter to check if stack is empty or not
struct node *head; // declaring head pointer globally assigned to NULL struct node *head; // declaring head pointer globally assigned to NULL
void push(char x) // function for pushing void push(char x) // function for pushing
{ {
struct node *p = head, *temp; struct node *p = head, *temp;
temp = (struct node *)malloc(sizeof(struct node)); temp = (struct node *)malloc(sizeof(struct node));
temp->data = x; temp->data = x;
if (head == if (head ==
NULL) // will be execute only one time i.e, 1st time push is called NULL) // will be execute only one time i.e, 1st time push is called
{ {
head = temp; head = temp;
p = head; p = head;
@ -36,7 +36,7 @@ void push(char x) // function for pushing
} }
} }
char pop(void) // function for pop char pop(void) // function for pop
{ {
char x; char x;
struct node *p = head; struct node *p = head;
@ -51,16 +51,16 @@ int isBalanced(char *s)
{ {
int i = 0; int i = 0;
char x; char x;
while (s[i] != '\0') // loop for covering entire string of brackets while (s[i] != '\0') // loop for covering entire string of brackets
{ {
// printf("\t s[i]=%c\n", s[i]); //DEBUG // printf("\t s[i]=%c\n", s[i]); //DEBUG
if (s[i] == '{' || s[i] == '(' || if (s[i] == '{' || s[i] == '(' ||
s[i] == '[') // if opening bracket then push s[i] == '[') // if opening bracket then push
push(s[i]); push(s[i]);
else else
{ {
if (c <= 0) // i.e, stack is empty as only opening brackets are if (c <= 0) // i.e, stack is empty as only opening brackets are
// added to stack // added to stack
return 0; return 0;
x = pop(); x = pop();

View File

@ -33,7 +33,6 @@ int offset = -1;
void initStack() void initStack()
{ {
array = malloc(sizeof(void *) * max); array = malloc(sizeof(void *) * max);
assert(array); /* tests whether pointer is assigned to memory. */ assert(array); /* tests whether pointer is assigned to memory. */
} }
@ -46,7 +45,7 @@ void grow()
{ {
max += 10; /* increases the capacity */ max += 10; /* increases the capacity */
int i; // for the loop int i; // for the loop
void **tmp = malloc(sizeof(void *) * max); void **tmp = malloc(sizeof(void *) * max);
/* copies the elements from the origin array in the new one. */ /* copies the elements from the origin array in the new one. */
@ -62,12 +61,10 @@ void grow()
/* push: pushs the argument onto the stack */ /* push: pushs the argument onto the stack */
void push(void *object) void push(void *object)
{ {
assert(object); /* tests whether pointer isn't null */ assert(object); /* tests whether pointer isn't null */
if (counter < max) if (counter < max)
{ {
offset++; /* increases the element-pointer */ offset++; /* increases the element-pointer */
/* /*
@ -81,7 +78,6 @@ void push(void *object)
} }
else /* stack is full */ else /* stack is full */
{ {
grow(); /* lets grow stack */ grow(); /* lets grow stack */
push(object); /* recursive call */ push(object); /* recursive call */
} }
@ -92,7 +88,6 @@ void push(void *object)
*/ */
void *pop() void *pop()
{ {
void *top = *(array + offset); void *top = *(array + offset);
/* check pointers */ /* check pointers */

View File

@ -1,7 +1,7 @@
#include "stack.h"
#include <assert.h> #include <assert.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include "stack.h"
int main() int main()
{ {

View File

@ -84,8 +84,7 @@ char *abbreviate(const char *phrase)
strcat(acr, words[i]); strcat(acr, words[i]);
} }
for (i = 0; i < counter; i++) for (i = 0; i < counter; i++) free(words[i]);
free(words[i]);
free(words); free(words);
return acr; return acr;

View File

@ -6,7 +6,6 @@
*/ */
bool is_isogram(const char phrase[]) bool is_isogram(const char phrase[])
{ {
/* use 'unsigned' because of the function strlen(...) */ /* use 'unsigned' because of the function strlen(...) */
unsigned int i = 0; unsigned int i = 0;
unsigned int j = 0; unsigned int j = 0;

View File

@ -4,7 +4,6 @@
char *to_rna(const char s[]) char *to_rna(const char s[])
{ {
/* determines the length of the given string */ /* determines the length of the given string */
int len = strlen(s); int len = strlen(s);

View File

@ -41,7 +41,6 @@ int word_count(const char *input_text, word_count_word_t *words)
input[index] = '\0'; input[index] = '\0';
if (strlen(p_str) <= MAX_WORD_LENGTH) if (strlen(p_str) <= MAX_WORD_LENGTH)
{ {
if (index_list <= MAX_WORDS) if (index_list <= MAX_WORDS)
{ {
strcpy(word_list[index_list], p_str); strcpy(word_list[index_list], p_str);

View File

@ -1,8 +1,8 @@
#ifndef WORD_COUNT_H #ifndef WORD_COUNT_H
#define WORD_COUNT_H #define WORD_COUNT_H
#define MAX_WORDS 20 // at most MAX_WORDS can be found in the test input string #define MAX_WORDS 20 // at most MAX_WORDS can be found in the test input string
#define MAX_WORD_LENGTH 50 // no individual word can exceed this length #define MAX_WORD_LENGTH 50 // no individual word can exceed this length
// results structure // results structure
typedef struct word_count_word typedef struct word_count_word

View File

@ -63,7 +63,6 @@ void dijkstra(int s)
int main(int argc, char const *argv[]) int main(int argc, char const *argv[])
{ {
printf("Enter the number of vertices: "); printf("Enter the number of vertices: ");
scanf(" %d", &V); scanf(" %d", &V);
printf("Enter the adj matrix: "); printf("Enter the adj matrix: ");

View File

@ -3,8 +3,8 @@
This file contains a simple test program for each hash-function. This file contains a simple test program for each hash-function.
*/ */
#include "hash.h"
#include <stdio.h> #include <stdio.h>
#include "hash.h"
int main(void) int main(void)
{ {

View File

@ -4,7 +4,6 @@ int min(int a, int b) { return ((a < b) ? a : b); }
// Two pointer approach to find maximum container area // Two pointer approach to find maximum container area
int maxArea(int *height, int heightSize) int maxArea(int *height, int heightSize)
{ {
// Start with maximum container width // Start with maximum container width
int start = 0; int start = 0;
int end = heightSize - 1; int end = heightSize - 1;

View File

@ -1,7 +1,6 @@
int distanceBetweenBusStops(int *distance, int distanceSize, int start, int distanceBetweenBusStops(int *distance, int distanceSize, int start,
int destination) int destination)
{ {
int sum1 = 0, sum2 = 0; int sum1 = 0, sum2 = 0;
if (start > destination) if (start > destination)
{ {

View File

@ -1,7 +1,6 @@
int singleNumber(int *nums, int numsSize) int singleNumber(int *nums, int numsSize)
{ {
int i, result = 0; int i, result = 0;
for (i = 0; i < numsSize; i++) for (i = 0; i < numsSize; i++) result = result ^ nums[i];
result = result ^ nums[i];
return result; return result;
} }

View File

@ -1,25 +1,26 @@
uint32_t reverseBits(uint32_t n) uint32_t reverseBits(uint32_t n)
{ {
uint TotalBits = 32; uint TotalBits = 32;
uint32_t reverse_int = 0; // stored in memory as 32 bits, each bit valued 0 uint32_t reverse_int = 0; // stored in memory as 32 bits, each bit valued 0
uint i; uint i;
for (i = 0; i < TotalBits; i++) for (i = 0; i < TotalBits; i++)
{ {
if ((n & (UINT32_C(1) if ((n & (UINT32_C(1)
<< i))) // if the bit on the ith position of 32 bit input is << i))) // if the bit on the ith position of 32 bit input is
// 1, then proceed Further note the use of UINT32_C to // 1, then proceed Further note the use of UINT32_C
// convert 1 to unsigned 32 bit int, since just 1 is // to convert 1 to unsigned 32 bit int, since just 1
// treated as int which cannot be shifted left more // is treated as int which cannot be shifted left
// than 30 times // more than 30 times
reverse_int = reverse_int =
reverse_int | reverse_int |
(UINT32_C(1) (UINT32_C(1)
<< (TotalBits - 1 - << (TotalBits - 1 -
i)); // Convert the ith bit from the end in reverse_int i)); // Convert the ith bit from the end in reverse_int
// from 0 to 1, if ith bit from beginning in n is 1 // from 0 to 1, if ith bit from beginning in n is 1
// This is achieved by using bitwise OR on reverse_int // This is achieved by using bitwise OR on
// (where ith bit from end is currently 0) and 1 // reverse_int (where ith bit from end is currently
// shifted left 31 - i bits (to ith bit from the end) // 0) and 1 shifted left 31 - i bits (to ith bit from
// the end)
} }
return reverse_int; return reverse_int;
} }

View File

@ -6,10 +6,10 @@ int hammingWeight(uint32_t n)
{ {
if (n & if (n &
(UINT32_C(1) (UINT32_C(1)
<< i)) // if the bit on the ith position of 32 bit input is 1, << i)) // if the bit on the ith position of 32 bit input is 1,
// then proceed Further note the use of UINT32_C to // then proceed Further note the use of UINT32_C to
// convert 1 to unsigned 32 bit int, as just 1 is treated // convert 1 to unsigned 32 bit int, as just 1 is treated
// as int which cannot be shifted left more than 30 times // as int which cannot be shifted left more than 30 times
weight += 1; weight += 1;
} }
return weight; return weight;

View File

@ -2,7 +2,6 @@ bool isPowerOfTwo(int n)
{ {
if (!n) if (!n)
return false; return false;
while (n % 2 == 0) while (n % 2 == 0) n /= 2;
n /= 2;
return n == 1; return n == 1;
} }

View File

@ -4,14 +4,11 @@ bool isAnagram(char *s, char *t)
int m = strlen(t); int m = strlen(t);
int cnt_s[1000], cnt_t[1000]; int cnt_s[1000], cnt_t[1000];
for (int c = 97; c < 97 + 26; c++) for (int c = 97; c < 97 + 26; c++) cnt_s[c] = cnt_t[c] = 0;
cnt_s[c] = cnt_t[c] = 0;
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++) cnt_s[s[i]]++;
cnt_s[s[i]]++;
for (int i = 0; i < m; i++) for (int i = 0; i < m; i++) cnt_t[t[i]]++;
cnt_t[t[i]]++;
for (int c = 97; c < 97 + 26; c++) for (int c = 97; c < 97 + 26; c++)
if (cnt_s[c] != cnt_t[c]) if (cnt_s[c] != cnt_t[c])

View File

@ -1,29 +1,28 @@
int lengthOfLongestSubstring(char *str) int lengthOfLongestSubstring(char *str)
{ {
int n = strlen(str); int n = strlen(str);
if (!n) if (!n)
return 0; return 0;
int L_len = 1; // lenght of longest substring int L_len = 1; // lenght of longest substring
int C_len = 1; // lenght of current substring int C_len = 1; // lenght of current substring
int P_ind, i; // P_ind for previous index int P_ind, i; // P_ind for previous index
int visited[256]; // visited will keep track of visiting char for the last int visited[256]; // visited will keep track of visiting char for the last
// instance. since there are 256 ASCII char, its size is // instance. since there are 256 ASCII char, its size is
// limited to that value. // limited to that value.
memset(visited, -1, sizeof(int) * 256); memset(visited, -1, sizeof(int) * 256);
visited[str[0]] = visited[str[0]] =
0; // the index of that char will tell us that when it was visited. 0; // the index of that char will tell us that when it was visited.
for (i = 1; i < n; i++) for (i = 1; i < n; i++)
{ {
P_ind = visited[str[i]]; P_ind = visited[str[i]];
if (P_ind == -1 || i - C_len > P_ind) if (P_ind == -1 || i - C_len > P_ind)
C_len++; // if the current char was not visited earlier, or it is C_len++; // if the current char was not visited earlier, or it is
// not the part of current substring // not the part of current substring
else else
{ // otherwise, we need to change the current/longest substring length { // otherwise, we need to change the current/longest substring length
if (C_len > L_len) if (C_len > L_len)
L_len = C_len; L_len = C_len;
C_len = i - P_ind; C_len = i - P_ind;
@ -57,8 +56,7 @@ int lengthOfLongestSubstring(char *s)
if (cur_max >= max) if (cur_max >= max)
max = cur_max; max = cur_max;
cur_max = 0; cur_max = 0;
while (s[end - 1] != c) while (s[end - 1] != c) end--;
end--;
} }
} }
if (cur_max >= max) if (cur_max >= max)

View File

@ -1,6 +1,5 @@
char *countAndSay(int n) char *countAndSay(int n)
{ {
// Calculating the length of array // Calculating the length of array
double result = 1.0; double result = 1.0;
for (int i = 0; i < n - 1; i++) for (int i = 0; i < n - 1; i++)

View File

@ -2,8 +2,7 @@ int firstUniqChar(char *s)
{ {
int *arr = calloc(256, sizeof(int)); int *arr = calloc(256, sizeof(int));
int i; int i;
for (i = 0; i < strlen(s); i++) for (i = 0; i < strlen(s); i++) arr[s[i]] = arr[s[i]] + 1;
arr[s[i]] = arr[s[i]] + 1;
for (i = 0; i < strlen(s); i++) for (i = 0; i < strlen(s); i++)
{ {
if (arr[s[i]] == 1) if (arr[s[i]] == 1)

View File

@ -2,9 +2,7 @@ char findTheDifference(char *s, char *t)
{ {
int sum1 = 0, sum2 = 0; int sum1 = 0, sum2 = 0;
int i; int i;
for (i = 0; i < strlen(s); i++) for (i = 0; i < strlen(s); i++) sum1 += s[i];
sum1 += s[i]; for (i = 0; i < strlen(t); i++) sum2 += t[i];
for (i = 0; i < strlen(t); i++)
sum2 += t[i];
return (char)(sum2 - sum1); return (char)(sum2 - sum1);
} }

View File

@ -2,7 +2,6 @@ int cmpval(const void *a, const void *b) { return *(int *)a - *(int *)b; }
int *findDuplicates(int *nums, int numsSize, int *returnSize) int *findDuplicates(int *nums, int numsSize, int *returnSize)
{ {
int i; int i;
qsort(nums, numsSize, sizeof(int), cmpval); qsort(nums, numsSize, sizeof(int), cmpval);
int *retArr = malloc(numsSize * sizeof(int)); int *retArr = malloc(numsSize * sizeof(int));

View File

@ -1,19 +1,19 @@
int hammingDistance(int x, int y) int hammingDistance(int x, int y)
{ {
int difference = int difference =
x ^ y; // The XOR operator generates the bitwise difference in the x ^ y; // The XOR operator generates the bitwise difference in the
// binary representation of two numbers If bit in ith position of // binary representation of two numbers If bit in ith position
// both numbers is same, bit in difference is 0, otherwise 1 // of both numbers is same, bit in difference is 0, otherwise 1
int TotalBits = sizeof(difference) * 8; // total number of bits int TotalBits = sizeof(difference) * 8; // total number of bits
int i, distance = 0; int i, distance = 0;
for (i = 0; i < TotalBits; i++) for (i = 0; i < TotalBits; i++)
{ {
if (difference & if (difference &
(UINT32_C(1) (UINT32_C(1)
<< i)) // if the bit on the ith position of 32 bit input is 1, then << i)) // if the bit on the ith position of 32 bit input is 1,
// proceed Further note the use of UINT32_C to convert 1 to // then proceed Further note the use of UINT32_C to convert
// unsigned 32 bit int, as just 1 is treated as int which // 1 to unsigned 32 bit int, as just 1 is treated as int
// cannot be shifted left more than 30 times // which cannot be shifted left more than 30 times
distance += 1; distance += 1;
} }
return distance; return distance;

View File

@ -3,21 +3,21 @@ int findComplement(int num)
int TotalBits = 0; int TotalBits = 0;
int temp = num; int temp = num;
while (temp) while (temp)
{ // To find position of MSB in given num. Since num is represented as a { // To find position of MSB in given num. Since num is represented as a
// standard size in memory, we cannot rely on size for that information. // standard size in memory, we cannot rely on size for that information.
TotalBits++; // increment TotalBits till temp becomes 0 TotalBits++; // increment TotalBits till temp becomes 0
temp >>= 1; // shift temp right by 1 bit every iteration; temp loses 1 temp >>= 1; // shift temp right by 1 bit every iteration; temp loses 1
// bit to underflow every iteration till it becomes 0 // bit to underflow every iteration till it becomes 0
} }
int i, int i,
flipNumber = flipNumber = 1; // Eg: 1's complement of 101(binary) can be found as
1; // Eg: 1's complement of 101(binary) can be found as 101^111 (XOR // 101^111 (XOR with 111 flips all bits that are 1 to 0
// with 111 flips all bits that are 1 to 0 and flips 0 to 1) // and flips 0 to 1)
for (i = 1; i < TotalBits; i++) for (i = 1; i < TotalBits; i++)
{ {
flipNumber += UINT32_C(1) flipNumber += UINT32_C(1)
<< i; // Note the use of unsigned int to facilitate left << i; // Note the use of unsigned int to facilitate left
// shift more than 31 times, if needed // shift more than 31 times, if needed
} }
num = num ^ flipNumber; num = num ^ flipNumber;
return num; return num;

View File

@ -3,7 +3,6 @@ int arrayPairSum(int *nums, int numsSize)
{ {
int sum = 0, i; int sum = 0, i;
qsort(nums, numsSize, sizeof(int), cmpval); qsort(nums, numsSize, sizeof(int), cmpval);
for (i = 0; i < numsSize; i = i + 2) for (i = 0; i < numsSize; i = i + 2) sum = sum + nums[i];
sum = sum + nums[i];
return sum; return sum;
} }

View File

@ -1,6 +1,5 @@
char *toLowerCase(char *str) char *toLowerCase(char *str)
{ {
for (int i = 0; i < strlen(str); i++) for (int i = 0; i < strlen(str); i++) str[i] = tolower(str[i]);
str[i] = tolower(str[i]);
return str; return str;
} }

View File

@ -8,12 +8,10 @@ int numJewelsInStones(char *j, char *s)
memset(cnt, 0, sizeof(cnt)); memset(cnt, 0, sizeof(cnt));
// lookup to know which character occurs in j // lookup to know which character occurs in j
for (int i = 0; i < lenj; i++) for (int i = 0; i < lenj; i++) cnt[j[i]]++;
cnt[j[i]]++;
// count the characters in s // count the characters in s
for (int i = 0; i < lens; i++) for (int i = 0; i < lens; i++) sol += cnt[s[i]];
sol += cnt[s[i]];
return sol; return sol;
} }

View File

@ -26,8 +26,7 @@ int cmpval(const void *a, const void *b) { return *(int *)a - *(int *)b; }
int *sortedSquares(int *A, int ASize, int *returnSize) int *sortedSquares(int *A, int ASize, int *returnSize)
{ {
int *res = malloc(ASize * sizeof(int)); int *res = malloc(ASize * sizeof(int));
for (int i = 0; i < ASize; i++) for (int i = 0; i < ASize; i++) res[i] = A[i] * A[i];
res[i] = A[i] * A[i];
*returnSize = ASize; *returnSize = ASize;
qsort(res, ASize, sizeof(int), cmpval); qsort(res, ASize, sizeof(int), cmpval);
return res; return res;

View File

@ -30,18 +30,17 @@
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
#define MAX_ITER 500 // INT_MAX ///< Maximum number of iterations to learn #define MAX_ITER 500 // INT_MAX ///< Maximum number of iterations to learn
/** structure to hold adaline model parameters */ /** structure to hold adaline model parameters */
struct adaline struct adaline
{ {
double eta; ///< learning rate of the algorithm
double eta; ///< learning rate of the algorithm double *weights; ///< weights of the neural network
double *weights; ///< weights of the neural network int num_weights; ///< number of weights of the neural network
int num_weights; ///< number of weights of the neural network
}; };
#define ACCURACY 1e-5 ///< convergence accuracy \f$=1\times10^{-5}\f$ #define ACCURACY 1e-5 ///< convergence accuracy \f$=1\times10^{-5}\f$
/** /**
* Default constructor * Default constructor
@ -70,8 +69,7 @@ struct adaline new_adaline(const int num_features, const double eta)
} }
// initialize with random weights in the range [-50, 49] // initialize with random weights in the range [-50, 49]
for (int i = 0; i < num_weights; i++) for (int i = 0; i < num_weights; i++) ada.weights[i] = 1.f;
ada.weights[i] = 1.f;
// ada.weights[i] = (double)(rand() % 100) - 50); // ada.weights[i] = (double)(rand() % 100) - 50);
return ada; return ada;
@ -100,7 +98,7 @@ int activation(double x) { return x > 0 ? 1 : -1; }
*/ */
char *get_weights_str(struct adaline *ada) char *get_weights_str(struct adaline *ada)
{ {
static char out[100]; // static so the value is persistent static char out[100]; // static so the value is persistent
sprintf(out, "<"); sprintf(out, "<");
for (int i = 0; i < ada->num_weights; i++) for (int i = 0; i < ada->num_weights; i++)
@ -124,15 +122,14 @@ char *get_weights_str(struct adaline *ada)
*/ */
int predict(struct adaline *ada, const double *x, double *out) int predict(struct adaline *ada, const double *x, double *out)
{ {
double y = ada->weights[ada->num_weights - 1]; // assign bias value double y = ada->weights[ada->num_weights - 1]; // assign bias value
for (int i = 0; i < ada->num_weights - 1; i++) for (int i = 0; i < ada->num_weights - 1; i++) y += x[i] * ada->weights[i];
y += x[i] * ada->weights[i];
if (out) // if out variable is not NULL if (out) // if out variable is not NULL
*out = y; *out = y;
return activation(y); // quantizer: apply ADALINE threshold function return activation(y); // quantizer: apply ADALINE threshold function
} }
/** /**
@ -148,7 +145,7 @@ double fit_sample(struct adaline *ada, const double *x, const int y)
{ {
/* output of the model with current weights */ /* output of the model with current weights */
int p = predict(ada, x, NULL); int p = predict(ada, x, NULL);
int prediction_error = y - p; // error in estimation int prediction_error = y - p; // error in estimation
double correction_factor = ada->eta * prediction_error; double correction_factor = ada->eta * prediction_error;
/* update each weight, the last weight is the bias term */ /* update each weight, the last weight is the bias term */
@ -156,7 +153,7 @@ double fit_sample(struct adaline *ada, const double *x, const int y)
{ {
ada->weights[i] += correction_factor * x[i]; ada->weights[i] += correction_factor * x[i];
} }
ada->weights[ada->num_weights - 1] += correction_factor; // update bias ada->weights[ada->num_weights - 1] += correction_factor; // update bias
return correction_factor; return correction_factor;
} }
@ -207,16 +204,16 @@ void fit(struct adaline *ada, double **X, const int *y, const int N)
*/ */
void test1(double eta) void test1(double eta)
{ {
struct adaline ada = new_adaline(2, eta); // 2 features struct adaline ada = new_adaline(2, eta); // 2 features
const int N = 10; // number of sample points const int N = 10; // number of sample points
const double saved_X[10][2] = {{0, 1}, {1, -2}, {2, 3}, {3, -1}, const double saved_X[10][2] = {{0, 1}, {1, -2}, {2, 3}, {3, -1},
{4, 1}, {6, -5}, {-7, -3}, {-8, 5}, {4, 1}, {6, -5}, {-7, -3}, {-8, 5},
{-9, 2}, {-10, -15}}; {-9, 2}, {-10, -15}};
double **X = (double **)malloc(N * sizeof(double *)); double **X = (double **)malloc(N * sizeof(double *));
const int Y[10] = {1, -1, 1, -1, -1, const int Y[10] = {1, -1, 1, -1, -1,
-1, 1, 1, 1, -1}; // corresponding y-values -1, 1, 1, 1, -1}; // corresponding y-values
for (int i = 0; i < N; i++) for (int i = 0; i < N; i++)
{ {
X[i] = (double *)saved_X[i]; X[i] = (double *)saved_X[i];
@ -255,19 +252,18 @@ void test1(double eta)
*/ */
void test2(double eta) void test2(double eta)
{ {
struct adaline ada = new_adaline(2, eta); // 2 features struct adaline ada = new_adaline(2, eta); // 2 features
const int N = 50; // number of sample points const int N = 50; // number of sample points
double **X = (double **)malloc(N * sizeof(double *)); double **X = (double **)malloc(N * sizeof(double *));
int *Y = (int *)malloc(N * sizeof(int)); // corresponding y-values int *Y = (int *)malloc(N * sizeof(int)); // corresponding y-values
for (int i = 0; i < N; i++) for (int i = 0; i < N; i++) X[i] = (double *)malloc(2 * sizeof(double));
X[i] = (double *)malloc(2 * sizeof(double));
// generate sample points in the interval // generate sample points in the interval
// [-range2/100 , (range2-1)/100] // [-range2/100 , (range2-1)/100]
int range = 500; // sample points full-range int range = 500; // sample points full-range
int range2 = range >> 1; // sample points half-range int range2 = range >> 1; // sample points half-range
for (int i = 0; i < N; i++) for (int i = 0; i < N; i++)
{ {
double x0 = ((rand() % range) - range2) / 100.f; double x0 = ((rand() % range) - range2) / 100.f;
@ -300,8 +296,7 @@ void test2(double eta)
printf(" ...passed\n"); printf(" ...passed\n");
} }
for (int i = 0; i < N; i++) for (int i = 0; i < N; i++) free(X[i]);
free(X[i]);
free(X); free(X);
free(Y); free(Y);
delete_adaline(&ada); delete_adaline(&ada);
@ -320,19 +315,18 @@ void test2(double eta)
*/ */
void test3(double eta) void test3(double eta)
{ {
struct adaline ada = new_adaline(6, eta); // 2 features struct adaline ada = new_adaline(6, eta); // 2 features
const int N = 50; // number of sample points const int N = 50; // number of sample points
double **X = (double **)malloc(N * sizeof(double *)); double **X = (double **)malloc(N * sizeof(double *));
int *Y = (int *)malloc(N * sizeof(int)); // corresponding y-values int *Y = (int *)malloc(N * sizeof(int)); // corresponding y-values
for (int i = 0; i < N; i++) for (int i = 0; i < N; i++) X[i] = (double *)malloc(6 * sizeof(double));
X[i] = (double *)malloc(6 * sizeof(double));
// generate sample points in the interval // generate sample points in the interval
// [-range2/100 , (range2-1)/100] // [-range2/100 , (range2-1)/100]
int range = 200; // sample points full-range int range = 200; // sample points full-range
int range2 = range >> 1; // sample points half-range int range2 = range >> 1; // sample points half-range
for (int i = 0; i < N; i++) for (int i = 0; i < N; i++)
{ {
double x0 = ((rand() % range) - range2) / 100.f; double x0 = ((rand() % range) - range2) / 100.f;
@ -374,8 +368,7 @@ void test3(double eta)
printf(" ...passed\n"); printf(" ...passed\n");
} }
for (int i = 0; i < N; i++) for (int i = 0; i < N; i++) free(X[i]);
free(X[i]);
free(X); free(X);
free(Y); free(Y);
delete_adaline(&ada); delete_adaline(&ada);
@ -384,10 +377,10 @@ void test3(double eta)
/** Main function */ /** Main function */
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
srand(time(NULL)); // initialize random number generator srand(time(NULL)); // initialize random number generator
double eta = 0.1; // default value of eta double eta = 0.1; // default value of eta
if (argc == 2) // read eta value from commandline argument if present if (argc == 2) // read eta value from commandline argument if present
eta = strtof(argv[1], NULL); eta = strtof(argv[1], NULL);
test1(eta); test1(eta);

View File

@ -47,7 +47,6 @@ void propagate(Contour *head)
void print(Contour *head) void print(Contour *head)
{ {
Contour *temp = head; Contour *temp = head;
while (temp != NULL) while (temp != NULL)
{ {
@ -62,7 +61,6 @@ void print(Contour *head)
int main(int argc, char const *argv[]) int main(int argc, char const *argv[])
{ {
head = NULL; head = NULL;
int start_num, end_num, levels; int start_num, end_num, levels;

View File

@ -19,25 +19,25 @@ int main()
{ {
theta = atan(y / x); theta = atan(y / x);
if ((x > 0 && y > 0) || (x == -y)) if ((x > 0 && y > 0) || (x == -y))
{ // Q1 { // Q1
thetaFinal = theta; thetaFinal = theta;
} }
else if (x < 0 && y > 0) else if (x < 0 && y > 0)
{ // Q2 { // Q2
thetaFinal = theta + pi; thetaFinal = theta + pi;
} }
else if (x < 0 && y < 0) else if (x < 0 && y < 0)
{ // Q3 { // Q3
thetaFinal = theta - pi; thetaFinal = theta - pi;
} }
else if (x > 0 && y < 0) else if (x > 0 && y < 0)
{ // Q4 { // Q4
thetaFinal = 2 * pi - theta; thetaFinal = 2 * pi - theta;
} }
} }
} }
if (x == 0) if (x == 0)
{ // exceptions when no actual angle is present { // exceptions when no actual angle is present
if (y > 0) if (y > 0)
{ {
thetaFinal = pi / 2; thetaFinal = pi / 2;

View File

@ -2,27 +2,27 @@
code for computing nth catalan number code for computing nth catalan number
*/ */
#include <stdio.h> #include <stdio.h>
long int factorial(int x) // long int for more than 10 factorial long int factorial(int x) // long int for more than 10 factorial
{ {
int i; int i;
long int fac; // fac stores x factorial long int fac; // fac stores x factorial
fac = x; fac = x;
for (i = 1; i < x; i++) // loop to calculate x factorial for (i = 1; i < x; i++) // loop to calculate x factorial
{ {
fac = fac * (x - i); fac = fac * (x - i);
} }
return fac; // returning x factorial return fac; // returning x factorial
} }
int main() int main()
{ {
long int f1, f2, f3; // long int for more than 10 factorial long int f1, f2, f3; // long int for more than 10 factorial
int n; int n;
float C; // C is catalan number for n; float C; // C is catalan number for n;
scanf("%d", &n); scanf("%d", &n);
f1 = factorial(2 * n); f1 = factorial(2 * n);
f2 = factorial(n + 1); f2 = factorial(n + 1);
f3 = factorial(n); f3 = factorial(n);
C = f1 / (f2 * f3); // formula for catalan number for n C = f1 / (f2 * f3); // formula for catalan number for n
printf("%0.2f", C); printf("%0.2f", C);
return 0; return 0;
} }

View File

@ -21,18 +21,18 @@ int main(int argc, char *argv[])
else else
{ {
printf("Enter starting number: "); printf("Enter starting number: ");
scanf("%lu", &n); // input number scanf("%lu", &n); // input number
} }
curr_no = n; // curr_no stores input number n curr_no = n; // curr_no stores input number n
while (curr_no != 1) // loop till series reaches 1 while (curr_no != 1) // loop till series reaches 1
{ {
num_steps++; num_steps++;
printf("%llu->", curr_no); printf("%llu->", curr_no);
if (curr_no % 2 == 0) // condition for even number if (curr_no % 2 == 0) // condition for even number
curr_no = curr_no / 2; curr_no = curr_no / 2;
else else
curr_no = (curr_no * 3) + 1; // condition for odd number curr_no = (curr_no * 3) + 1; // condition for odd number
} }
printf("1\nNumber of steps: %llu\n", num_steps); printf("1\nNumber of steps: %llu\n", num_steps);
return 0; return 0;

View File

@ -25,8 +25,7 @@ int main()
temp = temp / 10; temp = temp / 10;
} }
} }
for (i = counter; i >= 0; i--) for (i = counter; i >= 0; i--) printf("%d", a[i]);
printf("%d", a[i]);
} }
return 0; return 0;
} }

View File

@ -107,8 +107,7 @@ int main(int argc, char *argv[])
large_num *result = new_number(); large_num *result = new_number();
clock_t start_time = clock(); clock_t start_time = clock();
for (i = 2; i <= number; i++) for (i = 2; i <= number; i++) /* Multiply every number from 2 thru N */
/* Multiply every number from 2 thru N */
multiply(result, i); multiply(result, i);
double time_taken = (clock() - start_time) * (double)1e3 / CLOCKS_PER_SEC; double time_taken = (clock() - start_time) * (double)1e3 / CLOCKS_PER_SEC;
// time_taken = (clock() - start_time) / (double) CLOCKS_PER_SEC; // time_taken = (clock() - start_time) / (double) CLOCKS_PER_SEC;

View File

@ -2,7 +2,7 @@
programme for computing number of zeroes at the end of factorial of a given programme for computing number of zeroes at the end of factorial of a given
number n number n
*/ */
#include <math.h> //including math.h header file to use pow function #include <math.h> //including math.h header file to use pow function
#include <stdio.h> #include <stdio.h>
int main() int main()
{ {
@ -16,14 +16,14 @@ int main()
test = test =
n / n /
pow(5, pow(5,
i); // division of n by ith power of 5(storing in integer form) i); // division of n by ith power of 5(storing in integer form)
if (test != if (test !=
0) // condition for zeroes at end corresponding individual ith case 0) // condition for zeroes at end corresponding individual ith case
{ {
count = count + test; count = count + test;
} }
else else
break; // break the loop for if test=0 break; // break the loop for if test=0
} }
printf("%d\n", count); printf("%d\n", count);
return 0; return 0;

View File

@ -17,7 +17,7 @@ int fib(int n)
} }
// declaring array to store fibonacci numbers -- memoization // declaring array to store fibonacci numbers -- memoization
int *f = (int *)malloc( int *f = (int *)malloc(
(n + 2) * sizeof(int)); // one extra to handle edge case, n = 0 (n + 2) * sizeof(int)); // one extra to handle edge case, n = 0
int i; int i;
/* let 0th and 1st number of the series be 0 and 1*/ /* let 0th and 1st number of the series be 0 and 1*/

View File

@ -62,7 +62,7 @@ int main(int argc, char *argv[])
{ {
unsigned long number, result; unsigned long number, result;
setlocale(LC_NUMERIC, ""); // format the printf output setlocale(LC_NUMERIC, ""); // format the printf output
// Asks for the number/position of term in Fibonnacci sequence // Asks for the number/position of term in Fibonnacci sequence
if (argc == 2) if (argc == 2)

View File

@ -2,7 +2,6 @@
int main() int main()
{ {
int a[16500], T; int a[16500], T;
long long int i, j; long long int i, j;

View File

@ -14,8 +14,9 @@ int main()
printf("Input a number, this is the bigger bound of the lerp:\n"); printf("Input a number, this is the bigger bound of the lerp:\n");
scanf("%f", &finish); scanf("%f", &finish);
printf("Input a number, this is in how many steps you want to divide the " printf(
"lerp:\n"); "Input a number, this is in how many steps you want to divide the "
"lerp:\n");
scanf("%f", &steps); scanf("%f", &steps);
for (int i = 0; i < steps + 1; i++) for (int i = 0; i < steps + 1; i++)

View File

@ -50,7 +50,7 @@ void PrintSortedPermutations(char *str)
int main() int main()
{ {
int n; // size of string int n; // size of string
scanf("%d\n", &n); scanf("%d\n", &n);
char *str = (char *)malloc(n * sizeof(char)); char *str = (char *)malloc(n * sizeof(char));
scanf("%s", str); scanf("%s", str);

View File

@ -2,7 +2,7 @@
#include <stdlib.h> #include <stdlib.h>
void longestSub(int *ARRAY, int ARRAY_LENGTH, int **RESULT, int *RESULT_LENGTH) void longestSub(int *ARRAY, int ARRAY_LENGTH, int **RESULT, int *RESULT_LENGTH)
{ // RESULT and RESULT_LENGTH will be modified by their pointers { // RESULT and RESULT_LENGTH will be modified by their pointers
if (ARRAY_LENGTH <= 1) if (ARRAY_LENGTH <= 1)
{ {
@ -20,7 +20,6 @@ void longestSub(int *ARRAY, int ARRAY_LENGTH, int **RESULT, int *RESULT_LENGTH)
{ {
if (ARRAY[i] < PIVOT) if (ARRAY[i] < PIVOT)
{ {
TEMPORARY_ARRAY_LENGTH = 0; TEMPORARY_ARRAY_LENGTH = 0;
TEMPORARY_ARRAY = NULL; TEMPORARY_ARRAY = NULL;
@ -28,7 +27,6 @@ void longestSub(int *ARRAY, int ARRAY_LENGTH, int **RESULT, int *RESULT_LENGTH)
{ {
if (ARRAY[j] >= ARRAY[i]) if (ARRAY[j] >= ARRAY[i])
{ {
TEMPORARY_ARRAY_LENGTH++; TEMPORARY_ARRAY_LENGTH++;
TEMPORARY_ARRAY = (int *)realloc( TEMPORARY_ARRAY = (int *)realloc(
TEMPORARY_ARRAY, TEMPORARY_ARRAY,
@ -41,7 +39,6 @@ void longestSub(int *ARRAY, int ARRAY_LENGTH, int **RESULT, int *RESULT_LENGTH)
&TEMPORARY_ARRAY, &TEMPORARY_ARRAY_LENGTH); &TEMPORARY_ARRAY, &TEMPORARY_ARRAY_LENGTH);
if (LONGEST_SUB_LENGTH < TEMPORARY_ARRAY_LENGTH + 1) if (LONGEST_SUB_LENGTH < TEMPORARY_ARRAY_LENGTH + 1)
{ {
LONGEST_SUB_LENGTH = TEMPORARY_ARRAY_LENGTH + 1; LONGEST_SUB_LENGTH = TEMPORARY_ARRAY_LENGTH + 1;
LONGEST_SUB = (int *)realloc( LONGEST_SUB = (int *)realloc(
LONGEST_SUB, LONGEST_SUB_LENGTH * sizeof(int)); LONGEST_SUB, LONGEST_SUB_LENGTH * sizeof(int));
@ -57,7 +54,6 @@ void longestSub(int *ARRAY, int ARRAY_LENGTH, int **RESULT, int *RESULT_LENGTH)
TEMPORARY_ARRAY_LENGTH = 0; TEMPORARY_ARRAY_LENGTH = 0;
for (i = 1; i < ARRAY_LENGTH; i++) for (i = 1; i < ARRAY_LENGTH; i++)
{ {
if (ARRAY[i] >= PIVOT) if (ARRAY[i] >= PIVOT)
{ {
TEMPORARY_ARRAY_LENGTH++; TEMPORARY_ARRAY_LENGTH++;
@ -71,7 +67,6 @@ void longestSub(int *ARRAY, int ARRAY_LENGTH, int **RESULT, int *RESULT_LENGTH)
&TEMPORARY_ARRAY_LENGTH); &TEMPORARY_ARRAY_LENGTH);
if (TEMPORARY_ARRAY_LENGTH + 1 > LONGEST_SUB_LENGTH) if (TEMPORARY_ARRAY_LENGTH + 1 > LONGEST_SUB_LENGTH)
{ {
LONGEST_SUB_LENGTH = TEMPORARY_ARRAY_LENGTH + 1; LONGEST_SUB_LENGTH = TEMPORARY_ARRAY_LENGTH + 1;
LONGEST_SUB = LONGEST_SUB =
(int *)realloc(LONGEST_SUB, LONGEST_SUB_LENGTH * sizeof(int)); (int *)realloc(LONGEST_SUB, LONGEST_SUB_LENGTH * sizeof(int));
@ -86,7 +81,6 @@ void longestSub(int *ARRAY, int ARRAY_LENGTH, int **RESULT, int *RESULT_LENGTH)
int main() int main()
{ {
int EXAMPLE_LENGTH = 8; int EXAMPLE_LENGTH = 8;
int EXAMPLE[] = {18, 2, 15, 4, 30, 0, 11, 12}; int EXAMPLE[] = {18, 2, 15, 4, 30, 0, 11, 12};
@ -96,8 +90,7 @@ int main()
longestSub(EXAMPLE, EXAMPLE_LENGTH, &RESULT, &RESULT_LENGTH); longestSub(EXAMPLE, EXAMPLE_LENGTH, &RESULT, &RESULT_LENGTH);
printf("Longest Sub Sequence length: %d and it's:\n", RESULT_LENGTH); printf("Longest Sub Sequence length: %d and it's:\n", RESULT_LENGTH);
for (i = 0; i < RESULT_LENGTH; i++) for (i = 0; i < RESULT_LENGTH; i++) printf("%d ", RESULT[i]);
printf("%d ", RESULT[i]);
printf("\n"); printf("\n");
return 0; return 0;

View File

@ -1,8 +1,8 @@
#include <stdio.h> #include <stdio.h>
#include <string.h> // we include the library string.h to the use of string #include <string.h> // we include the library string.h to the use of string
void saisie( void saisie(
char *cpointeur); // Prototypes of the three functions used in the program char *cpointeur); // Prototypes of the three functions used in the program
int compte(char *s); int compte(char *s);
char *miroir(char *s); char *miroir(char *s);

View File

@ -62,8 +62,9 @@ int main()
struct pid controller = {.lastError = 0, .integral = 0}; struct pid controller = {.lastError = 0, .integral = 0};
// Take the controller gains from the user // Take the controller gains from the user
printf("Please enter controller gains in format kP, kI, KD. For example, " printf(
"\"1.2 2.1 3.2\"\n> "); "Please enter controller gains in format kP, kI, KD. For example, "
"\"1.2 2.1 3.2\"\n> ");
scanf("%f %f %f", &controller.kP, &controller.kI, &controller.kD); scanf("%f %f %f", &controller.kP, &controller.kI, &controller.kD);
printf("Using kP: %f, kI: %f, kD: %f\n", controller.kP, controller.kI, printf("Using kP: %f, kI: %f, kD: %f\n", controller.kP, controller.kI,
controller.kD); controller.kD);

View File

@ -45,7 +45,6 @@ void destroy(Range);
*/ */
int main() int main()
{ {
int n = 0; /* for user input */ int n = 0; /* for user input */
printf("\t\tPrim factoriziation\n\n"); printf("\t\tPrim factoriziation\n\n");

View File

@ -83,8 +83,7 @@ int main()
scanf("%d%d%d", &N, &R, &C); scanf("%d%d%d", &N, &R, &C);
int a[M], i, j; int a[M], i, j;
for (i = 0; i < N; i++) for (i = 0; i < N; i++)
for (j = 0; j < N; j++) for (j = 0; j < N; j++) scanf("%d", &a[i * N + j]);
scanf("%d", &a[i * N + j]);
if (solve(a)) if (solve(a))
print(a); print(a);

View File

@ -65,7 +65,6 @@ int main(void)
printf("\n"); printf("\n");
for (i = 0; i < n; i++) for (i = 0; i < n; i++)
{ {
printf("Enter Co-efficient Of Equations %d & Total --->>>\n", i + 1); printf("Enter Co-efficient Of Equations %d & Total --->>>\n", i + 1);
for (j = 0; j <= n; j++) for (j = 0; j <= n; j++)
{ {

View File

@ -32,7 +32,6 @@ int main()
p = 1.0; p = 1.0;
for (j = 0; j < n; j++) for (j = 0; j < n; j++)
{ {
if (i != j) if (i != j)
{ {
p = p * (a - x[j]) / (x[i] - x[j]); p = p * (a - x[j]) / (x[i] - x[j]);

View File

@ -32,8 +32,7 @@ int lu_decomposition(double **A, double **L, double **U, int mat_size)
{ {
// Summation of L[i,j] * U[j,k] // Summation of L[i,j] * U[j,k]
double lu_sum = 0.; double lu_sum = 0.;
for (j = 0; j < row; j++) for (j = 0; j < row; j++) lu_sum += L[row][j] * U[j][col];
lu_sum += L[row][j] * U[j][col];
// Evaluate U[i,k] // Evaluate U[i,k]
U[row][col] = A[row][col] - lu_sum; U[row][col] = A[row][col] - lu_sum;
@ -53,8 +52,7 @@ int lu_decomposition(double **A, double **L, double **U, int mat_size)
// Summation of L[i,j] * U[j,k] // Summation of L[i,j] * U[j,k]
double lu_sum = 0.; double lu_sum = 0.;
for (j = 0; j < row; j++) for (j = 0; j < row; j++) lu_sum += L[col][j] * U[j][row];
lu_sum += L[col][j] * U[j][row];
// Evaluate U[i,k] // Evaluate U[i,k]
L[col][row] = (A[col][row] - lu_sum) / U[row][row]; L[col][row] = (A[col][row] - lu_sum) / U[row][row];
@ -80,19 +78,19 @@ void display(double **A, int N)
/** Main function */ /** Main function */
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int mat_size = 3; // default matrix size int mat_size = 3; // default matrix size
const int range = 10; const int range = 10;
const int range2 = range >> 1; const int range2 = range >> 1;
if (argc == 2) if (argc == 2)
mat_size = atoi(argv[1]); mat_size = atoi(argv[1]);
srand(time(NULL)); // random number initializer srand(time(NULL)); // random number initializer
/* Create a square matrix with random values */ /* Create a square matrix with random values */
double **A = (double **)malloc(mat_size * sizeof(double *)); double **A = (double **)malloc(mat_size * sizeof(double *));
double **L = (double **)malloc(mat_size * sizeof(double *)); // output double **L = (double **)malloc(mat_size * sizeof(double *)); // output
double **U = (double **)malloc(mat_size * sizeof(double *)); // output double **U = (double **)malloc(mat_size * sizeof(double *)); // output
for (int i = 0; i < mat_size; i++) for (int i = 0; i < mat_size; i++)
{ {
// calloc so that all valeus are '0' by default // calloc so that all valeus are '0' by default

View File

@ -29,8 +29,7 @@ int main(int argc, char **argv)
} }
putchar('\n'); putchar('\n');
for (i = 0; i < n; i++) for (i = 0; i < n; i++) sum = sum + a[i];
sum = sum + a[i];
mean = sum / (float)n; mean = sum / (float)n;
printf("\nMean :"); printf("\nMean :");

View File

@ -25,8 +25,7 @@ void print_matrix(double **A, /**< matrix to print */
{ {
for (int row = 0; row < M; row++) for (int row = 0; row < M; row++)
{ {
for (int col = 0; col < N; col++) for (int col = 0; col < N; col++) printf("% 9.3g\t", A[row][col]);
printf("% 9.3g\t", A[row][col]);
putchar('\n'); putchar('\n');
} }
putchar('\n'); putchar('\n');
@ -49,8 +48,7 @@ double vector_dot(double *a, double *b, int L)
// parallelize on threads // parallelize on threads
#pragma omp parallel for reduction(+ : mag) #pragma omp parallel for reduction(+ : mag)
#endif #endif
for (i = 0; i < L; i++) for (i = 0; i < L; i++) mag += a[i] * b[i];
mag += a[i] * b[i];
return mag; return mag;
} }
@ -88,8 +86,7 @@ double *vector_proj(double *a, double *b, double *out, int L)
// parallelize on threads // parallelize on threads
#pragma omp for #pragma omp for
#endif #endif
for (i = 0; i < L; i++) for (i = 0; i < L; i++) out[i] = scalar * b[i];
out[i] = scalar * b[i];
return out; return out;
} }
@ -112,8 +109,7 @@ double *vector_sub(double *a, /**< minuend */
// parallelize on threads // parallelize on threads
#pragma omp for #pragma omp for
#endif #endif
for (i = 0; i < L; i++) for (i = 0; i < L; i++) out[i] = a[i] - b[i];
out[i] = a[i] - b[i];
return out; return out;
} }
@ -176,8 +172,7 @@ void qr_decompose(double **A, /**< input matrix to decompose */
} }
for (j = 0; j < i; j++) for (j = 0; j < i; j++)
{ {
for (int k = 0; k < M; k++) for (int k = 0; k < M; k++) col_vector2[k] = Q[k][j];
col_vector2[k] = Q[k][j];
vector_proj(col_vector, col_vector2, col_vector2, M); vector_proj(col_vector, col_vector2, col_vector2, M);
vector_sub(tmp_vector, col_vector2, tmp_vector, M); vector_sub(tmp_vector, col_vector2, tmp_vector, M);
} }
@ -187,16 +182,13 @@ void qr_decompose(double **A, /**< input matrix to decompose */
// parallelize on threads // parallelize on threads
#pragma omp for #pragma omp for
#endif #endif
for (j = 0; j < M; j++) for (j = 0; j < M; j++) Q[j][i] = tmp_vector[j] / mag;
Q[j][i] = tmp_vector[j] / mag;
/* compute upper triangular values of R */ /* compute upper triangular values of R */
for (int kk = 0; kk < M; kk++) for (int kk = 0; kk < M; kk++) col_vector[kk] = Q[kk][i];
col_vector[kk] = Q[kk][i];
for (int k = i; k < N; k++) for (int k = i; k < N; k++)
{ {
for (int kk = 0; kk < M; kk++) for (int kk = 0; kk < M; kk++) col_vector2[kk] = A[kk][k];
col_vector2[kk] = A[kk][k];
R[i][k] = vector_dot(col_vector, col_vector2, M); R[i][k] = vector_dot(col_vector, col_vector2, M);
} }
} }
@ -206,4 +198,4 @@ void qr_decompose(double **A, /**< input matrix to decompose */
free(tmp_vector); free(tmp_vector);
} }
#endif // QR_DECOMPOSE_H #endif // QR_DECOMPOSE_H

View File

@ -6,11 +6,11 @@
* \author [Krishna Vedala](https://github.com/kvedala) * \author [Krishna Vedala](https://github.com/kvedala)
*/ */
#include "qr_decompose.h"
#include <math.h> #include <math.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
#include "qr_decompose.h"
/** /**
* main function * main function
@ -24,8 +24,9 @@ int main(void)
scanf("%u %u", &ROWS, &COLUMNS); scanf("%u %u", &ROWS, &COLUMNS);
if (ROWS < COLUMNS) if (ROWS < COLUMNS)
{ {
fprintf(stderr, "Number of rows must be greater than or equal to " fprintf(stderr,
"number of columns.\n"); "Number of rows must be greater than or equal to "
"number of columns.\n");
return -1; return -1;
} }
@ -36,8 +37,7 @@ int main(void)
A[i] = (double *)malloc(COLUMNS * sizeof(double)); A[i] = (double *)malloc(COLUMNS * sizeof(double));
for (int i = 0; i < ROWS; i++) for (int i = 0; i < ROWS; i++)
for (int j = 0; j < COLUMNS; j++) for (int j = 0; j < COLUMNS; j++) scanf("%lf", &A[i][j]);
scanf("%lf", &A[i][j]);
print_matrix(A, ROWS, COLUMNS); print_matrix(A, ROWS, COLUMNS);

View File

@ -5,12 +5,12 @@
* method. * method.
* \author [Krishna Vedala](https://github.com/kvedala) * \author [Krishna Vedala](https://github.com/kvedala)
*/ */
#include "qr_decompose.h"
#include <assert.h> #include <assert.h>
#include <math.h> #include <math.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
#include "qr_decompose.h"
#ifdef _OPENMP #ifdef _OPENMP
#include <omp.h> #include <omp.h>
#endif #endif
@ -72,8 +72,7 @@ double **mat_mul(double **A, double **B, double **OUT, int R1, int C1, int R2,
for (int j = 0; j < C2; j++) for (int j = 0; j < C2; j++)
{ {
OUT[i][j] = 0.f; OUT[i][j] = 0.f;
for (int k = 0; k < C1; k++) for (int k = 0; k < C1; k++) OUT[i][j] += A[i][k] * B[k][j];
OUT[i][j] += A[i][k] * B[k][j];
} }
return OUT; return OUT;
} }
@ -144,8 +143,7 @@ double eigen_values(double **A, double *eigen_vals, int mat_size,
while (fabs(A[num_eigs][num_eigs - 1]) > EPSILON) while (fabs(A[num_eigs][num_eigs - 1]) > EPSILON)
{ {
last_eig = A[num_eigs][num_eigs]; last_eig = A[num_eigs][num_eigs];
for (int i = 0; i < rows; i++) for (int i = 0; i < rows; i++) A[i][i] -= last_eig; /* A - cI */
A[i][i] -= last_eig; /* A - cI */
qr_decompose(A, Q, R, rows, columns); qr_decompose(A, Q, R, rows, columns);
if (debug_print) if (debug_print)
@ -158,8 +156,7 @@ double eigen_values(double **A, double *eigen_vals, int mat_size,
} }
mat_mul(R, Q, A, columns, columns, rows, columns); mat_mul(R, Q, A, columns, columns, rows, columns);
for (int i = 0; i < rows; i++) for (int i = 0; i < rows; i++) A[i][i] += last_eig; /* A + cI */
A[i][i] += last_eig; /* A + cI */
} }
/* store the converged eigen value */ /* store the converged eigen value */
@ -209,13 +206,12 @@ void test1()
{ {
int mat_size = 2; int mat_size = 2;
double X[][2] = {{5, 7}, {7, 11}}; double X[][2] = {{5, 7}, {7, 11}};
double y[] = {15.56158, 0.384227}; // corresponding y-values double y[] = {15.56158, 0.384227}; // corresponding y-values
double eig_vals[2]; double eig_vals[2];
// The following steps are to convert a "double[][]" to "double **" // The following steps are to convert a "double[][]" to "double **"
double **A = (double **)malloc(mat_size * sizeof(double *)); double **A = (double **)malloc(mat_size * sizeof(double *));
for (int i = 0; i < mat_size; i++) for (int i = 0; i < mat_size; i++) A[i] = X[i];
A[i] = X[i];
printf("------- Test 1 -------\n"); printf("------- Test 1 -------\n");
@ -262,13 +258,12 @@ void test2()
{0, -3, 3, -1, -3}, {0, -3, 3, -1, -3},
{-3, -1, -3, -3, 0}}; {-3, -1, -3, -3, 0}};
double y[] = {9.27648, -9.26948, 2.0181, -1.03516, double y[] = {9.27648, -9.26948, 2.0181, -1.03516,
-5.98994}; // corresponding y-values -5.98994}; // corresponding y-values
double eig_vals[5]; double eig_vals[5];
// The following steps are to convert a "double[][]" to "double **" // The following steps are to convert a "double[][]" to "double **"
double **A = (double **)malloc(mat_size * sizeof(double *)); double **A = (double **)malloc(mat_size * sizeof(double *));
for (int i = 0; i < mat_size; i++) for (int i = 0; i < mat_size; i++) A[i] = X[i];
A[i] = X[i];
printf("------- Test 2 -------\n"); printf("------- Test 2 -------\n");
@ -306,7 +301,7 @@ int main(int argc, char **argv)
if (argc == 2) if (argc == 2)
mat_size = atoi(argv[1]); mat_size = atoi(argv[1]);
else else
{ // if invalid input argument is given run tests { // if invalid input argument is given run tests
test1(); test1();
test2(); test2();
printf("Usage: ./qr_eigen_values [mat_size]\n"); printf("Usage: ./qr_eigen_values [mat_size]\n");
@ -341,12 +336,10 @@ int main(int argc, char **argv)
double dtime = eigen_values(A, eigen_vals, mat_size, 0); double dtime = eigen_values(A, eigen_vals, mat_size, 0);
printf("Eigen vals: "); printf("Eigen vals: ");
for (i = 0; i < mat_size; i++) for (i = 0; i < mat_size; i++) printf("% 9.4g\t", eigen_vals[i]);
printf("% 9.4g\t", eigen_vals[i]);
printf("\nTime taken to compute: % .4g sec\n", dtime); printf("\nTime taken to compute: % .4g sec\n", dtime);
for (int i = 0; i < mat_size; i++) for (int i = 0; i < mat_size; i++) free(A[i]);
free(A[i]);
free(A); free(A);
free(eigen_vals); free(eigen_vals);
return 0; return 0;

View File

@ -4,7 +4,7 @@
float f(float x) float f(float x)
{ {
return 1.0 + return 1.0 +
x * x * x; // This is the expresion of the function to integrate? x * x * x; // This is the expresion of the function to integrate?
} }
int main() int main()

View File

@ -4,7 +4,6 @@
int main() int main()
{ {
int *ARRAY = NULL, ARRAY_LENGTH, i, TEMPORARY_ELEMENT, isSorted = 0; int *ARRAY = NULL, ARRAY_LENGTH, i, TEMPORARY_ELEMENT, isSorted = 0;
float MEAN = 0, VARIANCE = 0, STAND; float MEAN = 0, VARIANCE = 0, STAND;
@ -12,26 +11,25 @@ int main()
scanf("%d", &ARRAY_LENGTH); scanf("%d", &ARRAY_LENGTH);
ARRAY = (int *)realloc( ARRAY = (int *)realloc(
ARRAY, ARRAY,
ARRAY_LENGTH * (sizeof(int))); // We allocate the dedicated memory ARRAY_LENGTH * (sizeof(int))); // We allocate the dedicated memory
for (i = 0; i < ARRAY_LENGTH; i++) // We generate the random numbers for (i = 0; i < ARRAY_LENGTH; i++) // We generate the random numbers
ARRAY[i] = rand() % 100; ARRAY[i] = rand() % 100;
printf("Random Numbers Generated are :\n"); // We display them printf("Random Numbers Generated are :\n"); // We display them
for (i = 0; i < ARRAY_LENGTH; i++) for (i = 0; i < ARRAY_LENGTH; i++) printf("%d ", ARRAY[i]);
printf("%d ", ARRAY[i]);
printf("\nSorted Data: "); // Then we sort it using Bubble Sort.. printf("\nSorted Data: "); // Then we sort it using Bubble Sort..
while (!isSorted) while (!isSorted)
{ // While our array's not sorted { // While our array's not sorted
isSorted = 1; // we suppose that it's sorted isSorted = 1; // we suppose that it's sorted
for (i = 0; i < ARRAY_LENGTH - 1; i++) for (i = 0; i < ARRAY_LENGTH - 1; i++)
{ // then for each element of the array { // then for each element of the array
if (ARRAY[i] > ARRAY[i + 1]) if (ARRAY[i] > ARRAY[i + 1])
{ // if the two elements aren't sorted { // if the two elements aren't sorted
isSorted = 0; // it means that the array is not sorted isSorted = 0; // it means that the array is not sorted
TEMPORARY_ELEMENT = ARRAY[i]; // and we switch these elements TEMPORARY_ELEMENT = ARRAY[i]; // and we switch these elements
// using TEMPORARY_ELEMENT // using TEMPORARY_ELEMENT
ARRAY[i] = ARRAY[i + 1]; ARRAY[i] = ARRAY[i + 1];
ARRAY[i + 1] = TEMPORARY_ELEMENT; ARRAY[i + 1] = TEMPORARY_ELEMENT;
} }

View File

@ -14,12 +14,12 @@ int main()
int t; int t;
printf("Enter number of times you want to try"); printf("Enter number of times you want to try");
scanf("%d", &t); scanf("%d", &t);
while (t--) // while t > 0, decrement 't' before every iteration while (t--) // while t > 0, decrement 't' before every iteration
{ {
unsigned long long N, p = 0, sum = 0; unsigned long long N, p = 0, sum = 0;
printf("Enter the value of N "); printf("Enter the value of N ");
scanf("%lld", &N); // Take input of N from user scanf("%lld", &N); // Take input of N from user
p = (N - 1) / 3; p = (N - 1) / 3;
sum = ((3 * p * (p + 1)) / 2); sum = ((3 * p * (p + 1)) / 2);
@ -28,8 +28,8 @@ int main()
p = (N - 1) / 15; p = (N - 1) / 15;
sum = sum - ((15 * p * (p + 1)) / 2); sum = sum - ((15 * p * (p + 1)) / 2);
printf("%lld\n", sum); // print the sum of all numbers that are printf("%lld\n", sum); // print the sum of all numbers that are
// multiples of 3 & 5 below N // multiples of 3 & 5 below N
} }
return 0; return 0;
} }

View File

@ -19,7 +19,7 @@ int main()
scanf("%d", &n); scanf("%d", &n);
int terms = (n - 1) / 3; int terms = (n - 1) / 3;
sum += ((terms) * (6 + (terms - 1) * 3)) / 2; // sum of an A.P. sum += ((terms) * (6 + (terms - 1) * 3)) / 2; // sum of an A.P.
terms = (n - 1) / 5; terms = (n - 1) / 5;
sum += ((terms) * (10 + (terms - 1) * 5)) / 2; sum += ((terms) * (10 + (terms - 1) * 5)) / 2;
terms = (n - 1) / 15; terms = (n - 1) / 15;

View File

@ -19,7 +19,7 @@ int main()
unsigned long long N, p = 0, sum = 0; unsigned long long N, p = 0, sum = 0;
printf("Enter the value of N "); printf("Enter the value of N ");
scanf("%lld", &N); // Take input of N from user scanf("%lld", &N); // Take input of N from user
for (int i = 0; i < N; i++) for (int i = 0; i < N; i++)
{ {
if (i % 3 == 0 || i % 5 == 0) if (i % 3 == 0 || i % 5 == 0)
@ -27,8 +27,8 @@ int main()
sum = sum + i; sum = sum + i;
} }
} }
printf("%lld\n", sum); // print the sum of all numbers that are printf("%lld\n", sum); // print the sum of all numbers that are
// multiples of 3 & 5 below N // multiples of 3 & 5 below N
} }
return 0; return 0;
} }

View File

@ -85,8 +85,7 @@ int print_number(uint8_t *number, uint8_t N, int8_t num_digits_to_print)
uint8_t end_pos; uint8_t end_pos;
/* skip all initial zeros */ /* skip all initial zeros */
while (number[start_pos] == 0) while (number[start_pos] == 0) start_pos--;
start_pos--;
/* if end_pos < 0, print all digits */ /* if end_pos < 0, print all digits */
if (num_digits_to_print < 0) if (num_digits_to_print < 0)
@ -99,8 +98,7 @@ int print_number(uint8_t *number, uint8_t N, int8_t num_digits_to_print)
return -1; return -1;
} }
for (int i = start_pos; i >= end_pos; i--) for (int i = start_pos; i >= end_pos; i--) putchar(number[i] + 0x30);
putchar(number[i] + 0x30);
putchar('\n'); putchar('\n');

View File

@ -54,8 +54,7 @@ int main(int argc, char **argv)
} }
printf("2^%d = ", N); printf("2^%d = ", N);
for (int i = MAX_NUM_DIGITS - 1; i >= 0; i--) for (int i = MAX_NUM_DIGITS - 1; i >= 0; i--) putchar(digits[i] + 0x30);
putchar(digits[i] + 0x30);
printf("\n\t Sum: %d\t Num. digits: %lu\n", sum, MAX_NUM_DIGITS); printf("\n\t Sum: %d\t Num. digits: %lu\n", sum, MAX_NUM_DIGITS);
free(digits); free(digits);

View File

@ -122,9 +122,10 @@ int main(int argc, char **argv)
} }
} }
printf("Total number of Sundays that happened on the 1st of a month in the " printf(
"last century: %d\n", "Total number of Sundays that happened on the 1st of a month in the "
count_sundays); "last century: %d\n",
count_sundays);
return 0; return 0;
} }

View File

@ -25,7 +25,7 @@ int main()
while (j <= n) while (j <= n)
{ {
if ((j & 1) == 0) // can also use(j%2 == 0) if ((j & 1) == 0) // can also use(j%2 == 0)
sum += j; sum += j;
temp = i; temp = i;
i = j; i = j;

View File

@ -38,8 +38,7 @@ void shell_sort(char data[][MAX_NAME_LEN], int LEN)
} }
} }
#ifdef DEBUG #ifdef DEBUG
for (i = 0; i < LEN; i++) for (i = 0; i < LEN; i++) printf("%s\t", data[i]);
printf("%s\t", data[i]);
#endif #endif
} }
@ -63,8 +62,7 @@ void lazy_sort(char data[][MAX_NAME_LEN], int LEN)
} }
} }
#ifdef DEBUG #ifdef DEBUG
for (i = 0; i < LEN; i++) for (i = 0; i < LEN; i++) printf("%s\t", data[i]);
printf("%s\t", data[i]);
#endif #endif
} }

View File

@ -117,9 +117,10 @@ int main(int argc, char **argv)
} }
printf("Time taken: %.4g s\n", total_duration); printf("Time taken: %.4g s\n", total_duration);
printf("Sum of numbers that cannot be represented as sum of two abundant " printf(
"numbers : %lu\n", "Sum of numbers that cannot be represented as sum of two abundant "
sum); "numbers : %lu\n",
sum);
return 0; return 0;
} }

Some files were not shown because too many files have changed in this diff Show More