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

Friday 31 May 2019

Recursion in C


Recursion is the process which comes into existence when a function calls a copy of itself to work on a smaller problem. Any function which calls itself is called the recursive function, and such function calls are called recursive calls. Recursion involves several numbers of recursive calls. However, it is important to impose a termination condition of recursion. Recursion code is shorter than iterative code however it is difficult to understand.

Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be defined in terms of similar subtasks. For Example, recursion may be applied to sorting, searching, and traversal problems.

Generally, iterative solutions are more efficient than recursion since function call is always overhead. Any problem that can be solved recursively, can also be solved iteratively. However, some problems are best suited to be solved by the recursion, for example, the tower of Hanoi, Fibonacci series, factorial finding, etc.

In the following example, recursion is used to calculate the factorial of a number.

#include <stdio.h>  
int fact (int);  
int main()  
{  
    int n,f;  
    printf("Enter the number whose factorial you want to calculate?");  
    scanf("%d",&n);  
    f = fact(n);  
    printf("factorial = %d",f);  
}  
int fact(int n)  
{  
    if (n==0)  
    {  
        return 0;  
    }  
    else if ( n == 1)  
    {  
        return 1;  
    }  
    else   
    {  
        return n*fact(n-1);  
    }  


Output
Enter the number whose factorial you want to calculate? 5
factorial = 120 

We can understand the above program of the recursive method call by the figure given below:









Recursive Function

A recursive function performs the tasks by dividing it into the subtasks. There is a termination condition defined in the function which is satisfied by some specific subtask. After this, the recursion stops and the final result is returned from the function.

The case at which the function doesn't recur is called the base case whereas the instances where the function keeps calling itself to perform a subtask, is called the recursive case. All the recursive functions can be written using this format.

Pseudocode for writing any recursive function is given below.

if (test_for_base)  
{  
    return some_value;  
}  
else if (test_for_another_base)  
{  
    return some_another_value;  
}  
else  
{  
    // Statements;  
    recursive call;  
}  

Example of recursion in C

Let's see an example to find the nth term of the Fibonacci series.

#include<stdio.h>  
int fibonacci(int);  
void main ()  
{  
    int n,f;  
    printf("Enter the value of n?");  
    scanf("%d",&n);  
    f = fibonacci(n);  
    printf("%d",f);  
}  
int fibonacci (int n)  
{  
    if (n==0)  
    {  
    return 0;  
    }  
    else if (n == 1)  
    {  
        return 1;   
    }  
    else  
    {  
        return fibonacci(n-1)+fibonacci(n-2);  
    }  
}  

Output
Enter the value of n? 12 
144 

Memory allocation of Recursive method
Each recursive call creates a new copy of that method in the memory. Once some data is returned by the method, the copy is removed from the memory. Since all the variables and other stuff declared inside function get stored in the stack, therefore a separate stack is maintained at each recursive call. Once the value is returned from the corresponding function, the stack gets destroyed. Recursion involves so much complexity in resolving and tracking the values at each recursive call. Therefore we need to maintain the stack and track the values of the variables defined in the stack.

Let us consider the following example to understand the memory allocation of the recursive functions.

int display (int n)  
{  
    if(n == 0)  
        return 0; // terminating condition  
    else   
    {  
        printf("%d",n);  
        return display(n-1); // recursive call  
    }  
}  


Explanation

Let us examine this recursive function for n = 4. First, all the stacks are maintained which prints the corresponding value of n until n becomes 0, Once the termination condition is reached, the stacks get destroyed one by one by returning 0 to its calling stack. Consider the following image for more information regarding the stack trace for the recursive functions.







Fig: stack trace for recursive function

Aptitude Hack#97(31-5-19)

Question:

Mr.Jones gave 40% of the money he had to his wife. He also gave 20% of the remaining amount to his 3 sons. Half of the amount now left was spent on miscellaneous items and the remaining amount of Rs.12000 was deposited in the bank. How much money did Mr.jones have initially?

   A )   150000
   B )   110000
   C )   100000
   D )   99990


Thursday 30 May 2019

Operator precedence chart



The below table describes the precedence order and associativity of operators in C. Precedence of the operator decreases from top to bottom.



Operators in C:


