Frequently asked C Programs in Interview

 Write you own Power without using multiplication(*) and division(/) operators 
#include <stdio.h>
int multiply(int a, int b)
{
        if(b)
                return (a + multiply(a, b-1));
        else
                return 0;
}

int power(int x, int y)
{
        if(y)
                return multiply(x, power(x, y-1));
        else
                return 1;
}

int main()
{
        int i,j;
        printf("Enter the Numbers : ");
        scanf("%d %d", &i, &j);
        printf("The number is  : %d\n", power(i ,j));
        return 0;
}

Execution :
Enter the Numbers : 3  2
The number is  : 9


Enter the Numbers : 5  3
The number is  : 125


Largest Sum Contiguous Subarray : 

Write an efficient C program to find the sum of contiguous subarray within a one-dimensional array of numbers which has the largest sum.

Basic Algorithm :
Initialize:
    max_first = 0
    max_end = 0

Loop for each element of the array
  (a) max_first = max_first + a[i]
  (b) if(max_first < 0)
            max_first = 0
  (c) if(max_end < max_first)
            max_end = max_first
return max_end




C Programming
#include <stdio.h>
#include <stdlib.h>
int maxSumSubArray (int a[], int n)
{
        int max_first = 0, max_end = 0, i;
        for (i=0; i<n; i++)
        {
                max_first = max_first + a[i];
                if (max_first < 0)
                        max_first = 0;
                else if(max_end < max_first)
                        max_end = max_first;
        }
        return max_end;
}
void main()
{
        int a[] = {-1, -7, -3, 12, -1, 13, 14, -4, -1, -9};
        int n = sizeof(a)/sizeof(a[0]);
        int maxSum = maxSumSubArray (a, n);
        printf("\nMax Sum of Sub Array is : %d", maxSum);
        printf ("\n");
}

Execution :

[root@localhost Cisco]# gcc -g maxSumSubArray.c
[root@localhost Cisco]# ./a.out
Max Sum of Sub Array is : 38
[root@localhost Cisco]#


Swapping Nibbles :

 #include <stdio.h>

void swapNibble(unsigned char y)
{
        unsigned char z = ((y&0x0F)<<4 | (y&0xF0)>>4);
        printf("The Nibble value is : %u\n", z);
}
int main()
{
        unsigned char x = 100;
        swapNibble(x);
        return 0;
}

Execution : 
[root@BLRSRV07 Cisco]# gcc -g swapNibbles.c
[root@BLRSRV07 Cisco]# ./a.out
The Nibble value is : 70
[root@BLRSRV07 Cisco]# 
 
Explanation :
100 in binary form            ----> 0110 0100
Nibble value of 100 is 70 ----> 0100 0110

So basically we are doing masking and then we are shifting left and right using 'Bitwise Operator'.
(y&0x0F)<<4 | (y&0xF0)>>4
(y&0x0F)<<4--->(0110 0100 & 0000 1111) <<4---> 0100 0000
(y&0xF0)>>4--->(0110 0100 & 1111 0000) >>4---> 0000 0110

No comments:

Post a Comment