text
stringlengths
25
2.53k
code
stringlengths
46
4.32k
Find the smallest positive number missing from an unsorted array | Set 1 | C program to find the smallest positive missing number ; Utility to swap to integers ; Utility function that puts all non - positive ( 0 and negative ) numbers on left side of arr [ ] and return count of such numbers ; increment count of non - positive integers ; Find the smallest positive missing number in an array that contains all positive integers ; Mark arr [ i ] as visited by making arr [ arr [ i ] - 1 ] negative . Note that 1 is subtracted because index start from 0 and positive numbers start from 1 ; Return the first index value at which is positive ; 1 is added because indexes start from 0 ; Find the smallest positive missing number in an array that contains both positive and negative integers ; First separate positive and negative numbers ; Shift the array and call findMissingPositive for positive part ; Driver code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE void swap ( int * a , int * b ) { int temp ; temp = * a ; * a = * b ; * b = temp ; } int segregate ( int arr [ ] , int size ) { int j = 0 , i ; for ( i = 0 ; i < size ; i ++ ) { if ( arr [ i ] <= 0 ) { swap ( & arr [ i ] , & arr [ j ] ) ; j ++ ; } } return j ; } int findMissingPositive ( int arr [ ] , int size ) { int i ; for ( i = 0 ; i < size ; i ++ ) { if ( abs ( arr [ i ] ) - 1 < size && arr [ abs ( arr [ i ] ) - 1 ] > 0 ) arr [ abs ( arr [ i ] ) - 1 ] = - arr [ abs ( arr [ i ] ) - 1 ] ; } for ( i = 0 ; i < size ; i ++ ) if ( arr [ i ] > 0 ) return i + 1 ; return size + 1 ; } int findMissing ( int arr [ ] , int size ) { int shift = segregate ( arr , size ) ; return findMissingPositive ( arr + shift , size - shift ) ; } int main ( ) { int arr [ ] = { 0 , 10 , 2 , -10 , -20 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int missing = findMissing ( arr , arr_size ) ; printf ( " The ▁ smallest ▁ positive ▁ missing ▁ number ▁ is ▁ % d ▁ " , missing ) ; getchar ( ) ; return 0 ; }
Find the Missing Number | ; getMissingNo takes array and size of array as arguments ; program to test above function
#include <stdio.h> NEW_LINE int getMissingNo ( int a [ ] , int n ) { int i , total ; total = ( n + 1 ) * ( n + 2 ) / 2 ; for ( i = 0 ; i < n ; i ++ ) total -= a [ i ] ; return total ; } int main ( ) { int a [ ] = { 1 , 2 , 4 , 5 , 6 } ; int miss = getMissingNo ( a , 5 ) ; printf ( " % d " , miss ) ; getchar ( ) ; }
Find the repeating and the missing | Added 3 new methods | C program to Find the repeating and missing elements ; Driver code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE void printTwoElements ( int arr [ ] , int size ) { int i ; printf ( " The repeating element is " for ( i = 0 ; i < size ; i ++ ) { if ( arr [ abs ( arr [ i ] ) - 1 ] > 0 ) arr [ abs ( arr [ i ] ) - 1 ] = - arr [ abs ( arr [ i ] ) - 1 ] ; else printf ( " ▁ % d ▁ " , abs ( arr [ i ] ) ) ; } printf ( " and the missing element is " for ( i = 0 ; i < size ; i ++ ) { if ( arr [ i ] > 0 ) printf ( " % d " , i + 1 ) ; } } int main ( ) { int arr [ ] = { 7 , 3 , 4 , 5 , 5 , 6 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printTwoElements ( arr , n ) ; return 0 ; }
Find the repeating and the missing | Added 3 new methods | C program to Find the repeating and missing elements ; The output of this function is stored at * x and * y ; Will hold xor of all elements and numbers from 1 to n ; Will have only single set bit of xor1 ; Get the xor of all array elements ; XOR the previous result with numbers from 1 to n ; Get the rightmost set bit in set_bit_no ; Now divide elements in two sets by comparing rightmost set bit of xor1 with bit at same position in each element . Also , get XORs of two sets . The two XORs are the output elements . The following two for loops serve the purpose ; arr [ i ] belongs to first set ; arr [ i ] belongs to second set ; i belongs to first set ; i belongs to second set ; * x and * y hold the desired output elements ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE void getTwoElements ( int arr [ ] , int n , int * x , int * y ) { int xor1 ; int set_bit_no ; int i ; * x = 0 ; * y = 0 ; xor1 = arr [ 0 ] ; for ( i = 1 ; i < n ; i ++ ) xor1 = xor1 ^ arr [ i ] ; for ( i = 1 ; i <= n ; i ++ ) xor1 = xor1 ^ i ; set_bit_no = xor1 & ~ ( xor1 - 1 ) ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] & set_bit_no ) * x = * x ^ arr [ i ] ; else * y = * y ^ arr [ i ] ; } for ( i = 1 ; i <= n ; i ++ ) { if ( i & set_bit_no ) * x = * x ^ i ; else * y = * y ^ i ; } } int main ( ) { int arr [ ] = { 1 , 3 , 4 , 5 , 5 , 6 , 2 } ; int * x = ( int * ) malloc ( sizeof ( int ) ) ; int * y = ( int * ) malloc ( sizeof ( int ) ) ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; getTwoElements ( arr , n , x , y ) ; printf ( " ▁ The ▁ missing ▁ element ▁ is ▁ % d " " ▁ and ▁ the ▁ repeating ▁ number " " ▁ is ▁ % d " , * x , * y ) ; getchar ( ) ; }
Find four elements that sum to a given value | Set 1 ( n ^ 3 solution ) | ; A naive solution to print all combination of 4 elements in A [ ] with sum equal to X ; Fix the first element and find other three ; Fix the second element and find other two ; Fix the third element and find the fourth ; find the fourth ; Driver program to test above function
#include <stdio.h> NEW_LINE void findFourElements ( int A [ ] , int n , int X ) { for ( int i = 0 ; i < n - 3 ; i ++ ) { for ( int j = i + 1 ; j < n - 2 ; j ++ ) { for ( int k = j + 1 ; k < n - 1 ; k ++ ) { for ( int l = k + 1 ; l < n ; l ++ ) if ( A [ i ] + A [ j ] + A [ k ] + A [ l ] == X ) printf ( " % d , ▁ % d , ▁ % d , ▁ % d " , A [ i ] , A [ j ] , A [ k ] , A [ l ] ) ; } } } } int main ( ) { int A [ ] = { 10 , 20 , 30 , 40 , 1 , 2 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int X = 91 ; findFourElements ( A , n , X ) ; return 0 ; }
Find four elements that sum to a given value | Set 2 | C program to find 4 elements with given sum ; The following structure is needed to store pair sums in aux [ ] ; index ( int A [ ] ) of first element in pair ; index of second element in pair ; sum of the pair ; Following function is needed for library function qsort ( ) ; Function to check if two given pairs have any common element or not ; The function finds four elements with given sum X ; Create an auxiliary array to store all pair sums ; Generate all possible pairs from A [ ] and store sums of all possible pairs in aux [ ] ; Sort the aux [ ] array using library function for sorting ; Now start two index variables from two corners of array and move them toward each other . ; Driver code ; Function call
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct pairSum { int first ; int sec ; int sum ; } ; int compare ( const void * a , const void * b ) { return ( ( * ( pairSum * ) a ) . sum - ( * ( pairSum * ) b ) . sum ) ; } bool noCommon ( struct pairSum a , struct pairSum b ) { if ( a . first == b . first a . first == b . sec a . sec == b . first a . sec == b . sec ) return false ; return true ; } void findFourElements ( int arr [ ] , int n , int X ) { int i , j ; int size = ( n * ( n - 1 ) ) / 2 ; struct pairSum aux [ size ] ; int k = 0 ; for ( i = 0 ; i < n - 1 ; i ++ ) { for ( j = i + 1 ; j < n ; j ++ ) { aux [ k ] . sum = arr [ i ] + arr [ j ] ; aux [ k ] . first = i ; aux [ k ] . sec = j ; k ++ ; } } qsort ( aux , size , sizeof ( aux [ 0 ] ) , compare ) ; i = 0 ; j = size - 1 ; while ( i < size && j >= 0 ) { if ( ( aux [ i ] . sum + aux [ j ] . sum == X ) && noCommon ( aux [ i ] , aux [ j ] ) ) { printf ( " % d , ▁ % d , ▁ % d , ▁ % d STRNEWLINE " , arr [ aux [ i ] . first ] , arr [ aux [ i ] . sec ] , arr [ aux [ j ] . first ] , arr [ aux [ j ] . sec ] ) ; return ; } else if ( aux [ i ] . sum + aux [ j ] . sum < X ) i ++ ; else j -- ; } } int main ( ) { int arr [ ] = { 10 , 20 , 30 , 40 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int X = 91 ; findFourElements ( arr , n , X ) ; return 0 ; }
Minimum distance between two occurrences of maximum | C program to find Min distance of maximum element ; function to return min distance ; case a ; case b ; case c ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minDistance ( int arr [ ] , int n ) { int maximum_element = arr [ 0 ] ; int min_dis = n ; int index = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( maximum_element == arr [ i ] ) { min_dis = min ( min_dis , ( i - index ) ) ; index = i ; } else if ( maximum_element < arr [ i ] ) { maximum_element = arr [ i ] ; min_dis = n ; index = i ; } else continue ; } return min_dis ; } int main ( ) { int arr [ ] = { 6 , 3 , 1 , 3 , 6 , 4 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Minimum ▁ distance ▁ = ▁ " << minDistance ( arr , n ) ; return 0 ; }
Search an element in a Linked List ( Iterative and Recursive ) | Recursive C program to search an element in linked list ; Link list node ; Given a reference ( pointer to pointer ) to the head of a list and an int , push a new node on the front of the list . ; allocate node put in the key ; link the old list off the new node ; move the head to point to the new node ; Checks whether the value x is present in linked list ; Base case ; If key is present in current node , return true ; Recur for remaining list ; Driver program to test count function ; Start with the empty list ; Use push ( ) to construct below list 14 -> 21 -> 11 -> 30 -> 10
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <stdbool.h> NEW_LINE struct Node { int key ; struct Node * next ; } ; void push ( struct Node * * head_ref , int new_key ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> key = new_key ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } bool search ( struct Node * head , int x ) { if ( head == NULL ) return false ; if ( head -> key == x ) return true ; return search ( head -> next , x ) ; } int main ( ) { struct Node * head = NULL ; int x = 21 ; push ( & head , 10 ) ; push ( & head , 30 ) ; push ( & head , 11 ) ; push ( & head , 21 ) ; push ( & head , 14 ) ; search ( head , 21 ) ? printf ( " Yes " ) : printf ( " No " ) ; return 0 ; }
Delete alternate nodes of a Linked List | deletes alternate nodes of a list starting with head ; Change the next link of head ; free memory allocated for node ; Recursively call for the new next of head
void deleteAlt ( struct Node * head ) { if ( head == NULL ) return ; struct Node * node = head -> next ; if ( node == NULL ) return ; head -> next = node -> next ; free ( node ) ; deleteAlt ( head -> next ) ; }
Alternating split of a given Singly Linked List | Set 1 | ; points to the last node in ' a ' ; points to the last node in ' b ' ; add at ' a ' tail ; advance the ' a ' tail
void AlternatingSplit ( struct Node * source , struct Node * * aRef , struct Node * * bRef ) { struct Node aDummy ; struct Node * aTail = & aDummy ; struct Node bDummy ; struct Node * bTail = & bDummy ; struct Node * current = source ; aDummy . next = NULL ; bDummy . next = NULL ; while ( current != NULL ) { MoveNode ( & ( aTail -> next ) , t ) ; aTail = aTail -> next ; if ( current != NULL ) { MoveNode ( & ( bTail -> next ) , t ) ; bTail = bTail -> next ; } } * aRef = aDummy . next ; * bRef = bDummy . next ; }
Identical Linked Lists | An iterative C program to check if two linked lists are identical or not ; Structure for a linked list node ; Returns true if linked lists a and b are identical , otherwise false ; If we reach here , then a and b are not NULL and their data is same , so move to next nodes in both lists ; If linked lists are identical , then ' a ' and ' b ' must be NULL at this point . ; Given a reference ( pointer to pointer ) to the head of a list and an int , push a new node on the front of the list . ; allocate node put in the data ; link the old list off the new node ; move the head to point to the new node ; Driver program to test above function ; The constructed linked lists are : a : 3 -> 2 -> 1 b : 3 -> 2 -> 1
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <stdbool.h> NEW_LINE struct Node { int data ; struct Node * next ; } ; bool areIdentical ( struct Node * a , struct Node * b ) { while ( a != NULL && b != NULL ) { if ( a -> data != b -> data ) return false ; a = a -> next ; b = b -> next ; } return ( a == NULL && b == NULL ) ; } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int main ( ) { struct Node * a = NULL ; struct Node * b = NULL ; push ( & a , 1 ) ; push ( & a , 2 ) ; push ( & a , 3 ) ; push ( & b , 1 ) ; push ( & b , 2 ) ; push ( & b , 3 ) ; areIdentical ( a , b ) ? printf ( " Identical " ) : printf ( " Not ▁ identical " ) ; return 0 ; }
Identical Linked Lists | A recursive C function to check if two linked lists are identical or not ; If both lists are empty ; If both lists are not empty , then data of current nodes must match , and same should be recursively true for rest of the nodes . ; If we reach here , then one of the lists is empty and other is not
bool areIdentical ( struct Node * a , struct Node * b ) { if ( a == NULL && b == NULL ) return true ; if ( a != NULL && b != NULL ) return ( a -> data == b -> data ) && areIdentical ( a -> next , b -> next ) ; return false ; }
Sort a linked list of 0 s , 1 s and 2 s | C Program to sort a linked list 0 s , 1 s or 2 s ; Link list node ; Function to sort a linked list of 0 s , 1 s and 2 s ; Initialize count of '0' , '1' and '2' as 0 ; count total number of '0' , '1' and '2' * count [ 0 ] will store total number of '0' s * count [ 1 ] will store total number of '1' s * count [ 2 ] will store total number of '2' s ; Let say count [ 0 ] = n1 , count [ 1 ] = n2 and count [ 2 ] = n3 * now start traversing list from head node , * 1 ) fill the list with 0 , till n1 > 0 * 2 ) fill the list with 1 , till n2 > 0 * 3 ) fill the list with 2 , till n3 > 0 ; Function to push a node ; allocate node put in the data ; link the old list off the new node ; move the head to point to the new node ; Function to print linked list ; Driver program to test above function ; Constructed Linked List is 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 8 -> 9 -> null
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * next ; } ; void sortList ( struct Node * head ) { int count [ 3 ] = { 0 , 0 , 0 } ; struct Node * ptr = head ; while ( ptr != NULL ) { count [ ptr -> data ] += 1 ; ptr = ptr -> next ; } int i = 0 ; ptr = head ; while ( ptr != NULL ) { if ( count [ i ] == 0 ) ++ i ; else { ptr -> data = i ; -- count [ i ] ; ptr = ptr -> next ; } } } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( struct Node * node ) { while ( node != NULL ) { printf ( " % d ▁ " , node -> data ) ; node = node -> next ; } printf ( " n " ) ; } int main ( void ) { struct Node * head = NULL ; push ( & head , 0 ) ; push ( & head , 1 ) ; push ( & head , 0 ) ; push ( & head , 2 ) ; push ( & head , 1 ) ; push ( & head , 1 ) ; push ( & head , 2 ) ; push ( & head , 1 ) ; push ( & head , 2 ) ; printf ( " Linked ▁ List ▁ Before ▁ Sorting STRNEWLINE " ) ; printList ( head ) ; sortList ( head ) ; printf ( " Linked ▁ List ▁ After ▁ Sorting STRNEWLINE " ) ; printList ( head ) ; return 0 ; }
Flatten a multilevel linked list |
struct List { int data ; struct List * next ; struct List * child ; } ;
Rearrange a linked list such that all even and odd positioned nodes are together | C program to rearrange a linked list in such a way that all odd positioned node are stored before all even positioned nodes ; Linked List Node ; A utility function to create a new node ; Rearranges given linked list such that all even positioned nodes are before odd positioned . Returns new head of linked List . ; Corner case ; Initialize first nodes of even and odd lists ; Remember the first node of even list so that we can connect the even list at the end of odd list . ; If there are no more nodes , then connect first node of even list to the last node of odd list ; Connecting odd nodes ; If there are NO more even nodes after current odd . ; Connecting even nodes ; A utility function to print a linked list ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> data = key ; temp -> next = NULL ; return temp ; } Node * rearrangeEvenOdd ( Node * head ) { if ( head == NULL ) return NULL ; Node * odd = head ; Node * even = head -> next ; Node * evenFirst = even ; while ( 1 ) { if ( ! odd || ! even || ! ( even -> next ) ) { odd -> next = evenFirst ; break ; } odd -> next = even -> next ; odd = even -> next ; if ( odd -> next == NULL ) { even -> next = NULL ; odd -> next = evenFirst ; break ; } even -> next = odd -> next ; even = odd -> next ; } return head ; } void printlist ( Node * node ) { while ( node != NULL ) { cout << node -> data << " - > " ; node = node -> next ; } cout << " NULL " << endl ; } int main ( void ) { Node * head = newNode ( 1 ) ; head -> next = newNode ( 2 ) ; head -> next -> next = newNode ( 3 ) ; head -> next -> next -> next = newNode ( 4 ) ; head -> next -> next -> next -> next = newNode ( 5 ) ; cout << " Given ▁ Linked ▁ List STRNEWLINE " ; printlist ( head ) ; head = rearrangeEvenOdd ( head ) ; cout << " Modified Linked List " ; printlist ( head ) ; return 0 ; }
Delete last occurrence of an item from linked list | A C program to demonstrate deletion of last Node in singly linked list ; A linked list Node ; Function to delete the last occurrence ; If found key , update ; If the last occurrence is the last node ; If it is not the last node ; Utility function to create a new node with given key ; This function prints contents of linked list starting from the given Node ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * next ; } ; void deleteLast ( struct Node * head , int x ) { struct Node * temp = head , * ptr = NULL ; while ( temp ) { if ( temp -> data == x ) ptr = temp ; temp = temp -> next ; } if ( ptr != NULL && ptr -> next == NULL ) { temp = head ; while ( temp -> next != ptr ) temp = temp -> next ; temp -> next = NULL ; } if ( ptr != NULL && ptr -> next != NULL ) { ptr -> data = ptr -> next -> data ; temp = ptr -> next ; ptr -> next = ptr -> next -> next ; free ( temp ) ; } } struct Node * newNode ( int x ) { struct Node * node = malloc ( sizeof ( struct Node * ) ) ; node -> data = x ; node -> next = NULL ; return node ; } void display ( struct Node * head ) { struct Node * temp = head ; if ( head == NULL ) { printf ( " NULL STRNEWLINE " ) ; return ; } while ( temp != NULL ) { printf ( " % d ▁ - - > ▁ " , temp -> data ) ; temp = temp -> next ; } printf ( " NULL STRNEWLINE " ) ; } int main ( ) { struct Node * head = newNode ( 1 ) ; head -> next = newNode ( 2 ) ; head -> next -> next = newNode ( 3 ) ; head -> next -> next -> next = newNode ( 4 ) ; head -> next -> next -> next -> next = newNode ( 5 ) ; head -> next -> next -> next -> next -> next = newNode ( 4 ) ; head -> next -> next -> next -> next -> next -> next = newNode ( 4 ) ; printf ( " Created ▁ Linked ▁ list : ▁ " ) ; display ( head ) ; deleteLast ( head , 4 ) ; printf ( " List ▁ after ▁ deletion ▁ of ▁ 4 : ▁ " ) ; display ( head ) ; return 0 ; }
Check whether the length of given linked list is Even or Odd | C program to check length of a given linklist ; Defining structure ; Function to check the length of linklist ; Push function ; Allocating node ; Info into node ; Next of new node to head ; head points to new node ; Driver function ; Adding elements to Linked List ; Checking for length of linklist
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * next ; } ; int LinkedListLength ( struct Node * head ) { while ( head && head -> next ) { head = head -> next -> next ; } if ( ! head ) return 0 ; return 1 ; } void push ( struct Node * * head , int info ) { struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; node -> data = info ; node -> next = ( * head ) ; ( * head ) = node ; } int main ( void ) { struct Node * head = NULL ; push ( & head , 4 ) ; push ( & head , 5 ) ; push ( & head , 7 ) ; push ( & head , 2 ) ; push ( & head , 9 ) ; push ( & head , 6 ) ; push ( & head , 1 ) ; push ( & head , 2 ) ; push ( & head , 0 ) ; push ( & head , 5 ) ; push ( & head , 5 ) ; int check = LinkedListLength ( head ) ; if ( check == 0 ) { printf ( " Even STRNEWLINE " ) ; } else { printf ( " Odd STRNEWLINE " ) ; } return 0 ; }
Merge two sorted linked lists | ; point to the last result pointer ; tricky : advance to point to the next " . next " field
struct Node * SortedMerge ( struct Node * a , struct Node * b ) { struct Node * result = NULL ; struct Node * * lastPtrRef = & result ; while ( 1 ) { if ( a == NULL ) { * lastPtrRef = b ; break ; } else if ( b == NULL ) { * lastPtrRef = a ; break ; } if ( a -> data <= b -> data ) { MoveNode ( lastPtrRef , & a ) ; } else { MoveNode ( lastPtrRef , & b ) ; } lastPtrRef = & ( ( * lastPtrRef ) -> next ) ; } return ( result ) ; }
Make middle node head in a linked list | C program to make middle node as head of linked list . ; Link list node ; Function to get the middle and set at beginning of the linked list ; To traverse list nodes one by one ; To traverse list nodes by skipping one . ; To keep track of previous of middle ; for previous node of middle node ; move one node each time ; move two node each time ; set middle node at head ; To insert a node at the beginning of linked list . ; allocate node ; link the old list off the new node ; move the head to point to the new node ; A function to print a given linked list ; Driver function ; Create a list of 5 nodes
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * next ; } ; void setMiddleHead ( struct Node * * head ) { if ( * head == NULL ) return ; struct Node * one_node = ( * head ) ; struct Node * two_node = ( * head ) ; struct Node * prev = NULL ; while ( two_node != NULL && two_node -> next != NULL ) { prev = one_node ; two_node = two_node -> next -> next ; one_node = one_node -> next ; } prev -> next = prev -> next -> next ; one_node -> next = ( * head ) ; ( * head ) = one_node ; } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( struct Node * ptr ) { while ( ptr != NULL ) { printf ( " % d ▁ " , ptr -> data ) ; ptr = ptr -> next ; } printf ( " STRNEWLINE " ) ; } int main ( ) { struct Node * head = NULL ; int i ; for ( i = 5 ; i > 0 ; i -- ) push ( & head , i ) ; printf ( " ▁ list ▁ before : ▁ " ) ; printList ( head ) ; setMiddleHead ( & head ) ; printf ( " ▁ list ▁ After : ▁ " ) ; printList ( head ) ; return 0 ; }
Doubly Linked List | Set 1 ( Introduction and Insertion ) | Given a node as prev_node , insert a new node after the given node ; 1. check if the given prev_node is NULL ; 2. allocate new node 3. put in the data ; 4. Make next of new node as next of prev_node ; 5. Make the next of prev_node as new_node ; 6. Make prev_node as previous of new_node ; 7. Change previous of new_node 's next node
void insertAfter ( struct Node * prev_node , int new_data ) { if ( prev_node == NULL ) { printf ( " the ▁ given ▁ previous ▁ node ▁ cannot ▁ be ▁ NULL " ) ; return ; } struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = prev_node -> next ; prev_node -> next = new_node ; new_node -> prev = prev_node ; if ( new_node -> next != NULL ) new_node -> next -> prev = new_node ; }
XOR Linked List Γ’ β‚¬β€œ A Memory Efficient Doubly Linked List | Set 2 | C Implementation of Memory efficient Doubly Linked List ; Node structure of a memory efficient doubly linked list ; XOR of next and previous node ; returns XORed value of the node addresses ; Insert a node at the beginning of the XORed linked list and makes the newly inserted node as head ; Allocate memory for new node ; Since new node is being inserted at the beginning , npx of new node will always be XOR of current head and NULL ; If linked list is not empty , then npx of current head node will be XOR of new node and node next to current head ; * ( head_ref ) -> npx is XOR of NULL and next . So if we do XOR of it with NULL , we get next ; Change head ; prints contents of doubly linked list in forward direction ; print current node ; get address of next node : curr -> npx is next ^ prev , so curr -> npx ^ prev will be next ^ prev ^ prev which is next ; update prev and curr for next iteration ; Driver program to test above functions ; Create following Doubly Linked List head -- > 40 < -- > 30 < -- > 20 < -- > 10 ; print the created list
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <inttypes.h> NEW_LINE struct Node { int data ; struct Node * npx ; } ; struct Node * XOR ( struct Node * a , struct Node * b ) { return ( struct Node * ) ( ( uintptr_t ) ( a ) ^ ( uintptr_t ) ( b ) ) ; } void insert ( struct Node * * head_ref , int data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = data ; new_node -> npx = * head_ref ; if ( * head_ref != NULL ) { ( * head_ref ) -> npx = XOR ( new_node , ( * head_ref ) -> npx ) ; } * head_ref = new_node ; } void printList ( struct Node * head ) { struct Node * curr = head ; struct Node * prev = NULL ; struct Node * next ; printf ( " Following ▁ are ▁ the ▁ nodes ▁ of ▁ Linked ▁ List : ▁ STRNEWLINE " ) ; while ( curr != NULL ) { printf ( " % d ▁ " , curr -> data ) ; next = XOR ( prev , curr -> npx ) ; prev = curr ; curr = next ; } } int main ( ) { struct Node * head = NULL ; insert ( & head , 10 ) ; insert ( & head , 20 ) ; insert ( & head , 30 ) ; insert ( & head , 40 ) ; printList ( head ) ; return ( 0 ) ; }
Print nodes at k distance from root | ; 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 . ; Driver program to test above functions ; Constructed binary tree is 1 / \ 2 3 / \ / 4 5 8
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left ; struct node * right ; } ; void printKDistant ( struct node * root , int k ) { if ( root == NULL k < 0 ) return ; if ( k == 0 ) { printf ( " % d ▁ " , root -> data ) ; return ; } printKDistant ( root -> left , k - 1 ) ; printKDistant ( root -> right , k - 1 ) ; } 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 -> left = newNode ( 8 ) ; printKDistant ( root , 2 ) ; getchar ( ) ; return 0 ; }
Print Binary Tree in 2 | Program to print binary tree in 2D ; A binary tree node ; Helper function to allocates a new node ; Function to print binary tree in 2D It does reverse inorder traversal ; Base case ; Increase distance between levels ; Process right child first ; Print current node after space count ; Process left child ; Wrapper over print2DUtil ( ) ; Pass initial space count as 0 ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <malloc.h> NEW_LINE #define COUNT 10 NEW_LINE struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int data ) { struct Node * node = malloc ( sizeof ( struct Node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return node ; } void print2DUtil ( struct Node * root , int space ) { if ( root == NULL ) return ; space += COUNT ; print2DUtil ( root -> right , space ) ; printf ( " STRNEWLINE " ) ; for ( int i = COUNT ; i < space ; i ++ ) printf ( " ▁ " ) ; printf ( " % d STRNEWLINE " , root -> data ) ; print2DUtil ( root -> left , space ) ; } void print2D ( struct Node * root ) { print2DUtil ( root , 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 -> 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 ( 10 ) ; root -> left -> right -> right = newNode ( 11 ) ; root -> right -> left -> left = newNode ( 12 ) ; root -> right -> left -> right = newNode ( 13 ) ; root -> right -> right -> left = newNode ( 14 ) ; root -> right -> right -> right = newNode ( 15 ) ; print2D ( root ) ; return 0 ; }
Print Left View of a Binary Tree | C program to print left view of Binary Tree ; A utility function to create a new Binary Tree node ; Recursive function to print left view of a binary tree . ; Base Case ; If this is the first node of its level ; Recur for left and right subtrees ; A wrapper over leftViewUtil ( ) ; Driver code
#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 ; } void leftViewUtil ( struct node * root , int level , int * max_level ) { if ( root == NULL ) return ; if ( * max_level < level ) { printf ( " % d TABSYMBOL " , root -> data ) ; * max_level = level ; } leftViewUtil ( root -> left , level + 1 , max_level ) ; leftViewUtil ( root -> right , level + 1 , max_level ) ; } void leftView ( struct node * root ) { int max_level = 0 ; leftViewUtil ( root , 1 , & max_level ) ; } int main ( ) { struct node * root = newNode ( 12 ) ; root -> left = newNode ( 10 ) ; root -> right = newNode ( 30 ) ; root -> right -> left = newNode ( 25 ) ; root -> right -> right = newNode ( 40 ) ; leftView ( root ) ; return 0 ; }
Count number of rotated strings which have more number of vowels in the first half than second half | C implementation of the approach ; Function to return the count of rotated strings which have more number of vowels in the first half than the second half ; Compute the number of vowels in first - half ; Compute the number of vowels in second - half ; Check if first - half has more vowels ; Check for all possible rotations ; Return the answer ; Driver code ; Function call
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE int cntRotations ( char s [ ] , int n ) { int lh = 0 , rh = 0 , i , ans = 0 ; for ( i = 0 ; i < n / 2 ; ++ i ) if ( s [ i ] == ' a ' s [ i ] == ' e ' s [ i ] == ' i ' s [ i ] == ' o ' s [ i ] == ' u ' ) { lh ++ ; } for ( i = n / 2 ; i < n ; ++ i ) if ( s [ i ] == ' a ' s [ i ] == ' e ' s [ i ] == ' i ' s [ i ] == ' o ' s [ i ] == ' u ' ) { rh ++ ; } if ( lh > rh ) ans ++ ; for ( i = 1 ; i < n ; ++ i ) { if ( s [ i - 1 ] == ' a ' s [ i - 1 ] == ' e ' s [ i - 1 ] == ' i ' s [ i - 1 ] == ' o ' s [ i - 1 ] == ' u ' ) { rh ++ ; lh -- ; } if ( s [ ( i - 1 + n / 2 ) % n ] == ' a ' || s [ ( i - 1 + n / 2 ) % n ] == ' e ' || s [ ( i - 1 + n / 2 ) % n ] == ' i ' || s [ ( i - 1 + n / 2 ) % n ] == ' o ' || s [ ( i - 1 + n / 2 ) % n ] == ' u ' ) { rh -- ; lh ++ ; } if ( lh > rh ) ans ++ ; } return ans ; } int main ( ) { char s [ ] = " abecidft " ; int n = strlen ( s ) ; printf ( " % d " , cntRotations ( s , n ) ) ; return 0 ; }
Rotate Linked List block wise | C program to rotate a linked list block wise ; Link list node ; Recursive function to rotate one block ; Rotate Clockwise ; Rotate anti - Clockwise ; Function to rotate the linked list block wise ; If length is 0 or 1 return head ; if degree of rotation is 0 , return head ; Traverse upto last element of this block ; storing the first node of next block ; If nodes of this block are less than k . Rotate this block also ; Append the new head of next block to the tail of this block ; return head of updated Linked List ; Function to push a node ; Function to print linked list ; Driver program to test above function ; Start with the empty list ; create a list 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> NULL ; k is block size and d is number of rotations in every block .
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * next ; } ; struct Node * rotateHelper ( struct Node * blockHead , struct Node * blockTail , int d , struct Node * * tail , int k ) { if ( d == 0 ) return blockHead ; if ( d > 0 ) { struct Node * temp = blockHead ; for ( int i = 1 ; temp -> next -> next && i < k - 1 ; i ++ ) temp = temp -> next ; blockTail -> next = blockHead ; * tail = temp ; return rotateHelper ( blockTail , temp , d - 1 , tail , k ) ; } if ( d < 0 ) { blockTail -> next = blockHead ; * tail = blockHead ; return rotateHelper ( blockHead -> next , blockHead , d + 1 , tail , k ) ; } } struct Node * rotateByBlocks ( struct Node * head , int k , int d ) { if ( ! head ! head -> next ) return head ; if ( d == 0 ) return head ; struct Node * temp = head , * tail = NULL ; int i ; for ( i = 1 ; temp -> next && i < k ; i ++ ) temp = temp -> next ; struct Node * nextBlock = temp -> next ; if ( i < k ) head = rotateHelper ( head , temp , d % k , & tail , i ) ; else head = rotateHelper ( head , temp , d % k , & tail , k ) ; tail -> next = rotateByBlocks ( nextBlock , k , d % k ) ; return head ; } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = new Node ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( struct Node * node ) { while ( node != NULL ) { printf ( " % d ▁ " , node -> data ) ; node = node -> next ; } } int main ( ) { struct Node * head = NULL ; for ( int i = 9 ; i > 0 ; i -= 1 ) push ( & head , i ) ; printf ( " Given ▁ linked ▁ list ▁ STRNEWLINE " ) ; printList ( head ) ; int k = 3 , d = 2 ; head = rotateByBlocks ( head , k , d ) ; printf ( " Rotated by blocks Linked list " printList ( head ) ; return ( 0 ) ; }
Deletion at different positions in a Circular Linked List | Function to delete First node of Circular Linked List ; check if list doesn 't have any node if not then return ; check if list have single node if yes then delete it and return ; traverse second node to first ; now previous is last node and first node ( firstNode ) link address put in last node ( previous ) link ; make second node as head node
void DeleteFirst ( struct Node * * head ) { struct Node * previous = * head , * firstNode = * head ; if ( * head == NULL ) { printf ( " List is empty " return ; } if ( previous -> next == previous ) { * head = NULL ; return ; } while ( previous -> next != * head ) { previous = previous -> next ; } previous -> next = firstNode -> next ; * head = previous -> next ; free ( firstNode ) ; return ; }
Deletion at different positions in a Circular Linked List | Function delete last node of Circular Linked List ; check if list doesn 't have any node if not then return ; check if list have single node if yes then delete it and return ; move first node to last previous
void DeleteLast ( struct Node * * head ) { struct Node * current = * head , * temp = * head , * previous ; if ( * head == NULL ) { printf ( " List is empty " return ; } if ( current -> next == current ) { * head = NULL ; return ; } while ( current -> next != * head ) { previous = current ; current = current -> next ; } previous -> next = current -> next ; * head = previous -> next ; free ( current ) ; return ; }
Efficient method to store a Lower Triangular Matrix using Column | C program for the above approach ; Dimensions of the matrix ; Structure of a memory efficient matrix ; Function to set the values in the Matrix ; Function to store the values in the Matrix ; Function to display the elements of the matrix ; Traverse the matrix ; Function to generate an efficient matrix ; Declare efficient Matrix ; Initialize the Matrix ; Set the values in matrix ; Return the matrix ; Driver Code ; Given Input ; Function call to create a memory efficient matrix ; Function call to print the Matrix
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE const int N = 5 ; struct Matrix { int * A ; int size ; } ; void Set ( struct Matrix * m , int i , int j , int x ) { if ( i >= j ) m -> A [ ( ( m -> size ) * ( j - 1 ) - ( ( ( j - 2 ) * ( j - 1 ) ) / 2 ) + ( i - j ) ) ] = x ; } int Get ( struct Matrix m , int i , int j ) { if ( i >= j ) return m . A [ ( ( m . size ) * ( j - 1 ) - ( ( ( j - 2 ) * ( j - 1 ) ) / 2 ) + ( i - j ) ) ] ; else return 0 ; } void Display ( struct Matrix m ) { for ( int i = 1 ; i <= m . size ; i ++ ) { for ( int j = 1 ; j <= m . size ; j ++ ) { if ( i >= j ) printf ( " % d ▁ " , m . A [ ( ( m . size ) * ( j - 1 ) - ( ( ( j - 2 ) * ( j - 1 ) ) / 2 ) + ( i - j ) ) ] ) ; else printf ( "0 ▁ " ) ; } printf ( " STRNEWLINE " ) ; } } struct Matrix createMat ( int Mat [ N ] [ N ] ) { struct Matrix mat ; mat . size = N ; mat . A = ( int * ) malloc ( mat . size * ( mat . size + 1 ) / 2 * sizeof ( int ) ) ; for ( int i = 1 ; i <= mat . size ; i ++ ) { for ( int j = 1 ; j <= mat . size ; j ++ ) { Set ( & mat , i , j , Mat [ i - 1 ] [ j - 1 ] ) ; } } return mat ; } int main ( ) { int Mat [ 5 ] [ 5 ] = { { 1 , 0 , 0 , 0 , 0 } , { 1 , 2 , 0 , 0 , 0 } , { 1 , 2 , 3 , 0 , 0 } , { 1 , 2 , 3 , 4 , 0 } , { 1 , 2 , 3 , 4 , 5 } } ; struct Matrix mat = createMat ( Mat ) ; Display ( mat ) ; return 0 ; }
Count subarrays having sum of elements at even and odd positions equal | C program for the above approach ; Function to count subarrays in which sum of elements at even and odd positions are equal ; Initialize variables ; Iterate over the array ; Check if position is even then add to sum then add it to sum ; Else subtract it to sum ; Increment the count if the sum equals 0 ; Print the count of subarrays ; Driver Code ; Given array arr [ ] ; Size of the array ; Function call
#include <stdio.h> NEW_LINE void countSubarrays ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; for ( int j = i ; j < n ; j ++ ) { if ( ( j - i ) % 2 == 0 ) sum += arr [ j ] ; else sum -= arr [ j ] ; if ( sum == 0 ) count ++ ; } } printf ( " % d " , count ) ; } int main ( ) { int arr [ ] = { 2 , 4 , 6 , 4 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countSubarrays ( arr , n ) ; return 0 ; }
Tail Recursion | An example of tail recursive function ; The last executed statement is recursive call
void print ( int n ) { if ( n < 0 ) return ; cout << " ▁ " << n ; print ( n - 1 ) ; }
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 ; If currIndex stores even index or odd position ; Driver Code
#include <stdio.h> NEW_LINE void printAlter ( int arr [ ] , int N ) { for ( int currIndex = 0 ; currIndex < N ; currIndex ++ ) { if ( currIndex % 2 == 0 ) { printf ( " % d ▁ " , arr [ currIndex ] ) ; } } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printAlter ( arr , N ) ; }
Shuffle 2 n integers as a1 | C program for the above approach ; Function to reverse the array from the position ' start ' to position ' end ' ; Stores mid of start and end ; Traverse the array in the range [ start , end ] ; Stores arr [ start + i ] ; Update arr [ start + i ] ; Update arr [ end - i ] ; Utility function to shuffle the given array in the of form { a1 , b1 , a2 , b2 , ... . an , bn } ; Stores the length of the array ; If length of the array is 2 ; Stores mid of the { start , end } ; Divide array into two halves of even length ; Update mid ; Calculate the mid - points of both halves of the array ; Reverse the subarray made from mid1 to mid2 ; Reverse the subarray made from mid1 to mid ; Reverse the subarray made from mid to mid2 ; Recursively calls for both the halves of the array ; Function to shuffle the given array in the form of { a1 , b1 , a2 , b2 , ... . an , bn } ; Function Call ; Print the modified array ; Driver Code ; Given array ; Size of the array ; Shuffles the given array to the required permutation
#include <stdio.h> NEW_LINE void reverse ( int arr [ ] , int start , int end ) { int mid = ( end - start + 1 ) / 2 ; for ( int i = 0 ; i < mid ; i ++ ) { int temp = arr [ start + i ] ; arr [ start + i ] = arr [ end - i ] ; arr [ end - i ] = temp ; } return ; } void shuffleArrayUtil ( int arr [ ] , int start , int end ) { int i ; int l = end - start + 1 ; if ( l == 2 ) return ; int mid = start + l / 2 ; if ( l % 4 ) { mid -= 1 ; } int mid1 = start + ( mid - start ) / 2 ; int mid2 = mid + ( end + 1 - mid ) / 2 ; reverse ( arr , mid1 , mid2 - 1 ) ; reverse ( arr , mid1 , mid - 1 ) ; reverse ( arr , mid , mid2 - 1 ) ; shuffleArrayUtil ( arr , start , mid - 1 ) ; shuffleArrayUtil ( arr , mid , end ) ; } void shuffleArray ( int arr [ ] , int N , int start , int end ) { shuffleArrayUtil ( arr , start , end ) ; for ( int i = 0 ; i < N ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 2 , 4 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; shuffleArray ( arr , N , 0 , N - 1 ) ; return 0 ; }
Check if two arrays can be made equal by reversing subarrays multiple times | C implementation to check if two arrays can be made equal ; Function to check if array B can be made equal to array A ; Sort both arrays ; Check both arrays equal or not ; Driver Code
#include <stdio.h> NEW_LINE #include <math.h> NEW_LINE int sort ( int a [ ] , int n ) { int i , j , tmp ; for ( i = 0 ; i < n ; i ++ ) { for ( j = i + 1 ; j < n ; j ++ ) { if ( a [ j ] < a [ i ] ) { tmp = a [ i ] ; a [ i ] = a [ j ] ; a [ j ] = tmp ; } } } return 0 ; } int canMadeEqual ( int A [ ] , int B [ ] , int n ) { int i ; sort ( A , n ) ; sort ( B , n ) ; for ( i = 0 ; i < n ; i ++ ) { if ( A [ i ] != B [ i ] ) { return ( 0 ) ; } } return ( 1 ) ; } int main ( ) { int A [ ] = { 1 , 2 , 3 } ; int n ; int B [ ] = { 1 , 3 , 2 } ; n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; if ( canMadeEqual ( A , B , n ) ) { printf ( " Yes " ) ; } else { printf ( " No " ) ; } return 0 ; }
Bubble Sort for Linked List by Swapping nodes | C program to sort Linked List using Bubble Sort by swapping nodes ; structure for a node ; Function to swap the nodes ; Function to sort the list ; update the link after swapping ; break if the loop ended without any swap ; Function to print the list ; Function to insert a struct Node at the beginning of a linked list ; Driver Code ; start with empty linked list ; Create linked list from the array arr [ ] ; print list before sorting ; sort the linked list ; print list after sorting
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * next ; } Node ; struct Node * swap ( struct Node * ptr1 , struct Node * ptr2 ) { struct Node * tmp = ptr2 -> next ; ptr2 -> next = ptr1 ; ptr1 -> next = tmp ; return ptr2 ; } int bubbleSort ( struct Node * * head , int count ) { struct Node * * h ; int i , j , swapped ; for ( i = 0 ; i <= count ; i ++ ) { h = head ; swapped = 0 ; for ( j = 0 ; j < count - i - 1 ; j ++ ) { struct Node * p1 = * h ; struct Node * p2 = p1 -> next ; if ( p1 -> data > p2 -> data ) { * h = swap ( p1 , p2 ) ; swapped = 1 ; } h = & ( * h ) -> next ; } if ( swapped == 0 ) break ; } } void printList ( struct Node * n ) { while ( n != NULL ) { printf ( " % d ▁ - > ▁ " , n -> data ) ; n = n -> next ; } printf ( " STRNEWLINE " ) ; } void insertAtTheBegin ( struct Node * * start_ref , int data ) { struct Node * ptr1 = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; ptr1 -> data = data ; ptr1 -> next = * start_ref ; * start_ref = ptr1 ; } int main ( ) { int arr [ ] = { 78 , 20 , 10 , 32 , 1 , 5 } ; int list_size , i ; struct Node * start = NULL ; list_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; for ( i = 0 ; i < list_size ; i ++ ) insertAtTheBegin ( & start , arr [ i ] ) ; printf ( " Linked ▁ list ▁ before ▁ sorting STRNEWLINE " ) ; printList ( start ) ; bubbleSort ( & start , list_size ) ; printf ( " Linked ▁ list ▁ after ▁ sorting STRNEWLINE " ) ; printList ( start ) ; return 0 ; }
In | C ++ program in - place Merge Sort ; Merges two subarrays of arr [ ] . First subarray is arr [ l . . m ] Second subarray is arr [ m + 1. . r ] Inplace Implementation ; If the direct merge is already sorted ; Two pointers to maintain start of both arrays to merge ; If element 1 is in right place ; Shift all the elements between element 1 element 2 , right by 1. ; Update all the pointers ; l is for left index and r is right index of the sub - array of arr to be sorted ; Same as ( l + r ) / 2 , but avoids overflow for large l and r ; Sort first and second halves ; Function to print an array ; Driver program to test above functions
#include <stdio.h> NEW_LINE void merge ( int arr [ ] , int start , int mid , int end ) { int start2 = mid + 1 ; if ( arr [ mid ] <= arr [ start2 ] ) { return ; } while ( start <= mid && start2 <= end ) { if ( arr [ start ] <= arr [ start2 ] ) { start ++ ; } else { int value = arr [ start2 ] ; int index = start2 ; while ( index != start ) { arr [ index ] = arr [ index - 1 ] ; index -- ; } arr [ start ] = value ; start ++ ; mid ++ ; start2 ++ ; } } } void mergeSort ( int arr [ ] , int l , int r ) { if ( l < r ) { int m = l + ( r - l ) / 2 ; mergeSort ( arr , l , m ) ; mergeSort ( arr , m + 1 , r ) ; merge ( arr , l , m , r ) ; } } void printArray ( int A [ ] , int size ) { int i ; for ( i = 0 ; i < size ; i ++ ) printf ( " % d ▁ " , A [ i ] ) ; printf ( " STRNEWLINE " ) ; } int main ( ) { int arr [ ] = { 12 , 11 , 13 , 5 , 6 , 7 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; mergeSort ( arr , 0 , arr_size - 1 ) ; printArray ( arr , arr_size ) ; return 0 ; }
Dual pivot Quicksort | C program to implement dual pivot QuickSort ; lp means left pivot , and rp means right pivot . ; p is the left pivot , and q is the right pivot . ; if elements are less than the left pivot ; if elements are greater than or equal to the right pivot ; bring pivots to their appropriate positions . ; returning the indices of the pivots . * lp = j ; because we cannot return two elements from a function . ; Driver code
#include <stdio.h> NEW_LINE int partition ( int * arr , int low , int high , int * lp ) ; void swap ( int * a , int * b ) { int temp = * a ; * a = * b ; * b = temp ; } void DualPivotQuickSort ( int * arr , int low , int high ) { if ( low < high ) { int lp , rp ; rp = partition ( arr , low , high , & lp ) ; DualPivotQuickSort ( arr , low , lp - 1 ) ; DualPivotQuickSort ( arr , lp + 1 , rp - 1 ) ; DualPivotQuickSort ( arr , rp + 1 , high ) ; } } int partition ( int * arr , int low , int high , int * lp ) { if ( arr [ low ] > arr [ high ] ) swap ( & arr [ low ] , & arr [ high ] ) ; int j = low + 1 ; int g = high - 1 , k = low + 1 , p = arr [ low ] , q = arr [ high ] ; while ( k <= g ) { if ( arr [ k ] < p ) { swap ( & arr [ k ] , & arr [ j ] ) ; j ++ ; } else if ( arr [ k ] >= q ) { while ( arr [ g ] > q && k < g ) g -- ; swap ( & arr [ k ] , & arr [ g ] ) ; g -- ; if ( arr [ k ] < p ) { swap ( & arr [ k ] , & arr [ j ] ) ; j ++ ; } } k ++ ; } j -- ; g ++ ; swap ( & arr [ low ] , & arr [ j ] ) ; swap ( & arr [ high ] , & arr [ g ] ) ; return g ; } int main ( ) { int arr [ ] = { 24 , 8 , 42 , 75 , 29 , 77 , 38 , 57 } ; DualPivotQuickSort ( arr , 0 , 7 ) ; printf ( " Sorted ▁ array : ▁ " ) ; for ( int i = 0 ; i < 8 ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; printf ( " STRNEWLINE " ) ; return 0 ; }
Construct a graph using N vertices whose shortest distance between K pair of vertices is 2 | C program to implement the above approach ; Function to construct the simple and connected graph such that the distance between exactly K pairs of vertices is 2 ; Stores maximum possible count of edges in a graph ; Base Case ; Stores count of edges in a graph ; Connect all vertices of pairs ( i , j ) ; Update ; Driver Code
#include <stdio.h> NEW_LINE void constGraphWithCon ( int N , int K ) { int Max = ( ( N - 1 ) * ( N - 2 ) ) / 2 ; if ( K > Max ) { printf ( " - 1" ) ; return ; } int count = 0 ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = i + 1 ; j <= N ; j ++ ) { printf ( " % d ▁ % d STRNEWLINE " , i , j ) ; count ++ ; if ( count == N * ( N - 1 ) / 2 - K ) break ; } if ( count == N * ( N - 1 ) / 2 - K ) break ; } } int main ( ) { int N = 5 , K = 3 ; constGraphWithCon ( N , K ) ; return 0 ; }
Find N distinct numbers whose Bitwise XOR is equal to K | C program for the above approach ; Function to find N integers having Bitwise XOR equal to K ; Base Cases ; Assign values to P and Q ; Stores Bitwise XOR of the first ( N - 3 ) elements ; Print the first N - 3 elements ; Calculate Bitwise XOR of first ( N - 3 ) elements ; Driver Code ; Function Call
#include <stdio.h> NEW_LINE void findArray ( int N , int K ) { if ( N == 1 ) { printf ( " % d " , K ) ; return ; } if ( N == 2 ) { printf ( " % d ▁ % d " , 0 , K ) ; return ; } int P = N - 2 ; int Q = N - 1 ; int VAL = 0 ; for ( int i = 1 ; i <= ( N - 3 ) ; i ++ ) { printf ( " % d ▁ " , i ) ; VAL ^= i ; } if ( VAL == K ) { printf ( " % d ▁ % d ▁ % d " , P , Q , P ^ Q ) ; } else { printf ( " % d ▁ % d ▁ % d " , 0 , P , P ^ K ^ VAL ) ; } } int main ( ) { int N = 4 , X = 6 ; findArray ( N , X ) ; return 0 ; }
Count of N digit Numbers whose sum of every K consecutive digits is equal | C program for the above approach ; Function to count the number of N - digit numbers such that sum of every k consecutive digits are equal ; Range of numbers ; Extract digits of the number ; Store the sum of first K digits ; Check for every k - consecutive digits ; If sum is not equal then break the loop ; Increment the count if it satisfy the given condition ; Driver code ; Given N and K ; Function call
#include <math.h> NEW_LINE #include <stdio.h> NEW_LINE int countDigitSum ( int N , int K ) { int l = ( int ) pow ( 10 , N - 1 ) , r = ( int ) pow ( 10 , N ) - 1 ; int count = 0 ; for ( int i = l ; i <= r ; i ++ ) { int num = i ; int digits [ N ] ; for ( int j = N - 1 ; j >= 0 ; j -- ) { digits [ j ] = num % 10 ; num /= 10 ; } int sum = 0 , flag = 0 ; for ( int j = 0 ; j < K ; j ++ ) sum += digits [ j ] ; for ( int j = 1 ; j < N - K + 1 ; j ++ ) { int curr_sum = 0 ; for ( int m = j ; m < j + K ; m ++ ) curr_sum += digits [ m ] ; if ( sum != curr_sum ) { flag = 1 ; break ; } } if ( flag == 0 ) { count ++ ; } } return count ; } int main ( ) { int N = 2 , K = 1 ; printf ( " % d " , countDigitSum ( N , K ) ) ; return 0 ; }
Convert string to integer without using any in | C program for the above approach ; Function to convert string to integer without using functions ; Initialize a variable ; Iterate till length of the string ; Subtract 48 from the current digit ; Print the answer ; Driver Code ; Given string of number ; Function Call
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE void convert ( char s [ ] ) { int num = 0 ; int n = strlen ( s ) ; for ( int i = 0 ; i < n ; i ++ ) num = num * 10 + ( s [ i ] - 48 ) ; printf ( " % d " , num ) ; } int main ( ) { char s [ ] = "123" ; convert ( s ) ; return 0 ; }
Longest Arithmetic Progression | DP | The function returns true if there exist three elements in AP Assumption : set [ 0. . n - 1 ] is sorted . The code strictly implements the algorithm provided in the reference . ; One by fix every element as middle element ; Initialize i and k for the current j ; Find if there exist i and k that form AP with j as middle element
bool arithmeticThree ( int set [ ] , int n ) { for ( int j = 1 ; j < n - 1 ; j ++ ) { int i = j - 1 , k = j + 1 ; while ( i >= 0 && k <= n - 1 ) { if ( set [ i ] + set [ k ] == 2 * set [ j ] ) return true ; ( set [ i ] + set [ k ] < 2 * set [ j ] ) ? k ++ : i -- ; } } return false ; }
Maximum Sum Increasing Subsequence | DP | Dynamic Programming implementation of Maximum Sum Increasing Subsequence ( MSIS ) problem ; maxSumIS ( ) returns the maximum sum of increasing subsequence in arr [ ] of size n ; Initialize msis values for all indexes ; Compute maximum sum values in bottom up manner ; Pick maximum of all msis values ; Driver Code
#include <stdio.h> NEW_LINE int maxSumIS ( int arr [ ] , int n ) { int i , j , max = 0 ; int msis [ n ] ; for ( i = 0 ; i < n ; i ++ ) msis [ i ] = arr [ i ] ; for ( i = 1 ; i < n ; i ++ ) for ( j = 0 ; j < i ; j ++ ) if ( arr [ i ] > arr [ j ] && msis [ i ] < msis [ j ] + arr [ i ] ) msis [ i ] = msis [ j ] + arr [ i ] ; for ( i = 0 ; i < n ; i ++ ) if ( max < msis [ i ] ) max = msis [ i ] ; return max ; } int main ( ) { int arr [ ] = { 1 , 101 , 2 , 3 , 100 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Sum ▁ of ▁ maximum ▁ sum ▁ increasing ▁ " " subsequence ▁ is ▁ % d STRNEWLINE " , maxSumIS ( arr , n ) ) ; return 0 ; }
C / C ++ Program for Longest Increasing Subsequence | A Naive C recursive implementation of LIS problem ; To make use of recursive calls , this function must return two things : 1 ) Length of LIS ending with element arr [ n - 1 ] . We use max_ending_here for this purpose 2 ) Overall maximum as the LIS may end with an element before arr [ n - 1 ] max_ref is used this purpose . The value of LIS of full array of size n is stored in * max_ref which is our final result ; Base case ; ' max _ ending _ here ' is length of LIS ending with arr [ n - 1 ] ; Recursively get all LIS ending with arr [ 0 ] , arr [ 1 ] ... arr [ n - 2 ] . If arr [ i - 1 ] is smaller than arr [ n - 1 ] , and max ending with arr [ n - 1 ] needs to be updated , then update it ; Compare max_ending_here with the overall max . And update the overall max if needed ; Return length of LIS ending with arr [ n - 1 ] ; The wrapper function for _lis ( ) ; The max variable holds the result ; The function _lis ( ) stores its result in max ; returns max ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int _lis ( int arr [ ] , int n , int * max_ref ) { if ( n == 1 ) return 1 ; int res , max_ending_here = 1 ; for ( int i = 1 ; i < n ; i ++ ) { res = _lis ( arr , i , max_ref ) ; if ( arr [ i - 1 ] < arr [ n - 1 ] && res + 1 > max_ending_here ) max_ending_here = res + 1 ; } if ( * max_ref < max_ending_here ) * max_ref = max_ending_here ; return max_ending_here ; } int lis ( int arr [ ] , int n ) { int max = 1 ; _lis ( arr , n , & max ) ; return max ; } int main ( ) { int arr [ ] = { 10 , 22 , 9 , 33 , 21 , 50 , 41 , 60 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Length ▁ of ▁ lis ▁ is ▁ % d STRNEWLINE " , lis ( arr , n ) ) ; return 0 ; }
Overlapping Subproblems Property in Dynamic Programming | DP | a simple recursive program for Fibonacci numbers
int fib ( int n ) { if ( n <= 1 ) return n ; return fib ( n - 1 ) + fib ( n - 2 ) ; }
Count of number of given string in 2D character array | C code for finding count of string in a given 2D character array . ; utility function to search complete string from any given index of 2d char array ; through Backtrack searching in every directions ; Function to search the string in 2d array ; Driver code
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE #include <stdlib.h> NEW_LINE #define ARRAY_SIZE ( a ) (sizeof(a) / sizeof(*a)) NEW_LINE int internalSearch ( char * needle , int row , int col , char * * hay , int row_max , int col_max ) { int found = 0 ; if ( row >= 0 && row <= row_max && col >= 0 && col <= col_max && * needle == hay [ row ] [ col ] ) { char match = * needle ++ ; hay [ row ] [ col ] = 0 ; if ( * needle == 0 ) { found = 1 ; } else { found += internalSearch ( needle , row , col + 1 , hay , row_max , col_max ) ; found += internalSearch ( needle , row , col - 1 , hay , row_max , col_max ) ; found += internalSearch ( needle , row + 1 , col , hay , row_max , col_max ) ; found += internalSearch ( needle , row - 1 , col , hay , row_max , col_max ) ; } hay [ row ] [ col ] = match ; } return found ; } int searchString ( char * needle , int row , int col , char * * str , int row_count , int col_count ) { int found = 0 ; int r , c ; for ( r = 0 ; r < row_count ; ++ r ) { for ( c = 0 ; c < col_count ; ++ c ) { found += internalSearch ( needle , r , c , str , row_count - 1 , col_count - 1 ) ; } } return found ; } int main ( void ) { char needle [ ] = " MAGIC " ; char * input [ ] = { " BBABBM " , " CBMBBA " , " IBABBG " , " GOZBBI " , " ABBBBC " , " MCIGAM " } ; char * str [ ARRAY_SIZE ( input ) ] ; int i ; for ( i = 0 ; i < ARRAY_SIZE ( input ) ; ++ i ) { str [ i ] = malloc ( strlen ( input [ i ] ) ) ; strcpy ( str [ i ] , input [ i ] ) ; } printf ( " count : ▁ % d STRNEWLINE " , searchString ( needle , 0 , 0 , str , ARRAY_SIZE ( str ) , strlen ( str [ 0 ] ) ) ) ; return 0 ; }
Check if given Parentheses expression is balanced or not | C program of the above approach ; Function to check if parentheses are balanced ; Initialising Variables ; Traversing the Expression ; It is a closing parenthesis ; This means there are more Closing parenthesis than opening ones ; If count is not zero , It means there are more opening parenthesis ; Driver code
#include <stdbool.h> NEW_LINE #include <stdio.h> NEW_LINE bool isBalanced ( char exp [ ] ) { bool flag = true ; int count = 0 ; for ( int i = 0 ; exp [ i ] != ' \0' ; i ++ ) { if ( exp [ i ] == ' ( ' ) { count ++ ; } else { count -- ; } if ( count < 0 ) { flag = false ; break ; } } if ( count != 0 ) { flag = false ; } return flag ; } int main ( ) { char exp1 [ ] = " ( ( ( ) ) ) ( ) ( ) " ; if ( isBalanced ( exp1 ) ) printf ( " Balanced ▁ STRNEWLINE " ) ; else printf ( " Not ▁ Balanced ▁ STRNEWLINE " ) ; char exp2 [ ] = " ( ) ) ( ( ( ) ) " ; if ( isBalanced ( exp2 ) ) printf ( " Balanced ▁ STRNEWLINE " ) ; else printf ( " Not ▁ Balanced ▁ STRNEWLINE " ) ; return 0 ; }
Shortest distance to every other character from given character | C implementation of above approach ; Function to return required vector of distances ; list to hold position of c in s ; length of string ; To hold size of list ; Iterate over string to create list ; max value of p2 ; Initialize the pointers ; Create result array ; Values at current pointers ; Current Index is before than p1 ; Current Index is between p1 and p2 ; Current Index is nearer to p1 ; Current Index is nearer to p2 ; Move pointer 1 step ahead ; Current index is after p2 ; Driver code
#include <stdio.h> NEW_LINE #define MAX_SIZE 100 NEW_LINE void shortestToChar ( char s [ ] , char c , int * res ) { int list [ MAX_SIZE ] ; int len = 0 ; int l = 0 ; while ( s [ len ] != ' \0' ) { if ( s [ len ] == c ) { list [ l ] = len ; l ++ ; } len ++ ; } int p1 , p2 , v1 , v2 ; l = l - 1 ; p1 = 0 ; p2 = l > 0 ? 1 : 0 ; for ( int i = 0 ; i < len ; i ++ ) { v1 = list [ p1 ] ; v2 = list [ p2 ] ; if ( i <= v1 ) { res [ i ] = ( v1 - i ) ; } else if ( i <= v2 ) { if ( i - v1 < v2 - i ) { res [ i ] = ( i - v1 ) ; } else { res [ i ] = ( v2 - i ) ; p1 = p2 ; p2 = p2 < l ? ( p2 + 1 ) : p2 ; } } else { res [ i ] = ( i - v2 ) ; } } } int main ( ) { char s [ ] = " geeksforgeeks " ; char c = ' e ' ; int res [ MAX_SIZE ] ; shortestToChar ( s , c , res ) ; int i = 0 ; while ( s [ i ] != ' \0' ) printf ( " % d ▁ " , res [ i ++ ] ) ; return 0 ; }
Reverse String according to the number of words | C program to reverse string according to the number of words ; Reverse the letters of the word ; Temporary variable to store character ; Swapping the first and last character ; This function forms the required string ; Checking the number of words present in string to reverse ; Reverse the letter of the words ; Driver Code
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE void reverse ( char str [ ] , int start , int end ) { char temp ; while ( start <= end ) { temp = str [ start ] ; str [ start ] = str [ end ] ; str [ end ] = temp ; start ++ ; end -- ; } } void reverseletter ( char str [ ] , int start , int end ) { int wstart , wend ; for ( wstart = wend = start ; wend < end ; wend ++ ) { if ( str [ wend ] == ' ▁ ' ) continue ; while ( str [ wend ] != ' ▁ ' && wend <= end ) wend ++ ; wend -- ; reverse ( str , wstart , wend ) ; } } int main ( ) { char str [ 1000 ] = " Ashish ▁ Yadav ▁ Abhishek ▁ Rajput ▁ Sunil ▁ Pundir " ; reverseletter ( str , 0 , strlen ( str ) - 1 ) ; printf ( " % s " , str ) ; return 0 ; }
Number of substrings with count of each character as k |
#include <stdbool.h> NEW_LINE #include <stdio.h> NEW_LINE #include <string.h> NEW_LINE int min ( int a , int b ) { return a < b ? a : b ; } bool have_same_frequency ( int freq [ ] , int k ) { for ( int i = 0 ; i < 26 ; i ++ ) { if ( freq [ i ] != 0 && freq [ i ] != k ) { return false ; } } return true ; } int count_substrings ( char * s , int n , int k ) { int count = 0 ; int distinct = 0 ; bool have [ 26 ] = { false } ; for ( int i = 0 ; i < n ; i ++ ) { have [ s [ i ] - ' a ' ] = true ; } for ( int i = 0 ; i < 26 ; i ++ ) { if ( have [ i ] ) { distinct ++ ; } } for ( int length = 1 ; length <= distinct ; length ++ ) { int window_length = length * k ; int freq [ 26 ] = { 0 } ; int window_start = 0 ; int window_end = window_start + window_length - 1 ; for ( int i = window_start ; i <= min ( window_end , n - 1 ) ; i ++ ) { freq [ s [ i ] - ' a ' ] ++ ; } while ( window_end < n ) { if ( have_same_frequency ( freq , k ) ) { count ++ ; } freq [ s [ window_start ] - ' a ' ] -- ; window_start ++ ; window_end ++ ; if ( window_end < n ) { freq [ s [ window_end ] - ' a ' ] ++ ; } } } return count ; } int main ( ) { char * s = " aabbcc " ; int k = 2 ; printf ( " % d STRNEWLINE " , count_substrings ( s , 6 , k ) ) ; s = " aabbc " ; k = 2 ; printf ( " % d STRNEWLINE " , count_substrings ( s , 5 , k ) ) ; return 0 ; }
Toggle case of a string using Bitwise Operators | C program to get toggle case of a string ; tOGGLE cASE = swaps CAPS to lower case and lower case to CAPS ; Bitwise EXOR with 32 ; Driver Code
#include <stdio.h> NEW_LINE char * toggleCase ( char * a ) { for ( int i = 0 ; a [ i ] != ' \0' ; i ++ ) { a [ i ] ^= 32 ; } return a ; } int main ( ) { char str [ ] = " CheRrY " ; printf ( " Toggle ▁ case : ▁ % s STRNEWLINE " , toggleCase ( str ) ) ; printf ( " Original ▁ string : ▁ % s " , toggleCase ( str ) ) ; return 0 ; }
Write your own atoi ( ) |
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <string.h> NEW_LINE int main ( ) { int val ; char strn1 [ ] = "12546" ; val = atoi ( strn1 ) ; printf ( " String ▁ value ▁ = ▁ % s STRNEWLINE " , strn1 ) ; printf ( " Integer ▁ value ▁ = ▁ % d STRNEWLINE " , val ) ; char strn2 [ ] = " GeeksforGeeks " ; val = atoi ( strn2 ) ; printf ( " String ▁ value ▁ = ▁ % s STRNEWLINE " , strn2 ) ; printf ( " Integer ▁ value ▁ = ▁ % d STRNEWLINE " , val ) ; return ( 0 ) ; }
Write your own strcmp that ignores cases | ; implementation of strcmp that ignores cases ; If characters are same or inverting the 6 th bit makes them same ; Compare the last ( or first mismatching in case of not same ) characters ; Set the 6 th bit in both , then compare ; Driver program to test above function
#include <stdio.h> NEW_LINE int ic_strcmp ( char * s1 , char * s2 ) { int i ; for ( i = 0 ; s1 [ i ] && s2 [ i ] ; ++ i ) { if ( s1 [ i ] == s2 [ i ] || ( s1 [ i ] ^ 32 ) == s2 [ i ] ) continue ; else break ; } if ( s1 [ i ] == s2 [ i ] ) return 0 ; if ( ( s1 [ i ] 32 ) < ( s2 [ i ] 32 ) ) return -1 ; return 1 ; } int main ( void ) { printf ( " ret : ▁ % d STRNEWLINE " , ic_strcmp ( " Geeks " , " apple " ) ) ; printf ( " ret : ▁ % d STRNEWLINE " , ic_strcmp ( " " , " ABCD " ) ) ; printf ( " ret : ▁ % d STRNEWLINE " , ic_strcmp ( " ABCD " , " z " ) ) ; printf ( " ret : ▁ % d STRNEWLINE " , ic_strcmp ( " ABCD " , " abcdEghe " ) ) ; printf ( " ret : ▁ % d STRNEWLINE " , ic_strcmp ( " GeeksForGeeks " , " gEEksFORGeEKs " ) ) ; printf ( " ret : ▁ % d STRNEWLINE " , ic_strcmp ( " GeeksForGeeks " , " geeksForGeeks " ) ) ; return 0 ; }
Check whether two strings are anagram of each other | C program to check if two strings are anagrams of each other ; function to check whether two strings are anagram of each other ; Create 2 count arrays and initialize all values as 0 ; For each character in input strings , increment count in the corresponding count array ; If both strings are of different length . Removing this condition will make the program fail for strings like " aaca " and " aca " ; Compare count arrays ; Driver code ; Function Call
#include <stdio.h> NEW_LINE #define NO_OF_CHARS 256 NEW_LINE bool areAnagram ( char * str1 , char * str2 ) { int count1 [ NO_OF_CHARS ] = { 0 } ; int count2 [ NO_OF_CHARS ] = { 0 } ; int i ; for ( i = 0 ; str1 [ i ] && str2 [ i ] ; i ++ ) { count1 [ str1 [ i ] ] ++ ; count2 [ str2 [ i ] ] ++ ; } if ( str1 [ i ] str2 [ i ] ) return false ; for ( i = 0 ; i < NO_OF_CHARS ; i ++ ) if ( count1 [ i ] != count2 [ i ] ) return false ; return true ; } int main ( ) { char str1 [ ] = " geeksforgeeks " ; char str2 [ ] = " forgeeksgeeks " ; if ( areAnagram ( str1 , str2 ) ) printf ( " The ▁ two ▁ strings ▁ are ▁ anagram ▁ of ▁ each ▁ other " ) ; else printf ( " The ▁ two ▁ strings ▁ are ▁ not ▁ anagram ▁ of ▁ each ▁ " " other " ) ; return 0 ; }
Heptacontagon Number | C program for above approach ; Finding the nth heptacontagon Number ; Driver code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int heptacontagonNum ( int n ) { return ( 68 * n * n - 66 * n ) / 2 ; } int main ( ) { int N = 3 ; printf ( "3rd ▁ heptacontagon ▁ Number ▁ is ▁ = ▁ % d " , heptacontagonNum ( N ) ) ; return 0 ; }
Compute maximum of two integers in C / C ++ using Bitwise Operators | C program for the above approach ; Function to find the largest number ; Perform the subtraction ; Right shift and Bitwise AND ; Find the maximum number ; Return the maximum value ; Driver Code ; Function Call
#include <stdio.h> NEW_LINE int findMax ( int a , int b ) { int z , i , max ; z = a - b ; i = ( z >> 31 ) & 1 ; max = a - ( i * z ) ; return max ; } int main ( ) { int A = 40 , B = 54 ; printf ( " % d " , findMax ( A , B ) ) ; return 0 ; }
C / C ++ program for Armstrong Numbers | C program to find Armstrong number ; Function to calculate N raised to the power D ; Function to calculate the order of the number ; For each digit ; Function to check whether the given number is Armstrong number or not ; Calling order function ; For each digit ; If satisfies Armstrong condition ; Driver Code ; Given Number N ; Function Call
#include <stdio.h> NEW_LINE int power ( int N , unsigned int D ) { if ( D == 0 ) return 1 ; if ( D % 2 == 0 ) return power ( N , D / 2 ) * power ( N , D / 2 ) ; return N * power ( N , D / 2 ) * power ( N , D / 2 ) ; } int order ( int N ) { int r = 0 ; while ( N ) { r ++ ; N = N / 10 ; } return r ; } int isArmstrong ( int N ) { int D = order ( N ) ; int temp = N , sum = 0 ; while ( temp ) { int Ni = temp % 10 ; sum += power ( Ni , D ) ; temp = temp / 10 ; } if ( sum == N ) return 1 ; else return 0 ; } int main ( ) { int N = 153 ; if ( isArmstrong ( N ) == 1 ) printf ( " True STRNEWLINE " ) ; else printf ( " False STRNEWLINE " ) ; return 0 ; }
C / C ++ Program to find Prime Numbers between given range | C program to find the prime numbers between a given interval ; Function for print prime number in given range ; Traverse each number in the interval with the help of for loop ; Skip 0 and 1 as they are neither prime nor composite ; flag variable to tell if i is prime or not ; Iterate to check if i is prime or not ; flag = 1 means i is prime and flag = 0 means i is not prime ; Driver Code ; Given Range ; Function Call
#include <stdio.h> NEW_LINE void primeInRange ( int L , int R ) { int i , j , flag ; for ( i = L ; i <= R ; i ++ ) { if ( i == 1 i == 0 ) continue ; flag = 1 ; for ( j = 2 ; j <= i / 2 ; ++ j ) { if ( i % j == 0 ) { flag = 0 ; break ; } } if ( flag == 1 ) printf ( " % d ▁ " , i ) ; } } int main ( ) { int L = 1 ; int R = 10 ; primeInRange ( L , R ) ; return 0 ; }
Check whether count of odd and even factors of a number are equal | C code for the above approach ; Function to check condition ; Driver Code
#include <stdio.h> NEW_LINE #define lli long long int NEW_LINE void isEqualFactors ( lli N ) { if ( ( N % 2 == 0 ) && ( N % 4 != 0 ) ) printf ( " YES STRNEWLINE " ) ; else printf ( " NO STRNEWLINE " ) ; } int main ( ) { lli N = 10 ; isEqualFactors ( N ) ; N = 125 ; isEqualFactors ( N ) ; return 0 ; }
Lynch | C implementation for the above approach ; Function to check the divisibility of the number by its digit . ; If the digit divides the number then return true else return false . ; Function to check if all digits of n divide it or not ; Taking the digit of the number into digit var . ; Function to check if N has all distinct digits ; Create an array of size 10 and initialize all elements as false . This array is used to check if a digit is already seen or not . ; Traverse through all digits of given number ; Find the last digit ; If digit is already seen , return false ; Mark this digit as seen ; Remove the last digit from number ; Function to check Lynch - Bell numbers ; Driver Code ; Given number N ; Function call
#include <stdio.h> NEW_LINE int checkDivisibility ( int n , int digit ) { return ( digit != 0 && n % digit == 0 ) ; } int isAllDigitsDivide ( int n ) { int temp = n ; while ( temp > 0 ) { int digit = temp % 10 ; if ( ! ( checkDivisibility ( n , digit ) ) ) return 0 ; temp /= 10 ; } return 1 ; } int isAllDigitsDistinct ( int n ) { int arr [ 10 ] , i , digit ; for ( i = 0 ; i < 10 ; i ++ ) arr [ i ] = 0 ; while ( n > 0 ) { digit = n % 10 ; if ( arr [ digit ] ) return 0 ; arr [ digit ] = 1 ; n = n / 10 ; } return 1 ; } int isLynchBell ( int n ) { return isAllDigitsDivide ( n ) && isAllDigitsDistinct ( n ) ; } int main ( ) { int N = 12 ; if ( isLynchBell ( N ) ) printf ( " Yes " ) ; else printf ( " No " ) ; return 0 ; }
Maximum Bitwise AND pair ( X , Y ) from given range such that X and Y can be same | C implementation to find the Maximum Bitwise AND pair ( X , Y ) from given range such that X and Y can be same ; Function to return the maximum bitwise AND ; Driver code
#include <stdio.h> NEW_LINE int maximumAND ( int L , int R ) { return R ; } int main ( ) { int l = 3 ; int r = 7 ; printf ( " % d " , maximumAND ( l , r ) ) ; return 0 ; }
Average of Cubes of first N natural numbers | C program for the above approach ; Function to find average of cubes ; Store sum of cubes of numbers in the sum ; Calculate sum of cubes ; Return average ; Driver Code ; Given number ; Function Call
#include <stdio.h> NEW_LINE double findAverageOfCube ( int n ) { double sum = 0 ; int i ; for ( i = 1 ; i <= n ; i ++ ) { sum += i * i * i ; } return sum / n ; } int main ( ) { int n = 3 ; printf ( " % lf " , findAverageOfCube ( n ) ) ; return 0 ; }
C / C ++ program to add N distances given in inch | C program for the above approach ; Struct defined for the inch - feet system ; Variable to store the inch - feet ; Function to find the sum of all N set of Inch Feet distances ; Variable to store sum ; Traverse the InchFeet array ; Find the total sum of feet and inch ; If inch sum is greater than 11 convert it into feet as 1 feet = 12 inch ; Find integral part of inch_sum ; Delete the integral part x ; Add x % 12 to inch_sum ; Add x / 12 to feet_sum ; Print the corresponding sum of feet_sum and inch_sum ; Driver Code ; Given set of inch - feet ; Function Call
#include " stdio . h " NEW_LINE struct InchFeet { int feet ; float inch ; } ; void findSum ( struct InchFeet arr [ ] , int N ) { int feet_sum = 0 ; float inch_sum = 0.0 ; int x ; for ( int i = 0 ; i < N ; i ++ ) { feet_sum += arr [ i ] . feet ; inch_sum += arr [ i ] . inch ; } if ( inch_sum >= 12 ) { x = ( int ) inch_sum ; inch_sum -= x ; inch_sum += x % 12 ; feet_sum += x / 12 ; } printf ( " Feet ▁ Sum : ▁ % d STRNEWLINE " , feet_sum ) ; printf ( " Inch ▁ Sum : ▁ % .2f " , inch_sum ) ; } int main ( ) { struct InchFeet arr [ ] = { { 10 , 3.7 } , { 10 , 5.5 } , { 6 , 8.0 } } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findSum ( arr , N ) ; return 0 ; }
Logarithm tricks for Competitive Programming | C implementation to check if the number is power of K ; Function to check if the number is power of K ; Logarithm function to calculate value ; Compare to the result1 or result2 both are equal ; Driver Code
#include <stdio.h> NEW_LINE #include <math.h> NEW_LINE _Bool isPower ( int N , int K ) { int res1 = log ( N ) / log ( K ) ; double res2 = log ( N ) / log ( K ) ; return ( res1 == res2 ) ; } int main ( ) { int N = 8 ; int K = 2 ; if ( isPower ( N , K ) ) { printf ( " Yes " ) ; } else { printf ( " No " ) ; } return 0 ; }
Program for finding the Integral of a given function using Boole 's Rule | C program to implement Boole 's Rule on the given function ; Function to return the value of f ( x ) for the given value of x ; Function to computes the integrand of y at the given intervals of x with step size h and the initial limit a and final limit b ; Number of intervals ; Computing the step size ; Substituing a = 0 , b = 4 and h = 1 ; Driver code
#include <math.h> NEW_LINE #include <stdio.h> NEW_LINE float y ( float x ) { return ( 1 / ( 1 + x ) ) ; } float BooleRule ( float a , float b ) { int n = 4 ; int h ; h = ( ( b - a ) / n ) ; float sum = 0 ; float bl = ( 7 * y ( a ) + 32 * y ( a + h ) + 12 * y ( a + 2 * h ) + 32 * y ( a + 3 * h ) + 7 * y ( a + 4 * h ) ) * 2 * h / 45 ; sum = sum + bl ; return sum ; } int main ( ) { float lowlimit = 0 ; float upplimit = 4 ; printf ( " f ( x ) ▁ = ▁ % .4f " , BooleRule ( 0 , 4 ) ) ; return 0 ; }
Finding Integreand using Weedle 's Rule | C program to Implement Weedle 's Rule ; A sample function f ( x ) = 1 / ( 1 + x ^ 2 ) ; Function to find the integral value of f ( x ) with step size h , with initial lower limit and upper limit a and b ; Find step size h ; To store the final sum ; Find sum using Weedle 's Formula ; Return the final sum ; Driver Code ; lower limit and upper limit ; Function Call
#include <math.h> NEW_LINE #include <stdio.h> NEW_LINE float y ( float x ) { float num = 1 ; float denom = 1.0 + x * x ; return num / denom ; } float WeedleRule ( float a , float b ) { double h = ( b - a ) / 6 ; float sum = 0 ; sum = sum + ( ( ( 3 * h ) / 10 ) * ( y ( a ) + y ( a + 2 * h ) + 5 * y ( a + h ) + 6 * y ( a + 3 * h ) + y ( a + 4 * h ) + 5 * y ( a + 5 * h ) + y ( a + 6 * h ) ) ) ; return sum ; } int main ( ) { float a = 0 , b = 6 ; printf ( " f ( x ) ▁ = ▁ % f " , WeedleRule ( a , b ) ) ; return 0 ; }
Runge | C program to implement Runge Kutta method ; A sample differential equation " dy / dx ▁ = ▁ ( x ▁ - ▁ y ) /2" ; Finds value of y for a given x using step size h and initial value y0 at x0 . ; Count number of iterations using step size or step height h ; Iterate for number of iterations ; Apply Runge Kutta Formulas to find next value of y ; Update next value of y ; Update next value of x ; Driver Code
#include <stdio.h> NEW_LINE float dydx ( float x , float y ) { return ( x + y - 2 ) ; } float rungeKutta ( float x0 , float y0 , float x , float h ) { int n = ( int ) ( ( x - x0 ) / h ) ; float k1 , k2 ; float y = y0 ; for ( int i = 1 ; i <= n ; i ++ ) { k1 = h * dydx ( x0 , y ) ; k2 = h * dydx ( x0 + 0.5 * h , y + 0.5 * k1 ) ; y = y + ( 1.0 / 6.0 ) * ( k1 + 2 * k2 ) ; x0 = x0 + h ; } return y ; } int main ( ) { float x0 = 0 , y = 1 , x = 2 , h = 0.2 ; printf ( " y ( x ) ▁ = ▁ % f " , rungeKutta ( x0 , y , x , h ) ) ; return 0 ; }
Perimeter and Area of Varignon 's Parallelogram | C program to find the perimeter and area ; Function to find the perimeter ; Function to find the area ; Driver code
#include <stdio.h> NEW_LINE float per ( float a , float b ) { return ( a + b ) ; } float area ( float s ) { return ( s / 2 ) ; } int main ( ) { float a = 7 , b = 8 , s = 10 ; printf ( " % f STRNEWLINE " , per ( a , b ) ) ; printf ( " % f " , area ( s ) ) ; return 0 ; }
Area of a leaf inside a square | C program to find the area of leaf inside a square ; Function to find area of leaf ; Driver code
#include <stdio.h> NEW_LINE #define PI 3.14159265 NEW_LINE float area_leaf ( float a ) { return ( a * a * ( PI / 2 - 1 ) ) ; } int main ( ) { float a = 7 ; printf ( " % f " , area_leaf ( a ) ) ; return 0 ; }
Length of rope tied around three equal circles touching each other | C program to find the length of rope ; Function to find the length of rope ; Driver code
#include <stdio.h> NEW_LINE #define PI 3.14159265 NEW_LINE float length_rope ( float r ) { return ( ( 2 * PI * r ) + 6 * r ) ; } int main ( ) { float r = 7 ; printf ( " % f " , length_rope ( r ) ) ; return 0 ; }
Area of Incircle of a Right Angled Triangle | C program to find the area of incircle of right angled triangle ; Function to find area of incircle ; Driver code
#include <stdio.h> NEW_LINE #define PI 3.14159265 NEW_LINE float area_inscribed ( float P , float B , float H ) { return ( ( P + B - H ) * ( P + B - H ) * ( PI / 4 ) ) ; } int main ( ) { float P = 3 , B = 4 , H = 5 ; printf ( " % f " , area_inscribed ( P , B , H ) ) ; return 0 ; }
Area of Circumcircle of a Right Angled Triangle | C program to find the area of Cicumscribed circle of right angled triangle ; Function to find area of circumscribed circle ; Driver code
#include <stdio.h> NEW_LINE #define PI 3.14159265 NEW_LINE float area_circumscribed ( float c ) { return ( c * c * ( PI / 4 ) ) ; } int main ( ) { float c = 8 ; printf ( " % f " , area_circumscribed ( c ) ) ; return 0 ; }
Program to calculate the Area and Perimeter of Incircle of an Equilateral Triangle | C program to find the area of Inscribed circle of equilateral triangle ; function to find area of inscribed circle ; function to find Perimeter of inscribed circle ; Driver code
#include <math.h> NEW_LINE #include <stdio.h> NEW_LINE #define PI 3.14159265 NEW_LINE float area_inscribed ( float a ) { return ( a * a * ( PI / 12 ) ) ; } float perm_inscribed ( float a ) { return ( PI * ( a / sqrt ( 3 ) ) ) ; } int main ( ) { float a = 6 ; printf ( " Area ▁ of ▁ inscribed ▁ circle ▁ is ▁ : % f STRNEWLINE " , area_inscribed ( a ) ) ; printf ( " Perimeter ▁ of ▁ inscribed ▁ circle ▁ is ▁ : % f " , perm_inscribed ( a ) ) ; return 0 ; }
Program to find the Area and Perimeter of a Semicircle | C program to find the Area and Perimeter of a Semicircle ; Function for calculating the area ; Formula for finding the area ; Function for calculating the perimeter ; Formula for finding the perimeter ; driver code ; Get the radius ; Find the area ; Find the perimeter
#include <stdio.h> NEW_LINE float area ( float r ) { return ( 0.5 ) * ( 3.14 ) * ( r * r ) ; } float perimeter ( float r ) { return ( 3.14 ) * ( r ) ; } int main ( ) { float r = 10 ; printf ( " The ▁ Area ▁ of ▁ Semicircle : ▁ % f STRNEWLINE " , area ( r ) ) ; printf ( " The ▁ Perimeter ▁ of ▁ Semicircle : ▁ % f STRNEWLINE " , perimeter ( r ) ) ; return 0 ; }
Program to find equation of a plane passing through 3 points | C program to find equation of a plane passing through given 3 points . ; Function to find equation of plane . ; Driver Code
#include <stdio.h> NEW_LINE void equation_plane ( float x1 , float y1 , float z1 , float x2 , float y2 , float z2 , float x3 , float y3 , float z3 ) { float a1 = x2 - x1 ; float b1 = y2 - y1 ; float c1 = z2 - z1 ; float a2 = x3 - x1 ; float b2 = y3 - y1 ; float c2 = z3 - z1 ; float a = b1 * c2 - b2 * c1 ; float b = a2 * c1 - a1 * c2 ; float c = a1 * b2 - b1 * a2 ; float d = ( - a * x1 - b * y1 - c * z1 ) ; printf ( " equation ▁ of ▁ plane ▁ is ▁ % .2f ▁ x ▁ + ▁ % .2f " " ▁ y ▁ + ▁ % .2f ▁ z ▁ + ▁ % .2f ▁ = ▁ 0 . " , a , b , c , d ) ; return ; } int main ( ) { float x1 = -1 ; float y1 = 2 ; float z1 = 1 ; float x2 = 0 ; float y2 = -3 ; float z2 = 2 ; float x3 = 1 ; float y3 = 1 ; float z3 = -4 ; equation_plane ( x1 , y1 , z1 , x2 , y2 , z2 , x3 , y3 , z3 ) ; return 0 ; }
Perpendicular distance between a point and a Line in 2 D | C program to find the distance between a given point and a given line in 2 D . ; Function to find distance ; Driver Code
#include <stdio.h> NEW_LINE #include <math.h> NEW_LINE void shortest_distance ( float x1 , float y1 , float a , float b , float c ) { float d = fabs ( ( a * x1 + b * y1 + c ) ) / ( sqrt ( a * a + b * b ) ) ; printf ( " Perpendicular ▁ distance ▁ is ▁ % f STRNEWLINE " , d ) ; return ; } int main ( ) { float x1 = 5 ; float y1 = 6 ; float a = -2 ; float b = 3 ; float c = 4 ; shortest_distance ( x1 , y1 , a , b , c ) ; return 0 ; }
Program to determine the octant of the axial plane | C program to print octant of a given point . ; Function to print octant ; Driver Code
#include <stdio.h> NEW_LINE void octant ( float x , float y , float z ) { if ( x >= 0 && y >= 0 && z >= 0 ) printf ( " Point ▁ lies ▁ in ▁ 1st ▁ octant STRNEWLINE " ) ; else if ( x < 0 && y >= 0 && z >= 0 ) printf ( " Point ▁ lies ▁ in ▁ 2nd ▁ octant STRNEWLINE " ) ; else if ( x < 0 && y < 0 && z >= 0 ) printf ( " Point ▁ lies ▁ in ▁ 3rd ▁ octant STRNEWLINE " ) ; else if ( x >= 0 && y < 0 && z >= 0 ) printf ( " Point ▁ lies ▁ in ▁ 4th ▁ octant STRNEWLINE " ) ; else if ( x >= 0 && y >= 0 && z < 0 ) printf ( " Point ▁ lies ▁ in ▁ 5th ▁ octant STRNEWLINE " ) ; else if ( x < 0 && y >= 0 && z < 0 ) printf ( " Point ▁ lies ▁ in ▁ 6th ▁ octant STRNEWLINE " ) ; else if ( x < 0 && y < 0 && z < 0 ) printf ( " Point ▁ lies ▁ in ▁ 7th ▁ octant STRNEWLINE " ) ; else if ( x >= 0 && y < 0 && z < 0 ) printf ( " Point ▁ lies ▁ in ▁ 8th ▁ octant STRNEWLINE " ) ; } int main ( ) { float x = 2 , y = 3 , z = 4 ; octant ( x , y , z ) ; x = -4 , y = 2 , z = -8 ; octant ( x , y , z ) ; x = -6 , y = -2 , z = 8 ; octant ( x , y , z ) ; }
Maximum area of quadrilateral | CPP program to find maximum are of a quadrilateral ; Calculating the semi - perimeter of the given quadrilateral ; Applying Brahmagupta 's formula to get maximum area of quadrilateral ; Driver code
#include <stdio.h> NEW_LINE #include <math.h> NEW_LINE double maxArea ( double a , double b , double c , double d ) { double semiperimeter = ( a + b + c + d ) / 2 ; return sqrt ( ( semiperimeter - a ) * ( semiperimeter - b ) * ( semiperimeter - c ) * ( semiperimeter - d ) ) ; } int main ( ) { double a = 1 , b = 2 , c = 1 , d = 2 ; printf ( " % .2f STRNEWLINE " , maxArea ( a , b , c , d ) ) ; return 0 ; }
Find Array obtained after adding terms of AP for Q queries | C program for the above approach ; Function to find array after performing the given query to the array elements ; Traverse the given query ; Traverse the given array ; Update the value of A [ i ] ; Update the value of curr ; Print the array elements ; Driver Code ; Function Call
#include <stdio.h> NEW_LINE void addAP ( int A [ ] , int Q , int operations [ 2 ] [ 4 ] ) { for ( int j = 0 ; j < 2 ; ++ j ) { int L = operations [ j ] [ 0 ] , R = operations [ j ] [ 1 ] , a = operations [ j ] [ 2 ] , d = operations [ j ] [ 3 ] ; int curr = a ; for ( int i = L - 1 ; i < R ; i ++ ) { A [ i ] += curr ; curr += d ; } } for ( int i = 0 ; i < 4 ; ++ i ) printf ( " % d ▁ " , A [ i ] ) ; } int main ( ) { int A [ ] = { 5 , 4 , 2 , 8 } ; int Q = 2 ; int Query [ 2 ] [ 4 ] = { { 1 , 2 , 1 , 3 } , { 1 , 4 , 4 , 1 } } ; addAP ( A , Q , Query ) ; return 0 ; }
Estimating the value of Pi using Monte Carlo | Parallel Computing Method | C program for the above approach ; Function to find estimated value of PI using Monte Carlo algorithm ; Stores X and Y coordinates of a random point ; Stores distance of a random point from origin ; Stores number of points lying inside circle ; Stores number of points lying inside square ; Parallel calculation of random points lying inside a circle ; Initializes random points with a seed ; Finds random X co - ordinate ; Finds random X co - ordinate ; Finds the square of distance of point ( x , y ) from origin ; If d is less than or equal to 1 ; Increment pCircle by 1 ; Increment pSquare by 1 ; Stores the estimated value of PI ; Prints the value in pi ; Driver Code ; Input ; Function call
#include <omp.h> NEW_LINE #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <time.h> NEW_LINE void monteCarlo ( int N , int K ) { double x , y ; double d ; int pCircle = 0 ; int pSquare = 0 ; int i = 0 ; #pragma omp parallel firstprivate(x, y, d, i) reduction(+ : pCircle, pSquare) num_threads(K) NEW_LINE { srand48 ( ( int ) time ( NULL ) ) ; for ( i = 0 ; i < N ; i ++ ) { x = ( double ) drand48 ( ) ; y = ( double ) drand48 ( ) ; d = ( ( x * x ) + ( y * y ) ) ; if ( d <= 1 ) { pCircle ++ ; } pSquare ++ ; } } double pi = 4.0 * ( ( double ) pCircle / ( double ) ( pSquare ) ) ; printf ( " Final ▁ Estimation ▁ of ▁ Pi ▁ = ▁ % f STRNEWLINE " , pi ) ; } int main ( ) { int N = 100000 ; int K = 8 ; monteCarlo ( N , K ) ; }
Efficient method to store a Lower Triangular Matrix using row | C program for the above approach ; Dimensions of a matrix ; Structure of the efficient matrix ; Function to set the values in the Matrix ; Function to store the values in the Matrix ; Function to display the elements of the matrix ; Traverse the matrix ; Function to generate an efficient matrix ; Declare efficient Matrix ; Initialize the Matrix ; Set the values in matrix ; Return the matrix ; Driver Code ; Stores the efficient matrix ; Print the Matrix
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE const int N = 5 ; struct Matrix { int * A ; int size ; } ; void Set ( struct Matrix * mat , int i , int j , int x ) { if ( i >= j ) mat -> A [ i * ( i - 1 ) / 2 + j - 1 ] = x ; } int Get ( struct Matrix mat , int i , int j ) { if ( i >= j ) { return mat . A [ i * ( i - 1 ) / 2 + j - 1 ] ; } else { return 0 ; } } void Display ( struct Matrix mat ) { int i , j ; for ( i = 1 ; i <= mat . size ; i ++ ) { for ( j = 1 ; j <= mat . size ; j ++ ) { if ( i >= j ) { printf ( " % d ▁ " , mat . A [ i * ( i - 1 ) / 2 + j - 1 ] ) ; } else { printf ( "0 ▁ " ) ; } } printf ( " STRNEWLINE " ) ; } } struct Matrix createMat ( int Mat [ N ] [ N ] ) { struct Matrix mat ; mat . size = N ; mat . A = ( int * ) malloc ( mat . size * ( mat . size + 1 ) / 2 * sizeof ( int ) ) ; int i , j ; for ( i = 1 ; i <= mat . size ; i ++ ) { for ( j = 1 ; j <= mat . size ; j ++ ) { Set ( & mat , i , j , Mat [ i - 1 ] [ j - 1 ] ) ; } } return mat ; } int main ( ) { int Mat [ 5 ] [ 5 ] = { { 1 , 0 , 0 , 0 , 0 } , { 1 , 2 , 0 , 0 , 0 } , { 1 , 2 , 3 , 0 , 0 } , { 1 , 2 , 3 , 4 , 0 } , { 1 , 2 , 3 , 4 , 5 } } ; struct Matrix mat = createMat ( Mat ) ; Display ( mat ) ; return 0 ; }
Modulo Operator ( % ) in C / C ++ with Examples | Program to illustrate the working of the modulo operator ; To store two integer values ; To store the result of the modulo expression
#include <stdio.h> NEW_LINE int main ( void ) { int x , y ; int result ; x = -3 ; y = 4 ; result = x % y ; printf ( " % d " , result ) ; x = 4 ; y = -2 ; result = x % y ; printf ( " % d " , result ) ; x = -3 ; y = -4 ; result = x % y ; printf ( " % d " , result ) ; return 0 ; }
Program to compute log a to any base b ( logb a ) | C program to find log ( a ) on any base b ; Driver code
#include <math.h> NEW_LINE #include <stdio.h> NEW_LINE int log_a_to_base_b ( int a , int b ) { return log ( a ) / log ( b ) ; } int main ( ) { int a = 3 ; int b = 2 ; printf ( " % d STRNEWLINE " , log_a_to_base_b ( a , b ) ) ; a = 256 ; b = 4 ; printf ( " % d STRNEWLINE " , log_a_to_base_b ( a , b ) ) ; return 0 ; }
Program to compute log a to any base b ( logb a ) | C program to find log ( a ) on any base b using Recursion ; Recursive function to compute log a to the base b ; Driver code
#include <stdio.h> NEW_LINE int log_a_to_base_b ( int a , int b ) { return ( a > b - 1 ) ? 1 + log_a_to_base_b ( a / b , b ) : 0 ; } int main ( ) { int a = 3 ; int b = 2 ; printf ( " % d STRNEWLINE " , log_a_to_base_b ( a , b ) ) ; a = 256 ; b = 4 ; printf ( " % d STRNEWLINE " , log_a_to_base_b ( a , b ) ) ; return 0 ; }
Find Maximum and Minimum of two numbers using Absolute function | C program to find maximum and minimum using Absolute function ; Function to return maximum among the two numbers ; Function to return minimum among the two numbers ; Driver code ; Displaying the maximum value ; Displaying the minimum value
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int maximum ( int x , int y ) { return ( ( x + y + abs ( x - y ) ) / 2 ) ; } int minimum ( int x , int y ) { return ( ( x + y - abs ( x - y ) ) / 2 ) ; } void main ( ) { int x = 99 , y = 18 ; printf ( " Maximum : ▁ % d STRNEWLINE " , maximum ( x , y ) ) ; printf ( " Minimum : ▁ % d STRNEWLINE " , minimum ( x , y ) ) ; }
Program to Calculate e ^ x by Recursion ( using Taylor Series ) | C implementation of the approach ; Recursive Function with static variables p and f ; Termination condition ; Recursive call ; Update the power of x ; Factorial ; Driver code
#include <stdio.h> NEW_LINE double e ( int x , int n ) { static double p = 1 , f = 1 ; double r ; if ( n == 0 ) return 1 ; r = e ( x , n - 1 ) ; p = p * x ; f = f * n ; return ( r + p / f ) ; } int main ( ) { int x = 4 , n = 15 ; printf ( " % lf ▁ STRNEWLINE " , e ( x , n ) ) ; return 0 ; }
Midpoint ellipse drawing algorithm | C program for implementing Mid - Point Ellipse Drawing Algorithm ; Initial decision parameter of region 1 ; For region 1 ; Print points based on 4 - way symmetry ; Checking and updating value of decision parameter based on algorithm ; Decision parameter of region 2 ; Plotting points of region 2 ; printing points based on 4 - way symmetry ; Checking and updating parameter value based on algorithm ; Driver code ; To draw a ellipse of major and minor radius 15 , 10 centred at ( 50 , 50 )
#include <stdio.h> NEW_LINE void midptellipse ( int rx , int ry , int xc , int yc ) { float dx , dy , d1 , d2 , x , y ; x = 0 ; y = ry ; d1 = ( ry * ry ) - ( rx * rx * ry ) + ( 0.25 * rx * rx ) ; dx = 2 * ry * ry * x ; dy = 2 * rx * rx * y ; while ( dx < dy ) { printf ( " ( % f , ▁ % f ) STRNEWLINE " , x + xc , y + yc ) ; printf ( " ( % f , ▁ % f ) STRNEWLINE " , - x + xc , y + yc ) ; printf ( " ( % f , ▁ % f ) STRNEWLINE " , x + xc , - y + yc ) ; printf ( " ( % f , ▁ % f ) STRNEWLINE " , - x + xc , - y + yc ) ; if ( d1 < 0 ) { x ++ ; dx = dx + ( 2 * ry * ry ) ; d1 = d1 + dx + ( ry * ry ) ; } else { x ++ ; y -- ; dx = dx + ( 2 * ry * ry ) ; dy = dy - ( 2 * rx * rx ) ; d1 = d1 + dx - dy + ( ry * ry ) ; } } d2 = ( ( ry * ry ) * ( ( x + 0.5 ) * ( x + 0.5 ) ) ) + ( ( rx * rx ) * ( ( y - 1 ) * ( y - 1 ) ) ) - ( rx * rx * ry * ry ) ; while ( y >= 0 ) { printf ( " ( % f , ▁ % f ) STRNEWLINE " , x + xc , y + yc ) ; printf ( " ( % f , ▁ % f ) STRNEWLINE " , - x + xc , y + yc ) ; printf ( " ( % f , ▁ % f ) STRNEWLINE " , x + xc , - y + yc ) ; printf ( " ( % f , ▁ % f ) STRNEWLINE " , - x + xc , - y + yc ) ; if ( d2 > 0 ) { y -- ; dy = dy - ( 2 * rx * rx ) ; d2 = d2 + ( rx * rx ) - dy ; } else { y -- ; x ++ ; dx = dx + ( 2 * ry * ry ) ; dy = dy - ( 2 * rx * rx ) ; d2 = d2 + dx - dy + ( rx * rx ) ; } } } int main ( ) { midptellipse ( 10 , 15 , 50 , 50 ) ; return 0 ; }
Program to Convert Hexadecimal Number to Binary | C program to convert Hexadecimal number to Binary ; function to convert Hexadecimal to Binary Number ; driver code ; Get the Hexadecimal number ; Convert HexaDecimal to Binary
#include <stdio.h> NEW_LINE void HexToBin ( char * hexdec ) { long int i = 0 ; while ( hexdec [ i ] ) { switch ( hexdec [ i ] ) { case '0' : printf ( "0000" ) ; break ; case '1' : printf ( "0001" ) ; break ; case '2' : printf ( "0010" ) ; break ; case '3' : printf ( "0011" ) ; break ; case '4' : printf ( "0100" ) ; break ; case '5' : printf ( "0101" ) ; break ; case '6' : printf ( "0110" ) ; break ; case '7' : printf ( "0111" ) ; break ; case '8' : printf ( "1000" ) ; break ; case '9' : printf ( "1001" ) ; break ; case ' A ' : case ' a ' : printf ( "1010" ) ; break ; case ' B ' : case ' b ' : printf ( "1011" ) ; break ; case ' C ' : case ' c ' : printf ( "1100" ) ; break ; case ' D ' : case ' d ' : printf ( "1101" ) ; break ; case ' E ' : case ' e ' : printf ( "1110" ) ; break ; case ' F ' : case ' f ' : printf ( "1111" ) ; break ; default : printf ( " Invalid hexadecimal digit % c " , hexdec [ i ] ) ; } i ++ ; } } int main ( ) { char hexdec [ 100 ] = "1AC5" ; printf ( " Equivalent Binary value is : " HexToBin ( hexdec ) ; }
How to access elements of a Square Matrix | C Program to read a square matrix and print the elements on secondary diagonal ; Get the square matrix ; Display the matrix ; Print the elements on secondary diagonal ; check for elements on secondary diagonal
#include <stdio.h> NEW_LINE int main ( ) { int matrix [ 5 ] [ 5 ] , row_index , column_index , x = 0 , size = 5 ; for ( row_index = 0 ; row_index < size ; row_index ++ ) { for ( column_index = 0 ; column_index < size ; column_index ++ ) { matrix [ row_index ] [ column_index ] = ++ x ; } } printf ( " The ▁ matrix ▁ is STRNEWLINE " ) ; for ( row_index = 0 ; row_index < size ; row_index ++ ) { for ( column_index = 0 ; column_index < size ; column_index ++ ) { printf ( " % d TABSYMBOL " , matrix [ row_index ] [ column_index ] ) ; } printf ( " STRNEWLINE " ) ; } printf ( " Elements on Secondary diagonal : " for ( row_index = 0 ; row_index < size ; row_index ++ ) { for ( column_index = 0 ; column_index < size ; column_index ++ ) { if ( ( row_index + column_index ) == size - 1 ) printf ( " % d , ▁ " , matrix [ row_index ] [ column_index ] ) ; } } return 0 ; }
How to access elements of a Square Matrix | C Program to read a square matrix and print the elements above secondary diagonal ; Get the square matrix ; Display the matrix ; Print the elements above secondary diagonal ; check for elements above secondary diagonal
#include <stdio.h> NEW_LINE int main ( ) { int matrix [ 5 ] [ 5 ] , row_index , column_index , x = 0 , size = 5 ; for ( row_index = 0 ; row_index < size ; row_index ++ ) { for ( column_index = 0 ; column_index < size ; column_index ++ ) { matrix [ row_index ] [ column_index ] = ++ x ; } } printf ( " The ▁ matrix ▁ is STRNEWLINE " ) ; for ( row_index = 0 ; row_index < size ; row_index ++ ) { for ( column_index = 0 ; column_index < size ; column_index ++ ) { printf ( " % d TABSYMBOL " , matrix [ row_index ] [ column_index ] ) ; } printf ( " STRNEWLINE " ) ; } printf ( " Elements above Secondary diagonal are : " for ( row_index = 0 ; row_index < size ; row_index ++ ) { for ( column_index = 0 ; column_index < size ; column_index ++ ) { if ( ( row_index + column_index ) < size - 1 ) printf ( " % d , ▁ " , matrix [ row_index ] [ column_index ] ) ; } } return 0 ; }
How to access elements of a Square Matrix | C Program to read a square matrix and print the Corner Elements ; Get the square matrix ; Display the matrix ; Print the Corner elements ; check for corner elements
#include <stdio.h> NEW_LINE int main ( ) { int matrix [ 5 ] [ 5 ] , row_index , column_index , x = 0 , size = 5 ; for ( row_index = 0 ; row_index < size ; row_index ++ ) { for ( column_index = 0 ; column_index < size ; column_index ++ ) { matrix [ row_index ] [ column_index ] = ++ x ; } } printf ( " The ▁ matrix ▁ is STRNEWLINE " ) ; for ( row_index = 0 ; row_index < size ; row_index ++ ) { for ( column_index = 0 ; column_index < size ; column_index ++ ) { printf ( " % d TABSYMBOL " , matrix [ row_index ] [ column_index ] ) ; } printf ( " STRNEWLINE " ) ; } printf ( " Corner Elements are : " for ( row_index = 0 ; row_index < size ; row_index ++ ) { for ( column_index = 0 ; column_index < size ; column_index ++ ) { if ( ( row_index == 0 row_index == size - 1 ) && ( column_index == 0 column_index == size - 1 ) ) printf ( " % d , ▁ " , matrix [ row_index ] [ column_index ] ) ; } } return 0 ; }
Program to calculate distance between two points in 3 D | C program to find distance between two points in 3 D . ; function to print distance ; Driver Code ; function call for distance
#include <stdio.h> NEW_LINE #include <math.h> NEW_LINE void distance ( float x1 , float y1 , float z1 , float x2 , float y2 , float z2 ) { float d = sqrt ( pow ( x2 - x1 , 2 ) + pow ( y2 - y1 , 2 ) + pow ( z2 - z1 , 2 ) * 1.0 ) ; printf ( " Distance ▁ is ▁ % f " , d ) ; return ; } int main ( ) { float x1 = 2 ; float y1 = -5 ; float z1 = 7 ; float x2 = 3 ; float y2 = 4 ; float z2 = 5 ; distance ( x1 , y1 , z1 , x2 , y2 , z2 ) ; return 0 ; }
Find unique pairs such that each element is less than or equal to N | C program for finding the required pairs ; Finding the number of unique pairs ; Using the derived formula ; Printing the unique pairs ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int No_Of_Pairs ( int N ) { int i = 1 ; while ( ( i * i * i ) + ( 2 * i * i ) + i <= N ) i ++ ; return ( i - 1 ) ; } void print_pairs ( int pairs ) { int i = 1 , mul ; for ( i = 1 ; i <= pairs ; i ++ ) { mul = i * ( i + 1 ) ; printf ( " Pair ▁ no . ▁ % d ▁ - - > ▁ ( % d , ▁ % d ) STRNEWLINE " , i , ( mul * i ) , mul * ( i + 1 ) ) ; } } int main ( ) { int N = 500 , pairs , mul , i = 1 ; pairs = No_Of_Pairs ( N ) ; printf ( " No . ▁ of ▁ pairs ▁ = ▁ % d ▁ STRNEWLINE " , pairs ) ; print_pairs ( pairs ) ; return 0 ; }
Divide a big number into two parts that differ by k | C program to Divide a Big Number into two parts ; Function to adds two Numbers represented as array of character . ; length of string ; initializing extra character position to 0 ; Adding each element of character and storing the carry . ; If remainder remains . ; Function to subtracts two numbers represented by string . ; Finding the length of the string . ; initializing extra character position to 0. ; Substrating each element of character . ; Function divides a number represented by character array a constant . ; Dividing each character element by constant . ; Function to reverses the character array . ; Reversing the array . ; Wrapper Function ; Reversing the character array . ; Adding the each element of both array and storing the sum in array a [ ] . ; Dividing the array a [ ] by 2. ; Reversing the character array to get output . ; Substracting each element of array i . e calculating a = a - b ; Reversing the character array to get output . ; Driven Program
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE #define MAX 100 NEW_LINE void add ( char v1 [ ] , char v2 [ ] ) { int i , d , c = 0 ; int l1 = strlen ( v1 ) ; int l2 = strlen ( v2 ) ; for ( i = l1 ; i < l2 ; i ++ ) v1 [ i ] = '0' ; for ( i = l2 ; i < l1 ; i ++ ) v2 [ i ] = '0' ; for ( i = 0 ; i < l1 i < l2 ; i ++ ) { d = ( v1 [ i ] - '0' ) + ( v2 [ i ] - '0' ) + c ; c = d / 10 ; d %= 10 ; v1 [ i ] = '0' + d ; } while ( c ) { v1 [ i ] = '0' + ( c % 10 ) ; c /= 10 ; i ++ ; } v1 [ i ] = ' \0' ; v2 [ l2 ] = ' \0' ; } void subs ( char v1 [ ] , char v2 [ ] ) { int i , d , c = 0 ; int l1 = strlen ( v1 ) ; int l2 = strlen ( v2 ) ; for ( i = l2 ; i < l1 ; i ++ ) v2 [ i ] = '0' ; for ( i = 0 ; i < l1 ; i ++ ) { d = ( v1 [ i ] - '0' - c ) - ( v2 [ i ] - '0' ) ; if ( d < 0 ) { d += 10 ; c = 1 ; } else c = 0 ; v1 [ i ] = '0' + d ; } v2 [ l2 ] = ' \0' ; i = l1 - 1 ; while ( i > 0 && v1 [ i ] == '0' ) i -- ; v1 [ i + 1 ] = ' \0' ; } int divi ( char v [ ] , int q ) { int i , l = strlen ( v ) ; int c = 0 , d ; for ( i = l - 1 ; i >= 0 ; i -- ) { d = c * 10 + ( v [ i ] - '0' ) ; c = d % q ; d /= q ; v [ i ] = '0' + d ; } i = l - 1 ; while ( i > 0 && v [ i ] == '0' ) i -- ; v [ i + 1 ] = ' \0' ; return c ; } void rev ( char v [ ] ) { int l = strlen ( v ) ; int i ; char cc ; for ( i = 0 ; i < l - 1 - i ; i ++ ) { cc = v [ i ] ; v [ i ] = v [ l - 1 - i ] ; v [ l - i - 1 ] = cc ; } } void divideWithDiffK ( char a [ ] , char k [ ] ) { rev ( a ) ; rev ( k ) ; add ( a , k ) ; divi ( a , 2 ) ; rev ( a ) ; printf ( " % s ▁ " , a ) ; rev ( a ) ; subs ( a , k ) ; rev ( a ) ; printf ( " % s " , a ) ; } int main ( ) { char a [ MAX ] = "100" , k [ MAX ] = "20" ; divideWithDiffK ( a , k ) ; return 0 ; }
Area of a square from diagonal length | C Program to find the area of square when its diagonal is given . ; Returns area of square from given diagonal ; Driver function .
#include <stdio.h> NEW_LINE double findArea ( double d ) { return ( d * d ) / 2 ; } int main ( ) { double d = 10 ; printf ( " % .2f " , findArea ( d ) ) ; return 0 ; }
Average of Squares of Natural Numbers | C program to calculate 1 ^ 2 + 2 ^ 2 + 3 ^ 2 + ... average of square number ; Function to calculate average of square number ; Driver code
#include <stdio.h> NEW_LINE float AvgofSquareN ( int n ) { float sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) sum += ( i * i ) ; return sum / n ; } int main ( ) { int n = 2 ; printf ( " % f " , AvgofSquareN ( n ) ) ; return 0 ; }
Program to get the Sum of series : 1 | C program to get the sum of the series ; Function to get the series ; Sum of n - 1 terms starting from 2 nd term ; Driver Code
#include <math.h> NEW_LINE #include <stdio.h> NEW_LINE double Series ( double x , int n ) { double sum = 1 , term = 1 , fct , j , y = 2 , m ; int i ; for ( i = 1 ; i < n ; i ++ ) { fct = 1 ; for ( j = 1 ; j <= y ; j ++ ) { fct = fct * j ; } term = term * ( -1 ) ; m = term * pow ( x , y ) / fct ; sum = sum + m ; y += 2 ; } return sum ; } int main ( ) { double x = 9 ; int n = 10 ; printf ( " % .4f " , Series ( x , n ) ) ; return 0 ; }
Find largest prime factor of a number | C Program to find largest prime factor of number ; A function to find largest prime factor ; Initialize the maximum prime factor variable with the lowest one ; Print the number of 2 s that divide n ; n >>= 1 ; equivalent to n /= 2 ; n must be odd at this point ; now we have to iterate only for integers who does not have prime factor 2 and 3 ; This condition is to handle the case when n is a prime number greater than 4 ; Driver program to test above function
#include <math.h> NEW_LINE #include <stdio.h> NEW_LINE long long maxPrimeFactors ( long long n ) { long long maxPrime = -1 ; while ( n % 2 == 0 ) { maxPrime = 2 ; } while ( n % 3 == 0 ) { maxPrime = 3 ; n = n / 3 ; } for ( int i = 5 ; i <= sqrt ( n ) ; i += 6 ) { while ( n % i == 0 ) { maxPrime = i ; n = n / i ; } while ( n % ( i + 2 ) == 0 ) { maxPrime = i + 2 ; n = n / ( i + 2 ) ; } } if ( n > 4 ) maxPrime = n ; return maxPrime ; } int main ( ) { long long n = 15 ; printf ( " % lld STRNEWLINE " , maxPrimeFactors ( n ) ) ; n = 25698751364526 ; printf ( " % lld " , maxPrimeFactors ( 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 ^ 2 / 2 + x ^ 3 / 3 + ... . + x ^ n / n ; C 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 , multi = x ; for ( i = 1 ; i <= n ; i ++ ) { total = total + multi / i ; multi = multi * x ; } return total ; } int main ( ) { int x = 2 ; int n = 5 ; printf ( " % .2f " , sum ( x , n ) ) ; return 0 ; }
Chiliagon Number | C program for above approach ; Finding the nth chiliagon Number ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int chiliagonNum ( int n ) { return ( 998 * n * n - 996 * n ) / 2 ; } int main ( ) { int n = 3 ; printf ( "3rd ▁ chiliagon ▁ Number ▁ is ▁ = ▁ % d " , chiliagonNum ( n ) ) ; return 0 ; }