Operators are the foundation of any programming language. Thus the functionality of the C programming language is incomplete without the use of operators. We can define operators as symbols that help us to perform specific mathematical and logical computations on operands. In other words, we can say that an operator operates the operands.

For example, consider the below statement:

c = a + b;

Here, ‘+’ is the operator known as the addition operator and ‘a’ and ‘b’ are operands. The addition operator tells the compiler to add both of the operands ‘a’ and ‘b’. 

C has many built-in operator types and they can be classified as:

Arithmetic Operators: 
These are the operators used to perform arithmetic/mathematical operations on operands. Examples: (+, -, *, /, %,++,–).

The arithmetic operator is of two types:

Unary Operators: Operators that operates or works with a single operand are unary operators.
For example: (++ , –)

Binary Operators: Operators that operates or works with two operands are binary operators.For example: (+ , – , * , /)



Relational Operators:
 Relational operators are used for comparison of the values of two operands.
 For example: checking if one operand is equal to the other operand or not, an operand is greater than the other operand or not, etc. Some of the relational operators are (==, >= , <= ). 


Logical Operators: 
 Logical Operators are used to combining two or more conditions/constraints or to complement the evaluation of the original condition in consideration. The result of the operation of a logical operator is a boolean value either true or false. 

Bitwise Operators: 
The Bitwise operators are used to perform bit-level operations on the operands. The operators are first converted to bit-level and then the calculation is performed on the operands. The mathematical operations such as addition, subtraction, multiplication, etc. can be performed at bit-level for faster processing. 

Assignment Operators: 
Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error.

Different types of assignment operators are shown below:

“=”: This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left.
For example:
a = 10;
b = 20;
ch = 'y';

“+=”: This operator is a combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left.
Example:
(a += b) can be written as (a = a + b)
If initially, the value stored in a is 5. 
Then (a += 6) = 11.

“-=”: This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value on right from the current value of the variable on left and then assigns the result to the variable on the left.
Example:
(a -= b) can be written as (a = a - b)
If initially, the value stored in a is 8.
 Then (a -= 6) = 2.

“*=”: This operator is a combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left.
Example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5.
 Then (a *= 6) = 30.

“/=”: This operator is a combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.
Example:
(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. 
Then (a /= 2) = 3.

Other Operators: Apart from the above operators there are some other operators available in C used to perform some specific task.

 Some of them are discussed here:

Sizeof operator: 
sizeof is much used in the C programming language. It is a compile-time unary operator which can be used to compute the size of its operand. The result of sizeof is of the unsigned integral type which is usually denoted by size_t. Basically, the sizeof operator is used to computing the size of the variable.

Comma Operator:
 The comma operator (represented by the token,) is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value (and type). The comma operator has the lowest precedence of any C operator. Comma acts as both operator and separator.

Conditional Operator: 
The conditional operator is of the form Expression1? Expression2: Expression3. Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then we will execute and return the result of Expression2 otherwise if the condition(Expression1) is false then we will execute and return the result of Expression3. We may replace the use of if..else statements by conditional operators. 

CLICK HERE Operator precedence chart 

Puzzle#2

Question:

One of twelve pool balls is a bit lighter or heavier (you do not know) than the others. At least how many times do you have to use an old balance-type pair of scales to identify this ball?

(a) 1

(b) 3

(c) 7

(d) 12



Puzzle #2 Solution

Question:

One of twelve pool balls is a bit lighter or heavier (you do not know) than the others. At least how many times do you have to use an old balance-type pair of scales to identify this ball?

(a) 1

(b) 3

(c) 7

(d) 12

Answer:(b) 3

Explanation:

 Let's mark the balls using numbers from 1 to 12 and these special symbols:

 x? means I know nothing about ball number x;

 xL means that this ball is maybe lighter than the others; 

xH means that this ball is maybe heavier than the others;

 x. means this ball is "normal".

 At first, lay on the left pan balls 1? 2? 3? 4? and on the right pan balls 5? 6? 7? 8?.

 If there is equilibrium, then the wrong ball is among balls 9-12. Put 1. 2. 3. on the left and 9? 10? 11? on the right pan. 

If there is equilibrium, then the wrong ball is number 12 and comparing it with another ball it can find out if it is heavier or lighter.

 If the left pan is heavier, 12 is normal and 9L 10L 11L. weigh 9L and 10L.

 If they are the same weight, then ball 11 is lighter than all other balls.

 If they are not the same weight, then the lighter ball is the one up. 

If the right pan is heavier, then 9H 10H and 11H and the procedure is similar to the former text.

 If the left pan is heavier, then 1H 2H 3H 4H, 5L 6L 7L 8L and 9. 10. 11. 12. 

Now lay on the left pan 1H 2H 3H 5L and on the right pan 4H 9. 10. 11. 

If there is equilibrium, then the suspicious balls are 6L 7L and 8L.

 Identifying the wrong one is similar to the former case of 9L 10L 11L. 

If the left pan is lighter, then the wrong ball can be 5L or 4H. 

Compare for instance 1. and 4H. If they weigh the same, then ball 5 is lighter than all the others. Otherwise, ball 4 is heavier. If the left pan is heavier, then all balls are normal except for 1H 2H and 3H.

 Identifying the wrong ball among 3 balls was described earlier. In all possible way at least 3 times we have to weigh to find out which one is odd one.

Aptitude Hack#96(30-5-19)

Question:

Find the single discount equivalent to a series discount of 20 %, 10%, and 5%

   A )   Rs 68.40
   B )   Rs 66.40
   C )   Rs 65.40
   D )   Rs 58.40



