Showing posts with label C programming Concepts. Show all posts
Showing posts with label C programming Concepts. Show all posts

Thursday, 26 January 2012

Write a C program to display the message "Welcome to C" without a Semicolon.

// C program without a Semicolon.
This can done in three ways but one of them is infinite.(ie, while loop)Solution:1
#include<stdio.h>
void main( )
{
if(printf("Welcome to C"))
{
}
}

Solution:2
void main( )
{
swicth(printf("Welcome to C"))
{
}
}

Solution:3
void main( )
{
while(printf("Welcome to C")) //infinite loop
{
}
}

Write a C program to get the maximum and minimum values of a Data type

#include<stdio.h>
#include<conio.h>
void main( )
{
int x, y;
clrscr( );
x=1;
while( x > 0)
{
y = x;
x + + ;
}
printf("\nMaximum value : %d ", y );
printf("\nMinimum value : %d", x);
getch( );
}

Output:- Maximum value : 32767
Minimum value : -32768

Similarly we can find the below datatypes,
long int ( %ld )
char ( %d )
unsigned ( %u )
.....

C Interview Questions

1. Write a c program without using any semicolon which output will : Hello word.


Solution: 1
void main(){
    if(printf("Hello world")){
    }
}
Solution: 2
void main(){
    while(!printf("Hello world")){
    }
}
Solution: 3
void main(){
    switch(printf("Hello world")){
    }
}

2. Write a C program to Swap two variables without using third variable.

int main()
{
    int a=5,b=10;
//process one
    a=b+a;
    b=a-b;
    a=a-b;
    printf("a= %d  b=  %d",a,b);

//process two
    a=5;
    b=10;
    a=a+b-(b=a);
    printf("\na= %d  b=  %d",a,b);
//process three
    a=5;
    b=10;
    a=a^b;
    b=a^b;
    a=b^a;
    printf("\na= %d  b=  %d",a,b);
  
//process four
    a=5;
    b=10;
    a=b-~a-1;
    b=a+~b+1;
    a=a+~b+1;
    printf("\na= %d  b=  %d",a,b);
  
//process five
    a=5,
    b=10;
    a=b+a,b=a-b,a=a-b;
    printf("\na= %d  b=  %d",a,b);
    getch();

}

3. What is dangling pointer in c?

If any pointer is pointing the memory address of any variable but after some variable has deleted from that memory location while pointer is still pointing such memory location. Such pointer is known as dangling pointer and this problem is known as dangling pointer problem.

Initially:


Later: 


4. What is wild pointer in c ?

A pointer in c which has not been initialized is known as wild pointer.

Example:

(q)What will be output of following c program?

void main(){
int *ptr;
printf("%u\n",ptr);
printf("%d",*ptr);

}

Output: Any address
Garbage value

Here ptr is wild pointer because it has not been initialized.
There is difference between the NULL pointer and wild pointer. Null pointer points the base address of segmentwhile wild pointer doesn’t point any specific memory location.

5. What is the meaning of prototype of a function ?

Prototype of a function
Answer: Declaration of function is known as prototype of a function. Prototype of a function means
(1) What is return type of function?
(2) What parameters are we passing?
(3) For example prototype of printf function is:
int printf(const char *, …);
I.e. its return type is int data type, its first parameter constant character pointer and second parameter is ellipsis i.e. variable number of arguments.


6. What are merits and demerits of array in c?

(a) We can easily access each element of array.
(b) Not necessity to declare two many variables.
(c) Array elements are stored in continuous memory location.

Demerit:
(a) Wastage of memory space. We cannot change size of array at the run time.
(b) It can store only similar type of data.

Monday, 9 January 2012

Interesting C programming

1.)

main()
{
   int c= --2;
  printf("C =%d", c);
}

Answer :   c=2

Explanation : Here unary Minus ( or negation) operator is used twice.Same math rules applies, i.e minus*minus =  plus


2.)

 #include<stdio.h>
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}

Answer:
77

Explanation:
p is pointing to character '\n'. str1 is pointing to character 'a' ++*p. "p is pointing to '\n'
and that is incremented by one." the ASCII value of '\n' is 10, which is then incremented to 11.
The value of ++*p is 11. ++*str1, str1 is pointing to 'a' that is incremented by 1 and it becomes
'b'. ASCII value of 'b' is 98.
Now performing (11 + 98 – 32), we get 77("M");
So we get the output 77 :: "M" (Ascii is 77).

3.)
#include<stdio.h>
main()
{
struct xx
{
int x=3;
char name[]="hello";
};
struct xx *s;
printf("%d",s->x);
printf("%s",s->name);
}

Answer:
Compiler Error

