Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Showing posts with label C Question Group 0. Show all posts
Showing posts with label C Question Group 0. Show all posts

Tuesday, 14 May 2019

The Interview Question Today#27(26-3-19)(Size of structure)

Question:

Write a c program to find the size of structure without using sizeof operator?

Solution:

C program:

#include<stdio.h>
struct  XYZ{
    int x;
    float y;
    char z;
};

int main(){
    int sz = (int) (((struct XYZ *)0) + 1);
    printf("Size of Struct= %d",sz);
    return 0;

}


Output:

Size of Struct= 12

Wednesday, 27 March 2019

The Interview Question Today#28(27-3-19)

Question:

C program that will display this output:

A B C D E F G F E D C B A
A B C D E F F E D C B A
A B C D E E D C B A
A B C D D C B A
A B C C B A
A B B A
A A


Solution:

C program:

#include<stdio.h>


void main()
{

int no_of_lines, alphabet = 65, i, count, j;

printf("\nenter the number of lines you want to print\t:");
scanf("%d",&no_of_lines);
count=2*no_of_lines;
for(j=0;j<no_of_lines;j++)
{
if(j==0)
{
printf("\n\n");
for(i=0;i<count;i++)
{
if(i<no_of_lines)
{
printf(" %c", alphabet++);
}
else if(i == no_of_lines)
{
alphabet--;
}
else
{
printf(" %c",--alphabet);
}
}
}
else
{
printf("\n");
//printf("\nnothing\n");
for(i=0;i<count-2*j;i++)
{
if(i<no_of_lines-j)
{
printf(" %c", alphabet++);
}
else
{
printf(" %c",--alphabet);
}
}

}
}
}


OUTPUT:

enter the number of lines you want to print : 7

A B C D E F G F E D C B A
A B C D E F F E D C B A
A B C D E E D C B A
A B C D D C B A
A B C C B A
A B B A
A A

Monday, 25 March 2019

The Interview Question Today#26(25-3-19) (Swap two variables without using third variable.)

Question 

Swap two variables without using third variable.

Example:

Input: A=5, B=10
Output: A=10 B=5

Solution:

C program:

#include<stdio.h>
int main(){
int a=5,b=10;
    printf("\nBefore Swap: a= %d  b=  %d",a,b);
    a=a^b;
    b=a^b;
    a=b^a;
    printf("\nAfter Swap: a= %d  b=  %d",a,b);
}

Output:

Before Swap: a= 5  b=  10

After Swap: a= 10  b=  5

Sunday, 24 March 2019

The Interview Question Today#21(16-3-19)

Question:

Comparison Counting Sort



Solution:

 Approach:

1. First of all, I am reading n elements in the array a[]. While reading the array elements I have also calculated the maximum element.

2. Now the actual sorting is done in the counting_sort() function. Here I am counting the occurrence of each element in the array a[] and then storing it at the index equal to the value of that element. For example, the occurrence of element 5 will be stored at index 5, the occurrence of element 9 will be stored at index 9 and so on.

3. As the value at each index in the count[] array is the occurrence of that index or element, so the elements are printed in ascending order by printing each index number of times equal to its corresponding value.


 ALGORITHM ComparisonCountingSort(A[0..n 1])

//Sorts an array by comparison counting

//Input: ArrayA[0..n 1] of orderable values

//Output: ArrayS[0..n 1] of A’s elements sorted in nondecreasing order

for ← to do