Wednesday 29 May 2019

Aptitude Hack#95(29-5-9)

Question:

 Shobha’s mathematics test had 75 problems i.e. 10  arithmetic, 30 algebra, and 35 geometry problems. Although she answered 70% of the arithmetic, 40% of the algebra, and 60% of the geometry problems correctly.  she did not pass the test because she got less than  60% of the problems right.

 How many more questions she would have to answer correctly to earn 60% of the passing grade?
   
A )   6   
B )   5   
C )   8   
D )   9



Tuesday 28 May 2019

Aptitude Hack#94(28-5-19)

 Question:

A room is half as long again as it is broad. The cost of carpeting the at Rs. 5 per sq. m is Rs. 270 and the cost of papering the four walls at Rs. 10 per m2 are Rs. 1720. If a door and 2 windows occupy 8 sq. m, find the dimensions of the room.
   
A )   8 m
B )   9 m 
C )   6 m   
D )   5 m

Monday 27 May 2019

Aptitude Hack#93(27-5-19)

Question:

 How many spherical bullets can be made out of a lead cylinder 28cm high and with radius 6 cm, each bullet being 1.5 cm in diameter?

   A )   1795
   B )   1892
   C )   1772
   D )   1792

Sunday 26 May 2019

Composite Assignment Operators in C


Arithmetic operators may be combined with the assignment operator to obtain composite assignment operators. An arithmetic operator
 is written first followed by the assignment operator but not vice versa.

  In all the composite operators there should not be any blank space between the symbols.
   For instance, in+=
 if we give space between+ and= (suchas+  =),
   it may result in an error.

The statement A += 6; implies add 6 to the present value of A and assign the result to A'. So, it is equivalent to the following statement:

A= A + 6;

Similarly, the statement A /= 4; is equivalent to the following statement:

A= A/4;

Other composite operators can be similarly dealt with.

Illustrates the application of composite assignment operators.

#include <stdio.h>
void main ()
{
   int A=5, B=10, P=8, S = 20, T = 30;

   A += 3;
   B *= 2;
   P -= 4;
   S /=5;
   T %=8;

   printf("A =%d\nB = %d\n",   A, B);

   printf("P=%d\nS= %d\n", P, S);

   printf("T = %d\n", T );
}

Output:

A =8
B = 20
P = 4
S = 4
T = 6

Aptitude Hack#92(26-5-19)

Question:

A third of Arun’s marks in mathematics exceeds half of his marks in English by 80.if he got 240 marks In two subjects together how many marks did he got in English?

   A )   70
   B )   65
   C )   50
   D )   60

Saturday 25 May 2019

Aptitude Hack#91(25-5-19)

Question:

If the manufacturer gains 10%, the wholesale dealer 15% and the retailer 25 %, then find the cost of production of a retail price of which is Rs.1265?

   A )   Rs.900
   B )   Rs.600
   C )   Rs.1000
   D )   Rs.800