Explanation:
You should not initialize variables in declaration

4.)
void main()
{
int i=5;
printf("%d",i+++++i);
}

Answer:
Compiler Error

Explanation:
The expression i+++++i is parsed as i ++ ++ + i which is an illegal
combination of operators.

5.)

#include<stdio.h>
main()
{
int i=1,j=2;
switch(i)
{
case 1: printf("GOOD");
break;
case j: printf("BAD");
break;
}
}

Answer:
Compiler Error: Constant expression required in function main.

Explanation:
The case statement can have only constant expressions (this implies that we
cannot use variable names directly so an error).


6)
main()
{
int i=0;
for(;i++;printf("%d",i)) ;
printf("%d",i);
}

Answer:
1

Explanation:
before entering into the for loop the checking condition is "evaluated". Here it
evaluates to 0 (false) and comes out of the loop, and i is incremented (note
the semicolon after the for loop).

7)
 #include<stdio.h>
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%c",++*p + ++*str1-32);
}

Answer:
M

Explanation:
p is pointing to character '\n'.str1 is pointing to character 'a' ++*p
meAnswer:"p is pointing to '\n' and that is incremented by one." the ASCII
value of '\n' is 10. then it is incremented to 11. the value of ++*p is 11. ++*str1
meAnswer:"str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'.
ASCII value of 'b' is 98. both 11 and 98 is added and result is subtracted from
32.i.e. (11+98-32)=77("M");

8.)
#include<stdio.h>
main()
{
struct xx
{
int x=3;
char name[]="hello";
};
struct xx *s=malloc(sizeof(struct xx));
printf("%d",s->x);
printf("%s",s->name);
}

Answer:
Compiler Error

Explanation:
Initialization should not be done for structure members inside the structure
declaration

9)
 #include<stdio.h>
main()
{
struct xx
{
int x;
struct yy
{
char s;
struct xx *p;
};
struct yy *q;
};
}

Answer:
Compiler Error

Explanation:
in the end of nested structure yy a member have to be declared.

10.)
main()
{
extern int i;
i=20;
printf("%d",sizeof(i));
}

Answer:
Linker error: undefined symbol '_i'.

Explanation:
extern declaration specifies that the variable i is defined somewhere else.
The compiler passes the external variable to be resolved by the linker. So
compiler doesn't find an error. During linking the linker searches for the
definition of i. Since it is not found the linker flags an error.



11)
 main()
{
printf("%d", out);
}
int out=100;

Answer:
Compiler error: undefined symbol out in function main.

Explanation:

The rule is that a variable is available for use from the point of declaration.
Even though a is a global variable, it is not available for main. Hence an
error.

12)
 main()
{
extern out;
printf("%d", out);
}
int out=100;

Answer:
100

Explanation:
This is the correct way of writing the previous program.


13)
 main( )
{
int a[ ] = {10,20,30,40,50},j,*p;
for(j=0; j<5; j++)
{
printf(“%d” ,*a);
a++;
}
p = a;
for(j=0; j<5; j++)
{
printf(“%d ” ,*p);
p++;
}
}

Answer:

Compiler error: lvalue required.

Explanation:
Error is in line with statement a++. The operand must be an lvalue and may
be of any of scalar type for the any operator, array name only when
subscripted is an lvalue. Simply array name is a non-modifiable lvalue.


14.)
main( )
{
void *vp;
char ch = ‘g’, *cp = “goofy”;
int j = 20;
vp = &ch;
printf(“%c”, *(char *)vp);
vp = &j;
printf(“%d”,*(int *)vp);
vp = cp;
printf(“%s”,(char *)vp + 3);
}

Answer:
g20fy

Explanation:
Since a void pointer is used it can be type casted to any other type pointer.
vp = &ch stores address of char ch and the next statement prints the value
stored in vp after type casting it to the proper data type pointer. the output is
‘g’. Similarly the output from second printf is ‘20’. The third printf statement
type casts it to print the string from the 4th value hence the output is ‘fy’.

Various Preprocessor Question

(1) What will be output of following code?

#include<stdio.h>
#define max 10
int main(){
    int i;
    i=++max;
    printf("%d",i);
    return 0;
}

(2) What will be output of following code?

#include<stdio.h>
#define max 10+2
int main(){
    int i;
    i=max*max;
    printf("%d",i);
    return 0;
}

(3) What will be output of following code?

#include<stdio.h>
#define A 4-2
#define B 3-1
int main(){
     int ratio=A/B;
     printf("%d ",ratio);
     return 0;
}

(4) What will be output of following code?

