Sunday, May 21, 2017

C Programming Aptitude Set-1 with answer


C Programming Aptitude Question Set-1 (with output and justification)

Predict the output of following programs with justification.

Question - 1

#include<stdio.h>
int main()
{
    char name[ ]="INDIA";
    int i;
           
    for(i=0; name[i]; i++)
       printf("%c%c%c ",name[i],*(name+i),*(i+name));
    return 0;
}

/*
Output:
III NNN DDD III AAA

Justification: name[i], *(name+i) and *(i+name) are evaluated to same value.
*/

Question - 2

#include<stdio.h>
int main()
{
    int const marks=5;
    printf("%d",marks++);
    return 0;
}

/*
Output: Compiler error

Justification: Cannot modify a constant value.
*/

Question - 3

#include<stdio.h>
int main()
{
  static int number = 3;
  printf("%d ",number--);

  if(number)
main();

  return 0;
}

/*
Output:
3 2 1

Justification:
static storage class is initialized once. The value of a static variable is retained even between the function calls. Main is also function, which can be called recursively. This main function will be called until
value of number remains true(i.e. > 0)
*/

Question - 4

#include<stdio.h>
int main()
{
  float number1 = 5.1;
  double number2 = 5.1;
  if(number1 == number2)
printf("Equal numbers.");
  else
printf("Not equal numbers.");
}

/*
Output:
Not equal numbers.

Justification:
Values of floating point numbers (float, double, long double) are rounded after its defined precision value. Float takes 4 bytes and long double takes 10 bytes. So precision(rounded) value of float is different than long double.

Note: Be cautious while using floating point numbers with relational operators like == , >, <, <=, >= and != .
*/

Question - 5

#include<stdio.h>
int main()
{
   char ch='A';
   switch(ch)
   {
      default : printf("Error");
      case 'A': printf("Hello - A");
                break;
      case 'B': printf("Hello B");
                break;
      case 'C': printf("Hello C");
                break;
   }
}
/*
Output : Hello - A

Justification:
default case can be placed anywhere inside the loop. It will be executed only when other cases does not match.
*/


No comments:

Post a Comment