Count[i← 0

for ← to do

for← to do

ifA[i< A[j]

Count[j← Count[j1

else Count[i← Count[i1

for ← to do

S[Count[i]] ← A[i]

return S


C Program:


/*  C Program for counting sort */

#include <stdio.h> /*  Counting sort function  */

void counting_sort(int A[], int k, int n)

{

    int i, j;

    int B[15], C[100];

    for (i = 0; i <= k; i++)

        C[i] = 0;

    for (j = 1; j <= n; j++)

        C[A[j]] = C[A[j]] + 1;

    for (i = 1; i <= k; i++)

        C[i] = C[i] + C[i-1];

    for (j = n; j >= 1; j--)

    {

        B[C[A[j]]] = A[j];

        C[A[j]] = C[A[j]] - 1;

    }

    printf("The Sorted array is : ");

    for (i = 1; i <= n; i++)

        printf("%d ", B[i]);

}

/*  End of counting_sort()  */ /*  The main() begins  */

int main()

{

    int n, k = 0, A[15], i;

    printf("Enter the number of input : ");

    scanf("%d", &n);

    printf("\nEnter the elements to be sorted :\n");

    for (i = 1; i <= n; i++)

    {

        scanf("%d", &A[i]);

        if(A[i]>100){//max element should 100

            printf("error max element should <=100");

            exit(0);

        }

        if (A[i] > k) {

            k = A[i];

        }

    }

    counting_sort(A, k, n);

    printf("\n");

    return 0;

}


Output:


Enter the number of input : 5 Enter the elements to be sorted :

3

2

7

9

1

The Sorted array is : 1 2 3 7 9

The Interview Question Today#18(13-3-19)(Elements in a given array are distinct)

Question:

Determines whether all the elements in a given 

array are distinct


Example:


Input: arr[]={1,2,3,4,5,3}
Output: Repeated Element Exists




Solution:

Approach:

ALGORITHM UniqueElements(A[0..n 1])

//Determines whether all the elements in a given array are distinct

//Input: An array A[0..n 1]

//Output: Returns “true” if all the elements in are distinct

// and “false” otherwise

for ← to do

for ← to do


if A[iA[jreturn false

return true


C program:


#include <stdio.h>

int main(){

 int array[100],d, c, n,flag=0;


  printf("Enter number of elements in array\n");

  scanf("%d", &n);

  printf("Enter %d integer(s)\n", n);

  for (c = 0; c < n; c++)

    scanf("%d", &array[c]);

   for (c = 0; c < n; c++){

    for(d=c+1;d<n;d++)  {

    if (array[c] ==array[d])    /* If required element is found */    {

        flag=1;

      printf("%d is present at location %d and %d.\n",array[d], c+1,d+1);

      break;    }

  }

  }

  if (flag==0){    printf("No repeated element present in the array.\n");

  }

  if (flag==1){

    printf("Repeated element present in the array.\n");

  }

  return 0;

}

Output:

Enter number of elements in array

5

Enter 5 integer(s)

4

5

6

4

5

4 is present at location 1 and 4.

5 is present at location 2 and 5.

Repeated element present in the array.

The Interview Question Today#25(20-3-19)(Rectangles overlap or not.)

Question:
Given two rectangles, find if the given two rectangles overlap or not.

Example:














Solution:

Approach:

Two rectangles do not overlap if one of the following conditions is true.
1) One Rectangle is inside other rectangle.

2) One rectangle is above the top edge of other rectangle.

3) One rectangle is on the left side of the left edge of other rectangle.



C program:

#include<stdio.h>

struct Point
{
int x, y;
};

int doOverlap(struct Point l1, struct Point r1,struct Point l2,struct Point r2)
{


    if(l1.x<=l2.x && l1.y>=l2.y && r1.x>=r2.x && r1.y>=r2.y)
        return 1;

    if(l1.x>=l2.x && l1.y<=l2.y && r1.x<=r2.x && r1.y<=r2.y)
        return 1;
// If one rectangle is not on left side of other

if (l1.x > r2.x || l2.x > r1.x)
return 0;


// If one rectangle is not above other
if (l1.y < r2.y || l2.y < r1.y)
return 0;

return 1;
}
int main()
{
struct Point l1,b1;
struct Point l2 ,b2;
printf("Enter the Coordinates of rectangle 1 length");
scanf("%d %d",&l1.x,&l1.y);
printf("Enter the Coordinates of rectangle 1 breath");
scanf("%d %d",&b1.x,&b1.y);
printf("Enter the Coordinates of rectangle 2 length");
scanf("%d %d",&l2.x,&l2.y);
printf("Enter the Coordinates of rectangle 2 breath");
scanf("%d %d",&b2.x,&b2.y);

if (doOverlap(l1, b1, l2, b2))
printf("Rectangles Overlap");
else
printf("Rectangles Don't Overlap");
return 0;
}


Output:



Enter the Coordinates of rectangle 1 length0

10

Enter the Coordinates of rectangle 1 breath10

25
Enter the Coordinates of rectangle 2 length11
20
Enter the Coordinates of rectangle 2 breath20
25
Rectangles Don't Overlap

The Interview Question Today#24(19-3-19)

Question:

Given the perimeter of a rectangle, the task is to find the maximum area of a rectangle which can be formed.

Example:

Input: perimeter = 15

Output: Maximum Area = 12


Solution:

Approach:

For the area to be maximum of any rectangle the difference of length and breadth must be minimal. So, in such case, the length must be ceil (perimeter / 4) and breadth will be floor(perimeter /4).
 Hence the maximum area of a rectangle with a given perimeter is equal to ceil(perimeter/4) * floor(perimeter/4).

C program:

#include<stdio.h>


// Function to find max area
float maxArea(float perimeter)
{
int length = (int)ceil(perimeter / 4);
int breadth = (int)floor(perimeter / 4);

// return area
printf("Length=%d \nBreath=%d\n",length,breadth);
return length * breadth;
}

int main()
{
float n;
printf("Enter the Perimeter\n");
scanf("%f",&n);
printf("Maximum Area = %f",maxArea(n));

return 0;
}

Output:

Enter the Perimeter
30
Length=8
Breath=7
Maximum Area = 56.000000

The Interview Question Today#23(18-3-19)

Question:
Given four integers a, b, c and d which signifies the number of four types of brackets.

A=> “((“
B=> “()”
C=> “)(“
D=> “))”

The task is to print any balanced bracket expression using all the given brackets. If we cannot form a balanced bracket expression then print -1. 

Examples:

Input: a = 3, b = 1, c = 4, d = 3

Output: (((((()()()()())))))()

Solution:
Approach: 
First check if the balanced bracket expression can be formed with the given number of brackets. We can form the expression if the number of A brackets is equal to the number of D brackets with any number of C brackets And B type brackets or if there are only type B brackets. Hence the combining condition will be:

(a == d && a) || (a == 0 && c == 0 && d == 0)

C program:

#include <stdio.h>

// Function to print balanced bracket expression if it is possible
int printBalancedExpression(int a, int b, int c, int d)
{
int i;
    if ((a == d && a) || (a == 0 && c == 0 && d == 0)) {

        for ( i = 1; i <= a; i++)
            printf("((");

        for ( i = 1; i <= b; i++)
            printf("()");
        for ( i = 1; i <= c; i++)
            printf(")(");

        for ( i = 1; i <= d; i++)
            printf("))");


    }

    else{
        printf(-1);
        return 0;}
        return 1;
}
int main()
{
    int a,b,c,d;
    printf("Enter Value of A:");
    scanf("%d",&a);
    printf("\nEnter Value of B:");
    scanf("%d",&b);
    printf("\nEnter Value of C:");
    scanf("%d",&c);
    printf("\nEnter Value of D:");
    scanf("%d",&d);
    printf("\n");
    if(printBalancedExpression(a, b, c, d)){
     printf("\tBalanced Brackets");
    }
    else{
     printf("\tUnBalanced Brackets");
    }
    return 0;
}

Output:
Enter Value of A:1

Enter Value of B:1

Enter Value of C:1

Enter Value of D:1

((())())        Balanced Brackets

The Interview Question Today#22(17-3-19)


Question:
C Program to print numbers from 1 to N without using the semicolon?

Solution:


#include<stdio.h>
#define N 10

int main(int num)
{
    if (num <= N && printf("%d ", num) && main(num + 1))
    {
    }
}

The Interview Question Today#20 (15-3-19)

Question:
A Program to check if strings are rotations of each other or not


Example:

INPUT
String1 = "ABCDE"
String2 = "DEABC"

OUTPUT
Strings are rotations of each other

Solution:

Approach:

1. Concatenate s1 with s1

2. Now, if s2 is a substring of above concatenation, then s1 and s2 are rotations of each other.


C program:


# include <stdio.h>
# include <string.h>
# include <stdlib.h>

/* Function checks if passed strings (str1 and str2) are rotations of each other */
int areRotations(char *str1, char *str2)
{
  int size1   = strlen(str1);
  int size2   = strlen(str2);
  char temp[200];
  void *ptr;

  if (size1 != size2)
     return 0;

  strcat(temp, str1);
  strcat(temp, str1);

  ptr = strstr(temp, str2);
  free(temp);
  if (ptr != NULL)
    return 1;
  else
    return 0;
}

int main()
{
    char str1[100];
    char str2[100];
    printf("Enter the First String: ");
    scanf("%s",str1);
    printf("Enter the Second String: ");
    scanf("%s",str2);


    if (areRotations(str1, str2))
       printf("Strings are rotations of each other");
    else
       printf("Strings are not rotations of each other");

    return 0;
}

Output:

Enter the First String: ABCD
Enter the Second String: CDAB
Strings are rotations of each other

The Interview Question Today#19(14-3-19)

Question:

Check if two given strings are isomorphic to each other

Example:

Input:  String1 = "aab"
           String2 = "xxy"
Output: Given String Are Ismorphic ('a' is mapped to 'x' and 'b' is mapped to 'y'.)


Solution:

Approach:

1) If lengths of str1 and str2 are not same, return false.
2) Do following for every character in str1 and str2
   a) If this character is seen first time in str1, 
      then current of str2 must have not appeared before.
      (i) If current character of str2 is seen, return false.
          Mark current character of str2 as visited.
      (ii) Store mapping of current characters.
   b) Else check if previous occurrence of str1[i] mapped

      to same character.

C program:

#include<stdio.h>
#define MAX_CHARS 256
#include<string.h>

// This function returns true if str1 and str2 are ismorphic
int areIsomorphic(char *str1,char *str2)
{
int i;
for(i=0;str1[i]!='\0';i++);
int m=i;

for(i=0;str2[i]!='\0';i++);
int n=i;

    if (m != n)
      return 0;

    // To mark visited characters in str2
    int marked[MAX_CHARS] = {0};

    int map[MAX_CHARS];
    memset(map, -1, sizeof(map));

    for ( i = 0; i < n; i++)
    {
        if (map[str1[i]] == -1)
        {
            if (marked[str2[i]] == 1)
                return 0;

               marked[str2[i]] = 1;

            map[str1[i]] = str2[i];
        }

        else if (map[str1[i]] != str2[i])
            return 0;
    }

    return 1;

}

int main()
{
    char str1[100];
    char str2[100];
    printf("Enter the First String: ");
    scanf("%s",str1);
    printf("Enter the Second String: ");
    scanf("%s",str2);

    if(areIsomorphic(str1,str2))
   printf("Given String Are Ismorphic\n");
   else{
    printf("Given String Are Not Ismorphic\n");
   }
   return 0;
}

Output:
Enter the First String: aaa
Enter the Second String: xxx
Given String Are Ismorphic



The Interview Question Today#17(12-3-19)

Question:

Write a Program to check whether two given strings are an anagram of each other or not. 

Example:

Input: String1: silent

           String2: listen

Output: The two strings are an anagram of each other


Solution:

Approach 1:

1) Create count arrays of size 256 for both strings. Initialize all values in count arrays as 0.
2) Iterate through every character of both strings and increment the count of character in the corresponding count arrays.

