0 | A Dynamic Programming based solution for 0 - 1 Knapsack problem ; A utility function that returns maximum of two integers ; Returns the maximum value that can be put in a knapsack of capacity W ; Build table K [ ] [ ] in bottom up manner ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
int max ( int a , int b ) { return ( a > b ) ? a : b ; } int knapSack ( int W , int wt [ ] , int val [ ] , int n ) { int i , w ; int K [ n + 1 ] [ W + 1 ] ; for ( i = 0 ; i <= n ; i ++ ) { for ( w = 0 ; w <= W ; w ++ ) { if ( i == 0 w == 0 ) K [ i ] [ w ] = 0 ; else if ( wt [ i - 1 ] <= w ) K [ i ] [ w ] = max ( val [ i - 1 ] + K [ i - 1 ] [ w - wt [ i - 1 ] ] , K [ i - 1 ] [ w ] ) ; else K [ i ] [ w ] = K [ i - 1 ] [ w ] ; } } return K [ n ] [ W ] ; } int main ( ) { int val [ ] = { 60 , 100 , 120 } ; int wt [ ] = { 10 , 20 , 30 } ; int W = 50 ; int n = sizeof ( val ) / sizeof ( val [ 0 ] ) ; printf ( " % d " , knapSack ( W , wt , val , n ) ) ; return 0 ; }


0 | A Naive recursive implementation of 0 - 1 Knapsack problem ; A utility function that returns maximum of two integers ; Returns the maximum value that can be put in a knapsack of capacity W ; Base Case ; If weight of the nth item is more than Knapsack capacity W , then this item cannot be included in the optimal solution ; Return the maximum of two cases : ( 1 ) nth item included ( 2 ) not included ; Driver program to test above function
How can the above be solved in C?

 #include <stdio.h>
int max ( int a , int b ) { return ( a > b ) ? a : b ; } int knapSack ( int W , int wt [ ] , int val [ ] , int n ) { if ( n == 0 W == 0 ) return 0 ; if ( wt [ n - 1 ] > W ) return knapSack ( W , wt , val , n - 1 ) ; else return max ( val [ n - 1 ] + knapSack ( W - wt [ n - 1 ] , wt , val , n - 1 ) , knapSack ( W , wt , val , n - 1 ) ) ; } int main ( ) { int val [ ] = { 60 , 100 , 120 } ; int wt [ ] = { 10 , 20 , 30 } ; int W = 50 ; int n = sizeof ( val ) / sizeof ( val [ 0 ] ) ; printf ( " % d " , knapSack ( W , wt , val , n ) ) ; return 0 ; }


A Boolean Array Puzzle |  ; Driver code
How can the above be solved in C?

 void changeToZero ( int a [ 2 ] ) { a [ a [ 1 ] ] = a [ ! a [ 1 ] ] ; } int main ( ) { int a [ ] = { 1 , 0 } ; changeToZero ( a ) ; printf ( " ▁ arr [ 0 ] ▁ = ▁ % d ▁
 " , a [ 0 ] ) ; printf ( " ▁ arr [ 1 ] ▁ = ▁ % d ▁ " , a [ 1 ] ) ; getchar ( ) ; return 0 ; }


A program to check if a binary tree is BST or not |  ; false if left is > than node ; false if right is < than node ; false if , recursively , the left or right is not a BST ; passing all that , it 's a BST
How can the above be solved in C?

int isBST ( struct node * node ) { if ( node == NULL ) return 1 ; if ( node -> left != NULL && node -> left -> data > node -> data ) return 0 ; if ( node -> right != NULL && node -> right -> data < node -> data ) return 0 ; if ( ! isBST ( node -> left ) || ! isBST ( node -> right ) ) return 0 ; return 1 ; }


A program to check if a binary tree is BST or not | Returns true if a binary tree is a binary search tree ; false if the max of the left is > than us ; false if the min of the right is <= than us ; false if , recursively , the left or right is not a BST ; passing all that , it 's a BST
How can the above be solved in C?

int isBST ( struct node * node ) { if ( node == NULL ) return 1 ; if ( node -> left != NULL && maxValue ( node -> left ) > node -> data ) return 0 ; if ( node -> right != NULL && minValue ( node -> right ) < node -> data ) return 0 ; if ( ! isBST ( node -> left ) || ! isBST ( node -> right ) ) return 0 ; return 1 ; }


AVL with duplicate keys | C ++ program of AVL tree that handles duplicates ; An AVL tree node ; A utility function to get maximum of two integers ; A utility function to get height of the tree ; A utility function to get maximum of two integers ; Helper function that allocates a new node with the given key and NULL left and right pointers . ; new node is initially added at leaf ; A utility function to right rotate subtree rooted with y See the diagram given above . ; Perform rotation ; Update heights ; Return new root ; A utility function to left rotate subtree rooted with x See the diagram given above . ; Perform rotation ; Update heights ; Return new root ; Get Balance factor of node N ; 1. Perform the normal BST rotation ; If key already exists in BST , increment count and return ; Otherwise , recur down the tree ; 2. Update height of this ancestor node ; 3. Get the balance factor of this ancestor node to check whether this node became unbalanced ; If this node becomes unbalanced , then there are 4 cases Left Left Case ; Right Right Case ; Left Right Case ; Right Left Case ; return the ( unchanged ) node pointer ; Given a non - empty binary search tree , return the node with minimum key value found in that tree . Note that the entire tree does not need to be searched . ; loop down to find the leftmost leaf ; STEP 1 : PERFORM STANDARD BST DELETE ; If the key to be deleted is smaller than the root 's key,  then it lies in left subtree ; If the key to be deleted is greater than the root 's key,  then it lies in right subtree ; if key is same as root 's key, then This is the node  to be deleted ; If key is present more than once , simply decrement count and return ; Else , delete the node node with only one child or no child ; No child case ; One child case ; Copy the contents of the non - empty child ; node with two children : Get the inorder successor ( smallest in the right subtree ) ; Copy the inorder successor 's data to this node and update the count ; Delete the inorder successor ; If the tree had only...
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct node { int key ; struct node * left ; struct node * right ; int height ; int count ; } ; int max ( int a , int b ) ; int height ( struct node * N ) { if ( N == NULL ) return 0 ; return N -> height ; } int max ( int a , int b ) { return ( a > b ) ? a : b ; } struct node * newNode ( int key ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> key = key ; node -> left = NULL ; node -> right = NULL ; node -> height = 1 ; node -> count = 1 ; return ( node ) ; } struct node * rightRotate ( struct node * y ) { struct node * x = y -> left ; struct node * T2 = x -> right ; x -> right = y ; y -> left = T2 ; y -> height = max ( height ( y -> left ) , height ( y -> right ) ) + 1 ; x -> height = max ( height ( x -> left ) , height ( x -> right ) ) + 1 ; return x ; } struct node * leftRotate ( struct node * x ) { struct node * y = x -> right ; struct node * T2 = y -> left ; y -> left = x ; x -> right = T2 ; x -> height = max ( height ( x -> left ) , height ( x -> right ) ) + 1 ; y -> height = max ( height ( y -> left ) , height ( y -> right ) ) + 1 ; return y ; } int getBalance ( struct node * N ) { if ( N == NULL ) return 0 ; return height ( N -> left ) - height ( N -> right ) ; } struct node * insert ( struct node * node , int key ) { if ( node == NULL ) return ( newNode ( key ) ) ; if ( key == node -> key ) { ( node -> count ) ++ ; return node ; } if ( key < node -> key ) node -> left = insert ( node -> left , key ) ; else node -> right = insert ( node -> right , key ) ; node -> height = max ( height ( node -> left ) , height ( node -> right ) ) + 1 ; int balance = getBalance ( node ) ; if ( balance > 1 && key < node -> left -> key ) return rightRotate ( node ) ; if ( balance < -1 && key > node -> right -> key ) return leftRotate ( node ) ; if ( balance > 1 && key > node -> left -> key ) { node -> left = leftRotate ( node -> left ) ; return rightRotate ( node ) ; } if ( balance < -1 && key < node -> right -> key ) { node -> right =...


Activity Selection Problem | Greedy Algo | C program for activity selection problem . The following implementation assumes that the activities are already sorted according to their finish time ; Prints a maximum set of activities that can be done by a single person , one at a time . n -- > Total number of activities s [ ] -- > An array that contains start time of all activities f [ ] -- > An array that contains finish time of all activities ; The first activity always gets selected ; Consider rest of the activities ; If this activity has start time greater than or equal to the finish time of previously selected activity , then select it ; driver program to test above function
How can the above be solved in C?

 #include <stdio.h>
void printMaxActivities ( int s [ ] , int f [ ] , int n ) { int i , j ; printf ( " Following ▁ activities ▁ are ▁ selected ▁ n " ) ; i = 0 ; printf ( " % d ▁ " , i ) ; for ( j = 1 ; j < n ; j ++ ) { if ( s [ j ] >= f [ i ] ) { printf ( " % d ▁ " , j ) ; i = j ; } } } int main ( ) { int s [ ] = { 1 , 3 , 0 , 5 , 8 , 5 } ; int f [ ] = { 2 , 4 , 6 , 7 , 9 , 9 } ; int n = sizeof ( s ) / sizeof ( s [ 0 ] ) ; printMaxActivities ( s , f , n ) ; return 0 ; }


Add 1 to a given number |  ; Driver program to test above functions
How can the above be solved in C?

 #include <stdio.h>
int addOne ( int x ) { return ( - ( ~ x ) ) ; } int main ( ) { printf ( " % d " , addOne ( 13 ) ) ; getchar ( ) ; return 0 ; }


Add 1 to a given number | C ++ code to add add one to a given number ; Flip all the set bits until we find a 0 ; flip the rightmost 0 bit ; Driver program to test above functions
How can the above be solved in C?

 #include <stdio.h>
int addOne ( int x ) { int m = 1 ; while ( x & m ) { x = x ^ m ; m <<= 1 ; } x = x ^ m ; return x ; } int main ( ) { printf ( " % d " , addOne ( 13 ) ) ; getchar ( ) ; return 0 ; }


Alternating split of a given Singly Linked List | Set 1 |  ; points to the last node in ' a ' ; points to the last node in ' b ' ; add at ' a ' tail ; advance the ' a ' tail
How can the above be solved in C?

void AlternatingSplit ( struct Node * source , struct Node * * aRef , struct Node * * bRef ) { struct Node aDummy ; struct Node * aTail = & aDummy ; struct Node bDummy ; struct Node * bTail = & bDummy ; struct Node * current = source ; aDummy . next = NULL ; bDummy . next = NULL ; while ( current != NULL ) { MoveNode ( & ( aTail -> next ) , t ) ; aTail = aTail -> next ; if ( current != NULL ) { MoveNode ( & ( bTail -> next ) , t ) ; bTail = bTail -> next ; } } * aRef = aDummy . next ; * bRef = bDummy . next ; }


Analysis of Algorithms | Set 2 ( Worst , Average and Best Cases ) | C implementation of the approach ; Linearly search x in arr [ ] . If x is present then return the index , otherwise return - 1 ; Driver program to test above functions
How can the above be solved in C?

 #include <stdio.h>
int search ( int arr [ ] , int n , int x ) { int i ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == x ) return i ; } return -1 ; } int main ( ) { int arr [ ] = { 1 , 10 , 30 , 15 } ; int x = 30 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " % d ▁ is ▁ present ▁ at ▁ index ▁ % d " , x , search ( arr , n , x ) ) ; getchar ( ) ; return 0 ; }


Angle between two Planes in 3D | C program to find the Angle between two Planes in 3 D . ; Function to find Angle ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
#include <math.h>
void distance ( float a1 , float b1 , float c1 , float a2 , float b2 , float c2 ) { float d = ( a1 * a2 + b1 * b2 + c1 * c2 ) ; float e1 = sqrt ( a1 * a1 + b1 * b1 + c1 * c1 ) ; float e2 = sqrt ( a2 * a2 + b2 * b2 + c2 * c2 ) ; d = d / ( e1 * e2 ) ; float pi = 3.14159 ; float A = ( 180 / pi ) * ( acos ( d ) ) ; printf ( " Angle ▁ is ▁ % .2f ▁ degree " , A ) ; } int main ( ) { float a1 = 1 ; float b1 = 1 ; float c1 = 2 ; float d1 = 1 ; float a2 = 2 ; float b2 = -1 ; float c2 = 1 ; float d2 = -4 ; distance ( a1 , b1 , c1 , a2 , b2 , c2 ) ; return 0 ; }


Area of Circumcircle of a Right Angled Triangle | C program to find the area of Cicumscribed circle of right angled triangle ; Function to find area of circumscribed circle ; Driver code
How can the above be solved in C?

 #include <stdio.h>
#define PI  3.14159265
float area_circumscribed ( float c ) { return ( c * c * ( PI / 4 ) ) ; } int main ( ) { float c = 8 ; printf ( " % f " , area_circumscribed ( c ) ) ; return 0 ; }


Area of Incircle of a Right Angled Triangle | C program to find the area of incircle of right angled triangle ; Function to find area of incircle ; Driver code
How can the above be solved in C?

 #include <stdio.h>
#define PI  3.14159265
float area_inscribed ( float P , float B , float H ) { return ( ( P + B - H ) * ( P + B - H ) * ( PI / 4 ) ) ; } int main ( ) { float P = 3 , B = 4 , H = 5 ; printf ( " % f " , area_inscribed ( P , B , H ) ) ; return 0 ; }


Area of a leaf inside a square | C program to find the area of leaf inside a square ; Function to find area of leaf ; Driver code
How can the above be solved in C?

 #include <stdio.h>
#define PI  3.14159265
float area_leaf ( float a ) { return ( a * a * ( PI / 2 - 1 ) ) ; } int main ( ) { float a = 7 ; printf ( " % f " , area_leaf ( a ) ) ; return 0 ; }


Area of a square from diagonal length | C Program to find the area of square when its diagonal is given . ; Returns area of square from given diagonal ; Driver function .
How can the above be solved in C?

 #include <stdio.h>
double findArea ( double d ) { return ( d * d ) / 2 ; } int main ( ) { double d = 10 ; printf ( " % .2f " , findArea ( d ) ) ; return 0 ; }


Array value by repeatedly replacing max 2 elements with their absolute difference | C ++ program to find the array value by repeatedly replacing max 2 elements with their absolute difference ; function that return last value of array ; Build a binary max_heap . ; For max 2 elements ; Iterate until queue is not empty ; if only 1 element is left ; return the last remaining value ; check that difference is non zero ; finally return 0 ; Driver Code
How can the above be solved in C?

 #include <bits/stdc++.h>
using namespace std ; int lastElement ( vector < int > & arr ) { priority_queue < int > pq ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { pq . push ( arr [ i ] ) ; } int m1 , m2 ; while ( ! pq . empty ( ) ) { if ( pq . size ( ) == 1 ) return pq . top ( ) ; m1 = pq . top ( ) ; pq . pop ( ) ; m2 = pq . top ( ) ; pq . pop ( ) ; if ( m1 != m2 ) pq . push ( m1 - m2 ) ; } return 0 ; } int main ( ) { vector < int > arr = { 2 , 7 , 4 , 1 , 8 , 1 , 1 } ; cout << lastElement ( arr ) << endl ; return 0 ; }


Assembly Line Scheduling | DP | A C program to find minimum possible time by the car chassis to complete ; Utility function to find minimum of two numbers ; time taken to leave first station in line 1 ; time taken to leave first station in line 2 ; Fill tables T1 [ ] and T2 [ ] using the above given recursive relations ; Consider exit times and retutn minimum ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
#define NUM_LINE  2
#define NUM_STATION  4
int min ( int a , int b ) { return a < b ? a : b ; } int carAssembly ( int a [ ] [ NUM_STATION ] , int t [ ] [ NUM_STATION ] , int * e , int * x ) { int T1 [ NUM_STATION ] , T2 [ NUM_STATION ] , i ; T1 [ 0 ] = e [ 0 ] + a [ 0 ] [ 0 ] ; T2 [ 0 ] = e [ 1 ] + a [ 1 ] [ 0 ] ; for ( i = 1 ; i < NUM_STATION ; ++ i ) { T1 [ i ] = min ( T1 [ i - 1 ] + a [ 0 ] [ i ] , T2 [ i - 1 ] + t [ 1 ] [ i ] + a [ 0 ] [ i ] ) ; T2 [ i ] = min ( T2 [ i - 1 ] + a [ 1 ] [ i ] , T1 [ i - 1 ] + t [ 0 ] [ i ] + a [ 1 ] [ i ] ) ; } return min ( T1 [ NUM_STATION - 1 ] + x [ 0 ] , T2 [ NUM_STATION - 1 ] + x [ 1 ] ) ; } int main ( ) { int a [ ] [ NUM_STATION ] = { { 4 , 5 , 3 , 2 } , { 2 , 10 , 1 , 4 } } ; int t [ ] [ NUM_STATION ] = { { 0 , 7 , 4 , 5 } , { 0 , 9 , 2 , 8 } } ; int e [ ] = { 10 , 12 } , x [ ] = { 18 , 7 } ; printf ( " % d " , carAssembly ( a , t , e , x ) ) ; return 0 ; }


Average of Cubes of first N natural numbers | C program for the above approach ; Function to find average of cubes ; Store sum of cubes of numbers in the sum ; Calculate sum of cubes ; Return average ; Driver Code ; Given number ; Function Call
How can the above be solved in C?

 #include <stdio.h>
double findAverageOfCube ( int n ) { double sum = 0 ; int i ; for ( i = 1 ; i <= n ; i ++ ) { sum += i * i * i ; } return sum / n ; } int main ( ) { int n = 3 ; printf ( " % lf " , findAverageOfCube ( n ) ) ; return 0 ; }


Average of Squares of Natural Numbers | C program to calculate 1 ^ 2 + 2 ^ 2 + 3 ^ 2 + ... average of square number ; Function to calculate average of square number ; Driver code
How can the above be solved in C?

 #include <stdio.h>
float AvgofSquareN ( int n ) { float sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) sum += ( i * i ) ; return sum / n ; } int main ( ) { int n = 2 ; printf ( " % f " , AvgofSquareN ( n ) ) ; return 0 ; }