#include<stdio.h>
#define MAN(x,y) (x)>(y)?(x):(y)
int main(){
       int i=10,j=9,k=0;
       k=MAN(i++,++j);
       printf("%d %d %d",i,j,k);
       return 0;
}

(5) What will be output of following code?

#include<stdio.h>
#define START main() {
#define PRINT printf("*******");
#define END }
START
PRINT
END

(6) What will be output of following code?

#define CUBE(x) (x*x*x)
#define M 5
#define N M+1
#define PRINT printf("RITESH");
int main(){
      int volume =CUBE(3+2);
      printf("%d %d ",volume,N);
      PRINT
      return 0;
}

Solution section 

(1)output: compiler error.
Explanation:

Here max is preprocessor macro symbol which process first before the actual compilation. First preprocessor replace the symbol to its value in entire the program before the compilation. So in this program max will be replaced by 10 before compilation. Thus program will be converted like this:

int main(){
     int i;
     i=++10;
     printf("%d",i);
     return 0;
}

In this program we are trying to increment a constant symbol.

Meaning of ++10 is:
10=10+1
or 10=11

Which is error because we cannot assign constant value to another constant value .Hence compiler will give error.

(2)

Output: 32
Explanation:

Here max is preprocessor macro symbol which process first before the actual compilation start. Preprocessor replace the symbol to its value in entire the program before the compilation. So in this program max will be replaced by 10+2 before compilation. Thus program will be converted as:
 
int main(){
    int i;
    i=10+2*10+2;
    printf("%d",i);
    return 0;
}

now i=10+2*10+2
i=10+20+2
i=32

(3)

Output: 3
Explanation:

A and B are preprocessor macro symbol which process first before the actual compilation start. Preprocessor replace the symbol to its value in entire the program before the compilation. So in this program A and B will be replaced by 4-2 and 3-1 respectively before compilation. Thus program will be converted as: 

int main(){
    int ratio=4-2/3-1;
    printf("%d ",ratio);
    return 0;
}

Here ratio=4-2/3-1
ratio=4-0-1
ratio=3

(4)

Output: 11 11 11

Explanation:

Preprocessor’s macro which process first before the actual compilation. Thus program will be converted as: 

int main(){
    int i=10,j=9,k=0;
    k=(i++)>(++j)?(i++):(++j);
    printf("%d %d %d",i,j,k);
    return 0;
}

now k=(i++)>(++j)?(i++):(++j);
first it will check the condition
(i++)>(++j)

i++ i.e. when postfix is used with variable in expression then expression is evaluated first with original value then variable is incremented

Or 10>10

This condition is false.
Now i = 10+1 = 11
There is rule, only false part will execute after? i.e. ++j, i++ will be not execute.
So after ++j
j=10+1=11;

And k will assign value of j .so k=11; 

(5)

Output: *******
Explanation:
This program will be converted as: 

main(){
    printf("*******");
}

(6)

Output: 17 6
Explanation: This program will be converted as:

int main(){
    int volume =(3+2*3+2*3+2);
    printf("%d %d ",volume,5+1);
    PRINT
    return 0;
}

Recursion Concept

Introduction

Definition:-

Recursion is the process where a function is called itself but stack frame will be out of limit because function call will be infinite times. So a termination condition is mandatory to a recursion.


Many complex problem can be solved by recursion in a simple code. But it's too much costly than iterative. because in every recursion call one stack frame will formed.You all already know that about it's cost. but if problem is very complex than no way to solve except recursion.


Background


First recursion came into mathematics and then came into Computer science. Idea of it's use that first broke your problem into subproblems and solve it by using recursion.


The code


In C++, Recursion can be divided into two types:

(a)Run- Time Recursion: Normal as in C

(b)Compile- Time Recursion: By using Template


Each of these can be also divided into following types:


1. Linear Recursion

2. Binary Recursion

3. Tail Recursion

4. Mutual Recursion

5. Nested Recursion



1. Linear Recursion: This recursion is the most commonly used. In this recursion a function call itself in a simple manner and by termination condition it terminates. This process called 'Winding' and when it returns to caller that is called 'Un-Winding'. Termination condition also known as Base condition.


Example: Factorial calculation by linear recursion


Run-Time Version


Code:

int Fact(long n)
{
  if(0>n)
               return -1;
 if(0 == n)
    return 1;
 else
{
      return ( n* Fact(n-1));
}
}

Winding Process:


Function called Function return


Fact(6) 6*Fact(5)

Fact(5) 5*Fact(4)

Fact(4) 4*Fact(3)

Fact(3) 3* Fact(2)

Fact(2) 2* Fact(1)

Fact(1) 1* Fact(0)

Terminating Point

Fact(0) 1