3) Compare count arrays. If both count arrays are the same, then return true.


Approach 2:

1)Compare the length of both strings if equal continue or else false and exit.
2) Sorting Both Strings.
3) Comparing them.
4) if equal then true or false.

C program://Approach 1

#include <stdio.h>
#define NO_OF_CHARS 256

/* function to check whether two strings are an anagram of each other */
int 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 0;

    for (i = 0; i < NO_OF_CHARS; i++)
        if (count1[i] != count2[i])
            return 0;

    return 1;
}
int main()
{
    char str1[100];
    char str2[100];
    printf("Enter the First String: ");
    scanf("%s",str1);
    printf("Enter the Second String: ");
    scanf("%s",str2);

    if (areAnagram(str1, str2))
        printf("The two strings are an anagram of each other");
    else
        printf("The two strings are not an anagram of each other");

    return 0;

}

Output:

Enter the First String: amit
Enter the Second String: tima

The two strings are an anagram of each other



C program: //Appoarch 2.

#include <stdio.h>
#include<stdlib.h>
#include<string.h>

void main()
{
    printf("Enter 2 strings ");
    char s1[30],s2[30];
    scanf("%s",s1);
    scanf("%s",s2);
    int m=strlen(s1);
    int n=strlen(s2);
    if(m!=n){// Comparing the Length.
        printf("Strings are not anagram case 1\n");
        exit(0);
    }
//Sorting Both Array using Bubble Sort.
    int i,j,flag=0;
   char temp;
   for(i=0;i<m-1;i++)
  {
      for(j=0;j<n-i-1;j++)
        if(s1[j]>s1[j+1])
        {   temp=s1[j];
            s1[j]=s1[j+1];
            s1[j+1]=temp;
        }
  }

    for(i=0;i<m-1;i++)
     {

        for(j=0;j<n-i-1;j++)
            if(s2[j]>s2[j+1])
            {   //printf("Hello");
                temp=s2[j];
                s2[j]=s2[j+1];
                s2[j+1]=temp;
        }
    }



//Comparing Both The Array.
    for(i=0;i<n;i++){
        if(s1[i]!=s2[i])
            flag=2;
    }
    if(flag==2)
        printf("Strings are not anagram\n");
    else
        printf("Strings are anagram\n");


}

Java: Approach 2
import java.util.Arrays;
import java.util.Scanner;

/*
 * A way to check if two Strings are anagram or not in Java
 * return true, if both Strings are anagram. 
 * else false, 
 * And it is case Sensitive 
 @JavaAbhigyan
 */

public class anagram {
private static Scanner s;
private static String str1,str2;
private static boolean ans;
public static boolean iAnagram(String word, String anagram)
{
char[] charFromWord = word.toCharArray();
char[] charFromAnagram = anagram.toCharArray();
Arrays.sort(charFromWord); Arrays.sort(charFromAnagram);

return Arrays.equals(charFromWord, charFromAnagram); 
}
public static void main(String[] args) {
s = new Scanner(System.in);
System.out.println("Enter the Main String\n");
str1 = s.nextLine();
System.out.println("Enter the test String\n");
    str2=s.nextLine();
ans = iAnagram(str1, str2);
System.out.println("Enter String:"+str1+" And String:"+str2+" are Anagram:"+ans);
}

}