Friday 24 May 2019

Aptitude Hack#90(24-5-19)

Question:

A man can row 7 ½ kmph in still water.if in a river running at 1.5 km/hr an hour, it takes him 50 minutes to row to a place and back, how far off is the place?

   A )   6km
   B )   5km
   C )   8km
   D )   3km

Thursday 23 May 2019

Aptitude Hack#89(23-5-19)

Question:

A Cone, a hemisphere and a cylinder stand on equal bases and have the same height. Find the ratio of their volumes.

   A )   2:4:6
   B )   1:5:8
   C )   1:2:3
   D )   1:4:6



The Interview Question Today#91(25-5-19)


Wednesday 22 May 2019

Aptitude Hack#88(22-5-19)

Question:

 The difference between the two parallel sides of a trapezium is 4 cm. the perpendicular distance between them is 19 cm. If the area of the trapezium is 475 find the lengths of the parallel sides.
   A )   27 cm and 23 cm.
   B )   26 cm and 24 cm. 
   C )   29 cm and 21 cm.
   D )   25 cm and 25 cm.



Tuesday 21 May 2019

Aptitude Hack#52(16-4-19)

Question:
If in a certain language, NATURAL is coded as NBTVRBL, how is REPUBLIC coded in that code?

A)RFPVBMJD
B)RFPVBNID
C)RFPVCMID
D)RFPVBMID



Aptitude Hack#45(9-4-19)

Question:
The least number, which when divided by 12, 15, 20 and 54 leaves in each case a remainder of 8 is: 
    
    A) 544
    B) 548
    C) 504
    D) 536


Aptitude Hack#87(21-5-19)

Question:

A is twice as good a workman as B and together they finish a piece in 18 days. In how many days will A alone finish the work?

   A )   25 days
   B )   26 days
   C )   28 days
   D )   27 days


Monday 20 May 2019

Aptitude Hack#86(20-5-19)

Question:

 A man is standing on a railway bridge which is 180 m long. He finds that a train crosses the bridge in 20 seconds but himself in 8 seconds. Find the length of the train and its speed?

   A )   52 km
   B )   53 km
   C )   54 km
   D )   55 km



Sunday 19 May 2019

Aptitude Hack#85(19-5-19)

Question:

A crate of mangoes contains one bruised mango for every thirty mangoes in the crate. If three out of every four bruised mango are considerably unsaleable and there are 12 unsaleable mangoes in the crate then how many mangoes is there in the crate?

   A )   450
   B )   480
   C )   500
   D )   490



Saturday 18 May 2019

Aptitude Hack#84(18-5-19)

Question:

 In a caravan, in addition to 50 hens, there are 45 goats and 8 camels with some keepers. If the total number of feet be 224 more than the number of heads, find the number of keepers?

  A )   17
  B )   16
  C )   14
  D )   15




Friday 17 May 2019

Aptitude Hack#83(17-5-19)

Question:

The ages of two persons differ by 16 years. If 6 years ago, the elder one is 3 times as old as the younger one, find their present ages.

   A )   15 years and 31 years
   B )   14 years and 30 years   
   C )   13 years and 29 years
   D )   12 years and 28 years



Triplets with a given sum

Question:

Write Program to find Triplets with a given sum

Solution:


Repeating elements in an array

Question:


Write Program to find repeating elements in an array 

Solution:



Count distinct elements of an array

Question:

Write a Program to count distinct elements of an array
Solution:



The numbers of an array be made equal

Question:

Write Program to find whether the numbers of an array be made equal?


Solution:


The maximum scalar product of two vectors

Question:

Write Program to find the maximum scalar product of two vectors


Solution:


Array is a subset of another array or not

Question:

Write Program to find whether an array is a subset of another array or not


Solution:


Arrays are disjoint or not

Question:

Write a Program to find whether Arrays are disjoint or not


Solution:


Maximum product subarray in a given array

Question:

Write Program to find maximum product subarray in a given array

Solution:


Reversing an array

Question:

Write Program for Reversing an array
Solution:



Sorting the elements of an array

Question:

Write Program for  Sorting the elements of an array


Solution:


The second smallest element in an array

