Skip to main content

Posts

Binary Search using Recursion

#include<stdio.h> void bins(int lb,int ub,int item,int a[]); void main() { int i,n,item,a[20]; printf("Enter the size of an array: "); scanf("%d",&n); printf("Enter the elements of the array: " ); for(i=0;i<n;i++) { scanf("%d",&a[i]); } printf("Enter the number to be search: "); scanf("%d",&item); bins(0,n-1,item,a); } void bins(int lb,int ub,int item,int a[]) { int mid,flag=0; if(lb<=ub) { mid=(lb+ub)/2; if(item==a[mid]) { flag=flag+1; } else if(item<a[mid]) { return bins(lb,mid-1,item,a); } else return bins(mid+1,ub,item,a); } if(flag==0) printf("Number is not found."); else printf("Number is found at %d", mid+1); } Output   Print   Out

Find the maximum length of the subarray in increasing order.

For example we have an array {5,4,6,-2,-1,0,1,9}. The biggest sub-array in increasing order is: {-2,-1,0,1,9}. So the length is 5. #include<stdio.h> void main () { int arr[8] = {5,4,6,-2,-1,0,1,9},i,arrn[8],count=1,j=0,max; printf("The given array is: "); for(i=0;i<8;i++) printf(" %d" ,arr[i]); // printing the actual array - unnecessary step. printf("\n"); for(i=0;i<7;i++){ if(arr[i]<arr[i+1]) { count++; } else { arrn[j]=count; // adding the length of sub array count=1; j++; } } arrn[j]=count; // adding the final length max=arrn[0]; printf("Length of sub arrays in increasing order"); for(i=0;i<=j;i++){ if(max<arrn[i]) max=arrn[i]; printf(" %d",arrn[i]); // printing the new array - unnecessary step. } printf("\n Maximum Length of the substring: %d",max); // print max va

Spiral Matrix

#include <stdio.h> #define R 3 #define C 3 void spiralPrint(int m, int n, int a[R][C]) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ while (k < m && l < n) { /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { printf("%d ", a[k][i]); } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { printf("%d ", a[i][n-1]); } n--; /* Print the last row from the remaining rows */ if ( k < m) { for (i = n-1; i >= l; --i) { printf("%d ", a[m-1][i]); } m--; } /* Print the first column from the remaining columns */ if (l < n)