Average of Squares of Natural Numbers | C program to get the Average of Square of first n natural numbers ; Function to get the average ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
float AvgofSquareN ( int n ) { return ( float ) ( ( n + 1 ) * ( 2 * n + 1 ) ) / 6 ; } int main ( ) { int n = 10 ; printf ( " % f " , AvgofSquareN ( n ) ) ; return 0 ; }


Binary Search | C program to implement iterative Binary Search ; A iterative binary search function . It returns location of x in given array arr [ l . . r ] if present , otherwise - 1 ; Check if x is present at mid ; If x greater , ignore left half ; If x is smaller , ignore right half ; if we reach here , then element was not present ; Driver method to test above
How can the above be solved in C?

 #include <stdio.h>
int binarySearch ( int arr [ ] , int l , int r , int x ) { while ( l <= r ) { int m = l + ( r - l ) / 2 ; if ( arr [ m ] == x ) return m ; if ( arr [ m ] < x ) l = m + 1 ; else r = m - 1 ; } return -1 ; } int main ( void ) { int arr [ ] = { 2 , 3 , 4 , 10 , 40 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 10 ; int result = binarySearch ( arr , 0 , n - 1 , x ) ; ( result == -1 ) ? printf ( " Element ▁ is ▁ not ▁ present " " ▁ in ▁ array " ) : printf ( " Element ▁ is ▁ present ▁ at ▁ " " index ▁ % d " , result ) ; return 0 ; }


Binary Search | C program to implement recursive Binary Search ; A recursive binary search function . It returns location of x in given array arr [ l . . r ] is present , otherwise - 1 ; If the element is present at the middle itself ; If element is smaller than mid , then it can only be present in left subarray ; Else the element can only be present in right subarray ; We reach here when element is not present in array ; Driver method to test above
How can the above be solved in C?

 #include <stdio.h>
int binarySearch ( int arr [ ] , int l , int r , int x ) { if ( r >= l ) { int mid = l + ( r - l ) / 2 ; if ( arr [ mid ] == x ) return mid ; if ( arr [ mid ] > x ) return binarySearch ( arr , l , mid - 1 , x ) ; return binarySearch ( arr , mid + 1 , r , x ) ; } return -1 ; } int main ( void ) { int arr [ ] = { 2 , 3 , 4 , 10 , 40 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 10 ; int result = binarySearch ( arr , 0 , n - 1 , x ) ; ( result == -1 ) ? printf ( " Element ▁ is ▁ not ▁ present ▁ in ▁ array " ) : printf ( " Element ▁ is ▁ present ▁ at ▁ index ▁ % d " , result ) ; return 0 ; }


Binary Tree | Set 1 ( Introduction ) |  ; struct containing left and right child of current node and key value ; newNode ( ) allocates a new node with the given data and NULL left and right pointers . ; Driver code
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct node { int data ; struct node * left ; struct node * right ; } ; struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; getchar ( ) ; return 0 ; }


Binary representation of a given number |  ; bin function ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
void bin ( unsigned n ) { unsigned i ; for ( i = 1 << 31 ; i > 0 ; i = i / 2 ) ( n & i ) ? printf ( "1" ) : printf ( "0" ) ; } int main ( void ) { bin ( 7 ) ; printf ( "
 " ) ; bin ( 4 ) ; }


Bitwise Operators in C / C ++ |
How can the above be solved in C?

 #include <stdio.h>
int main ( ) { int x = 2 , y = 5 ; ( x & y ) ? printf ( " True ▁ " ) : printf ( " False ▁ " ) ; ( x && y ) ? printf ( " True ▁ " ) : printf ( " False ▁ " ) ; return 0 ; }


Bitwise Operators in C / C ++ |  ; Function to return the only odd occurring element ; Driver Method
How can the above be solved in C?

 #include <stdio.h>
int findOdd ( int arr [ ] , int n ) { int res = 0 , i ; for ( i = 0 ; i < n ; i ++ ) res ^= arr [ i ] ; return res ; } int main ( void ) { int arr [ ] = { 12 , 12 , 14 , 90 , 14 , 14 , 14 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " The ▁ odd ▁ occurring ▁ element ▁ is ▁ % d ▁ " , findOdd ( arr , n ) ) ; return 0 ; }


Bitwise Operators in C / C ++ | C Program to demonstrate use of bitwise operators ; a = 5 ( 00000101 ) , b = 9 ( 00001001 ) ; The result is 00000001 ; The result is 00001101 ; The result is 00001100 ; The result is 11111010 ; The result is 00010010 ; The result is 00000100
How can the above be solved in C?

 #include <stdio.h>
int main ( ) { unsigned char a = 5 , b = 9 ; printf ( " a ▁ = ▁ % d , ▁ b ▁ = ▁ % d
 " , a , b ) ; printf ( " a & b ▁ = ▁ % d
 " , a & b ) ; printf ( " a ▁ b ▁ = ▁ % d
 " , a b ) ; printf ( " a ^ b ▁ = ▁ % d
 " , a ^ b ) ; printf ( " ~ a ▁ = ▁ % d
 " , a = ~ a ) ; printf ( " b < < 1 ▁ = ▁ % d
 " , b << 1 ) ; printf ( " b > > 1 ▁ = ▁ % d
 " , b >> 1 ) ; return 0 ; }


Bitwise recursive addition of two integers | C program to do recursive addition of two integers ; If bitwise & is 0 , then there is not going to be any carry . Hence result of XOR is addition . ; Driver code
How can the above be solved in C?

 #include <stdio.h>
int add ( int x , int y ) { int keep = ( x & y ) << 1 ; int res = x ^ y ; if ( keep == 0 ) return res ; add ( keep , res ) ; } int main ( ) { printf ( " % d " , add ( 15 , 38 ) ) ; return 0 ; }


Block swap algorithm for array rotation |  ; Prototype for utility functions ; Return If number of elements to be rotated is zero or equal to array size ; If number of elements to be rotated is exactly half of array size ; If A is shorter ; If B is shorter ; function to print an array ; This function swaps d elements starting at index fi with d elements starting at index si ; Driver program to test above functions
How can the above be solved in C?

 #include <stdio.h>
void printArray ( int arr [ ] , int size ) ; void swap ( int arr [ ] , int fi , int si , int d ) ; void leftRotate ( int arr [ ] , int d , int n ) { if ( d == 0 d == n ) return ; if ( n - d == d ) { swap ( arr , 0 , n - d , d ) ; return ; } if ( d < n - d ) { swap ( arr , 0 , n - d , d ) ; leftRotate ( arr , d , n - d ) ; } else { swap ( arr , 0 , d , n - d ) ; leftRotate ( arr + n - d , 2 * d - n , d ) ; } } void printArray ( int arr [ ] , int size ) { int i ; for ( i = 0 ; i < size ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; printf ( "
 ▁ " ) ; } void swap ( int arr [ ] , int fi , int si , int d ) { int i , temp ; for ( i = 0 ; i < d ; i ++ ) { temp = arr [ fi + i ] ; arr [ fi + i ] = arr [ si + i ] ; arr [ si + i ] = temp ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 } ; leftRotate ( arr , 2 , 7 ) ; printArray ( arr , 7 ) ; getchar ( ) ; return 0 ; }


Block swap algorithm for array rotation | C code for above implementation ; A is shorter ; B is shorter ; Finally , block swap A and B
How can the above be solved in C?

void leftRotate ( int arr [ ] , int d , int n ) { int i , j ; if ( d == 0 d == n ) return ; i = d ; j = n - d ; while ( i != j ) { if ( i < j ) { swap ( arr , d - i , d + j - i , i ) ; j -= i ; } else { swap ( arr , d - i , d , j ) ; i -= j ; } } swap ( arr , d - i , d , i ) ; }


Boyer Moore Algorithm for Pattern Searching | C Program for Bad Character Heuristic of Boyer Moore String Matching Algorithm ; A utility function to get maximum of two integers ; The preprocessing function for Boyer Moore 's bad character heuristic ; Initialize all occurrences as - 1 ; Fill the actual value of last occurrence of a character ; A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm ; Fill the bad character array by calling the preprocessing function badCharHeuristic ( ) for given pattern ; s is shift of the pattern with respect to text ; Keep reducing index j of pattern while characters of pattern and text are matching at this shift s ; If the pattern is present at current shift , then index j will become - 1 after the above loop ; Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern . The condition s + m < n is necessary for the case when pattern occurs at the end of text ; Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern . The max function is used to make sure that we get a positive shift . We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character . ; Driver program to test above function
How can the above be solved in C?

 # include <limits.h>
# include <string.h>
# include <stdio.h>
# define NO_OF_CHARS  256
int max ( int a , int b ) { return ( a > b ) ? a : b ; } void badCharHeuristic ( char * str , int size , int badchar [ NO_OF_CHARS ] ) { int i ; for ( i = 0 ; i < NO_OF_CHARS ; i ++ ) badchar [ i ] = -1 ; for ( i = 0 ; i < size ; i ++ ) badchar [ ( int ) str [ i ] ] = i ; } void search ( char * txt , char * pat ) { int m = strlen ( pat ) ; int n = strlen ( txt ) ; int badchar [ NO_OF_CHARS ] ; badCharHeuristic ( pat , m , badchar ) ; int s = 0 ; while ( s <= ( n - m ) ) { int j = m - 1 ; while ( j >= 0 && pat [ j ] == txt [ s + j ] ) j -- ; if ( j < 0 ) { printf ( " pattern occurs at shift = % d " , s ) ; s += ( s + m < n ) ? m - badchar [ txt [ s + m ] ] : 1 ; } else s += max ( 1 , j - badchar [ txt [ s + j ] ] ) ; } } int main ( ) { char txt [ ] = " ABAAABCD " ; char pat [ ] = " ABC " ; search ( txt , pat ) ; return 0 ; }


Boyer Moore Algorithm for Pattern Searching | C Program for Bad Character Heuristic of Boyer Moore String Matching Algorithm ; A utility function to get maximum of two integers ; The preprocessing function for Boyer Moore 's bad character heuristic ; Initialize all occurrences as - 1 ; Fill the actual value of last occurrence of a character ; A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm ; Fill the bad character array by calling the preprocessing function badCharHeuristic ( ) for given pattern ; s is shift of the pattern with respect to text ; there are n - m + 1 potential allignments ; Keep reducing index j of pattern while characters of pattern and text are matching at this shift s ; If the pattern is present at current shift , then index j will become - 1 after the above loop ; Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern . The condition s + m < n is necessary for the case when pattern occurs at the end of text ; Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern . The max function is used to make sure that we get a positive shift . We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character . ; Driver program to test above function
How can the above be solved in C?


Bubble Sort for Linked List by Swapping nodes | C program to sort Linked List using Bubble Sort by swapping nodes ; structure for a node ; Function to swap the nodes ; Function to sort the list ; update the link after swapping ; break if the loop ended without any swap ; Function to print the list ; Function to insert a struct Node at the beginning of a linked list ; Driver Code ; start with empty linked list ; Create linked list from the array arr [ ] ; print list before sorting ; sort the linked list ; print list after sorting
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct Node { int data ; struct Node * next ; } Node ; struct Node * swap ( struct Node * ptr1 , struct Node * ptr2 ) { struct Node * tmp = ptr2 -> next ; ptr2 -> next = ptr1 ; ptr1 -> next = tmp ; return ptr2 ; } int bubbleSort ( struct Node * * head , int count ) { struct Node * * h ; int i , j , swapped ; for ( i = 0 ; i <= count ; i ++ ) { h = head ; swapped = 0 ; for ( j = 0 ; j < count - i - 1 ; j ++ ) { struct Node * p1 = * h ; struct Node * p2 = p1 -> next ; if ( p1 -> data > p2 -> data ) { * h = swap ( p1 , p2 ) ; swapped = 1 ; } h = & ( * h ) -> next ; } if ( swapped == 0 ) break ; } } void printList ( struct Node * n ) { while ( n != NULL ) { printf ( " % d ▁ - > ▁ " , n -> data ) ; n = n -> next ; } printf ( "
 " ) ; } void insertAtTheBegin ( struct Node * * start_ref , int data ) { struct Node * ptr1 = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; ptr1 -> data = data ; ptr1 -> next = * start_ref ; * start_ref = ptr1 ; } int main ( ) { int arr [ ] = { 78 , 20 , 10 , 32 , 1 , 5 } ; int list_size , i ; struct Node * start = NULL ; list_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; for ( i = 0 ; i < list_size ; i ++ ) insertAtTheBegin ( & start , arr [ i ] ) ; printf ( " Linked ▁ list ▁ before ▁ sorting
 " ) ; printList ( start ) ; bubbleSort ( & start , list_size ) ; printf ( " Linked ▁ list ▁ after ▁ sorting
 " ) ; printList ( start ) ; return 0 ; }


C / C ++ Program for Longest Increasing Subsequence | A Naive C recursive implementation of LIS problem ; To make use of recursive calls , this function must return two things : 1 ) Length of LIS ending with element arr [ n - 1 ] . We use max_ending_here for this purpose 2 ) Overall maximum as the LIS may end with an element before arr [ n - 1 ] max_ref is used this purpose . The value of LIS of full array of size n is stored in * max_ref which is our final result ; Base case ; ' max _ ending _ here ' is length of LIS ending with arr [ n - 1 ] ; Recursively get all LIS ending with arr [ 0 ] , arr [ 1 ] ... arr [ n - 2 ] . If arr [ i - 1 ] is smaller than arr [ n - 1 ] , and max ending with arr [ n - 1 ] needs to be updated , then update it ; Compare max_ending_here with the overall max . And update the overall max if needed ; Return length of LIS ending with arr [ n - 1 ] ; The wrapper function for _lis ( ) ; The max variable holds the result ; The function _lis ( ) stores its result in max ; returns max ; Driver program to test above function
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
int _lis ( int arr [ ] , int n , int * max_ref ) { if ( n == 1 ) return 1 ; int res , max_ending_here = 1 ; for ( int i = 1 ; i < n ; i ++ ) { res = _lis ( arr , i , max_ref ) ; if ( arr [ i - 1 ] < arr [ n - 1 ] && res + 1 > max_ending_here ) max_ending_here = res + 1 ; } if ( * max_ref < max_ending_here ) * max_ref = max_ending_here ; return max_ending_here ; } int lis ( int arr [ ] , int n ) { int max = 1 ; _lis ( arr , n , & max ) ; return max ; } int main ( ) { int arr [ ] = { 10 , 22 , 9 , 33 , 21 , 50 , 41 , 60 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Length ▁ of ▁ lis ▁ is ▁ % d
 " , lis ( arr , n ) ) ; return 0 ; }


C / C ++ Program to find Prime Numbers between given range | C program to find the prime numbers between a given interval ; Function for print prime number in given range ; Traverse each number in the interval with the help of for loop ; Skip 0 and 1 as they are neither prime nor composite ; flag variable to tell if i is prime or not ; Iterate to check if i is prime or not ; flag = 1 means i is prime and flag = 0 means i is not prime ; Driver Code ; Given Range ; Function Call
How can the above be solved in C?

 #include <stdio.h>
void primeInRange ( int L , int R ) { int i , j , flag ; for ( i = L ; i <= R ; i ++ ) { if ( i == 1 i == 0 ) continue ; flag = 1 ; for ( j = 2 ; j <= i / 2 ; ++ j ) { if ( i % j == 0 ) { flag = 0 ; break ; } } if ( flag == 1 ) printf ( " % d ▁ " , i ) ; } } int main ( ) { int L = 1 ; int R = 10 ; primeInRange ( L , R ) ; return 0 ; }


C / C ++ program for Armstrong Numbers | C program to find Armstrong number ; Function to calculate N raised to the power D ; Function to calculate the order of the number ; For each digit ; Function to check whether the given number is Armstrong number or not ; Calling order function ; For each digit ; If satisfies Armstrong condition ; Driver Code ; Given Number N ; Function Call
How can the above be solved in C?

 #include <stdio.h>
int power ( int N , unsigned int D ) { if ( D == 0 ) return 1 ; if ( D % 2 == 0 ) return power ( N , D / 2 ) * power ( N , D / 2 ) ; return N * power ( N , D / 2 ) * power ( N , D / 2 ) ; } int order ( int N ) { int r = 0 ; while ( N ) { r ++ ; N = N / 10 ; } return r ; } int isArmstrong ( int N ) { int D = order ( N ) ; int temp = N , sum = 0 ; while ( temp ) { int Ni = temp % 10 ; sum += power ( Ni , D ) ; temp = temp / 10 ; } if ( sum == N ) return 1 ; else return 0 ; } int main ( ) { int N = 153 ; if ( isArmstrong ( N ) == 1 ) printf ( " True
 " ) ; else printf ( " False
 " ) ; return 0 ; }


C / C ++ program to add N distances given in inch | C program for the above approach ; Struct defined for the inch - feet system ; Variable to store the inch - feet ; Function to find the sum of all N set of Inch Feet distances ; Variable to store sum ; Traverse the InchFeet array ; Find the total sum of feet and inch ; If inch sum is greater than 11 convert it into feet as 1 feet = 12 inch ; Find integral part of inch_sum ; Delete the integral part x ; Add x % 12 to inch_sum ; Add x / 12 to feet_sum ; Print the corresponding sum of feet_sum and inch_sum ; Driver Code ; Given set of inch - feet ; Function Call
How can the above be solved in C?

 #include " stdio . h "
struct InchFeet { int feet ; float inch ; } ; void findSum ( struct InchFeet arr [ ] , int N ) { int feet_sum = 0 ; float inch_sum = 0.0 ; int x ; for ( int i = 0 ; i < N ; i ++ ) { feet_sum += arr [ i ] . feet ; inch_sum += arr [ i ] . inch ; } if ( inch_sum >= 12 ) { x = ( int ) inch_sum ; inch_sum -= x ; inch_sum += x % 12 ; feet_sum += x / 12 ; } printf ( " Feet ▁ Sum : ▁ % d
 " , feet_sum ) ; printf ( " Inch ▁ Sum : ▁ % .2f " , inch_sum ) ; } int main ( ) { struct InchFeet arr [ ] = { { 10 , 3.7 } , { 10 , 5.5 } , { 6 , 8.0 } } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findSum ( arr , N ) ; return 0 ; }


Calculate the angle between hour hand and minute hand | C program to find angle between hour and minute hands ; Utility function to find minimum of two integers ; Function to calculate the angle ; validate the input ; Calculate the angles moved by hour and minute hands with reference to 12 : 00 ; Find the difference between two angles ; Return the smaller angle of two possible angles ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
int min ( int x , int y ) { return ( x < y ) ? x : y ; } int calcAngle ( double h , double m ) { if ( h < 0 m < 0 h > 12 m > 60 ) printf ( " Wrong ▁ input " ) ; if ( h == 12 ) h = 0 ; if ( m == 60 ) { m = 0 ; h += 1 ; if ( h > 12 ) h = h - 12 ; } int hour_angle = 0.5 * ( h * 60 + m ) ; int minute_angle = 6 * m ; int angle = abs ( hour_angle - minute_angle ) ; angle = min ( 360 - angle , angle ) ; return angle ; } int main ( ) { printf ( " % d ▁ n " , calcAngle ( 9 , 60 ) ) ; printf ( " % d ▁ n " , calcAngle ( 3 , 30 ) ) ; return 0 ; }


Ceiling in a sorted array |  ; Function to get index of ceiling of x in arr [ low . . high ] ; If x is smaller than or equal to first element , then return the first element ; Otherwise , linearly search for ceil value ; if x lies between arr [ i ] and arr [ i + 1 ] including arr [ i + 1 ] , then return arr [ i + 1 ] ; If we reach here then x is greater than the last element of the array , return - 1 in this case ; Driver program to check above functions
How can the above be solved in C?

 #include <stdio.h>
int ceilSearch ( int arr [ ] , int low , int high , int x ) { int i ; if ( x <= arr [ low ] ) return low ; for ( i = low ; i < high ; i ++ ) { if ( arr [ i ] == x ) return i ; if ( arr [ i ] < x && arr [ i + 1 ] >= x ) return i + 1 ; } return -1 ; } int main ( ) { int arr [ ] = { 1 , 2 , 8 , 10 , 10 , 12 , 19 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 3 ; int index = ceilSearch ( arr , 0 , n - 1 , x ) ; if ( index == -1 ) printf ( " Ceiling ▁ of ▁ % d ▁ doesn ' t ▁ exist ▁ in ▁ array ▁ " , x ) ; else printf ( " ceiling ▁ of ▁ % d ▁ is ▁ % d " , x , arr [ index ] ) ; getchar ( ) ; return 0 ; }


Ceiling in a sorted array |  ; Function to get index of ceiling of x in arr [ low . . high ] ; If x is smaller than or equal to the first element , then return the first element ; If x is greater than the last element , then return - 1 ; get the index of middle element of arr [ low . . high ] ; If x is same as middle element , then return mid ; If x is greater than arr [ mid ] , then either arr [ mid + 1 ] is ceiling of x or ceiling lies in arr [ mid + 1. . . high ] ; If x is smaller than arr [ mid ] , then either arr [ mid ] is ceiling of x or ceiling lies in arr [ low ... mid - 1 ] ; Driver program to check above functions
How can the above be solved in C?

 #include <stdio.h>
int ceilSearch ( int arr [ ] , int low , int high , int x ) { int mid ; if ( x <= arr [ low ] ) return low ; if ( x > arr [ high ] ) return -1 ; mid = ( low + high ) / 2 ; if ( arr [ mid ] == x ) return mid ; else if ( arr [ mid ] < x ) { if ( mid + 1 <= high && x <= arr [ mid + 1 ] ) return mid + 1 ; else return ceilSearch ( arr , mid + 1 , high , x ) ; } else { if ( mid - 1 >= low && x > arr [ mid - 1 ] ) return mid ; else return ceilSearch ( arr , low , mid - 1 , x ) ; } } int main ( ) { int arr [ ] = { 1 , 2 , 8 , 10 , 10 , 12 , 19 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 20 ; int index = ceilSearch ( arr , 0 , n - 1 , x ) ; if ( index == -1 ) printf ( " Ceiling ▁ of ▁ % d ▁ doesn ' t ▁ exist ▁ in ▁ array ▁ " , x ) ; else printf ( " ceiling ▁ of ▁ % d ▁ is ▁ % d " , x , arr [ index ] ) ; getchar ( ) ; return 0 ; }


Change a Binary Tree so that every node stores sum of all nodes in left subtree | C program to store sum of nodes in left subtree in every node ; A tree node ; Function to modify a Binary Tree so that every node stores sum of values in its left child including its own value ; Base cases ; Update left and right subtrees ; Add leftsum to current node ; Return sum of values under root ; Utility function to do inorder traversal ; Utility function to create a new node ; Driver program ; Let us construct below tree 1 / \ 2 3 / \ \ 4 5 6
How can the above be solved in C?

 #include <bits/stdc++.h>
using namespace std ; struct node { int data ; struct node * left , * right ; } ; int updatetree ( node * root ) { if ( ! root ) return 0 ; if ( root -> left == NULL && root -> right == NULL ) return root -> data ; int leftsum = updatetree ( root -> left ) ; int rightsum = updatetree ( root -> right ) ; root -> data += leftsum ; return root -> data + rightsum ; } void inorder ( struct node * node ) { if ( node == NULL ) return ; inorder ( node -> left ) ; printf ( " % d ▁ " , node -> data ) ; inorder ( node -> right ) ; } struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 6 ) ; updatetree ( root ) ; cout << " Inorder ▁ traversal ▁ of ▁ the ▁ modified ▁ tree ▁ is ▁
 " ; inorder ( root ) ; return 0 ; }


Channel Assignment Problem |  ; A Depth First Search based recursive function that returns true if a matching for vertex u is possible ; Try every receiver one by one ; If sender u has packets to send to receiver v and receiver v is not already mapped to any other sender just check if the number of packets is greater than '0' because only one packet can be sent in a time frame anyways ; Mark v as visited ; If receiver ' v ' is not assigned to any sender OR previously assigned sender for receiver v ( which is matchR [ v ] ) has an alternate receiver available . Since v is marked as visited in the above line , matchR [ v ] in the following recursive call will not get receiver ' v ' again ; Returns maximum number of packets that can be sent parallely in 1 time slot from sender to receiver ; An array to keep track of the receivers assigned to the senders . The value of matchR [ i ] is the sender ID assigned to receiver i . the value - 1 indicates nobody is assigned . ; Initially all receivers are not mapped to any senders ; Count of receivers assigned to senders ; Mark all receivers as not seen for next sender ; Find if the sender ' u ' can be assigned to the receiver ; Driver program to test above function
How can the above be solved in C?

 #include <iostream>
#include <string.h>
#include <vector>
#define M  3
#define N  4
using namespace std ; bool bpm ( int table [ M ] [ N ] , int u , bool seen [ ] , int matchR [ ] ) { for ( int v = 0 ; v < N ; v ++ ) { if ( table [ u ] [ v ] > 0 && ! seen [ v ] ) { seen [ v ] = true ; if ( matchR [ v ] < 0 || bpm ( table , matchR [ v ] , seen , matchR ) ) { matchR [ v ] = u ; return true ; } } } return false ; } int maxBPM ( int table [ M ] [ N ] ) { int matchR [ N ] ; memset ( matchR , -1 , sizeof ( matchR ) ) ; int result = 0 ; for ( int u = 0 ; u < M ; u ++ ) { bool seen [ N ] ; memset ( seen , 0 , sizeof ( seen ) ) ; if ( bpm ( table , u , seen , matchR ) ) result ++ ; } cout << " The ▁ number ▁ of ▁ maximum ▁ packets ▁ sent ▁ in ▁ the ▁ time ▁ slot ▁ is ▁ " << result << "
 " ; for ( int x = 0 ; x < N ; x ++ ) if ( matchR [ x ] + 1 != 0 ) cout << " T " << matchR [ x ] + 1 << " - > ▁ R " << x + 1 << "
 " ; return result ; } int main ( ) { int table [ M ] [ N ] = { { 0 , 2 , 0 } , { 3 , 0 , 1 } , { 2 , 4 , 0 } } ; int max_flow = maxBPM ( table ) ; return 0 ; }


Check for Children Sum Property in a Binary Tree | Program to check children sum property ; A binary tree node has data , left child and right child ; returns 1 if children sum property holds for the given node and both of its children ; left_data is left child data and right_data is for right child data ; If node is NULL or it 's a leaf node then  return true  ; If left child is not present then 0 is used as data of left child ; If right child is not present then 0 is used as data of right child ; if the node and both of its children satisfy the property return 1 else 0 ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver program to test above function
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct node { int data ; struct node * left ; struct node * right ; } ; int isSumProperty ( struct node * node ) { int left_data = 0 , right_data = 0 ; if ( node == NULL || ( node -> left == NULL && node -> right == NULL ) ) return 1 ; else { if ( node -> left != NULL ) left_data = node -> left -> data ; if ( node -> right != NULL ) right_data = node -> right -> data ; if ( ( node -> data == left_data + right_data ) && isSumProperty ( node -> left ) && isSumProperty ( node -> right ) ) return 1 ; else return 0 ; } } struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } int main ( ) { struct node * root = newNode ( 10 ) ; root -> left = newNode ( 8 ) ; root -> right = newNode ( 2 ) ; root -> left -> left = newNode ( 3 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 2 ) ; if ( isSumProperty ( root ) ) printf ( " The ▁ given ▁ tree ▁ satisfies ▁ the ▁ children ▁ sum ▁ property ▁ " ) ; else printf ( " The ▁ given ▁ tree ▁ does ▁ not ▁ satisfy ▁ the ▁ children ▁ sum ▁ property ▁ " ) ; getchar ( ) ; return 0 ; }


Check for Integer Overflow |
How can the above be solved in C?

 #include <stdio.h>
#include <limits.h>
#include <stdlib.h>
int addOvf ( int * result , int a , int b ) { if ( a > INT_MAX - b ) return -1 ; else { * result = a + b ; return 0 ; } } int main ( ) { int * res = ( int * ) malloc ( sizeof ( int ) ) ; int x = 2147483640 ; int y = 10 ; printf ( " % d " , addOvf ( res , x , y ) ) ; printf ( " % d " , * res ) ; getchar ( ) ; return 0 ; }


Check for Integer Overflow |  ; Takes pointer to result and two numbers as arguments . If there is no overflow , the function places the resultant = sum a + b in result and returns 0 , otherwise it returns - 1 ; Driver code
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
int addOvf ( int * result , int a , int b ) { * result = a + b ; if ( a > 0 && b > 0 && * result < 0 ) return -1 ; if ( a < 0 && b < 0 && * result > 0 ) return -1 ; return 0 ; } int main ( ) { int * res = ( int * ) malloc ( sizeof ( int ) ) ; int x = 2147483640 ; int y = 10 ; printf ( " % d " , addOvf ( res , x , y ) ) ; printf ( " % d " , * res ) ; getchar ( ) ; return 0 ; }


Check if N contains all digits as K in base B | C implementation of the approach ; Function to print the number of digits ; Calculate log using base change property and then take its floor and then add 1 ; Return the output ; Function that returns true if n contains all one 's in base b ; Calculate the sum ; Driver code ; Given number N ; Given base B ; Given digit K ; Function call
How can the above be solved in C?

 #include <stdio.h>
#include <math.h>
int findNumberOfDigits ( int n , int base ) { int dig = ( floor ( log ( n ) / log ( base ) ) + 1 ) ; return ( dig ) ; } int isAllKs ( int n , int b , int k ) { int len = findNumberOfDigits ( n , b ) ; int sum = k * ( 1 - pow ( b , len ) ) / ( 1 - b ) ; if ( sum == n ) { return ( sum ) ; } } int main ( void ) { int N = 13 ; int B = 3 ; int K = 1 ; if ( isAllKs ( N , B , K ) ) { printf ( " Yes " ) ; } else { printf ( " No " ) ; } return 0 ; }


Check if a number can be expressed as a sum of consecutive numbers |  ; Updating n with 2 n ; ( n & ( n - 1 ) ) = > Checking whether we can write 2 n as 2 ^ k if yes ( can 't represent 2n as 2^k) then answer 1  if no (can represent 2n as 2^k) then answer 0
How can the above be solved in C?

 #include <stdio.h>
long long int canBeSumofConsec ( long long int n ) { n = 2 * n ; return ( ( n & ( n - 1 ) ) != 0 ) ; } int main ( ) { long long int n = 10 ; printf ( " % lld " , canBeSumofConsec ( n ) ) ; }


Check if a number is magic ( Recursive sum of digits is 1 ) | C program to check Whether the number is Magic or not . ; Accepting sample input ; Condition to check Magic number
How can the above be solved in C?

 #include <stdio.h>
int main ( ) { int x = 1234 ; if ( x % 9 == 1 ) printf ( " Magic ▁ Number " ) ; else printf ( " Not ▁ a ▁ Magic ▁ Number " ) ; return 0 ; }


Check if a number is multiple of 5 without using / and % operators | Assuming that integer takes 4 bytes , there can be maximum 10 digits in a integer ; Check the last character of string ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
# define MAX  11
bool isMultipleof5 ( int n ) { char str [ MAX ] ; int len = strlen ( str ) ; if ( str [ len - 1 ] == '5' str [ len - 1 ] == '0' ) return true ; return false ; } int main ( ) { int n = 19 ; if ( isMultipleof5 ( n ) == true ) printf ( " % d ▁ is ▁ multiple ▁ of ▁ 5
 " , n ) ; else printf ( " % d ▁ is ▁ not ▁ a ▁ multiple ▁ of ▁ 5
 " , n ) ; return 0 ; }


Check if a number is multiple of 5 without using / and % operators | C program for the above approach ; assumes that n is a positive integer ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
bool isMultipleof5 ( int n ) { while ( n > 0 ) n = n - 5 ; if ( n == 0 ) return true ; return false ; } int main ( ) { int n = 19 ; if ( isMultipleof5 ( n ) == true ) printf ( " % d ▁ is ▁ multiple ▁ of ▁ 5
 " , n ) ; else printf ( " % d ▁ is ▁ not ▁ a ▁ multiple ▁ of ▁ 5
 " , n ) ; return 0 ; }


Check if all leaves are at same level | C program to check if all leaves are at same level ; A binary tree node ; A utility function to allocate a new tree node ; Recursive function which checks whether all leaves are at same level ; Base case ; If a leaf node is encountered ; When a leaf node is found first time ; Set first found leaf 's level ; If this is not first leaf node , compare its level with first leaf 's level ; If this node is not leaf , recursively check left and right subtrees ; The main function to check if all leafs are at same level . It mainly uses checkUtil ( ) ; Driver program to test above function ; Let us create tree shown in thirdt example
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int data ) { struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return node ; } bool checkUtil ( struct Node * root , int level , int * leafLevel ) { if ( root == NULL ) return true ; if ( root -> left == NULL && root -> right == NULL ) { if ( * leafLevel == 0 ) { * leafLevel = level ; return true ; } return ( level == * leafLevel ) ; } return checkUtil ( root -> left , level + 1 , leafLevel ) && checkUtil ( root -> right , level + 1 , leafLevel ) ; } bool check ( struct Node * root ) { int level = 0 , leafLevel = 0 ; return checkUtil ( root , level , & leafLevel ) ; } int main ( ) { struct Node * root = newNode ( 12 ) ; root -> left = newNode ( 5 ) ; root -> left -> left = newNode ( 3 ) ; root -> left -> right = newNode ( 9 ) ; root -> left -> left -> left = newNode ( 1 ) ; root -> left -> right -> left = newNode ( 1 ) ; if ( check ( root ) ) printf ( " Leaves ▁ are ▁ at ▁ same ▁ level
 " ) ; else printf ( " Leaves ▁ are ▁ not ▁ at ▁ same ▁ level
 " ) ; getchar ( ) ; return 0 ; }


Check if count of divisors is even or odd | Naive Solution to find if count of divisors is even or odd ; Function to count the divisors ; Initialize count of divisors ; Note that this loop runs till square root ; If divisors are equal increment count by one Otherwise increment count by 2 ; Driver Code
How can the above be solved in C?

 #include <math.h>
#include <stdio.h>
void countDivisors ( int n ) { int count = 0 ; for ( int i = 1 ; i <= sqrt ( n ) + 1 ; i ++ ) { if ( n % i == 0 ) count += ( n / i == i ) ? 1 : 2 ; } if ( count % 2 == 0 ) printf ( " Even
 " ) ; else printf ( " Odd
 " ) ; } int main ( ) { printf ( " The ▁ count ▁ of ▁ divisor : ▁ " ) ; countDivisors ( 10 ) ; return 0 ; }


Check if each internal node of a BST has exactly one child | Check if each internal node of BST has only one child ; Initialize min and max using last two elements ; Every element must be either smaller than min or greater than max ; Driver program to test above function
How can the above be solved in C?

 #include <stdio.h>
int hasOnlyOneChild ( int pre [ ] , int size ) { int min , max ; if ( pre [ size - 1 ] > pre [ size - 2 ] ) { max = pre [ size - 1 ] ; min = pre [ size - 2 ] ) : else { max = pre [ size - 2 ] ; min = pre [ size - 1 ] ; } for ( int i = size - 3 ; i >= 0 ; i -- ) { if ( pre [ i ] < min ) min = pre [ i ] ; else if ( pre [ i ] > max ) max = pre [ i ] ; else return false ; } return true ; } int main ( ) { int pre [ ] = { 8 , 3 , 5 , 7 , 6 } ; int size = sizeof ( pre ) / sizeof ( pre [ 0 ] ) ; if ( hasOnlyOneChild ( pre , size ) ) printf ( " Yes " ) ; else printf ( " No " ) ; return 0 ; }


Check if each internal node of a BST has exactly one child | Check if each internal node of BST has only one child ; driver program to test above function
How can the above be solved in C?

 #include <stdio.h>
bool hasOnlyOneChild ( int pre [ ] , int size ) { int nextDiff , lastDiff ; for ( int i = 0 ; i < size - 1 ; i ++ ) { nextDiff = pre [ i ] - pre [ i + 1 ] ; lastDiff = pre [ i ] - pre [ size - 1 ] ; if ( nextDiff * lastDiff < 0 ) return false ; ; } return true ; } int main ( ) { int pre [ ] = { 8 , 3 , 5 , 7 , 6 } ; int size = sizeof ( pre ) / sizeof ( pre [ 0 ] ) ; if ( hasOnlyOneChild ( pre , size ) == true ) printf ( " Yes " ) ; else printf ( " No " ) ; return 0 ; }


Check if given Parentheses expression is balanced or not | C program of the above approach ; Function to check if parentheses are balanced ; Initialising Variables ; Traversing the Expression ; It is a closing parenthesis ; This means there are more Closing parenthesis than opening ones ; If count is not zero , It means there are more opening parenthesis ; Driver code
How can the above be solved in C?

 #include <stdbool.h>
#include <stdio.h>
bool isBalanced ( char exp [ ] ) { bool flag = true ; int count = 0 ; for ( int i = 0 ; exp [ i ] != ' \0' ; i ++ ) { if ( exp [ i ] == ' ( ' ) { count ++ ; } else { count -- ; } if ( count < 0 ) { flag = false ; break ; } } if ( count != 0 ) { flag = false ; } return flag ; } int main ( ) { char exp1 [ ] = " ( ( ( ) ) ) ( ) ( ) " ; if ( isBalanced ( exp1 ) ) printf ( " Balanced ▁
 " ) ; else printf ( " Not ▁ Balanced ▁
 " ) ; char exp2 [ ] = " ( ) ) ( ( ( ) ) " ; if ( isBalanced ( exp2 ) ) printf ( " Balanced ▁
 " ) ; else printf ( " Not ▁ Balanced ▁
 " ) ; return 0 ; }


Check if two arrays can be made equal by reversing subarrays multiple times | C implementation to check if two arrays can be made equal ; Function to check if array B can be made equal to array A ; Sort both arrays ; Check both arrays equal or not ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
#include <math.h>
int sort ( int a [ ] , int n ) { int i , j , tmp ; for ( i = 0 ; i < n ; i ++ ) { for ( j = i + 1 ; j < n ; j ++ ) { if ( a [ j ] < a [ i ] ) { tmp = a [ i ] ; a [ i ] = a [ j ] ; a [ j ] = tmp ; } } } return 0 ; } int canMadeEqual ( int A [ ] , int B [ ] , int n ) { int i ; sort ( A , n ) ; sort ( B , n ) ; for ( i = 0 ; i < n ; i ++ ) { if ( A [ i ] != B [ i ] ) { return ( 0 ) ; } } return ( 1 ) ; } int main ( ) { int A [ ] = { 1 , 2 , 3 } ; int n ; int B [ ] = { 1 , 3 , 2 } ; n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; if ( canMadeEqual ( A , B , n ) ) { printf ( " Yes " ) ; } else { printf ( " No " ) ; } return 0 ; }


Check if two nodes are cousins in a Binary Tree | C program to check if two Nodes in a binary tree are cousins ; A Binary Tree Node ; A utility function to create a new Binary Tree Node ; Recursive function to check if two Nodes are siblings ; Base case ; Recursive function to find level of Node ' ptr ' in a binary tree ; base cases ; Return level if Node is present in left subtree ; Else search in right subtree ; Returns 1 if a and b are cousins , otherwise 0 ; 1. The two Nodes should be on the same level in the binary tree . 2. The two Nodes should not be siblings ( means that they should not have the same parent Node ) . ; Driver Program to test above functions
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int item ) { struct Node * temp = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; temp -> data = item ; temp -> left = temp -> right = NULL ; return temp ; } int isSibling ( struct Node * root , struct Node * a , struct Node * b ) { if ( root == NULL ) return 0 ; return ( ( root -> left == a && root -> right == b ) || ( root -> left == b && root -> right == a ) || isSibling ( root -> left , a , b ) || isSibling ( root -> right , a , b ) ) ; } int level ( struct Node * root , struct Node * ptr , int lev ) { if ( root == NULL ) return 0 ; if ( root == ptr ) return lev ; int l = level ( root -> left , ptr , lev + 1 ) ; if ( l != 0 ) return l ; return level ( root -> right , ptr , lev + 1 ) ; } int isCousin ( struct Node * root , struct Node * a , struct Node * b ) { if ( ( level ( root , a , 1 ) == level ( root , b , 1 ) ) && ! ( isSibling ( root , a , b ) ) ) return 1 ; else return 0 ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> left -> right -> right = newNode ( 15 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> right -> left -> right = newNode ( 8 ) ; struct Node * Node1 , * Node2 ; Node1 = root -> left -> left ; Node2 = root -> right -> right ; isCousin ( root , Node1 , Node2 ) ? puts ( " Yes " ) : puts ( " No " ) ; return 0 ; }


Check whether a binary tree is a full binary tree or not | C program to check whether a given Binary Tree is full or not ; Tree node structure ; Helper function that allocates a new node with the given key and NULL left and right pointer . ; This function tests if a binary tree is a full binary tree . ; If empty tree ; If leaf node ; If both left and right are not NULL , and left & right subtrees are full ; We reach here when none of the above if conditions work ; Driver Program
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct Node { int key ; struct Node * left , * right ; } ; struct Node * newNode ( char k ) { struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; node -> key = k ; node -> right = node -> left = NULL ; return node ; } bool isFullTree ( struct Node * root ) { if ( root == NULL ) return true ; if ( root -> left == NULL && root -> right == NULL ) return true ; if ( ( root -> left ) && ( root -> right ) ) return ( isFullTree ( root -> left ) && isFullTree ( root -> right ) ) ; return false ; } int main ( ) { struct Node * root = NULL ; root = newNode ( 10 ) ; root -> left = newNode ( 20 ) ; root -> right = newNode ( 30 ) ; root -> left -> right = newNode ( 40 ) ; root -> left -> left = newNode ( 50 ) ; root -> right -> left = newNode ( 60 ) ; root -> right -> right = newNode ( 70 ) ; root -> left -> left -> left = newNode ( 80 ) ; root -> left -> left -> right = newNode ( 90 ) ; root -> left -> right -> left = newNode ( 80 ) ; root -> left -> right -> right = newNode ( 90 ) ; root -> right -> left -> left = newNode ( 80 ) ; root -> right -> left -> right = newNode ( 90 ) ; root -> right -> right -> left = newNode ( 80 ) ; root -> right -> right -> right = newNode ( 90 ) ; if ( isFullTree ( root ) ) printf ( " The ▁ Binary ▁ Tree ▁ is ▁ full
 " ) ; else printf ( " The ▁ Binary ▁ Tree ▁ is ▁ not ▁ full
 " ) ; return ( 0 ) ; }


Check whether a number is semiprime or not | C Program to check whether number is semiprime or not ; Utility function to check whether number is semiprime or not ; If number is greater than 1 , add it to the count variable as it indicates the number remain is prime number ; Return '1' if count is equal to '2' else return '0' ; Function to print ' True ' or ' False ' according to condition of semiprime ; Driver code
How can the above be solved in C?

 #include <stdio.h>
int checkSemiprime ( int num ) { int cnt = 0 ; for ( int i = 2 ; cnt < 2 && i * i <= num ; ++ i ) while ( num % i == 0 ) num /= i , ++ cnt ; if ( num > 1 ) ++ cnt ; return cnt == 2 ; } void semiprime ( int n ) { if ( checkSemiprime ( n ) ) printf ( " True
 " ) ; else printf ( " False
 " ) ; } int main ( ) { int n = 6 ; semiprime ( n ) ; n = 8 ; semiprime ( n ) ; return 0 ; }


Check whether count of odd and even factors of a number are equal | C code for the above approach ; Function to check condition ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
#define lli  long long int
void isEqualFactors ( lli N ) { if ( ( N % 2 == 0 ) && ( N % 4 != 0 ) ) printf ( " YES
 " ) ; else printf ( " NO
 " ) ; } int main ( ) { lli N = 10 ; isEqualFactors ( N ) ; N = 125 ; isEqualFactors ( N ) ; return 0 ; }


Check whether the length of given linked list is Even or Odd | C program to check length of a given linklist ; Defining structure ; Function to check the length of linklist ; Push function ; Allocating node ; Info into node ; Next of new node to head ; head points to new node ; Driver function ; Adding elements to Linked List ; Checking for length of linklist
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct Node { int data ; struct Node * next ; } ; int LinkedListLength ( struct Node * head ) { while ( head && head -> next ) { head = head -> next -> next ; } if ( ! head ) return 0 ; return 1 ; } void push ( struct Node * * head , int info ) { struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; node -> data = info ; node -> next = ( * head ) ; ( * head ) = node ; } int main ( void ) { struct Node * head = NULL ; push ( & head , 4 ) ; push ( & head , 5 ) ; push ( & head , 7 ) ; push ( & head , 2 ) ; push ( & head , 9 ) ; push ( & head , 6 ) ; push ( & head , 1 ) ; push ( & head , 2 ) ; push ( & head , 0 ) ; push ( & head , 5 ) ; push ( & head , 5 ) ; int check = LinkedListLength ( head ) ; if ( check == 0 ) { printf ( " Even
 " ) ; } else { printf ( " Odd
 " ) ; } return 0 ; }


Check whether two strings are anagram of each other | C program to check if two strings are anagrams of each other ; function to check whether two strings are anagram of each other ; Create 2 count arrays and initialize all values as 0 ; For each character in input strings , increment count in the corresponding count array ; If both strings are of different length . Removing this condition will make the program fail for strings like " aaca " and " aca " ; Compare count arrays ; Driver code ; Function Call
How can the above be solved in C?

 #include <stdio.h>
#define NO_OF_CHARS  256
bool areAnagram ( char * str1 , char * str2 ) { int count1 [ NO_OF_CHARS ] = { 0 } ; int count2 [ NO_OF_CHARS ] = { 0 } ; int i ; for ( i = 0 ; str1 [ i ] && str2 [ i ] ; i ++ ) { count1 [ str1 [ i ] ] ++ ; count2 [ str2 [ i ] ] ++ ; } if ( str1 [ i ] str2 [ i ] ) return false ; for ( i = 0 ; i < NO_OF_CHARS ; i ++ ) if ( count1 [ i ] != count2 [ i ] ) return false ; return true ; } int main ( ) { char str1 [ ] = " geeksforgeeks " ; char str2 [ ] = " forgeeksgeeks " ; if ( areAnagram ( str1 , str2 ) ) printf ( " The ▁ two ▁ strings ▁ are ▁ anagram ▁ of ▁ each ▁ other " ) ; else printf ( " The ▁ two ▁ strings ▁ are ▁ not ▁ anagram ▁ of ▁ each ▁ " " other " ) ; return 0 ; }


Chiliagon Number | C program for above approach ; Finding the nth chiliagon Number ; Driver program to test above function
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
int chiliagonNum ( int n ) { return ( 998 * n * n - 996 * n ) / 2 ; } int main ( ) { int n = 3 ; printf ( "3rd ▁ chiliagon ▁ Number ▁ is ▁ = ▁ % d " , chiliagonNum ( n ) ) ; return 0 ; }


Chocolate Distribution Problem | Set 2 | C program for above approach ; Function to return minimum number of chocolates ; decreasing sequence ; add the chocolates received by that person ; end point of decreasing sequence ; val = 1 ; reset value at that index ; increasing sequence ; flat sequence ; add value of chocolates at position n - 1 ; Helper function to get sum of decreasing sequence ; value obtained from decreasing sequence also the count of values in the sequence ; assigning max of values obtained from increasing and decreasing sequences ; sum of count - 1 values & peak value sum of natural numbers : ( n * ( n + 1 ) ) / 2 ; Driver code
How can the above be solved in C?

 #include <stdio.h>
int minChocolates ( int a [ ] , int n ) { int i = 0 , j = 0 ; int res = 0 , val = 1 ; while ( j < n - 1 ) { if ( a [ j ] > a [ j + 1 ] ) { j += 1 ; continue ; } if ( i == j ) res += val ; else { res += get_sum ( val , i , j ) ; } if ( a [ j ] < a [ j + 1 ] ) val += 1 ; else val = 1 ; j += 1 ; i = j ; } if ( i == j ) res += val ; else res += get_sum ( val , i , j ) ; return res ; } int get_sum ( int peak , int start , int end ) { int count = end - start + 1 ; peak = ( peak > count ) ? peak : count ; int s = peak + ( ( ( count - 1 ) * count ) >> 1 ) ; return s ; } int main ( ) { int a [ ] = { 5 , 5 , 4 , 3 , 2 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; printf ( " Minimum ▁ number ▁ of ▁ chocolates ▁ = ▁ % d " , minChocolates ( a , n ) ) ; return 0 ; }


Closest Pair of Points using Divide and Conquer algorithm | A divide and conquer program in C / C ++ to find the smallest distance from a given set of points . ; A structure to represent a Point in 2D plane ; Needed to sort array of points according to X coordinate ; Needed to sort array of points according to Y coordinate ; A utility function to find the distance between two points ; A Brute Force method to return the smallest distance between two points in P [ ] of size n ; A utility function to find a minimum of two float values ; A utility function to find the distance between the closest points of strip of a given size . All points in strip [ ] are sorted according to y coordinate . They all have an upper bound on minimum distance as d . Note that this method seems to be a O ( n ^ 2 ) method , but it 's a O(n) method as the inner loop runs at most 6 times ; Initialize the minimum distance as d ; Pick all points one by one and try the next points till the difference between y coordinates is smaller than d . This is a proven fact that this loop runs at most 6 times ; A recursive function to find the smallest distance . The array P contains all points sorted according to x coordinate ; If there are 2 or 3 points , then use brute force ; Find the middle point ; Consider the vertical line passing through the middle point calculate the smallest distance dl on left of middle point and dr on right side ; Find the smaller of two distances ; Build an array strip [ ] that contains points close ( closer than d ) to the line passing through the middle point ; Find the closest points in strip . Return the minimum of d and closest distance is strip [ ] ; The main function that finds the smallest distance This method mainly uses closestUtil ( ) ; Use recursive function closestUtil ( ) to find the smallest distance ; Driver program to test above functions
How can the above be solved in C?

 #include <stdio.h>
#include <float.h>
#include <stdlib.h>
#include <math.h>
struct Point { int x , y ; } ; int compareX ( const void * a , const void * b ) { Point * p1 = ( Point * ) a , * p2 = ( Point * ) b ; return ( p1 -> x - p2 -> x ) ; } int compareY ( const void * a , const void * b ) { Point * p1 = ( Point * ) a , * p2 = ( Point * ) b ; return ( p1 -> y - p2 -> y ) ; } float dist ( Point p1 , Point p2 ) { return sqrt ( ( p1 . x - p2 . x ) * ( p1 . x - p2 . x ) + ( p1 . y - p2 . y ) * ( p1 . y - p2 . y ) ) ; } float bruteForce ( Point P [ ] , int n ) { float min = FLT_MAX ; for ( int i = 0 ; i < n ; ++ i ) for ( int j = i + 1 ; j < n ; ++ j ) if ( dist ( P [ i ] , P [ j ] ) < min ) min = dist ( P [ i ] , P [ j ] ) ; return min ; } float min ( float x , float y ) { return ( x < y ) ? x : y ; } float stripClosest ( Point strip [ ] , int size , float d ) { float min = d ; qsort ( strip , size , sizeof ( Point ) , compareY ) ; for ( int i = 0 ; i < size ; ++ i ) for ( int j = i + 1 ; j < size && ( strip [ j ] . y - strip [ i ] . y ) < min ; ++ j ) if ( dist ( strip [ i ] , strip [ j ] ) < min ) min = dist ( strip [ i ] , strip [ j ] ) ; return min ; } float closestUtil ( Point P [ ] , int n ) { if ( n <= 3 ) return bruteForce ( P , n ) ; int mid = n / 2 ; Point midPoint = P [ mid ] ; float dl = closestUtil ( P , mid ) ; float dr = closestUtil ( P + mid , n - mid ) ; float d = min ( dl , dr ) ; Point strip [ n ] ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( abs ( P [ i ] . x - midPoint . x ) < d ) strip [ j ] = P [ i ] , j ++ ; return min ( d , stripClosest ( strip , j , d ) ) ; } float closest ( Point P [ ] , int n ) { qsort ( P , n , sizeof ( Point ) , compareX ) ; return closestUtil ( P , n ) ; } int main ( ) { Point P [ ] = { { 2 , 3 } , { 12 , 30 } , { 40 , 50 } , { 5 , 1 } , { 12 , 10 } , { 3 , 4 } } ; int n = sizeof ( P ) / sizeof ( P [ 0 ] ) ; printf ( " The ▁ smallest ▁ distance ▁ is ▁ % f ▁ " , closest ( P , n ) ) ; return 0 ; }


Combinatorial Game Theory | Set 2 ( Game of Nim ) | A C program to implement Game of Nim . The program assumes that both players are playing optimally ; A Structure to hold the two parameters of a move A move has two parameters - 1 ) pile_index = The index of pile from which stone is going to be removed 2 ) stones_removed = Number of stones removed from the pile indexed = pile_index ; A C function to output the current game state . ; A C function that returns True if game has ended and False if game is not yet over ; A C function to declare the winner of the game ; A C function to calculate the Nim - Sum at any point of the game . ; A C function to make moves of the Nim Game ; The player having the current turn is on a winning position . So he / she / it play optimally and tries to make Nim - Sum as 0 ; If this is not an illegal move then make this move . ; If you want to input yourself then remove the rand ( ) functions and modify the code to take inputs . But remember , you still won 't be able to change your  fate/prediction. ; Create an array to hold indices of non - empty piles ; A C function to play the Game of Nim ; Driver program to test above functions ; Test Case 1 ; We will predict the results before playing The COMPUTER starts first ; Let us play the game with COMPUTER starting first and check whether our prediction was right or not ; Test Case 2 int piles [ ] = { 3 , 4 , 7 } ; int n = sizeof ( piles ) / sizeof ( piles [ 0 ] ) ; We will predict the results before playing The HUMAN ( You ) starts first ; Let us play the game with COMPUTER starting first and check whether our prediction was right or not playGame ( piles , n , HUMAN ) ;
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define COMPUTER  1
#define HUMAN  2
struct move { int pile_index ; int stones_removed ; } ; void showPiles ( int piles [ ] , int n ) { int i ; printf ( " Current ▁ Game ▁ Status ▁ - > ▁ " ) ; for ( i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , piles [ i ] ) ; printf ( "
 " ) ; return ; } bool gameOver ( int piles [ ] , int n ) { int i ; for ( i = 0 ; i < n ; i ++ ) if ( piles [ i ] != 0 ) return ( false ) ; return ( true ) ; } void declareWinner ( int whoseTurn ) { if ( whoseTurn == COMPUTER ) printf ( " HUMAN won " else printf ( " COMPUTER won " return ; } int calculateNimSum ( int piles [ ] , int n ) { int i , nimsum = piles [ 0 ] ; for ( i = 1 ; i < n ; i ++ ) nimsum = nimsum ^ piles [ i ] ; return ( nimsum ) ; } void makeMove ( int piles [ ] , int n , struct move * moves ) { int i , nim_sum = calculateNimSum ( piles , n ) ; if ( nim_sum != 0 ) { for ( i = 0 ; i < n ; i ++ ) { if ( ( piles [ i ] ^ nim_sum ) < piles [ i ] ) { ( * moves ) . pile_index = i ; ( * moves ) . stones_removed = piles [ i ] - ( piles [ i ] ^ nim_sum ) ; piles [ i ] = ( piles [ i ] ^ nim_sum ) ; break ; } } } else { int non_zero_indices [ n ] , count ; for ( i = 0 , count = 0 ; i < n ; i ++ ) if ( piles [ i ] > 0 ) non_zero_indices [ count ++ ] = i ; ( * moves ) . pile_index = ( rand ( ) % ( count ) ) ; ( * moves ) . stones_removed = 1 + ( rand ( ) % ( piles [ ( * moves ) . pile_index ] ) ) ; piles [ ( * moves ) . pile_index ] = piles [ ( * moves ) . pile_index ] - ( * moves ) . stones_removed ; if ( piles [ ( * moves ) . pile_index ] < 0 ) piles [ ( * moves ) . pile_index ] = 0 ; } return ; } void playGame ( int piles [ ] , int n , int whoseTurn ) { printf ( " GAME STARTS " struct move moves ; while ( gameOver ( piles , n ) == false ) { showPiles ( piles , n ) ; makeMove ( piles , n , & moves ) ; if ( whoseTurn == COMPUTER ) { printf ( " COMPUTER ▁ removes ▁ % d ▁ stones ▁ from ▁ pile ▁ " " at ▁ index ▁ % d
 " , moves . stones_removed , moves . pile_index ) ; whoseTurn =...


Compute maximum of two integers in C / C ++ using Bitwise Operators | C program for the above approach ; Function to find the largest number ; Perform the subtraction ; Right shift and Bitwise AND ; Find the maximum number ; Return the maximum value ; Driver Code ; Function Call
How can the above be solved in C?

 #include <stdio.h>
int findMax ( int a , int b ) { int z , i , max ; z = a - b ; i = ( z >> 31 ) & 1 ; max = a - ( i * z ) ; return max ; } int main ( ) { int A = 40 , B = 54 ; printf ( " % d " , findMax ( A , B ) ) ; return 0 ; }


Compute the minimum or maximum of two integers without branching |  ; Function to find minimum of x and y ; Function to find maximum of x and y ; Driver program to test above functions
How can the above be solved in C?

 #include <stdio.h>
#define CHAR_BIT  8
int min ( int x , int y ) { return y + ( ( x - y ) & ( ( x - y ) >> ( sizeof ( int ) * CHAR_BIT - 1 ) ) ) ; } int max ( int x , int y ) { return x - ( ( x - y ) & ( ( x - y ) >> ( sizeof ( int ) * CHAR_BIT - 1 ) ) ) ; } int main ( ) { int x = 15 ; int y = 6 ; printf ( " Minimum ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ " , x , y ) ; printf ( " % d " , min ( x , y ) ) ; printf ( " Maximum of % d and % d is " printf ( " % d " , max ( x , y ) ) ; getchar ( ) ; }


Compute the minimum or maximum of two integers without branching | C program to Compute the minimum or maximum of two integers without branching ; Function to find minimum of x and y ; Function to find maximum of x and y ; Driver program to test above functions
How can the above be solved in C?

 #include <stdio.h>
int min ( int x , int y ) { return y ^ ( ( x ^ y ) & - ( x < y ) ) ; } int max ( int x , int y ) { return x ^ ( ( x ^ y ) & - ( x < y ) ) ; } int main ( ) { int x = 15 ; int y = 6 ; printf ( " Minimum ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ " , x , y ) ; printf ( " % d " , min ( x , y ) ) ; printf ( " Maximum of % d and % d is " printf ( " % d " , max ( x , y ) ) ; getchar ( ) ; }


Connect nodes at same level using constant extra space | Iterative C program to connect nodes at same level using constant extra space ; Constructor that allocates a new node with the given data and NULL left and right pointers . ; This function returns the leftmost child of nodes at the same level as p . This function is used to getNExt right of p 's right child  If right child of is NULL then this can also be used for the left child  ; Traverse nodes at p ' s ▁ level ▁ and ▁ find ▁ and ▁ return ▁ ▁ the ▁ first ▁ node ' s first child ; If all the nodes at p 's level are leaf nodes then return NULL ; Sets nextRight of all nodes of a tree with root as p ; Set nextRight for root ; set nextRight of all levels one by one ; Connect all childrem nodes of p and children nodes of all other nodes at same level as p ; Set the nextRight pointer for p 's left child ; If q has right child , then right child is nextRight of p and we also need to set nextRight of right child ; Set nextRight for other nodes in pre order fashion ; start from the first node of next level ; Driver program to test above functions ; Constructed binary tree is 10 / \ 8 2 / \ 3 90 ; Populates nextRight pointer in all nodes ; Let us check the values of nextRight pointers
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct node { int data ; struct node * left ; struct node * right ; struct node * nextRight ; } ; struct node * newnode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; node -> nextRight = NULL ; return ( node ) ; } struct node * getNextRight ( struct node * p ) { struct node * temp = p -> nextRight ; while ( temp != NULL ) { if ( temp -> left != NULL ) return temp -> left ; if ( temp -> right != NULL ) return temp -> right ; temp = temp -> nextRight ; } return NULL ; } void connect ( struct node * p ) { struct node * temp ; if ( ! p ) return ; p -> nextRight = NULL ; while ( p != NULL ) { struct node * q = p ; while ( q != NULL ) { if ( q -> left ) { if ( q -> right ) q -> left -> nextRight = q -> right ; else q -> left -> nextRight = getNextRight ( q ) ; } if ( q -> right ) q -> right -> nextRight = getNextRight ( q ) ; q = q -> nextRight ; } if ( p -> left ) p = p -> left ; else if ( p -> right ) p = p -> right ; else p = getNextRight ( p ) ; } } int main ( ) { struct node * root = newnode ( 10 ) ; root -> left = newnode ( 8 ) ; root -> right = newnode ( 2 ) ; root -> left -> left = newnode ( 3 ) ; root -> right -> right = newnode ( 90 ) ; connect ( root ) ; printf ( " Following ▁ are ▁ populated ▁ nextRight ▁ pointers ▁ in ▁ the ▁ tree ▁ " " ( -1 ▁ is ▁ printed ▁ if ▁ there ▁ is ▁ no ▁ nextRight ) ▁
 " ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁
 " , root -> data , root -> nextRight ? root -> nextRight -> data : -1 ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁
 " , root -> left -> data , root -> left -> nextRight ? root -> left -> nextRight -> data : -1 ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁
 " , root -> right -> data , root -> right -> nextRight ? root -> right -> nextRight -> data : -1 ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁
 " , root -> left -> left -> data , root -> left -> left -> nextRight ? root -> left -> left ->...


Connect nodes at same level | C program to connect nodes at same level using extended pre - order traversal ; A binary tree node ; Sets the nextRight of root and calls connectRecur ( ) for other nodes ; Set the nextRight for root ; Set the next right for rest of the nodes ( other than root ) ; Set next right of all descendents of p . Assumption : p is a compete binary tree ; Base case ; Set the nextRight pointer for p 's left child ; Set the nextRight pointer for p 's right child  p->nextRight will be NULL if p is the right  most child at its level ; Set nextRight for other nodes in pre order fashion ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver program to test above functions ; Constructed binary tree is 10 / \ 8 2 / 3 ; Populates nextRight pointer in all nodes ; Let us check the values of nextRight pointers
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
void connectRecur ( struct node * p ) ; struct node { int data ; struct node * left ; struct node * right ; struct node * nextRight ; } ; void connect ( struct node * p ) { p -> nextRight = NULL ; connectRecur ( p ) ; } void connectRecur ( struct node * p ) { if ( ! p ) return ; if ( p -> left ) p -> left -> nextRight = p -> right ; if ( p -> right ) p -> right -> nextRight = ( p -> nextRight ) ? p -> nextRight -> left : NULL ; connectRecur ( p -> left ) ; connectRecur ( p -> right ) ; } struct node * newnode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; node -> nextRight = NULL ; return ( node ) ; } int main ( ) { struct node * root = newnode ( 10 ) ; root -> left = newnode ( 8 ) ; root -> right = newnode ( 2 ) ; root -> left -> left = newnode ( 3 ) ; connect ( root ) ; printf ( " Following ▁ are ▁ populated ▁ nextRight ▁ pointers ▁ in ▁ the ▁ tree ▁ " " ( -1 ▁ is ▁ printed ▁ if ▁ there ▁ is ▁ no ▁ nextRight ) ▁
 " ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁
 " , root -> data , root -> nextRight ? root -> nextRight -> data : -1 ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁
 " , root -> left -> data , root -> left -> nextRight ? root -> left -> nextRight -> data : -1 ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁
 " , root -> right -> data , root -> right -> nextRight ? root -> right -> nextRight -> data : -1 ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁
 " , root -> left -> left -> data , root -> left -> left -> nextRight ? root -> left -> left -> nextRight -> data : -1 ) ; return 0 ; }


Construct Full Binary Tree from given preorder and postorder traversals | program for construction of full binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; A utility function to create a node ; A recursive function to construct Full from pre [ ] and post [ ] . preIndex is used to keep track of index in pre [ ] . l is low index and h is high index for the current subarray in post [ ] ; Base case ; The first node in preorder traversal is root . So take the node at preIndex from preorder and make it root , and increment preIndex ; If the current subarry has only one element , no need to recur ; Search the next element of pre [ ] in post [ ] ; Use the index of element found in postorder to divide postorder array in two parts . Left subtree and right subtree ; The main function to construct Full Binary Tree from given preorder and postorder traversals . This function mainly uses constructTreeUtil ( ) ; A utility function to print inorder traversal of a Binary Tree ; Driver program to test above functions
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct node { int data ; struct node * left ; struct node * right ; } ; struct node * newNode ( int data ) { struct node * temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } struct node * constructTreeUtil ( int pre [ ] , int post [ ] , int * preIndex , int l , int h , int size ) { if ( * preIndex >= size l > h ) return NULL ; struct node * root = newNode ( pre [ * preIndex ] ) ; ++ * preIndex ; if ( l == h ) return root ; int i ; for ( i = l ; i <= h ; ++ i ) if ( pre [ * preIndex ] == post [ i ] ) break ; if ( i <= h ) { root -> left = constructTreeUtil ( pre , post , preIndex , l , i , size ) ; root -> right = constructTreeUtil ( pre , post , preIndex , i + 1 , h , size ) ; } return root ; } struct node * constructTree ( int pre [ ] , int post [ ] , int size ) { int preIndex = 0 ; return constructTreeUtil ( pre , post , & preIndex , 0 , size - 1 , size ) ; } void printInorder ( struct node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; printf ( " % d ▁ " , node -> data ) ; printInorder ( node -> right ) ; } int main ( ) { int pre [ ] = { 1 , 2 , 4 , 8 , 9 , 5 , 3 , 6 , 7 } ; int post [ ] = { 8 , 9 , 4 , 5 , 2 , 6 , 7 , 3 , 1 } ; int size = sizeof ( pre ) / sizeof ( pre [ 0 ] ) ; struct node * root = constructTree ( pre , post , size ) ; printf ( " Inorder ▁ traversal ▁ of ▁ the ▁ constructed ▁ tree : ▁
 " ) ; printInorder ( root ) ; return 0 ; }


Construct Special Binary Tree from given Inorder traversal | program to construct tree from inorder traversal ; A binary tree node has data , pointer to left child and a pointer to right child ; Prototypes of a utility function to get the maximum value in inorder [ start . . end ] ; Recursive function to construct binary of size len from Inorder traversal inorder [ ] . Initial values of start and end should be 0 and len - 1. ; Find index of the maximum element from Binary Tree ; Pick the maximum value and make it root ; If this is the only element in inorder [ start . . end ] , then return it ; Using index in Inorder traversal , construct left and right subtress ; Function to find index of the maximum value in arr [ start ... end ] ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; This funtcion is here just to test buildTree ( ) ; first recur on left child ; then print the data of node ; now recur on right child ; Driver program to test above functions ; Assume that inorder traversal of following tree is given 40 / \ 10 30 / \ 5 28 ; Let us test the built tree by printing Insorder traversal
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct node { int data ; struct node * left ; struct node * right ; } ; int max ( int inorder [ ] , int strt , int end ) ; struct node * newNode ( int data ) ; struct node * buildTree ( int inorder [ ] , int start , int end ) { if ( start > end ) return NULL ; int i = max ( inorder , start , end ) ; struct node * root = newNode ( inorder [ i ] ) ; if ( start == end ) return root ; root -> left = buildTree ( inorder , start , i - 1 ) ; root -> right = buildTree ( inorder , i + 1 , end ) ; return root ; } int max ( int arr [ ] , int strt , int end ) { int i , max = arr [ strt ] , maxind = strt ; for ( i = strt + 1 ; i <= end ; i ++ ) { if ( arr [ i ] > max ) { max = arr [ i ] ; maxind = i ; } } return maxind ; } struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return node ; } void printInorder ( struct node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; printf ( " % d ▁ " , node -> data ) ; printInorder ( node -> right ) ; } int main ( ) { int inorder [ ] = { 5 , 10 , 40 , 30 , 28 } ; int len = sizeof ( inorder ) / sizeof ( inorder [ 0 ] ) ; struct node * root = buildTree ( inorder , 0 , len - 1 ) ; printf ( " Inorder traversal of the constructed tree is " printInorder ( root ) ; return 0 ; }


Construct Tree from given Inorder and Preorder traversals | program to construct tree using inorder and preorder traversals ; A binary tree node has data , pointer to left child and a pointer to right child ; Prototypes for utility functions ; Recursive function to construct binary of size len from Inorder traversal in [ ] and Preorder traversal pre [ ] . Initial values of inStrt and inEnd should be 0 and len - 1. The function doesn 't  do any error checking for cases where inorder and preorder  do not form a tree  ; Pick current node from Preorder traversal using preIndex and increment preIndex ; If this node has no children then return ; Else find the index of this node in Inorder traversal ; Using index in Inorder traversal , construct left and right subtress ; Function to find index of value in arr [ start ... end ] The function assumes that value is present in in [ ] ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; This funtcion is here just to test buildTree ( ) ; first recur on left child ; then print the data of node ; now recur on right child ; Driver program to test above functions ; Let us test the built tree by printing Insorder traversal
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct node { char data ; struct node * left ; struct node * right ; } ; int search ( char arr [ ] , int strt , int end , char value ) ; struct node * newNode ( char data ) ; struct node * buildTree ( char in [ ] , char pre [ ] , int inStrt , int inEnd ) { static int preIndex = 0 ; if ( inStrt > inEnd ) return NULL ; struct node * tNode = newNode ( pre [ preIndex ++ ] ) ; if ( inStrt == inEnd ) return tNode ; int inIndex = search ( in , inStrt , inEnd , tNode -> data ) ; tNode -> left = buildTree ( in , pre , inStrt , inIndex - 1 ) ; tNode -> right = buildTree ( in , pre , inIndex + 1 , inEnd ) ; return tNode ; } int search ( char arr [ ] , int strt , int end , char value ) { int i ; for ( i = strt ; i <= end ; i ++ ) { if ( arr [ i ] == value ) return i ; } } struct node * newNode ( char data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } void printInorder ( struct node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; printf ( " % c ▁ " , node -> data ) ; printInorder ( node -> right ) ; } int main ( ) { char in [ ] = { ' D ' , ' B ' , ' E ' , ' A ' , ' F ' , ' C ' } ; char pre [ ] = { ' A ' , ' B ' , ' D ' , ' E ' , ' C ' , ' F ' } ; int len = sizeof ( in ) / sizeof ( in [ 0 ] ) ; struct node * root = buildTree ( in , pre , 0 , len - 1 ) ; printf ( " Inorder ▁ traversal ▁ of ▁ the ▁ constructed ▁ tree ▁ is ▁
 " ) ; printInorder ( root ) ; getchar ( ) ; }


Construct XOR tree by Given leaf nodes of Perfect Binary Tree | C program to build xor tree by leaf nodes of perfect binary tree and root node value of tree ; maximum size for xor tree ; Allocating space to xor tree ; A recursive function that constructs xor tree for array [ start ... . . end ] . x is index of current node in xor tree st ; If there is one element in array , store it in current node of xor tree and return ; printf ( " % d ▁ " , xortree [ x ] ) ; ; for left subtree ; for right subtree ; for getting the middle index from corner indexes . ; Build the left and the right subtrees by xor operation ; merge the left and right subtrees by XOR operation ; Function to construct XOR tree from given array . This function calls construct_Xor_Tree_Util ( ) to fill the allocated memory of xort array ; Driver Code ; leaf nodes of Binary Tree ; Build the xor tree ; Height of xor tree ; Maximum size of xor tree ; Root node is at index 0 considering 0 - based indexing in XOR Tree ; print value at root node
How can the above be solved in C?

 #include <math.h>
#include <stdio.h>
#define maxsize  10005
int xortree [ maxsize ] ; void construct_Xor_Tree_Util ( int current [ ] , int start , int end , int x ) { if ( start == end ) { xortree [ x ] = current [ start ] ; return ; } int left = x * 2 + 1 ; int right = x * 2 + 2 ; int mid = start + ( end - start ) / 2 ; construct_Xor_Tree_Util ( current , start , mid , left ) ; construct_Xor_Tree_Util ( current , mid + 1 , end , right ) ; xortree [ x ] = ( xortree [ left ] ^ xortree [ right ] ) ; } void construct_Xor_Tree ( int arr [ ] , int n ) { int i = 0 ; for ( i = 0 ; i < maxsize ; i ++ ) xortree [ i ] = 0 ; construct_Xor_Tree_Util ( arr , 0 , n - 1 , 0 ) ; } int main ( ) { int leaf_nodes [ ] = { 40 , 32 , 12 , 1 , 4 , 3 , 2 , 7 } , i = 0 ; int n = sizeof ( leaf_nodes ) / sizeof ( leaf_nodes [ 0 ] ) ; construct_Xor_Tree ( leaf_nodes , n ) ; int x = ( int ) ( ceil ( log2 ( n ) ) ) ; int max_size = 2 * ( int ) pow ( 2 , x ) - 1 ; printf ( " Nodes ▁ of ▁ the ▁ XOR ▁ tree
 " ) ; for ( i = 0 ; i < max_size ; i ++ ) { printf ( " % d ▁ " , xortree [ i ] ) ; } int root = 0 ; printf ( " Root : % d " , xortree [ root ] ) ; }


Construct a graph using N vertices whose shortest distance between K pair of vertices is 2 | C program to implement the above approach ; Function to construct the simple and connected graph such that the distance between exactly K pairs of vertices is 2 ; Stores maximum possible count of edges in a graph ; Base Case ; Stores count of edges in a graph ; Connect all vertices of pairs ( i , j ) ; Update ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
void constGraphWithCon ( int N , int K ) { int Max = ( ( N - 1 ) * ( N - 2 ) ) / 2 ; if ( K > Max ) { printf ( " - 1" ) ; return ; } int count = 0 ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = i + 1 ; j <= N ; j ++ ) { printf ( " % d ▁ % d
 " , i , j ) ; count ++ ; if ( count == N * ( N - 1 ) / 2 - K ) break ; } if ( count == N * ( N - 1 ) / 2 - K ) break ; } } int main ( ) { int N = 5 , K = 3 ; constGraphWithCon ( N , K ) ; return 0 ; }


Convert a Binary Tree into its Mirror Tree | C program to convert a binary tree to its mirror ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Change a tree so that the roles of the left and right pointers are swapped at every node . So the tree ... 4 / \ 2 5 / \ 1 3 is changed to ... 4 / \ 5 2 / \ 3 1 ; do the subtrees ; swap the pointers in this node ; Helper function to print Inorder traversal . ; Driver program to test mirror ( ) ; Print inorder traversal of the input tree ; Convert tree to its mirror ; Print inorder traversal of the mirror tree
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct Node { int data ; struct Node * left ; struct Node * right ; } ; struct Node * newNode ( int data ) { struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } void mirror ( struct Node * node ) { if ( node == NULL ) return ; else { struct Node * temp ; mirror ( node -> left ) ; mirror ( node -> right ) ; temp = node -> left ; node -> left = node -> right ; node -> right = temp ; } } void inOrder ( struct Node * node ) { if ( node == NULL ) return ; inOrder ( node -> left ) ; printf ( " % d ▁ " , node -> data ) ; inOrder ( node -> right ) ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; printf ( " Inorder ▁ traversal ▁ of ▁ the ▁ constructed " " ▁ tree ▁ is ▁
 " ) ; inOrder ( root ) ; mirror ( root ) ; printf ( " Inorder traversal of the mirror tree " ▁ " is " inOrder ( root ) ; return 0 ; }


Convert a given Binary Tree to Doubly Linked List | Set 1 | A C program for in - place conversion of Binary Tree to DLL ; A binary tree node has data , and left and right pointers ; This is the core function to convert Tree to list . This function follows steps 1 and 2 of the above algorithm ; Base case ; Convert the left subtree and link to root ; Convert the left subtree ; Find inorder predecessor . After this loop , left will point to the inorder predecessor ; Make root as next of the predecessor ; Make predecssor as previous of root ; Convert the right subtree and link to root ; Convert the right subtree ; Find inorder successor . After this loop , right will point to the inorder successor ; Make root as previous of successor ; Make successor as next of root ; The main function that first calls bintree2listUtil ( ) , then follows step 3 of the above algorithm ; Base case ; Convert to DLL using bintree2listUtil ( ) ; bintree2listUtil ( ) returns root node of the converted DLL . We need pointer to the leftmost node which is head of the constructed DLL , so move to the leftmost node ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Function to print nodes in a given doubly linked list ; Driver program to test above functions ; Let us create the tree shown in above diagram ; Convert to DLL ; Print the converted list
How can the above be solved in C?

 #include <stdio.h>
struct node { int data ; node * left ; node * right ; } ; node * bintree2listUtil ( node * root ) { if ( root == NULL ) return root ; if ( root -> left != NULL ) { node * left = bintree2listUtil ( root -> left ) ; for ( ; left -> right != NULL ; left = left -> right ) ; left -> right = root ; root -> left = left ; } if ( root -> right != NULL ) { node * right = bintree2listUtil ( root -> right ) ; for ( ; right -> left != NULL ; right = right -> left ) ; right -> left = root ; root -> right = right ; } return root ; } node * bintree2list ( node * root ) { if ( root == NULL ) return root ; root = bintree2listUtil ( root ) ; while ( root -> left != NULL ) root = root -> left ; return ( root ) ; } node * newNode ( int data ) { node * new_node = new node ; new_node -> data = data ; new_node -> left = new_node -> right = NULL ; return ( new_node ) ; } void printList ( node * node ) { while ( node != NULL ) { printf ( " % d ▁ " , node -> data ) ; node = node -> right ; } } int main ( ) { node * root = newNode ( 10 ) ; root -> left = newNode ( 12 ) ; root -> right = newNode ( 15 ) ; root -> left -> left = newNode ( 25 ) ; root -> left -> right = newNode ( 30 ) ; root -> right -> left = newNode ( 36 ) ; node * head = bintree2list ( root ) ; printList ( head ) ; return 0 ; }


Convert a given Binary Tree to Doubly Linked List | Set 2 | A simple inorder traversal based program to convert a Binary Tree to DLL ; A tree node ; A utility function to create a new tree node ; Standard Inorder traversal of tree ; Changes left pointers to work as previous pointers in converted DLL The function simply does inorder traversal of Binary Tree and updates left pointer using previously visited node ; Changes right pointers to work as next pointers in converted DLL ; Find the right most node in BT or last node in DLL ; Start from the rightmost node , traverse back using left pointers . While traversing , change right pointer of nodes . ; The leftmost node is head of linked list , return it ; The main function that converts BST to DLL and returns head of DLL ; Set the previous pointer ; Set the next pointer and return head of DLL ; Traverses the DLL from left tor right ; Driver program to test above functions ; Let us create the tree shown in above diagram
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct node { int data ; struct node * left , * right ; } ; struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } void inorder ( struct node * root ) { if ( root != NULL ) { inorder ( root -> left ) ; printf ( " 	 % d " , root -> data ) ; inorder ( root -> right ) ; } } void fixPrevPtr ( struct node * root ) { static struct node * pre = NULL ; if ( root != NULL ) { fixPrevPtr ( root -> left ) ; root -> left = pre ; pre = root ; fixPrevPtr ( root -> right ) ; } } struct node * fixNextPtr ( struct node * root ) { struct node * prev = NULL ; while ( root && root -> right != NULL ) root = root -> right ; while ( root && root -> left != NULL ) { prev = root ; root = root -> left ; root -> right = prev ; } return ( root ) ; } struct node * BTToDLL ( struct node * root ) { fixPrevPtr ( root ) ; return fixNextPtr ( root ) ; } void printList ( struct node * root ) { while ( root != NULL ) { printf ( " 	 % d " , root -> data ) ; root = root -> right ; } } int main ( void ) { struct node * root = newNode ( 10 ) ; root -> left = newNode ( 12 ) ; root -> right = newNode ( 15 ) ; root -> left -> left = newNode ( 25 ) ; root -> left -> right = newNode ( 30 ) ; root -> right -> left = newNode ( 36 ) ; printf ( " Inorder Tree Traversal " inorder ( root ) ; struct node * head = BTToDLL ( root ) ; printf ( " DLL Traversal " printList ( head ) ; return 0 ; }


Convert a given temperature to another system based on given boiling and freezing points | C program for above approach ; Function to return temperature in the second thermometer ; Calculate the temperature ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
double temp_convert ( int F1 , int B1 , int F2 , int B2 , int T ) { float t2 ; t2 = F2 + ( float ) ( B2 - F2 ) / ( B1 - F1 ) * ( T - F1 ) ; return t2 ; } int main ( ) { int F1 = 0 , B1 = 100 ; int F2 = 32 , B2 = 212 ; int T = 37 ; float t2 ; printf ( " % .2f " , temp_convert ( F1 , B1 , F2 , B2 , T ) ) ; return 0 ; }