Unwinding Process


Fact(1) 1*1

Fact(2) 2*1

Fact(3) 3*2*1

Fact(4) 4*3*2*1

Fact(5) 5*4*3*2*1

Fact(6) 6*5*4*3*2*1



Compile-Time Version


Code:

// template for Base Condition
template <>
struct Fact<0>
{
   enum
  {
      factVal = 1
   };
};

template
struct Fact
{
   // Recursion call by linear method
   enum
  {
value = n * Fact::factVal
   };
};

To test it how it's working at compile time, just call

cout << Fact<-1>::factVal ;

And compile it then compiler error will come, because no template for -1.


2. Binary Recursion: Binary Recursion is a process where function is called twice at a time inplace of once at a time. Mostly it's using in data structure like operations for tree as traversal, finding height, merging, etc.


Example: Fibonacci number


Run Time Version Code

Code:

int FibNum(int n)
{
   // Base conditions
      if (n < 1)
         return -1;
      if (1 == n || 2 == n)
        return 1;

   // Recursive call by Binary Method
     return FibNum(n - 1) + FibNum(n - 2);   // At a time two recursive function called so              
                                                                      //   binary
}

Compile Time Version Code

Code:

// Base Conditions
template<>
struct FibNum<2>
{
   enum { val = 1 };
};
template <>
struct FibNum<1>
{
   enum { val = 1 };
};

// Recursive call by Binary Method
template
struct FibNum
{  
   enum { val= FibNum::val + FibNum::val };
};


3. Tail Recursion: In this method, recursive function is called at the last. So it's more efficient than linear recursion method. Means you can say termination point will come(100%) only you have to put that condition.


Example: Fibonacci number


Run Time Version Code

Code:

int FibNum(int n, int x, int y)
{  
   if (1 == n)    // Base Condition
   {
      return y;
   }
   else        // Recursive call by Tail method
  {
      return FibNum(n-1, y, x+y);
   }
}

Compile Time Version Code


Code:

template
struct FibNum
{
   // Recursive call By tail method
   enum
  {
        val = FibNum::val
   };
};

// Base Condition or Termination
template
struct FibNum<1, x, y>
{
   enum
  {
      val = y
   };
};


4. Mutual Recursion: Functions calling each other. Let's say FunA calling FunB and FunB calling FunA recursively. This is not actually not recursive but it's doing same as recursive. So you can say Programming languages which are not supporting recursive calls, mutual recursion can be applied there to fulfill the requirement of recursion. Base condition can be applied to any into one or more than one or all functions.


Example: To find Even Or Odd number


Run Time Version Code

Code:

bool IsOddNumber(int n)
{
   // Base or Termination Condition
   if (0 == n)
      return 0;
   else
      // Recursive call by Mutual Method
      return IsEvenNumber(n - 1);
}
bool IsEvenNumber(int n)
{
   // Base or Termination Condition
   if (0 == n)
      return 1;
   else
      // Recursive call by Mutual Method
      return IsOddNumber(n - 1);
}

Compile Time Version Code

Code:

// Base Or Termination Conditions
template <>
struct IsOddNumber<0>
{
   enum
  {
     val = 0
  };
};
template <>
struct IsEvenNumber<0>
{
   enum
  {
      val = 1
  };
};

// Recursive calls by Mutual Method

template
struct IsOddNumber
{
   enum
  {
         val = n == 0 ? 0 : IsEvenNumber::val
   };
};


template
struct IsEvenNumber
{
   enum
  {
       val = n == 0 ? 1 : IsOddNumber::val
  };
};


5.Nested Recursion: It's very different than all recursions. All recursion can be converted to iterative (loop) except nested recursion. You can understand this recursion by example of Ackermann function.


Example: Ackermann function


Run Time Version Code

Code:

int Ackermann(int x, int y)
{
      // Base or Termination Condition
    if (0 == x)
   {
      return y + 1;
 }  
// Error Handling condition
   if (x < 0  ||  y < 0)
  {
      return -1;
   } 
// Recursive call by Linear method
   else if (x > 0 && 0 == y)
  {
      return Ackermann(x-1, 1);
  }
   // Recursive call by Nested method
   else
  {
      return Ackermann(x-1, Ackermann(x, y-1));
  }
}

Compile Time Version Code

Code:

// Base Or Termination condition
template
struct Ackermann<0, y>
{
   enum { val = y + 1 };
};

   // Recursive Call by Linear Method
template
struct Ackermann
{
   enum
   {
            val = Ackermann::val
   };
};
// Recursive Call by Nested Method
template
struct Ackermann
{
   Enum
   {
         val = Ackermann ::val>::val
   };
};