Question:

Write a Program to find the second smallest element in an array

Solution:


The sum of positive square elements in an array

Question:

Write a Program to find the sum of positive square elements in an array

Solution:


The minimum scalar product of two vectors

Question:

Write Program to find the minimum scalar product of two vectors
Solution:








































}

Remove duplicate elements in an array

Question:

Write Program to remove duplicate elements in an array


Solution:























  }

The longest palindrome in an array

Question:

Write Program to find the longest palindrome in an array

Solution:



The sum of elements in an array

Question:

Write Program to find the sum of elements in an array

Solution:


The smallest and largest element in an array

Question:

Write Program to find the smallest and largest element in an array

Solution:


Basic array operations

Question:

Write Program for basic array operations (Insert, delete and search an element)

Solution:

#include<stdio.h>

#include<stdlib.h>


int a[20],b[20],c[40];

int m,n,p,val,i,j,key,pos,temp;

/*Function Prototype*/void create();

void display();

void insert();

void del();

void search();

void merge();

void sort();

int main()
{
int choice;

do{
printf(
"\n\n--------Menu-----------\n");

printf("1.Create\n");

printf("2.Display\n");

printf("3.Insert\n");

printf("4.Delete\n");

printf("5.Search\n");

printf("6.Sort\n");

printf("7.Merge\n");

printf("8.Exit\n");

printf("-----------------------");

printf("\nEnter your choice:\t");

scanf("%d",&choice);

switch(choice)
{
case 1:

 create();

break;

case 2:
display();


break;

case 3:
insert();


break;

case 4:
del();


break;

case 5:
search();



break;

case 6:
sort();


break;

case 7:
merge();


break;

case 8:
exit(
0);

break;

default:printf("\nInvalid choice:\n");

break;
}

 }while(choice!=8);

return 0;
}

void create() //creating an array
{
printf(
"\nEnter the size of the array elements:\t");
scanf(
"%d",&n);

printf("\nEnter the elements for the array:\n");

for(i=0;i<n;i++)
{
scanf(
"%d",&a[i]);
}


 }//end of create()

void display() //displaying an array elements{int i;
printf(
"\nThe array elements are:\n");

for(i=0;i<n;i++)
{
printf(
"%d\t",a[i]);

}
 }//end of display()

void insert() //inserting an element in to an array{
printf(
"\nEnter the position for the new element:\t");
scanf(
"%d",&pos);

printf("\nEnter the element to be inserted :\t");
scanf(
"%d",&val);

for(i=n-1;i>=pos;i--)
{
a[i
+1]=a[i];
}

a[pos]=val;
n=n+1;
}
//end of insert()

void del() //deleting an array element{
printf(
"\nEnter the position of the element to be deleted:\t");
scanf(
"%d",&pos);

val=a[pos];

for(i=pos;i<n-1;i++)
{
a[i]
=a[i+1];
}

 n=n-1;
printf(
"\nThe deleted element is =%d",val);

}//end of delete()

void search() //searching an array element{
printf(
"\nEnter the element to be searched:\t");
scanf(
"%d",&key);

for(i=0;i<n;i++)
{
if(a[i]==key)
{
printf(
"\nThe element is present at position %d",i);

break;
}

 }

if(i==n)
{
printf(
"\nThe search is unsuccessful");
}

 }
 }//end of search()

void sort() //sorting the array elements{for(i=0;i<n-1;i++)
{


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

if(a[j]>a[j+1])
{
temp
=a[j];
a[j]
=a[j+1];
a[j
+1]=temp;
}

 }
 }
printf(
"\nAfter sorting the array elements are:\n");

display();


}//end of sort

void merge() //merging two arrays{
printf(
"\nEnter the size of the second array:\t");
scanf(
"%d",&m);

printf("\nEnter the elements for the second array:\n");

for(i=0;i<m;i++)
{
scanf(
"%d",&b[i]);
}


for(i=0,j=0;i<n;i++,j++)
{
c[j]
=a[i];
}


for(i=0;i<m;i++,j++)
{
c[j]
=b[i];
}


 p=n+m;
printf(
"\nArray elements after merging:\n");


for(i=0;i<p;i++)
{
printf(
"%d\t",c[i]);
}


 }