text
stringlengths
25
2.53k
code
stringlengths
46
4.32k
Minimum number of coins having value equal to powers of 2 required to obtain N | C program for above approach ; Function to count of set bit in N ; Stores count of set bit in N ; Iterate over the range [ 0 , 31 ] ; If current bit is set ; Update result ; Driver Code
#include <stdio.h> NEW_LINE void count_setbit ( int N ) { int result = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) { if ( ( 1 << i ) & N ) { result ++ ; } } printf ( " % d STRNEWLINE " , result ) ; } int main ( ) { int N = 43 ; count_setbit ( N ) ; return 0 ; }
Logarithm tricks for Competitive Programming | C implementation to check that a integer is a power of Two ; Function to check if the number is a power of two ; Driver Code
#include <stdio.h> NEW_LINE #include <math.h> NEW_LINE _Bool isPowerOfTwo ( int n ) { return ( ceil ( log2 ( n ) ) == floor ( log2 ( n ) ) ) ; } int main ( ) { int N = 8 ; if ( isPowerOfTwo ( N ) ) { printf ( " Yes " ) ; } else { printf ( " No " ) ; } }
Ternary representation of Cantor set | C implementation to find the cantor set for n levels and for a given start_num and end_num ; The Linked List Structure for the Cantor Set ; Function to initialize the Cantor Set List ; Function to propogate the list by adding new nodes for the next levels ; Modifying the start and end values for the next level ; Changing the pointers to the next node ; Recursively call the function to generate the Cantor Set for the entire level ; Function to print a level of the Set ; Function to build and display the Cantor Set for each level ; Driver code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <string.h> NEW_LINE typedef struct cantor { double start , end ; struct cantor * next ; } Cantor ; Cantor * startList ( Cantor * head , double start_num , double end_num ) { if ( head == NULL ) { head = ( Cantor * ) malloc ( sizeof ( Cantor ) ) ; head -> start = start_num ; head -> end = end_num ; head -> next = NULL ; } return head ; } Cantor * propagate ( Cantor * head ) { Cantor * temp = head ; if ( temp != NULL ) { Cantor * newNode = ( Cantor * ) malloc ( sizeof ( Cantor ) ) ; double diff = ( ( ( temp -> end ) - ( temp -> start ) ) / 3 ) ; newNode -> end = temp -> end ; temp -> end = ( ( temp -> start ) + diff ) ; newNode -> start = ( newNode -> end ) - diff ; newNode -> next = temp -> next ; temp -> next = newNode ; propagate ( temp -> next -> next ) ; } return head ; } void print ( Cantor * temp ) { while ( temp != NULL ) { printf ( " [ % lf ] ▁ - - ▁ [ % lf ] TABSYMBOL " , temp -> start , temp -> end ) ; temp = temp -> next ; } printf ( " STRNEWLINE " ) ; } void buildCantorSet ( int A , int B , int L ) { Cantor * head = NULL ; head = startList ( head , A , B ) ; for ( int i = 0 ; i < L ; i ++ ) { printf ( " Level _ % d ▁ : ▁ " , i ) ; print ( head ) ; propagate ( head ) ; } printf ( " Level _ % d ▁ : ▁ " , L ) ; print ( head ) ; } int main ( ) { int A = 0 ; int B = 9 ; int L = 2 ; buildCantorSet ( A , B , L ) ; return 0 ; }
Optimized Naive Algorithm for Pattern Searching | C program for A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different ; A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different ; For current index i , check for pattern match ; if ( j == M ) if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; slide the pattern by j ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE void search ( char pat [ ] , char txt [ ] ) { int M = strlen ( pat ) ; int N = strlen ( txt ) ; int i = 0 ; while ( i <= N - M ) { int j ; for ( j = 0 ; j < M ; j ++ ) if ( txt [ i + j ] != pat [ j ] ) break ; { printf ( " Pattern ▁ found ▁ at ▁ index ▁ % d ▁ STRNEWLINE " , i ) ; i = i + M ; } else if ( j == 0 ) i = i + 1 ; else i = i + j ; } } int main ( ) { char txt [ ] = " ABCEABCDABCEABCD " ; char pat [ ] = " ABCD " ; search ( pat , txt ) ; return 0 ; }
Program to Encrypt a String using ! and @ | C program to Encrypt the String using ! and @ ; Function to encrypt the string ; evenPos is for storing encrypting char at evenPosition oddPos is for storing encrypting char at oddPosition ; Get the number of times the character is to be repeated ; if i is odd , print ' ! ' else print ' @ ' ; Driver code ; Encrypt the String
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE void encrypt ( char input [ 100 ] ) { char evenPos = ' @ ' , oddPos = ' ! ' ; int repeat , ascii ; for ( int i = 0 ; i <= strlen ( input ) ; i ++ ) { ascii = input [ i ] ; repeat = ascii >= 97 ? ascii - 96 : ascii - 64 ; for ( int j = 0 ; j < repeat ; j ++ ) { if ( i % 2 == 0 ) printf ( " % c " , oddPos ) ; else printf ( " % c " , evenPos ) ; } } } void main ( ) { char input [ 100 ] = { ' A ' , ' b ' , ' C ' , ' d ' } ; encrypt ( input ) ; }
Recursive function to check if a string is palindrome | A recursive C program to check whether a given number is palindrome or not ; A recursive function that check a str [ s . . e ] is palindrome or not . ; If there is only one character ; If first and last characters do not match ; If there are more than two characters , check if middle substring is also palindrome or not . ; An empty string is considered as palindrome ; Driver Code
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE #include <stdbool.h> NEW_LINE bool isPalRec ( char str [ ] , int s , int e ) { if ( s == e ) return true ; if ( str [ s ] != str [ e ] ) return false ; if ( s < e + 1 ) return isPalRec ( str , s + 1 , e - 1 ) ; return true ; } bool isPalindrome ( char str [ ] ) { int n = strlen ( str ) ; if ( n == 0 ) return true ; return isPalRec ( str , 0 , n - 1 ) ; } int main ( ) { char str [ ] = " geeg " ; if ( isPalindrome ( str ) ) printf ( " Yes " ) ; else printf ( " No " ) ; return 0 ; }
Write your own atoi ( ) | A simple C ++ program for implementation of atoi ; if whitespaces then ignore . ; sign of number ; checking for valid input ; handling overflow test case ; Driver Code ; Functional Code
#include <stdio.h> NEW_LINE #include <limits.h> NEW_LINE int myAtoi ( const char * str ) { int sign = 1 , base = 0 , i = 0 ; while ( str [ i ] == ' ▁ ' ) { i ++ ; } if ( str [ i ] == ' - ' str [ i ] == ' + ' ) { sign = 1 - 2 * ( str [ i ++ ] == ' - ' ) ; } while ( str [ i ] >= '0' && str [ i ] <= '9' ) { if ( base > INT_MAX / 10 || ( base == INT_MAX / 10 && str [ i ] - '0' > 7 ) ) { if ( sign == 1 ) return INT_MAX ; else return INT_MIN ; } base = 10 * base + ( str [ i ++ ] - '0' ) ; } return base * sign ; } int main ( ) { char str [ ] = " ▁ - 123" ; int val = myAtoi ( str ) ; printf ( " % d ▁ " , val ) ; return 0 ; }
Fill two instances of all numbers from 1 to n in a specific way | A backtracking based C Program to fill two instances of all numbers from 1 to n in a specific way ; A recursive utility function to fill two instances of numbers from 1 to n in res [ 0. .2 n - 1 ] . ' curr ' is current value of n . ; If current number becomes 0 , then all numbers are filled ; Try placing two instances of ' curr ' at all possible locations till solution is found ; Two ' curr ' should be placed at ' curr + 1' distance ; Plave two instances of ' curr ' ; Recur to check if the above placement leads to a solution ; If solution is not possible , then backtrack ; This function prints the result for input number ' n ' using fillUtil ( ) ; Create an array of size 2 n and initialize all elements in it as 0 ; If solution is possible , then print it . ; Driver program
#include <stdio.h> NEW_LINE #include <stdbool.h> NEW_LINE bool fillUtil ( int res [ ] , int curr , int n ) { if ( curr == 0 ) return true ; int i ; for ( i = 0 ; i < 2 * n - curr - 1 ; i ++ ) { if ( res [ i ] == 0 && res [ i + curr + 1 ] == 0 ) { res [ i ] = res [ i + curr + 1 ] = curr ; if ( fillUtil ( res , curr - 1 , n ) ) return true ; res [ i ] = res [ i + curr + 1 ] = 0 ; } } return false ; } void fill ( int n ) { int res [ 2 * n ] , i ; for ( i = 0 ; i < 2 * n ; i ++ ) res [ i ] = 0 ; if ( fillUtil ( res , n , n ) ) { for ( i = 0 ; i < 2 * n ; i ++ ) printf ( " % d ▁ " , res [ i ] ) ; } else puts ( " Not ▁ Possible " ) ; } int main ( ) { fill ( 7 ) ; 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
#include <stdio.h> NEW_LINE #include <math.h> NEW_LINE 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 ; }
Program to Calculate the Perimeter of a Decagon | C program to Calculate the Perimeter of a Decagon ; Function for finding the perimeter ; Driver code
#include <stdio.h> NEW_LINE void CalPeri ( ) { int s = 5 , Perimeter ; Perimeter = 10 * s ; printf ( " The ▁ Perimeter ▁ of ▁ Decagon ▁ is ▁ : ▁ % d " , Perimeter ) ; } int main ( ) { CalPeri ( ) ; 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
#include <stdio.h> NEW_LINE #include <math.h> NEW_LINE 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 ; }
Mirror of a point through a 3 D plane | C program to find Mirror of a point through a 3 D plane ; Function to mirror image ; Driver Code ; function call
#include <stdio.h> NEW_LINE void mirror_point ( float a , float b , float c , float d , float x1 , float y1 , float z1 ) { float k = ( - a * x1 - b * y1 - c * z1 - d ) / ( float ) ( a * a + b * b + c * c ) ; float x2 = a * k + x1 ; float y2 = b * k + y1 ; float z2 = c * k + z1 ; float x3 = 2 * x2 - x1 ; float y3 = 2 * y2 - y1 ; float z3 = 2 * z2 - z1 ; printf ( " x3 ▁ = ▁ % .1f ▁ " , x3 ) ; printf ( " y3 ▁ = ▁ % .1f ▁ " , y3 ) ; printf ( " z3 ▁ = ▁ % .1f ▁ " , z3 ) ; } int main ( ) { float a = 1 ; float b = -2 ; float c = 0 ; float d = 0 ; float x1 = -1 ; float y1 = 3 ; float z1 = 4 ; mirror_point ( a , b , c , d , x1 , y1 , z1 ) ; }
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
#include <bits/stdc++.h> NEW_LINE 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 ▁ STRNEWLINE " ; inorder ( root ) ; return 0 ; }
The Stock Span Problem | C program for brute force method to calculate stock span values ; Fills array S [ ] with span values ; Span value of first day is always 1 ; Calculate span value of remaining days by linearly checking previous days ; Initialize span value ; Traverse left while the next element on left is smaller than price [ i ] ; A utility function to print elements of array ; Driver program to test above function ; Fill the span values in array S [ ] ; print the calculated span values
#include <stdio.h> NEW_LINE void calculateSpan ( int price [ ] , int n , int S [ ] ) { S [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { S [ i ] = 1 ; for ( int j = i - 1 ; ( j >= 0 ) && ( price [ i ] >= price [ j ] ) ; j -- ) S [ i ] ++ ; } } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; } int main ( ) { int price [ ] = { 10 , 4 , 5 , 90 , 120 , 80 } ; int n = sizeof ( price ) / sizeof ( price [ 0 ] ) ; int S [ n ] ; calculateSpan ( price , n , S ) ; printArray ( S , n ) ; return 0 ; }
Next Greater Element | Simple C program to print next greater elements in a given array ; prints element and NGE pair for all elements of arr [ ] of size n ; Driver Code
#include <stdio.h> NEW_LINE void printNGE ( int arr [ ] , int n ) { int next , i , j ; for ( i = 0 ; i < n ; i ++ ) { next = -1 ; for ( j = i + 1 ; j < n ; j ++ ) { if ( arr [ i ] < arr [ j ] ) { next = arr [ j ] ; break ; } } printf ( " % d ▁ - - ▁ % dn " , arr [ i ] , next ) ; } } int main ( ) { int arr [ ] = { 11 , 13 , 21 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printNGE ( arr , n ) ; 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
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE 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 ▁ STRNEWLINE " ) ; inOrder ( root ) ; mirror ( root ) ; printf ( " Inorder traversal of the mirror tree " ▁ " is " inOrder ( root ) ; return 0 ; }
Foldable Binary Trees | ; A binary tree node has data , pointer to left child and a pointer to right child ; A utility function that checks if trees with roots as n1 and n2 are mirror of each other ; Returns true if the given tree can be folded ; A utility function that checks if trees with roots as n1 and n2 are mirror of each other ; If both left and right subtrees are NULL , then return true ; If one of the trees is NULL and other is not , then return false ; Otherwise check if left and right subtrees are mirrors of their counterparts ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver program to test mirror ( ) ; The constructed binary tree is 1 / \ 2 3 \ / 4 5
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #define bool int NEW_LINE #define true 1 NEW_LINE #define false 0 NEW_LINE struct node { int data ; struct node * left ; struct node * right ; } ; bool IsFoldableUtil ( struct node * n1 , struct node * n2 ) ; bool IsFoldable ( struct node * root ) { if ( root == NULL ) { return true ; } return IsFoldableUtil ( root -> left , root -> right ) ; } bool IsFoldableUtil ( struct node * n1 , struct node * n2 ) { if ( n1 == NULL && n2 == NULL ) { return true ; } if ( n1 == NULL n2 == NULL ) { return false ; } return IsFoldableUtil ( n1 -> left , n2 -> right ) && IsFoldableUtil ( n1 -> right , n2 -> left ) ; } 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 ( void ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> right = newNode ( 4 ) ; root -> right -> left = newNode ( 5 ) ; if ( IsFoldable ( root ) == true ) { printf ( " tree is foldable " } else { printf ( " tree is not foldable " } getchar ( ) ; 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
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE 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 ; }
Program to find HCF ( Highest Common Factor ) of 2 Numbers | C program to find GCD of two numbers ; Recursive function to return gcd of a and b ; Everything divides 0 ; base case ; a is greater ; Driver program to test above function
#include <stdio.h> NEW_LINE int gcd ( int a , int b ) { if ( a == 0 && b == 0 ) return 0 ; if ( a == 0 ) return b ; if ( b == 0 ) return a ; if ( a == b ) return a ; if ( a > b ) return gcd ( a - b , b ) ; return gcd ( a , b - a ) ; } int main ( ) { int a = 0 , b = 56 ; printf ( " GCD ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ % d ▁ " , a , b , gcd ( a , b ) ) ; return 0 ; }
Josephus Problem Using Bit Magic | C program for josephus problem ; function to find the position of the Most Significant Bit ; keeps shifting bits to the right until we are left with 0 ; function to return at which place Josephus should sit to avoid being killed ; Getting the position of the Most Significant Bit ( MSB ) . The leftmost '1' . If the number is '41' then its binary is '101001' . So msbPos ( 41 ) = 6 ; ' j ' stores the number with which to XOR the number ' n ' . Since we need '100000' We will do 1 << 6 - 1 to get '100000' ; Toggling the Most Significant Bit . Changing the leftmost '1' to '0' . 101001 ^ 100000 = 001001 ( 9 ) ; Left - shifting once to add an extra '0' to the right end of the binary number 001001 = 010010 ( 18 ) ; Toggling the '0' at the end to '1' which is essentially the same as putting the MSB at the rightmost place . 010010 | 1 = 010011 ( 19 ) ; hard coded driver main function to run the program
#include <stdio.h> NEW_LINE int msbPos ( int n ) { int pos = 0 ; while ( n != 0 ) { pos ++ ; n = n >> 1 ; } return pos ; } int josephify ( int n ) { int position = msbPos ( n ) ; int j = 1 << ( position - 1 ) ; n = n ^ j ; n = n << 1 ; n = n | 1 ; return n ; } int main ( ) { int n = 41 ; printf ( " % d STRNEWLINE " , josephify ( n ) ) ; return 0 ; }
Sum of Bitwise And of all pairs in a given array | An efficient C ++ program to compute sum of bitwise AND of all pairs ; Returns value of " arr [ 0 ] ▁ & ▁ arr [ 1 ] ▁ + ▁ arr [ 0 ] ▁ & ▁ arr [ 2 ] ▁ + ▁ . . . ▁ arr [ i ] ▁ & ▁ arr [ j ] ▁ + ▁ . . . . . ▁ arr [ n - 2 ] ▁ & ▁ arr [ n - 1 ] " ; Traverse over all bits ; Count number of elements with i 'th bit set int k = 0; Initialize the count ; There are k set bits , means k ( k - 1 ) / 2 pairs . Every pair adds 2 ^ i to the answer . Therefore , we add "2 ^ i ▁ * ▁ [ k * ( k - 1 ) / 2 ] " to the answer . ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int pairAndSum ( int arr [ ] , int n ) { for ( int i = 0 ; i < 32 ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) if ( ( arr [ j ] & ( 1 << i ) ) ) k ++ ; ans += ( 1 << i ) * ( k * ( k - 1 ) / 2 ) ; } return ans ; } int main ( ) { int arr [ ] = { 5 , 10 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << pairAndSum ( arr , n ) << endl ; return 0 ; }
Puzzle | Program to find number of squares in a chessboard | Function to return count of squares ; ; A better way to write n * ( n + 1 ) * ( 2 n + 1 ) / 6 ; Driver Code
function countSquares ( n ) { return ( n * ( n + 1 ) / 2 ) * ( 2 * n + 1 ) / 3 ; } let n = 4 ; document . write ( " Count ▁ of ▁ squares ▁ is ▁ " + countSquares ( n ) ) ;
Program to find GCD or HCF of two numbers | C program to find GCD of two numbers ; Recursive function to return gcd of a and b ; Everything divides 0 ; base case ; a is greater ; Driver program to test above function
#include <stdio.h> NEW_LINE int gcd ( int a , int b ) { if ( a == 0 ) return b ; if ( b == 0 ) return a ; if ( a == b ) return a ; if ( a > b ) return gcd ( a - b , b ) ; return gcd ( a , b - a ) ; } int main ( ) { int a = 98 , b = 56 ; printf ( " GCD ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ % d ▁ " , a , b , gcd ( a , b ) ) ; return 0 ; }
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
#include <math.h> NEW_LINE #include <stdio.h> NEW_LINE #define maxsize 10005 NEW_LINE 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 STRNEWLINE " ) ; for ( i = 0 ; i < max_size ; i ++ ) { printf ( " % d ▁ " , xortree [ i ] ) ; } int root = 0 ; printf ( " Root : % d " , xortree [ root ] ) ; }
How to swap two bits in a given integer ? | C code for swapping given bits of a number ; left - shift 1 p1 and p2 times and using XOR ; Driver Code
#include <stdio.h> NEW_LINE int swapBits ( int n , int p1 , int p2 ) { n ^= 1 << p1 ; n ^= 1 << p2 ; return n ; } int main ( ) { printf ( " Result ▁ = ▁ % d " , swapBits ( 28 , 0 , 3 ) ) ; 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
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE 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 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
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE 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 STRNEWLINE " ) ; else printf ( " Leaves ▁ are ▁ not ▁ at ▁ same ▁ level STRNEWLINE " ) ; getchar ( ) ; 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
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <stdbool.h> NEW_LINE 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 STRNEWLINE " ) ; else printf ( " The ▁ Binary ▁ Tree ▁ is ▁ not ▁ full STRNEWLINE " ) ; return ( 0 ) ; }
Print alternate elements of an array | C program to implement the above approach ; Function to print Alternate elements of the given array ; Print elements at odd positions ; Print elements of array ; Driver Code
#include <stdio.h> NEW_LINE void printAlter ( int arr [ ] , int N ) { for ( int currIndex = 0 ; currIndex < N ; currIndex += 2 ) { printf ( " % d ▁ " , arr [ currIndex ] ) ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printAlter ( arr , N ) ; }
Write Code to Determine if Two Trees are Identical | ; 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 . ; Given two trees , return true if they are structurally identical ; 1. both empty ; 2. both non - empty -> compare them ; 3. one empty , one not -> false ; Driver program to test identicalTrees function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE 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 identicalTrees ( struct node * a , struct node * b ) { if ( a == NULL && b == NULL ) return 1 ; if ( a != NULL && b != NULL ) { return ( a -> data == b -> data && identicalTrees ( a -> left , b -> left ) && identicalTrees ( a -> right , b -> right ) ) ; } return 0 ; } int main ( ) { struct node * root1 = newNode ( 1 ) ; struct node * root2 = newNode ( 1 ) ; root1 -> left = newNode ( 2 ) ; root1 -> right = newNode ( 3 ) ; root1 -> left -> left = newNode ( 4 ) ; root1 -> left -> right = newNode ( 5 ) ; root2 -> left = newNode ( 2 ) ; root2 -> right = newNode ( 3 ) ; root2 -> left -> left = newNode ( 4 ) ; root2 -> left -> right = newNode ( 5 ) ; if ( identicalTrees ( root1 , root2 ) ) printf ( " Both ▁ tree ▁ are ▁ identical . " ) ; else printf ( " Trees ▁ are ▁ not ▁ identical . " ) ; getchar ( ) ; return 0 ; }
Print cousins of a given node in Binary Tree | C program to print cousins of a node ; A Binary Tree Node ; A utility function to create a new Binary Tree Node ; It returns level of the node if it is present in tree , otherwise returns 0. ; base cases ; If node is present in left subtree ; If node is not present in left subtree ; Print nodes at a given level such that sibling of node is not printed if it exists ; Base cases ; If current node is parent of a node with given level ; Recur for left and right subtrees ; This function prints cousins of a given node ; Get level of given node ; Print nodes of given level . ; Driver Program to test above functions
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int item ) { Node * temp = new Node ; temp -> data = item ; temp -> left = temp -> right = NULL ; return temp ; } int getLevel ( Node * root , Node * node , int level ) { if ( root == NULL ) return 0 ; if ( root == node ) return level ; int downlevel = getLevel ( root -> left , node , level + 1 ) ; if ( downlevel != 0 ) return downlevel ; return getLevel ( root -> right , node , level + 1 ) ; } void printGivenLevel ( Node * root , Node * node , int level ) { if ( root == NULL level < 2 ) return ; if ( level == 2 ) { if ( root -> left == node root -> right == node ) return ; if ( root -> left ) printf ( " % d ▁ " , root -> left -> data ) ; if ( root -> right ) printf ( " % d ▁ " , root -> right -> data ) ; } else if ( level > 2 ) { printGivenLevel ( root -> left , node , level - 1 ) ; printGivenLevel ( root -> right , node , level - 1 ) ; } } void printCousins ( Node * root , Node * node ) { int level = getLevel ( root , node , 1 ) ; printGivenLevel ( root , node , level ) ; } int main ( ) { 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 ) ; printCousins ( root , root -> left -> right ) ; return 0 ; }
Given a binary tree , print out all of its root | program to print all of its root - to - leaf paths for a tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Function prototypes ; Given a binary tree , print out all of its root - to - leaf paths , one per line . Uses a recursive helper to do the work . ; Recursive helper function -- given a node , and an array containing the path from the root node up to but not including this node , print out all the root - leaf paths . ; append this node to the path array ; it 's a leaf, so print the path that led to here ; otherwise try both subtrees ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Utility that prints out an array on a line ; Driver program to test mirror ( ) ; Print all root - to - leaf paths of the input tree
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left ; struct node * right ; } ; void printArray ( int [ ] , int ) ; void printPathsRecur ( struct node * , int [ ] , int ) ; struct node * newNode ( int ) ; void printPaths ( struct node * ) ; void printPaths ( struct node * node ) { int path [ 1000 ] ; printPathsRecur ( node , path , 0 ) ; } void printPathsRecur ( struct node * node , int path [ ] , int pathLen ) { if ( node == NULL ) return ; path [ pathLen ] = node -> data ; pathLen ++ ; if ( node -> left == NULL && node -> right == NULL ) { printArray ( path , pathLen ) ; } else { printPathsRecur ( node -> left , path , pathLen ) ; printPathsRecur ( node -> right , path , pathLen ) ; } } 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 printArray ( int ints [ ] , int len ) { int i ; for ( i = 0 ; i < len ; i ++ ) { printf ( " % d ▁ " , ints [ i ] ) ; } printf ( " STRNEWLINE " ) ; } 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 ) ; printPaths ( root ) ; getchar ( ) ; return 0 ; }
Introduction to Arrays | ; Creating an integer array named arr of size 10. ; accessing element at 0 index and setting its value to 5. ; access and print value at 0 index we get the output as 5.
#include <stdio.h> NEW_LINE int main ( ) { int arr [ 10 ] ; arr [ 0 ] = 5 ; printf ( " % d " , arr [ 0 ] ) ; 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
#include <stdio.h> NEW_LINE 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 ( " STRNEWLINE ▁ " ) ; } 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
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 ) ; }
Program to cyclically rotate an array by one | ; swap ; i and j pointing to first and last element respectively ; Driver code
#include <stdio.h> NEW_LINE void swap ( int * x , int * y ) { int temp = * x ; * x = * y ; * y = temp ; } void rotate ( int arr [ ] , int n ) { int i = 0 , j = n - 1 ; while ( i != j ) { swap ( & arr [ i ] , & arr [ j ] ) ; i ++ ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } , i ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Given ▁ array ▁ is STRNEWLINE " ) ; for ( i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; rotate ( arr , n ) ; printf ( " Rotated array is " for ( i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; return 0 ; }
Program to sort an array of strings using Selection Sort | C program to implement selection sort for array of strings . ; Sorts an array of strings where length of every string should be smaller than MAX_LEN ; One by one move boundary of unsorted subarray ; Find the minimum element in unsorted array ; If min is greater than arr [ j ] ; Make arr [ j ] as minStr and update min_idx ; Swap the found minimum element with the first element ; Driver code ; Printing the array before sorting ; Printing the array after sorting
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE #define MAX_LEN 100 NEW_LINE void selectionSort ( char arr [ ] [ MAX_LEN ] , int n ) { int i , j , min_idx ; char minStr [ MAX_LEN ] ; for ( i = 0 ; i < n - 1 ; i ++ ) { int min_idx = i ; strcpy ( minStr , arr [ i ] ) ; for ( j = i + 1 ; j < n ; j ++ ) { if ( strcmp ( minStr , arr [ j ] ) > 0 ) { strcpy ( minStr , arr [ j ] ) ; min_idx = j ; } } if ( min_idx != i ) { char temp [ MAX_LEN ] ; strcpy ( temp , arr [ i ] ) ; strcpy ( arr [ i ] , arr [ min_idx ] ) ; strcpy ( arr [ min_idx ] , temp ) ; } } } int main ( ) { char arr [ ] [ MAX_LEN ] = { " GeeksforGeeks " , " Practice . GeeksforGeeks " , " GeeksQuiz " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int i ; printf ( " Given ▁ array ▁ is STRNEWLINE " ) ; for ( i = 0 ; i < n ; i ++ ) printf ( " % d : ▁ % s ▁ STRNEWLINE " , i , arr [ i ] ) ; selectionSort ( arr , n ) ; printf ( " Sorted array is " for ( i = 0 ; i < n ; i ++ ) printf ( " % d : ▁ % s ▁ STRNEWLINE " , i , arr [ i ] ) ; return 0 ; }
Rearrange an array such that ' arr [ j ] ' becomes ' i ' if ' arr [ i ] ' is ' j ' | Set 1 | A simple C program to rearrange contents of arr [ ] such that arr [ j ] becomes j if arr [ i ] is j ; A simple method to rearrange ' arr [ 0 . . n - 1 ] ' so that ' arr [ j ] ' becomes ' i ' if ' arr [ i ] ' is ' j ' ; Create an auxiliary array of same size ; Store result in temp [ ] ; Copy temp back to arr [ ] ; A utility function to print contents of arr [ 0. . n - 1 ] ; Driver program
#include <stdio.h> NEW_LINE void rearrangeNaive ( int arr [ ] , int n ) { int temp [ n ] , i ; for ( i = 0 ; i < n ; i ++ ) temp [ arr [ i ] ] = i ; for ( i = 0 ; i < n ; i ++ ) arr [ i ] = temp [ i ] ; } void printArray ( int arr [ ] , int n ) { int i ; for ( i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; printf ( " STRNEWLINE " ) ; } int main ( ) { int arr [ ] = { 1 , 3 , 0 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Given ▁ array ▁ is ▁ STRNEWLINE " ) ; printArray ( arr , n ) ; rearrangeNaive ( arr , n ) ; printf ( " Modified ▁ array ▁ is ▁ STRNEWLINE " ) ; printArray ( arr , n ) ; return 0 ; }
Program to find largest element in an array | C program to find maximum in arr [ ] of size n ; C function to find maximum in arr [ ] of size n ; Initialize maximum element ; Traverse array elements from second and compare every element with current max ; Driver Code
#include <stdio.h> NEW_LINE int largest ( int arr [ ] , int n ) { int i ; int max = arr [ 0 ] ; for ( i = 1 ; i < n ; i ++ ) if ( arr [ i ] > max ) max = arr [ i ] ; return max ; } int main ( ) { int arr [ ] = { 10 , 324 , 45 , 90 , 9808 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Largest ▁ in ▁ given ▁ array ▁ is ▁ % d " , largest ( arr , n ) ) ; return 0 ; }
Find Second largest element in an array | C program to find second largest element in an array ; Function to print the second largest elements ; There should be atleast two elements ; If current element is greater than first then update both first and second ; If arr [ i ] is in between first and second then update second ; Driver program to test above function
#include <limits.h> NEW_LINE #include <stdio.h> NEW_LINE void print2largest ( int arr [ ] , int arr_size ) { int i , first , second ; if ( arr_size < 2 ) { printf ( " ▁ Invalid ▁ Input ▁ " ) ; return ; } first = second = INT_MIN ; for ( i = 0 ; i < arr_size ; i ++ ) { if ( arr [ i ] > first ) { second = first ; first = arr [ i ] ; } else if ( arr [ i ] > second && arr [ i ] != first ) second = arr [ i ] ; } if ( second == INT_MIN ) printf ( " There ▁ is ▁ no ▁ second ▁ largest ▁ element STRNEWLINE " ) ; else printf ( " The ▁ second ▁ largest ▁ element ▁ is ▁ % dn " , second ) ; } int main ( ) { int arr [ ] = { 12 , 35 , 1 , 10 , 34 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; print2largest ( arr , n ) ; return 0 ; }
Maximum and minimum of an array using minimum number of comparisons | structure is used to return two values from minMax ( ) ; If there is only one element then return it as min and max both ; If there are more than one elements , then initialize min and max ; Driver program to test above function
#include <stdio.h> NEW_LINE struct pair { int min ; int max ; } ; struct pair getMinMax ( int arr [ ] , int n ) { struct pair minmax ; int i ; if ( n == 1 ) { minmax . max = arr [ 0 ] ; minmax . min = arr [ 0 ] ; return minmax ; } if ( arr [ 0 ] > arr [ 1 ] ) { minmax . max = arr [ 0 ] ; minmax . min = arr [ 1 ] ; } else { minmax . max = arr [ 1 ] ; minmax . min = arr [ 0 ] ; } for ( i = 2 ; i < n ; i ++ ) { if ( arr [ i ] > minmax . max ) minmax . max = arr [ i ] ; else if ( arr [ i ] < minmax . min ) minmax . min = arr [ i ] ; } return minmax ; } int main ( ) { int arr [ ] = { 1000 , 11 , 445 , 1 , 330 , 3000 } ; int arr_size = 6 ; struct pair minmax = getMinMax ( arr , arr_size ) ; printf ( " nMinimum ▁ element ▁ is ▁ % d " , minmax . min ) ; printf ( " nMaximum ▁ element ▁ is ▁ % d " , minmax . max ) ; getchar ( ) ; }
Maximum and minimum of an array using minimum number of comparisons | ; structure is used to return two values from minMax ( ) ; If array has even number of elements then initialize the first two elements as minimum and maximum ; set the starting index for loop ; If array has odd number of elements then initialize the first element as minimum and maximum ; set the starting index for loop ; In the while loop , pick elements in pair and compare the pair with max and min so far ; Increment the index by 2 as two elements are processed in loop ; Driver program to test above function
#include <stdio.h> NEW_LINE struct pair { int min ; int max ; } ; struct pair getMinMax ( int arr [ ] , int n ) { struct pair minmax ; int i ; if ( n % 2 == 0 ) { if ( arr [ 0 ] > arr [ 1 ] ) { minmax . max = arr [ 0 ] ; minmax . min = arr [ 1 ] ; } else { minmax . min = arr [ 0 ] ; minmax . max = arr [ 1 ] ; } i = 2 ; } else { minmax . min = arr [ 0 ] ; minmax . max = arr [ 0 ] ; i = 1 ; } while ( i < n - 1 ) { if ( arr [ i ] > arr [ i + 1 ] ) { if ( arr [ i ] > minmax . max ) minmax . max = arr [ i ] ; if ( arr [ i + 1 ] < minmax . min ) minmax . min = arr [ i + 1 ] ; } else { if ( arr [ i + 1 ] > minmax . max ) minmax . max = arr [ i + 1 ] ; if ( arr [ i ] < minmax . min ) minmax . min = arr [ i ] ; } i += 2 ; } return minmax ; } int main ( ) { int arr [ ] = { 1000 , 11 , 445 , 1 , 330 , 3000 } ; int arr_size = 6 ; struct pair minmax = getMinMax ( arr , arr_size ) ; printf ( " nMinimum ▁ element ▁ is ▁ % d " , minmax . min ) ; printf ( " nMaximum ▁ element ▁ is ▁ % d " , minmax . max ) ; getchar ( ) ; }
Minimum number of jumps to reach end | C program to find Minimum number of jumps to reach end ; Returns minimum number of jumps to reach arr [ h ] from arr [ l ] ; Base case : when source and destination are same ; When nothing is reachable from the given source ; Traverse through all the points reachable from arr [ l ] . Recursively get the minimum number of jumps needed to reach arr [ h ] from these reachable points . ; Driver program to test above function
#include <limits.h> NEW_LINE #include <stdio.h> NEW_LINE int minJumps ( int arr [ ] , int l , int h ) { if ( h == l ) return 0 ; if ( arr [ l ] == 0 ) return INT_MAX ; int min = INT_MAX ; for ( int i = l + 1 ; i <= h && i <= l + arr [ l ] ; i ++ ) { int jumps = minJumps ( arr , i , h ) ; if ( jumps != INT_MAX && jumps + 1 < min ) min = jumps + 1 ; } return min ; } int main ( ) { int arr [ ] = { 1 , 3 , 6 , 3 , 2 , 3 , 6 , 8 , 9 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Minimum ▁ number ▁ of ▁ jumps ▁ to ▁ reach ▁ end ▁ is ▁ % d ▁ " , minJumps ( arr , 0 , n - 1 ) ) ; return 0 ; }
Smallest subarray with sum greater than a given value | ; Returns length of smallest subarray with sum greater than x . If there is no subarray with given sum , then returns n + 1 ; Initialize length of smallest subarray as n + 1 ; Pick every element as starting point ; Initialize sum starting with current start ; If first element itself is greater ; Try different ending points for curremt start ; add last element to current sum ; If sum becomes more than x and length of this subarray is smaller than current smallest length , update the smallest length ( or result ) ; Driver program to test above function
# include <iostream> NEW_LINE using namespace std ; int smallestSubWithSum ( int arr [ ] , int n , int x ) { int min_len = n + 1 ; for ( int start = 0 ; start < n ; start ++ ) { int curr_sum = arr [ start ] ; if ( curr_sum > x ) return 1 ; for ( int end = start + 1 ; end < n ; end ++ ) { curr_sum += arr [ end ] ; if ( curr_sum > x && ( end - start + 1 ) < min_len ) min_len = ( end - start + 1 ) ; } } return min_len ; } int main ( ) { int arr1 [ ] = { 1 , 4 , 45 , 6 , 10 , 19 } ; int x = 51 ; int n1 = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int res1 = smallestSubWithSum ( arr1 , n1 , x ) ; ( res1 == n1 + 1 ) ? cout << " Not ▁ possible STRNEWLINE " : cout << res1 << endl ; int arr2 [ ] = { 1 , 10 , 5 , 2 , 7 } ; int n2 = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; x = 9 ; int res2 = smallestSubWithSum ( arr2 , n2 , x ) ; ( res2 == n2 + 1 ) ? cout << " Not ▁ possible STRNEWLINE " : cout << res2 << endl ; int arr3 [ ] = { 1 , 11 , 100 , 1 , 0 , 200 , 3 , 2 , 1 , 250 } ; int n3 = sizeof ( arr3 ) / sizeof ( arr3 [ 0 ] ) ; x = 280 ; int res3 = smallestSubWithSum ( arr3 , n3 , x ) ; ( res3 == n3 + 1 ) ? cout << " Not ▁ possible STRNEWLINE " : cout << res3 << endl ; return 0 ; }
Tree Traversals ( Inorder , Preorder and Postorder ) | C program for different tree traversals ; 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 . ; Given a binary tree , print its nodes according to the " bottom - up " postorder traversal . ; first recur on left subtree ; then recur on right subtree ; now deal with the node ; Given a binary tree , print its nodes in inorder ; first recur on left child ; then print the data of node ; now recur on right child ; Given a binary tree , print its nodes in preorder ; first print data of node ; then recur on left sutree ; now recur on right subtree ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE 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 printPostorder ( struct node * node ) { if ( node == NULL ) return ; printPostorder ( node -> left ) ; printPostorder ( node -> right ) ; printf ( " % d ▁ " , node -> data ) ; } void printInorder ( struct node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; printf ( " % d ▁ " , node -> data ) ; printInorder ( node -> right ) ; } void printPreorder ( struct node * node ) { if ( node == NULL ) return ; printf ( " % d ▁ " , node -> data ) ; printPreorder ( node -> left ) ; printPreorder ( 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 ( " Preorder traversal of binary tree is " printPreorder ( root ) ; printf ( " Inorder traversal of binary tree is " printInorder ( root ) ; printf ( " Postorder traversal of binary tree is " printPostorder ( root ) ; getchar ( ) ; return 0 ; }
Remove all nodes which don 't lie in any path with sum>= k | ; A Binary Tree Node ; A utility function to create a new Binary Tree node with given data ; print the tree in LVR ( Inorder traversal ) way . ; Main function which truncates the binary tree . ; Base Case ; Recur for left and right subtrees ; If we reach leaf whose data is smaller than sum , we delete the leaf . An important thing to note is a non - leaf node can become leaf when its chilren are deleted . ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE 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 print ( struct Node * root ) { if ( root != NULL ) { print ( root -> left ) ; printf ( " % d ▁ " , root -> data ) ; print ( root -> right ) ; } } struct Node * prune ( struct Node * root , int sum ) { if ( root == NULL ) return NULL ; root -> left = prune ( root -> left , sum - root -> data ) ; root -> right = prune ( root -> right , sum - root -> data ) ; if ( root -> left == NULL && root -> right == NULL ) { if ( root -> data < sum ) { free ( root ) ; return NULL ; } } return root ; } int main ( ) { int k = 45 ; 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 -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> left -> left -> left = newNode ( 8 ) ; root -> left -> left -> right = newNode ( 9 ) ; root -> left -> right -> left = newNode ( 12 ) ; root -> right -> right -> left = newNode ( 10 ) ; root -> right -> right -> left -> right = newNode ( 11 ) ; root -> left -> left -> right -> left = newNode ( 13 ) ; root -> left -> left -> right -> right = newNode ( 14 ) ; root -> left -> left -> right -> right -> left = newNode ( 15 ) ; printf ( " Tree ▁ before ▁ truncation STRNEWLINE " ) ; print ( root ) ;
Merge an array of size n into another array of size m + n | C program to Merge an array of size n into another array of size m + n ; Assuming - 1 is filled for the places where element is not available ; Function to move m elements at the end of array mPlusN [ ] ; Merges array N [ ] of size n into array mPlusN [ ] of size m + n ; Current index of i / p part of mPlusN [ ] ; Current index of N [ ] ; Current index of output mPlusN [ ] ; Take an element from mPlusN [ ] if a ) value of the picked element is smaller and we have not reached end of it b ) We have reached end of N [ ] ; Otherwise take element from N [ ] ; Utility that prints out an array on a line ; Driver code ; Initialize arrays ; Move the m elements at the end of mPlusN ; Merge N [ ] into mPlusN [ ] ; Print the resultant mPlusN
#include <stdio.h> NEW_LINE #define NA -1 NEW_LINE void moveToEnd ( int mPlusN [ ] , int size ) { int i = 0 , j = size - 1 ; for ( i = size - 1 ; i >= 0 ; i -- ) if ( mPlusN [ i ] != NA ) { mPlusN [ j ] = mPlusN [ i ] ; j -- ; } } int merge ( int mPlusN [ ] , int N [ ] , int m , int n ) { int i = n ; int j = 0 ; int k = 0 ; while ( k < ( m + n ) ) { if ( ( j == n ) || ( i < ( m + n ) && mPlusN [ i ] <= N [ j ] ) ) { mPlusN [ k ] = mPlusN [ i ] ; k ++ ; i ++ ; } else { mPlusN [ k ] = N [ j ] ; k ++ ; j ++ ; } } } void printArray ( int arr [ ] , int size ) { int i ; for ( i = 0 ; i < size ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; printf ( " STRNEWLINE " ) ; } int main ( ) { int mPlusN [ ] = { 2 , 8 , NA , NA , NA , 13 , NA , 15 , 20 } ; int N [ ] = { 5 , 7 , 9 , 25 } ; int n = sizeof ( N ) / sizeof ( N [ 0 ] ) ; int m = sizeof ( mPlusN ) / sizeof ( mPlusN [ 0 ] ) - n ; moveToEnd ( mPlusN , m + n ) ; merge ( mPlusN , N , m , n ) ; printArray ( mPlusN , m + n ) ; return 0 ; }
Count of N | C program to implement the above approach ; Function to find maximum between two numbers ; Function to find minimum between two numbers ; Function to return the count of such numbers ; For 1 - digit numbers , the count is 10 irrespective of K ; dp [ j ] stores the number of such i - digit numbers ending with j ; Stores the results of length i ; Initialize count for 1 - digit numbers ; Compute values for count of digits greater than 1 ; Find the range of allowed numbers if last digit is j ; Perform Range update ; Prefix sum to find actual count of i - digit numbers ending with j ; Update dp [ ] ; Stores the final answer ; Return the final answer ; Driver Code
#include <stdio.h> NEW_LINE int max ( int num1 , int num2 ) { return ( num1 > num2 ) ? num1 : num2 ; } int min ( int num1 , int num2 ) { return ( num1 > num2 ) ? num2 : num1 ; } int getCount ( int n , int k ) { if ( n == 1 ) return 10 ; int dp [ 11 ] = { 0 } ; int next [ 11 ] = { 0 } ; for ( int i = 1 ; i <= 9 ; i ++ ) dp [ i ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= 9 ; j ++ ) { int l = max ( 0 , ( j - k ) ) ; int r = min ( 9 , ( j + k ) ) ; next [ l ] += dp [ j ] ; next [ r + 1 ] -= dp [ j ] ; } for ( int j = 1 ; j <= 9 ; j ++ ) next [ j ] += next [ j - 1 ] ; for ( int j = 0 ; j < 10 ; j ++ ) { dp [ j ] = next [ j ] ; next [ j ] = 0 ; } } int count = 0 ; for ( int i = 0 ; i <= 9 ; i ++ ) count += dp [ i ] ; return count ; } int main ( ) { int n = 2 , k = 1 ; printf ( " % d " , getCount ( n , k ) ) ; }
Count Inversions in an array | Set 1 ( Using Merge Sort ) | C program to Count Inversions in an array ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int getInvCount ( int arr [ ] , int n ) { int inv_count = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] > arr [ j ] ) inv_count ++ ; return inv_count ; } int main ( ) { int arr [ ] = { 1 , 20 , 6 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " ▁ Number ▁ of ▁ inversions ▁ are ▁ % d ▁ STRNEWLINE " , getInvCount ( arr , n ) ) ; return 0 ; }
Two elements whose sum is closest to zero | C code to find Two elements whose sum is closest to zero ; Array should have at least two elements ; Initialization of values ; Driver program to test above function
# include <stdio.h> NEW_LINE # include <stdlib.h> NEW_LINE # include <math.h> NEW_LINE void minAbsSumPair ( int arr [ ] , int arr_size ) { int inv_count = 0 ; int l , r , min_sum , sum , min_l , min_r ; if ( arr_size < 2 ) { printf ( " Invalid ▁ Input " ) ; return ; } min_l = 0 ; min_r = 1 ; min_sum = arr [ 0 ] + arr [ 1 ] ; for ( l = 0 ; l < arr_size - 1 ; l ++ ) { for ( r = l + 1 ; r < arr_size ; r ++ ) { sum = arr [ l ] + arr [ r ] ; if ( abs ( min_sum ) > abs ( sum ) ) { min_sum = sum ; min_l = l ; min_r = r ; } } } printf ( " ▁ The ▁ two ▁ elements ▁ whose ▁ sum ▁ is ▁ minimum ▁ are ▁ % d ▁ and ▁ % d " , arr [ min_l ] , arr [ min_r ] ) ; } int main ( ) { int arr [ ] = { 1 , 60 , -10 , 70 , -80 , 85 } ; minAbsSumPair ( arr , 6 ) ; getchar ( ) ; return 0 ; }
Union and Intersection of two sorted arrays | C program to find union of two sorted arrays ; Function prints union of arr1 [ ] and arr2 [ ] m is the number of elements in arr1 [ ] n is the number of elements in arr2 [ ] ; Print remaining elements of the larger array ; Driver program to test above function
#include <stdio.h> NEW_LINE void printUnion ( int arr1 [ ] , int arr2 [ ] , int m , int n ) { int i = 0 , j = 0 ; while ( i < m && j < n ) { if ( arr1 [ i ] < arr2 [ j ] ) printf ( " ▁ % d ▁ " , arr1 [ i ++ ] ) ; else if ( arr2 [ j ] < arr1 [ i ] ) printf ( " ▁ % d ▁ " , arr2 [ j ++ ] ) ; else { printf ( " ▁ % d ▁ " , arr2 [ j ++ ] ) ; i ++ ; } } while ( i < m ) printf ( " ▁ % d ▁ " , arr1 [ i ++ ] ) ; while ( j < n ) printf ( " ▁ % d ▁ " , arr2 [ j ++ ] ) ; } int main ( ) { int arr1 [ ] = { 1 , 2 , 4 , 5 , 6 } ; int arr2 [ ] = { 2 , 3 , 5 , 7 } ; int m = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int n = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; printUnion ( arr1 , arr2 , m , n ) ; getchar ( ) ; return 0 ; }
Union and Intersection of two sorted arrays | C program to find intersection of two sorted arrays ; Function prints Intersection of arr1 [ ] and arr2 [ ] m is the number of elements in arr1 [ ] n is the number of elements in arr2 [ ] ; Driver program to test above function ; Function calling
#include <stdio.h> NEW_LINE void printIntersection ( int arr1 [ ] , int arr2 [ ] , int m , int n ) { int i = 0 , j = 0 ; while ( i < m && j < n ) { if ( arr1 [ i ] < arr2 [ j ] ) i ++ ; else if ( arr2 [ j ] < arr1 [ i ] ) j ++ ; else { printf ( " ▁ % d ▁ " , arr2 [ j ++ ] ) ; i ++ ; } } } int main ( ) { int arr1 [ ] = { 1 , 2 , 4 , 5 , 6 } ; int arr2 [ ] = { 2 , 3 , 5 , 7 } ; int m = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int n = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; printIntersection ( arr1 , arr2 , m , n ) ; getchar ( ) ; return 0 ; }
Find the maximum sum leaf to root path in a Binary Tree | C program to find maximum sum leaf to root path in Binary Tree ; A tree node structure ; A utility function that prints all nodes on the path from root to target_leaf ; base case ; return true if this node is the target_leaf or target leaf is present in one of its descendants ; This function Sets the target_leaf_ref to refer the leaf node of the maximum path sum . Also , returns the max_sum using max_sum_ref ; Update current sum to hold sum of nodes on path from root to this node ; If this is a leaf node and path to this node has maximum sum so far , then make this node target_leaf ; If this is not a leaf node , then recur down to find the target_leaf ; Returns the maximum sum and prints the nodes on max sum path ; base case ; find the target leaf and maximum sum ; print the path from root to the target leaf ; return maximum sum ; Utility function to create a new Binary Tree node ; Driver function to test above functions
#include <limits.h> NEW_LINE #include <stdbool.h> NEW_LINE #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left ; struct node * right ; } ; bool printPath ( struct node * root , struct node * target_leaf ) { if ( root == NULL ) return false ; if ( root == target_leaf || printPath ( root -> left , target_leaf ) || printPath ( root -> right , target_leaf ) ) { printf ( " % d ▁ " , root -> data ) ; return true ; } return false ; } void getTargetLeaf ( struct node * node , int * max_sum_ref , int curr_sum , struct node * * target_leaf_ref ) { if ( node == NULL ) return ; curr_sum = curr_sum + node -> data ; if ( node -> left == NULL && node -> right == NULL ) { if ( curr_sum > * max_sum_ref ) { * max_sum_ref = curr_sum ; * target_leaf_ref = node ; } } getTargetLeaf ( node -> left , max_sum_ref , curr_sum , target_leaf_ref ) ; getTargetLeaf ( node -> right , max_sum_ref , curr_sum , target_leaf_ref ) ; } int maxSumPath ( struct node * node ) { if ( node == NULL ) return 0 ; struct node * target_leaf ; int max_sum = INT_MIN ; getTargetLeaf ( node , & max_sum , 0 , & target_leaf ) ; printPath ( node , target_leaf ) ; return max_sum ; } struct node * newNode ( int data ) { struct node * temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> data = data ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } int main ( ) { struct node * root = NULL ; root = newNode ( 10 ) ; root -> left = newNode ( -2 ) ; root -> right = newNode ( 7 ) ; root -> left -> left = newNode ( 8 ) ; root -> left -> right = newNode ( -4 ) ; printf ( " Following ▁ are ▁ the ▁ nodes ▁ on ▁ the ▁ maximum ▁ " " sum ▁ path ▁ STRNEWLINE " ) ; int sum = maxSumPath ( root ) ; printf ( " Sum of the nodes is % d " , sum ) ; getchar ( ) ; return 0 ; }
Sort an array of 0 s , 1 s and 2 s | C program to sort an array with 0 , 1 and 2 in a single pass ; Function to swap * a and * b ; Sort the input array , the array is assumed to have values in { 0 , 1 , 2 } ; Utility function to print array arr [ ] ; driver program to test
#include <stdio.h> NEW_LINE void swap ( int * a , int * b ) { int temp = * a ; * a = * b ; * b = temp ; } void sort012 ( int a [ ] , int arr_size ) { int lo = 0 ; int hi = arr_size - 1 ; int mid = 0 ; while ( mid <= hi ) { switch ( a [ mid ] ) { case 0 : swap ( & a [ lo ++ ] , & a [ mid ++ ] ) ; break ; case 1 : mid ++ ; break ; case 2 : swap ( & a [ mid ] , & a [ hi -- ] ) ; break ; } } } void printArray ( int arr [ ] , int arr_size ) { int i ; for ( i = 0 ; i < arr_size ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; printf ( " n " ) ; } int main ( ) { int arr [ ] = { 0 , 1 , 1 , 0 , 1 , 2 , 1 , 2 , 0 , 0 , 0 , 1 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int i ; sort012 ( arr , arr_size ) ; printf ( " array ▁ after ▁ segregation ▁ " ) ; printArray ( arr , arr_size ) ; getchar ( ) ; return 0 ; }
Find the Minimum length Unsorted Subarray , sorting which makes the complete array sorted | C program to find the Minimum length Unsorted Subarray , sorting which makes the complete array sorted ; step 1 ( a ) of above algo ; step 1 ( b ) of above algo ; step 2 ( a ) of above algo ; step 2 ( b ) of above algo ; step 2 ( c ) of above algo ; step 3 of above algo
#include <stdio.h> NEW_LINE void printUnsorted ( int arr [ ] , int n ) { int s = 0 , e = n - 1 , i , max , min ; for ( s = 0 ; s < n - 1 ; s ++ ) { if ( arr [ s ] > arr [ s + 1 ] ) break ; } if ( s == n - 1 ) { printf ( " The ▁ complete ▁ array ▁ is ▁ sorted " ) ; return ; } for ( e = n - 1 ; e > 0 ; e -- ) { if ( arr [ e ] < arr [ e - 1 ] ) break ; } max = arr [ s ] ; min = arr [ s ] ; for ( i = s + 1 ; i <= e ; i ++ ) { if ( arr [ i ] > max ) max = arr [ i ] ; if ( arr [ i ] < min ) min = arr [ i ] ; } for ( i = 0 ; i < s ; i ++ ) { if ( arr [ i ] > min ) { s = i ; break ; } } for ( i = n - 1 ; i >= e + 1 ; i -- ) { if ( arr [ i ] < max ) { e = i ; break ; } } printf ( " ▁ The ▁ unsorted ▁ subarray ▁ which ▁ makes ▁ the ▁ given ▁ array ▁ " " ▁ sorted ▁ lies ▁ between ▁ the ▁ indees ▁ % d ▁ and ▁ % d " , s , e ) ; return ; } int main ( ) { int arr [ ] = { 10 , 12 , 20 , 30 , 25 , 40 , 32 , 31 , 35 , 50 , 60 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printUnsorted ( arr , arr_size ) ; getchar ( ) ; return 0 ; }
Count the number of possible triangles | C program to count number of triangles that can be formed from given array ; Following function is needed for library function qsort ( ) . Refer www . cplusplus . com / reference / clibrary / cstdlib / qsort / ; Function to count all possible triangles with arr [ ] elements ; Sort the array elements in non - decreasing order ; Initialize count of triangles ; Fix the first element . We need to run till n - 3 as the other two elements are selected from arr [ i + 1. . . n - 1 ] ; Initialize index of the rightmost third element ; Fix the second element ; Find the rightmost element which is smaller than the sum of two fixed elements The important thing to note here is , we use the previous value of k . If value of arr [ i ] + arr [ j - 1 ] was greater than arr [ k ] , then arr [ i ] + arr [ j ] must be greater than k , because the array is sorted . ; Total number of possible triangles that can be formed with the two fixed elements is k - j - 1. The two fixed elements are arr [ i ] and arr [ j ] . All elements between arr [ j + 1 ] / to arr [ k - 1 ] can form a triangle with arr [ i ] and arr [ j ] . One is subtracted from k because k is incremented one extra in above while loop . k will always be greater than j . If j becomes equal to k , then above loop will increment k , because arr [ k ] + arr [ i ] is always greater than arr [ k ] ; Driver program to test above functionarr [ j + 1 ]
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE http : int comp ( const void * a , const void * b ) { return * ( int * ) a > * ( int * ) b ; } int findNumberOfTriangles ( int arr [ ] , int n ) { qsort ( arr , n , sizeof ( arr [ 0 ] ) , comp ) ; int count = 0 ; for ( int i = 0 ; i < n - 2 ; ++ i ) { int k = i + 2 ; for ( int j = i + 1 ; j < n ; ++ j ) { while ( k < n && arr [ i ] + arr [ j ] > arr [ k ] ) ++ k ; if ( k > j ) count += k - j - 1 ; } } return count ; } int main ( ) { int arr [ ] = { 10 , 21 , 22 , 100 , 101 , 200 , 300 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Total ▁ number ▁ of ▁ triangles ▁ possible ▁ is ▁ % d ▁ " , findNumberOfTriangles ( arr , size ) ) ; return 0 ; }
Search , insert and delete in an unsorted array | C program to implement linear search in unsorted array ; Function to implement search operation ; Driver Code ; Using a last element as search element
#include <stdio.h> NEW_LINE int findElement ( int arr [ ] , int n , int key ) { int i ; for ( i = 0 ; i < n ; i ++ ) if ( arr [ i ] == key ) return i ; return -1 ; } int main ( ) { int arr [ ] = { 12 , 34 , 10 , 6 , 40 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int key = 40 ; int position = findElement ( arr , n , key ) ; if ( position == - 1 ) printf ( " Element ▁ not ▁ found " ) ; else printf ( " Element ▁ Found ▁ at ▁ Position : ▁ % d " , position + 1 ) ; return 0 ; }
Search , insert and delete in an unsorted array | C program to implement insert operation in an unsorted array . ; Inserts a key in arr [ ] of given capacity . n is current size of arr [ ] . This function returns n + 1 if insertion is successful , else n . ; Cannot insert more elements if n is already more than or equal to capcity ; Driver Code ; Inserting key
#include <stdio.h> NEW_LINE int insertSorted ( int arr [ ] , int n , int key , int capacity ) { if ( n >= capacity ) return n ; arr [ n ] = key ; return ( n + 1 ) ; } int main ( ) { int arr [ 20 ] = { 12 , 16 , 20 , 40 , 50 , 70 } ; int capacity = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int n = 6 ; int i , key = 26 ; printf ( " Before Insertion : " for ( i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; n = insertSorted ( arr , n , key , capacity ) ; printf ( " After Insertion : " for ( i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; return 0 ; }
Search , insert and delete in an unsorted array | C program to implement delete operation in a unsorted array ; Function to implement search operation ; Function to delete an element ; Find position of element to be deleted ; Deleting element ; Driver code
#include <stdio.h> NEW_LINE int findElement ( int arr [ ] , int n , int key ) { int i ; for ( i = 0 ; i < n ; i ++ ) if ( arr [ i ] == key ) return i ; return - 1 ; } int deleteElement ( int arr [ ] , int n , int key ) { int pos = findElement ( arr , n , key ) ; if ( pos == - 1 ) { printf ( " Element ▁ not ▁ found " ) ; return n ; } int i ; for ( i = pos ; i < n - 1 ; i ++ ) arr [ i ] = arr [ i + 1 ] ; return n - 1 ; } int main ( ) { int i ; int arr [ ] = { 10 , 50 , 30 , 40 , 20 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int key = 30 ; printf ( " Array ▁ before ▁ deletion STRNEWLINE " ) ; for ( i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; n = deleteElement ( arr , n , key ) ; printf ( " Array after deletion " for ( i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; return 0 ; }
Search , insert and delete in a sorted array | C program to implement binary search in sorted array ; function to implement binary search ; low + ( high - low ) / 2 ; ; Driver Code Let us search 3 in below array
#include <stdio.h> NEW_LINE int binarySearch ( int arr [ ] , int low , int high , int key ) { if ( high < low ) return -1 ; int mid = ( low + high ) / 2 ; if ( key == arr [ mid ] ) return mid ; if ( key > arr [ mid ] ) return binarySearch ( arr , ( mid + 1 ) , high , key ) ; return binarySearch ( arr , low , ( mid - 1 ) , key ) ; } int main ( ) { int arr [ ] = { 5 , 6 , 7 , 8 , 9 , 10 } ; int n , key ; n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; key = 10 ; printf ( " Index : ▁ % d STRNEWLINE " , binarySearch ( arr , 0 , n - 1 , key ) ) ; return 0 ; }
Search , insert and delete in a sorted array | C program to implement insert operation in an sorted array . ; Inserts a key in arr [ ] of given capacity . n is current size of arr [ ] . This function returns n + 1 if insertion is successful , else n . ; Cannot insert more elements if n is already more than or equal to capcity ; Driver program to test above function ; Inserting key
#include <stdio.h> NEW_LINE int insertSorted ( int arr [ ] , int n , int key , int capacity ) { if ( n >= capacity ) return n ; int i ; for ( i = n - 1 ; ( i >= 0 && arr [ i ] > key ) ; i -- ) arr [ i + 1 ] = arr [ i ] ; arr [ i + 1 ] = key ; return ( n + 1 ) ; } int main ( ) { int arr [ 20 ] = { 12 , 16 , 20 , 40 , 50 , 70 } ; int capacity = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int n = 6 ; int i , key = 26 ; printf ( " Before Insertion : " for ( i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; n = insertSorted ( arr , n , key , capacity ) ; printf ( " After Insertion : " for ( i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; return 0 ; }
Search , insert and delete in a sorted array | C program to implement delete operation in a sorted array ; To search a ley to be deleted ; Function to delete an element ; Find position of element to be deleted ; Deleting element ; Driver code
#include <stdio.h> NEW_LINE int binarySearch ( int arr [ ] , int low , int high , int key ) ; int binarySearch ( int arr [ ] , int low , int high , int key ) { if ( high < low ) return -1 ; int mid = ( low + high ) / 2 ; if ( key == arr [ mid ] ) return mid ; if ( key > arr [ mid ] ) return binarySearch ( arr , ( mid + 1 ) , high , key ) ; return binarySearch ( arr , low , ( mid - 1 ) , key ) ; } int deleteElement ( int arr [ ] , int n , int key ) { int pos = binarySearch ( arr , 0 , n - 1 , key ) ; if ( pos == -1 ) { printf ( " Element ▁ not ▁ found " ) ; return n ; } int i ; for ( i = pos ; i < n - 1 ; i ++ ) arr [ i ] = arr [ i + 1 ] ; return n - 1 ; } int main ( ) { int i ; int arr [ ] = { 10 , 20 , 30 , 40 , 50 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int key = 30 ; printf ( " Array ▁ before ▁ deletion STRNEWLINE " ) ; for ( i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; n = deleteElement ( arr , n , key ) ; printf ( " Array after deletion " for ( i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; }
Equilibrium index of an array | C program to find equilibrium index of an array ; function to find the equilibrium index ; Check for indexes one by one until an equilibrium index is found ; get left sum ; get right sum ; if leftsum and rightsum are same , then we are done ; return - 1 if no equilibrium index is found ; Driver code
#include <stdio.h> NEW_LINE int equilibrium ( int arr [ ] , int n ) { int i , j ; int leftsum , rightsum ; for ( i = 0 ; i < n ; ++ i ) { leftsum = 0 ; rightsum = 0 ; for ( j = 0 ; j < i ; j ++ ) leftsum += arr [ j ] ; for ( j = i + 1 ; j < n ; j ++ ) rightsum += arr [ j ] ; if ( leftsum == rightsum ) return i ; } return -1 ; } int main ( ) { int arr [ ] = { -7 , 1 , 5 , 2 , -4 , 3 , 0 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " % d " , equilibrium ( arr , arr_size ) ) ; getchar ( ) ; return 0 ; }
Equilibrium index of an array | C program to find equilibrium index of an array ; function to find the equilibrium index ; initialize sum of whole array ; initialize leftsum ; Find sum of the whole array ; sum is now right sum for index i ; If no equilibrium index found , then return 0 ; Driver code
#include <stdio.h> NEW_LINE int equilibrium ( int arr [ ] , int n ) { int sum = 0 ; int leftsum = 0 ; for ( int i = 0 ; i < n ; ++ i ) sum += arr [ i ] ; for ( int i = 0 ; i < n ; ++ i ) { sum -= arr [ i ] ; if ( leftsum == sum ) return i ; leftsum += arr [ i ] ; } return -1 ; } int main ( ) { int arr [ ] = { -7 , 1 , 5 , 2 , -4 , 3 , 0 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " First ▁ equilibrium ▁ index ▁ is ▁ % d " , equilibrium ( arr , arr_size ) ) ; 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 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
#include <stdio.h> NEW_LINE 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
#include <stdio.h> NEW_LINE 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 ; }
Two Pointers Technique | Naive solution to find if there is a pair in A [ 0. . N - 1 ] with given sum . ; as equal i and j means same element ; pair exists ; as the array is sorted ; No pair found with given sum . ; Driver Code ; Function call
#include <stdio.h> NEW_LINE int isPairSum ( int A [ ] , int N , int X ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( i == j ) continue ; if ( A [ i ] + A [ j ] == X ) return true ; if ( A [ i ] + A [ j ] > X ) break ; } } return 0 ; } int main ( ) { int arr [ ] = { 3 , 5 , 9 , 2 , 8 , 10 , 11 } ; int val = 17 ; int arrSize = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " % d " , isPairSum ( arr , arrSize , val ) ) ; return 0 ; }
Two Pointers Technique | ; Two pointer technique based solution to find if there is a pair in A [ 0. . N - 1 ] with a given sum . ; represents first pointer ; represents second pointer ; If we find a pair ; If sum of elements at current pointers is less , we move towards higher values by doing i ++ ; If sum of elements at current pointers is more , we move towards lower values by doing j -- ; Driver code ; array declaration ; value to search ; size of the array ; Function call
#include <stdio.h> NEW_LINE int isPairSum ( int A [ ] , int N , int X ) { int i = 0 ; int j = N - 1 ; while ( i < j ) { if ( A [ i ] + A [ j ] == X ) return 1 ; else if ( A [ i ] + A [ j ] < X ) i ++ ; else j -- ; } return 0 ; } int main ( ) { int arr [ ] = { 3 , 5 , 9 , 2 , 8 , 10 , 11 } ; int val = 17 ; int arrSize = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " % d " , isPairSum ( arr , arrSize , val ) ) ; 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
#include <stdio.h> NEW_LINE #define NUM_LINE 2 NEW_LINE #define NUM_STATION 4 NEW_LINE 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 ; }
Minimum insertions to form a palindrome | DP | A Dynamic Programming based program to find minimum number insertions needed to make a string palindrome ; A utility function to find minimum of two integers ; A DP function to find minimum number of insertions ; Create a table of size n * n . table [ i ] [ j ] will store minimum number of insertions needed to convert str [ i . . j ] to a palindrome . ; Fill the table ; Return minimum number of insertions for str [ 0. . n - 1 ] ; Driver program to test above function .
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE int min ( int a , int b ) { return a < b ? a : b ; } int findMinInsertionsDP ( char str [ ] , int n ) { int table [ n ] [ n ] , l , h , gap ; memset ( table , 0 , sizeof ( table ) ) ; for ( gap = 1 ; gap < n ; ++ gap ) for ( l = 0 , h = gap ; h < n ; ++ l , ++ h ) table [ l ] [ h ] = ( str [ l ] == str [ h ] ) ? table [ l + 1 ] [ h - 1 ] : ( min ( table [ l ] [ h - 1 ] , table [ l + 1 ] [ h ] ) + 1 ) ; return table [ 0 ] [ n - 1 ] ; } int main ( ) { char str [ ] = " geeks " ; printf ( " % d " , findMinInsertionsDP ( str , strlen ( str ) ) ) ; return 0 ; }
Largest Independent Set Problem | DP | A naive recursive implementation of Largest Independent Set problem ; A utility function to find max of two integers ; A binary tree node has data , pointer to left child and a pointer to right child ; The function returns size of the largest independent set in a given binary tree ; Calculate size excluding the current node ; Calculate size including the current node ; Return the maximum of two sizes ; A utility function to create a node ; Driver program to test above functions ; Let us construct the tree given in the above diagram
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int max ( int x , int y ) { return ( x > y ) ? x : y ; } struct node { int data ; struct node * left , * right ; } ; int LISS ( struct node * root ) { if ( root == NULL ) return 0 ; int size_excl = LISS ( root -> left ) + LISS ( root -> right ) ; int size_incl = 1 ; if ( root -> left ) size_incl += LISS ( root -> left -> left ) + LISS ( root -> left -> right ) ; if ( root -> right ) size_incl += LISS ( root -> right -> left ) + LISS ( root -> right -> right ) ; return max ( size_incl , size_excl ) ; } struct node * newNode ( int data ) { struct node * temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { struct node * root = newNode ( 20 ) ; root -> left = newNode ( 8 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 12 ) ; root -> left -> right -> left = newNode ( 10 ) ; root -> left -> right -> right = newNode ( 14 ) ; root -> right = newNode ( 22 ) ; root -> right -> right = newNode ( 25 ) ; printf ( " Size ▁ of ▁ the ▁ Largest ▁ Independent ▁ Set ▁ is ▁ % d ▁ " , LISS ( root ) ) ; return 0 ; }
Maximum Length Chain of Pairs | DP | ; This function assumes that arr [ ] is sorted in increasing order according the first ( or smaller ) values in pairs . ; Initialize MCL ( max chain length ) values for all indexes ; Compute optimized chain length values in bottom up manner ; Pick maximum of all MCL values ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct pair { int a ; int b ; } ; int maxChainLength ( struct pair arr [ ] , int n ) { int i , j , max = 0 ; int * mcl = ( int * ) malloc ( sizeof ( int ) * n ) ; for ( i = 0 ; i < n ; i ++ ) mcl [ i ] = 1 ; for ( i = 1 ; i < n ; i ++ ) for ( j = 0 ; j < i ; j ++ ) if ( arr [ i ] . a > arr [ j ] . b && mcl [ i ] < mcl [ j ] + 1 ) mcl [ i ] = mcl [ j ] + 1 ; for ( i = 0 ; i < n ; i ++ ) if ( max < mcl [ i ] ) max = mcl [ i ] ; free ( mcl ) ; return max ; } int main ( ) { struct pair arr [ ] = { { 5 , 24 } , { 15 , 25 } , { 27 , 40 } , { 50 , 60 } } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Length ▁ of ▁ maximum ▁ size ▁ chain ▁ is ▁ % d STRNEWLINE " , maxChainLength ( arr , n ) ) ; return 0 ; }
Palindrome Partitioning | DP | Dynamic Programming Solution for Palindrome Partitioning Problem ; Returns the minimum number of cuts needed to partition a string such that every part is a palindrome ; Get the length of the string ; Create two arrays to build the solution in bottom up manner C [ i ] [ j ] = Minimum number of cuts needed for palindrome partitioning of substring str [ i . . j ] P [ i ] [ j ] = true if substring str [ i . . j ] is palindrome , else false Note that C [ i ] [ j ] is 0 if P [ i ] [ j ] is true ; different looping variables ; Every substring of length 1 is a palindrome ; L is substring length . Build the solution in bottom up manner by considering all substrings of length starting from 2 to n . The loop structure is same as Matrix Chain Multiplication problem ( See https : www . geeksforgeeks . org / matrix - chain - multiplication - dp - 8 / ) ; For substring of length L , set different possible starting indexes ; Set ending index ; If L is 2 , then we just need to compare two characters . Else need to check two corner characters and value of P [ i + 1 ] [ j - 1 ] ; IF str [ i . . j ] is palindrome , then C [ i ] [ j ] is 0 ; Make a cut at every possible location starting from i to j , and get the minimum cost cut . ; Return the min cut value for complete string . i . e . , str [ 0. . n - 1 ] ; Driver program to test above function
#include <limits.h> NEW_LINE #include <stdio.h> NEW_LINE #include <string.h> NEW_LINE int min ( int a , int b ) { return ( a < b ) ? a : b ; } int minPalPartion ( char * str ) { int n = strlen ( str ) ; int C [ n ] [ n ] ; bool P [ n ] [ n ] ; int i , j , k , L ; for ( i = 0 ; i < n ; i ++ ) { P [ i ] [ i ] = true ; C [ i ] [ i ] = 0 ; } for ( L = 2 ; L <= n ; L ++ ) { for ( i = 0 ; i < n - L + 1 ; i ++ ) { j = i + L - 1 ; if ( L == 2 ) P [ i ] [ j ] = ( str [ i ] == str [ j ] ) ; else P [ i ] [ j ] = ( str [ i ] == str [ j ] ) && P [ i + 1 ] [ j - 1 ] ; if ( P [ i ] [ j ] == true ) C [ i ] [ j ] = 0 ; else { C [ i ] [ j ] = INT_MAX ; for ( k = i ; k <= j - 1 ; k ++ ) C [ i ] [ j ] = min ( C [ i ] [ j ] , C [ i ] [ k ] + C [ k + 1 ] [ j ] + 1 ) ; } } } return C [ 0 ] [ n - 1 ] ; } int main ( ) { char str [ ] = " ababbbabbababa " ; printf ( " Min ▁ cuts ▁ needed ▁ for ▁ Palindrome ▁ Partitioning ▁ is ▁ % d " , minPalPartion ( str ) ) ; 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 ; 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
# include <limits.h> NEW_LINE # include <string.h> NEW_LINE # include <stdio.h> NEW_LINE # define NO_OF_CHARS 256 NEW_LINE 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 ; }
Difference between sums of odd level and even level nodes of a Binary Tree | A recursive program to find difference between sum of nodes at odd level and sum at even level ; Binary Tree node ; A utility function to allocate a new tree node with given data ; The main function that return difference between odd and even level nodes ; Base case ; Difference for root is root 's data - difference for left subtree - difference for right subtree ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE 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 ) ; } int getLevelDiff ( struct node * root ) { if ( root == NULL ) return 0 ; return root -> data - getLevelDiff ( root -> left ) - getLevelDiff ( root -> right ) ; } int main ( ) { struct node * root = newNode ( 5 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 6 ) ; root -> left -> left = newNode ( 1 ) ; root -> left -> right = newNode ( 4 ) ; root -> left -> right -> left = newNode ( 3 ) ; root -> right -> right = newNode ( 8 ) ; root -> right -> right -> right = newNode ( 9 ) ; root -> right -> right -> left = newNode ( 7 ) ; printf ( " % d ▁ is ▁ the ▁ required ▁ difference STRNEWLINE " , getLevelDiff ( root ) ) ; getchar ( ) ; return 0 ; }
Root to leaf path sum equal to a given number | ; A binary tree node has data , pointer to left child and a pointer to right child ; Given a tree and a sum , return true if there is a path from the root down to a leaf , such that adding up all the values along the path equals the given sum . Strategy : subtract the node value from the sum when recurring down , and check to see if the sum is 0 when you run out of tree . ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver Code ; Constructed binary tree is 10 / \ 8 2 / \ / 3 5 2
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #define bool int NEW_LINE struct node { int data ; struct node * left ; struct node * right ; } ; bool hasPathSum ( struct node * node , int sum ) { if ( node == NULL ) { return ( sum == 0 ) ; } else { bool ans = 0 ; int subSum = sum - node -> data ; if ( subSum == 0 && node -> left == NULL && node -> right == NULL ) return 1 ; if ( node -> left ) ans = ans || hasPathSum ( node -> left , subSum ) ; if ( node -> right ) ans = ans || hasPathSum ( node -> right , subSum ) ; return ans ; } } 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 ( ) { int sum = 21 ; 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 -> left = newnode ( 2 ) ; if ( hasPathSum ( root , sum ) ) printf ( " There ▁ is ▁ a ▁ root - to - leaf ▁ path ▁ with ▁ sum ▁ % d " , sum ) ; else printf ( " There ▁ is ▁ no ▁ root - to - leaf ▁ path ▁ with ▁ sum ▁ % d " , sum ) ; getchar ( ) ; return 0 ; }
Sum of all the numbers that are formed from root to leaf paths | C program to find sum of all paths from root to leaves ; function to allocate new node with given data ; Returns sum of all root to leaf paths . The first parameter is root of current subtree , the second parameter is value of the number formed by nodes from root to this node ; Base case ; Update val ; if current node is leaf , return the current value of val ; recur sum of values for left and right subtree ; A wrapper function over treePathsSumUtil ( ) ; Pass the initial value as 0 as there is nothing above root ; Driver function to test the above functions
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE 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 ) ; } int treePathsSumUtil ( struct node * root , int val ) { if ( root == NULL ) return 0 ; val = ( val * 10 + root -> data ) ; if ( root -> left == NULL && root -> right == NULL ) return val ; return treePathsSumUtil ( root -> left , val ) + treePathsSumUtil ( root -> right , val ) ; } int treePathsSum ( struct node * root ) { return treePathsSumUtil ( root , 0 ) ; } int main ( ) { struct node * root = newNode ( 6 ) ; root -> left = newNode ( 3 ) ; root -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 2 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 4 ) ; root -> left -> right -> left = newNode ( 7 ) ; root -> left -> right -> right = newNode ( 4 ) ; printf ( " Sum ▁ of ▁ all ▁ paths ▁ is ▁ % d " , treePathsSum ( root ) ) ; return 0 ; }
Lowest Common Ancestor in a Binary Tree | Set 2 ( Using Parent Pointer ) | C ++ program to find lowest common ancestor using parent pointer ; A Tree Node ; A utility function to create a new BST node ; A utility function to insert a new node with given key in Binary Search Tree ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; return the ( unchanged ) node pointer ; To find LCA of nodes n1 and n2 in Binary Tree ; Creata a map to store ancestors of n1 ; Insert n1 and all its ancestors in map ; Check if n2 or any of its ancestors is in map . ; Driver method to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { Node * left , * right , * parent ; int key ; } ; Node * newNode ( int item ) { Node * temp = new Node ; temp -> key = item ; temp -> parent = temp -> left = temp -> right = NULL ; return temp ; } Node * insert ( Node * node , int key ) { if ( node == NULL ) return newNode ( key ) ; if ( key < node -> key ) { node -> left = insert ( node -> left , key ) ; node -> left -> parent = node ; } else if ( key > node -> key ) { node -> right = insert ( node -> right , key ) ; node -> right -> parent = node ; } return node ; } Node * LCA ( Node * n1 , Node * n2 ) { map < Node * , bool > ancestors ; while ( n1 != NULL ) { ancestors [ n1 ] = true ; n1 = n1 -> parent ; } while ( n2 != NULL ) { if ( ancestors . find ( n2 ) != ancestors . end ( ) ) return n2 ; n2 = n2 -> parent ; } return NULL ; } int main ( void ) { Node * root = NULL ; root = insert ( root , 20 ) ; root = insert ( root , 8 ) ; root = insert ( root , 22 ) ; root = insert ( root , 4 ) ; root = insert ( root , 12 ) ; root = insert ( root , 10 ) ; root = insert ( root , 14 ) ; Node * n1 = root -> left -> right -> left ; Node * n2 = root -> left ; Node * lca = LCA ( n1 , n2 ) ; printf ( " LCA ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , n1 -> key , n2 -> key , lca -> key ) ; 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
#include <stdio.h> NEW_LINE 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 ; }
Program to find sum of harmonic series | C program to find sum of harmonic series ; Function to return sum of harmonic series ; Driver code
#include <stdio.h> NEW_LINE double sum ( int n ) { double i , s = 0.0 ; for ( i = 1 ; i <= n ; i ++ ) s = s + 1 / i ; return s ; } int main ( ) { int n = 5 ; printf ( " Sum ▁ is ▁ % f " , sum ( n ) ) ; return 0 ; }
Find nth term of the series 5 2 13 41 | C program to find nth term of the series 5 2 13 41 ; function to calculate nth term of the series ; to store the nth term of series ; if n is even number ; if n is odd number ; return nth term ; Driver code
#include <math.h> NEW_LINE #include <stdio.h> NEW_LINE int nthTermOfTheSeries ( int n ) { int nthTerm ; if ( n % 2 == 0 ) nthTerm = pow ( n - 1 , 2 ) + n ; else nthTerm = pow ( n + 1 , 2 ) + n ; return nthTerm ; } int main ( ) { int n ; n = 8 ; printf ( " % d STRNEWLINE " , nthTermOfTheSeries ( n ) ) ; n = 12 ; printf ( " % d STRNEWLINE " , nthTermOfTheSeries ( n ) ) ; n = 102 ; printf ( " % d STRNEWLINE " , nthTermOfTheSeries ( n ) ) ; n = 999 ; printf ( " % d STRNEWLINE " , nthTermOfTheSeries ( n ) ) ; n = 9999 ; printf ( " % d STRNEWLINE " , nthTermOfTheSeries ( n ) ) ; return 0 ; }
Logarithm | C program to find log ( n ) using Recursion ; Driver code
#include <stdio.h> NEW_LINE unsigned int Log2n ( unsigned int n ) { return ( n > 1 ) ? 1 + Log2n ( n / 2 ) : 0 ; } int main ( ) { unsigned int n = 32 ; printf ( " % u " , Log2n ( n ) ) ; getchar ( ) ; return 0 ; }
Find amount to be added to achieve target ratio in a given mixture | C program to find amount of water to be added to achieve given target ratio . ; Driver code
#include <stdio.h> NEW_LINE float findAmount ( float X , float W , float Y ) { return ( X * ( Y - W ) ) / ( 100 - Y ) ; } int main ( ) { float X = 100 , W = 50 , Y = 60 ; printf ( " Water ▁ to ▁ be ▁ added ▁ = ▁ % .2f ▁ " , findAmount ( X , W , Y ) ) ; 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
#include <stdio.h> NEW_LINE float AvgofSquareN ( int n ) { return ( float ) ( ( n + 1 ) * ( 2 * n + 1 ) ) / 6 ; } int main ( ) { int n = 10 ; printf ( " % f " , AvgofSquareN ( n ) ) ; return 0 ; }
Program to print triangular number series till n | C Program to find Triangular Number Series ; Function to find triangular number ; Driven Function
#include <stdio.h> NEW_LINE void triangular_series ( int n ) { for ( int i = 1 ; i <= n ; i ++ ) printf ( " ▁ % d ▁ " , i * ( i + 1 ) / 2 ) ; } int main ( ) { int n = 5 ; triangular_series ( n ) ; return 0 ; }
Sum of all divisors from 1 to n | C program to find sum of all divisor of number up to ' n ' ; Utility function to find sum of all divisor of number up to ' n ' ; Driver code
#include <stdio.h> NEW_LINE int divisorSum ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; ++ i ) sum += ( n / i ) * i ; return sum ; } int main ( ) { int n = 4 ; printf ( " % d STRNEWLINE " , divisorSum ( n ) ) ; n = 5 ; printf ( " % d " , divisorSum ( n ) ) ; return 0 ; }
Sum of the Series 1 + x / 1 + x ^ 2 / 2 + x ^ 3 / 3 + . . + x ^ n / n | C program to find sum of series 1 + x / 1 + x ^ 2 / 2 + x ^ 3 / 3 + ... . + x ^ n / n ; Code to print the sum of the series ; Driver code
#include <math.h> NEW_LINE #include <stdio.h> NEW_LINE double sum ( int x , int n ) { double i , total = 1.0 ; for ( i = 1 ; i <= n ; i ++ ) total = total + ( pow ( x , i ) / i ) ; return total ; } int main ( ) { int x = 2 ; int n = 5 ; printf ( " % .2f " , sum ( x , n ) ) ; return 0 ; }
Find whether a given integer is a power of 3 or not | C ++ program to check if a number is power of 3 or not . ; Returns true if n is power of 3 , else false ; The maximum power of 3 value that integer can hold is 1162261467 ( 3 ^ 19 ) . ; Driver code
#include <stdio.h> NEW_LINE #include <stdbool.h> NEW_LINE bool check ( int n ) { if ( n <= 0 ) return false ; return 1162261467 % n == 0 ; } int main ( ) { int n = 9 ; if ( check ( n ) ) printf ( " Yes " ) ; else printf ( " No " ) ; return 0 ; }
Program for Perrin numbers | Optimized C program for n 'th perrin number ; Driver code
#include <stdio.h> NEW_LINE int per ( int n ) { int a = 3 , b = 0 , c = 2 , i ; int m ; if ( n == 0 ) return a ; if ( n == 1 ) return b ; if ( n == 2 ) return c ; while ( n > 2 ) { m = a + b ; a = b ; b = c ; c = m ; n -- ; } return m ; } int main ( ) { int n = 9 ; printf ( " % d " , per ( n ) ) ; 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
#include <math.h> NEW_LINE #include <stdio.h> NEW_LINE 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 STRNEWLINE " ) ; else printf ( " Odd STRNEWLINE " ) ; } int main ( ) { printf ( " The ▁ count ▁ of ▁ divisor : ▁ " ) ; countDivisors ( 10 ) ; return 0 ; }
How to avoid overflow in modular multiplication ? | A Simple solution that causes overflow when value of ( a % mod ) * ( b % mod ) becomes more than maximum value of long long int
#define ll long long NEW_LINE ll multiply ( ll a , ll b , ll mod ) { return ( ( a % mod ) * ( b % mod ) ) % mod ; }
Count number of squares in a rectangle | C program to count squares in a rectangle of size m x n ; Returns count of all squares in a rectangle of size m x n ; If n is smaller , swap m and n ; Now n is greater dimension , apply formula ; Driver Code
#include <stdio.h> NEW_LINE int countSquares ( int m , int n ) { int temp ; if ( n < m ) { temp = n ; n = m ; m = temp ; } return m * ( m + 1 ) * ( 2 * m + 1 ) / 6 + ( n - m ) * m * ( m + 1 ) / 2 ; } int main ( ) { int m = 4 , n = 3 ; printf ( " Count ▁ of ▁ squares ▁ is ▁ % d " , countSquares ( m , n ) ) ; }
Program to find sum of series 1 + 1 / 2 + 1 / 3 + 1 / 4 + . . + 1 / n | C program to find sum of series ; Function to return sum of 1 / 1 + 1 / 2 + 1 / 3 + . . + 1 / n ; Driver code
#include <stdio.h> NEW_LINE double sum ( int n ) { double i , s = 0.0 ; for ( i = 1 ; i <= n ; i ++ ) s = s + 1 / i ; return s ; } int main ( ) { int n = 5 ; printf ( " Sum ▁ is ▁ % f " , sum ( n ) ) ; return 0 ; }
Program to find GCD or HCF of two numbers | C program to find GCD of two numbers ; Recursive function to return gcd of a and b ; Driver program to test above function
#include <stdio.h> NEW_LINE int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } int main ( ) { int a = 98 , b = 56 ; printf ( " GCD ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ % d ▁ " , a , b , gcd ( a , b ) ) ; return 0 ; }
Print all sequences of given length | C ++ program of above approach ; A utility function that prints a given arr [ ] of length size ; The core function that recursively generates and prints all sequences of length k ; A function that uses printSequencesRecur ( ) to prints all sequences from 1 , 1 , . .1 to n , n , . . n ; Driver Program to test above functions
#include <stdio.h> NEW_LINE void printArray ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; printf ( " STRNEWLINE " ) ; return ; } void printSequencesRecur ( int arr [ ] , int n , int k , int index ) { int i ; if ( k == 0 ) { printArray ( arr , index ) ; } if ( k > 0 ) { for ( i = 1 ; i <= n ; ++ i ) { arr [ index ] = i ; printSequencesRecur ( arr , n , k - 1 , index + 1 ) ; } } } void printSequences ( int n , int k ) { int * arr = new int [ k ] ; printSequencesRecur ( arr , n , k , 0 ) ; return ; } int main ( ) { int n = 3 ; int k = 2 ; printSequences ( n , k ) ; 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
#include <stdio.h> NEW_LINE 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 STRNEWLINE " , n ) ; else printf ( " % d ▁ is ▁ not ▁ a ▁ multiple ▁ of ▁ 5 STRNEWLINE " , n ) ; return 0 ; }
Count total bits in a number | Function to get no of bits in binary representation of positive integer ; Driver program
#include <stdio.h> NEW_LINE unsigned int countBits ( unsigned int n ) { unsigned int count = 0 ; while ( n ) { count ++ ; n >>= 1 ; } return count ; } int main ( ) { int i = 65 ; printf ( " % d " , countBits ( i ) ) ; return 0 ; }
Find the n | C program to find n - th number whose binary representation is palindrome . ; Finds if the kth bit is set in the binary representation ; Returns the position of leftmost set bit in the binary representation ; Finds whether the integer in binary representation is palindrome or not ; One by one compare bits ; Compare left and right bits and converge ; Start from 1 , traverse through all the integers ; If we reach n , break the loop ; Driver code ; Function Call
#include <stdio.h> NEW_LINE #define INT_MAX 2147483647 NEW_LINE int isKthBitSet ( int x , int k ) { return ( x & ( 1 << ( k - 1 ) ) ) ? 1 : 0 ; } int leftmostSetBit ( int x ) { int count = 0 ; while ( x ) { count ++ ; x = x >> 1 ; } return count ; } int isBinPalindrome ( int x ) { int l = leftmostSetBit ( x ) ; int r = 1 ; while ( l > r ) { if ( isKthBitSet ( x , l ) != isKthBitSet ( x , r ) ) return 0 ; l -- ; r ++ ; } return 1 ; } int findNthPalindrome ( int n ) { int pal_count = 0 ; int i = 0 ; for ( i = 1 ; i <= INT_MAX ; i ++ ) { if ( isBinPalindrome ( i ) ) { pal_count ++ ; } if ( pal_count == n ) break ; } return i ; } int main ( ) { int n = 9 ; printf ( " % d " , findNthPalindrome ( n ) ) ; }
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
#include <stdio.h> NEW_LINE int main ( ) { unsigned char a = 5 , b = 9 ; printf ( " a ▁ = ▁ % d , ▁ b ▁ = ▁ % d STRNEWLINE " , a , b ) ; printf ( " a & b ▁ = ▁ % d STRNEWLINE " , a & b ) ; printf ( " a ▁ b ▁ = ▁ % d STRNEWLINE " , a b ) ; printf ( " a ^ b ▁ = ▁ % d STRNEWLINE " , a ^ b ) ; printf ( " ~ a ▁ = ▁ % d STRNEWLINE " , a = ~ a ) ; printf ( " b < < 1 ▁ = ▁ % d STRNEWLINE " , b << 1 ) ; printf ( " b > > 1 ▁ = ▁ % d STRNEWLINE " , b >> 1 ) ; 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
#include <stdio.h> NEW_LINE 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 ; }