Sunday, March 29, 2009

C Programs with Solution Logic

  • Transpose of a Matrix
Interchanging the Rows with Columns or Vice-Verse
for(i=0;i&k;i++)
for(j=i+1;j&l;j++)
{
temp=mat[i][j];
mat[i][j]=mat[j][i];
mat[j][i]=temp;
}
  • Finding the Saddle point of a Matrix
A matrix a is said to have a saddle point if some entry a[I][j] is the smallest value in the ith row and the largest value in the jth column. A matrix may have more than one saddle point.

for Eg:
7 6 5
1 8 1
2 9 2

Here saddle Point value is 5.

  • How to find year is leap year.
if a year is divisible by 4 and not by 100 is called leap year.
if a year is divisible by 400 is called leap year.

  • How to swap two variables without using temporary variable?
a^=b^=a^=b

How to know system is using little Endian or Big Endain?
int i=1;
if( * (char *)&i == 1)
printf("Little Endian");
else
printf("Big Endian");

Introduction to Arrays Sorting

  • Introduction about Array
Array is a sequence collection of elements are of same type.The elements of array are accessed by index.
Array can be 1 dimensional or n dimensional.

In C Array declaration is in the form:
char name[100];

Here char is the data type and name is the base pointer of array.
The Base pointer of array cannot be changed.The Compiler treats it has constant pointer.

Array is used in application like storing list of records. etc
Arrays are used to implement various types of programs and algorithms like sorting,tress,Graphs etc.

  • Merging two sorted list
Algorithm
1) Take three Arrays A1,A2 and C1.
2)Compare each elements of A1 with A2,During comparing of elements,if 1st less than 2nd one,Then insert the 1st one C1 else 2nd one into C1. The Array from which the element is taken for insertion in third list,Increment the index of that Array.
3)Repeat step 2 for all the elements in the Array.If you get Nth index in any of the Array then go to step 4.
4) Insert the non finished Array directly in the Third array.
4) The third Array contains the list of sorted elements.
  • Bubble Sort
1) take a array and Compare first two elements,If greater swap with other element.So at last we get largest element in nth location.
So no of Comparisons required is n-1 first time.

Like that total comparisons are (n-1)+(n-2)+--------1= n(n-1)/2.
Order = O(n^2);
  • Quick Sort
1)Quick sort is the fastest sorting algorithm.
2)Take a Array of elements.Consider the first element as pivot.
3) traverse from left if the current element is greater than pivot,stop there.
4) traverse the list from right,if no is less than pivot,wait there.
4)Swap the two wait locations elements.
5) traverse the list again until their traverse won't cross with each other.
6) always traverse from left first.
7) if they cross with each other,swap the right location value with pivot.
8) two lists are formed now.
8) 0 to right and left to n-1.
9) perform quick sort again on two lists.

Average time complexity of Quick sort is O(nlogn).
worst case time complexity = O(n^2). ( always one of list is empty).
worst case space complexity =O(n). ( every time list splits into two).
  • Selection Sort
  1. Find the minimum value in the list
  2. Swap it with the value in the first position
  3. Repeat the steps above for remainder of the list.
Timing Complexity: worst=best=average=O(n^2).

Tuesday, March 24, 2009

C Aptitude Multiple Choice Questions and Answers

Q1. What will be the output of the following arithmetic expression ?

5+3*2%10-8*6

a) -37
b) -42
c) -32
d) -28

Q2. What will be the output of the following statement ?

int a=10; printf("%d &i",a,10);

a) error
b) 10
c) 10 10
d) none of these

Q3. What will be the output of the following statement ?

printf("%X%x%ci%x",11,10,'s',12);

a) error
b) basc
c) Bas94c
d) none of these

Q4. What will be the output of the following statements ?

int a = 4, b = 7,c; c = a = = b; printf("%i",c);

a) 0
b) error
c) 1
d) garbage value

Q 5. What will be the output of the following statements ?

int a = 5, b = 2, c = 10, i = a>b
void main()
{ printf("hello"); main(); }

a) 1
b) 2
c) infinite number of times
d) none of these

Q7. What will be the output of the following statements ?

int x[4] = {1,2,3}; printf("%d %d %D",x[3],x[2],x[1]);

a) 03%D
b) 000
c) 032
d) 321

Q8. What will be the output of the following statement ?

printf( 3 + "goodbye");

a) goodbye
b) odbye
c) bye
d) dbye


Q9. What will be the output of the following statements ?

long int a = scanf("%ld%ld",&a,&a); printf("%ld",a);

a) error
b) garbage value
c) 0
d) 2

Q10. What will be the output of the following program ?

#include
void main()
{ int a = 2;
switch(a)
{ case 1:
printf("goodbye"); break;
case 2:
continue;
case 3:
printf("bye");
}
}

a) error
b) goodbye
c) bye
d) byegoodbye



Q11. What will be the output of the following statements ?

int i = 1,j; j=i--- -2; printf("%d",j);

a) error
b) 2
c) 3
d) -3

Q12. What will be the output of following program ?

#include
main()
{
int x,y = 10;
x = y * NULL;
printf("%d",x);
}

a) error
b) 0
c) 10
d) garbage value

Q13. What will be the output of following statements ?

char x[ ] = "hello hi"; printf("%d%d",sizeof(*x),sizeof(x));

a) 88
b) 18
c) 29
d) 19

Q14. What will be the output of the following statements
?
int a=5,b=6,c=9,d; d=(ac?1:2):(c>b?6:8)); printf("%d",d);

a) 1
b) 2
c) 6
d) 8

Q15. What will be the output of the following statements ?

int i = 3;
printf("%d%d",i,i++);

a) 34
b) 43
c) 44
d) 33

Q16. What will be the output of the following program ?

#include
void main()
{
int a = 36, b = 9;
printf("%d",a>>a/b-2);
}

a) 9
b) 7
c) 5
d) none of these


Q17)
int testarray[3][2][2] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
What value does testarray[2][1][0] in the sample code above contain?

a) 11
b) 7
c) 5
d) 9

Q18)

void main()
{
int a=10,b=20;
char x=1,y=0;
if(a,b,x,y)
{
printf("EXAM");
}
}
What is the output?

1) XAM is printed
2) exam is printed
3) Compiler Error
4) Nothing is printed

Q19)

What is the output of the following code?
#include
void main()
{
int s=0;
while(s++<10)>
# define a 10
main()
{
printf("%d..",a);
foo();
printf("%d",a);
}
void foo()
{
#undef a
#define a 50
}

1) 10..10
2) 10..50
3) Error
4) 0

Q21)

main()
{
struct
{
int i;
}xyz;
(*xyz)->i=10;
printf("%d",xyz.i);
}
What is the output of this program?

1) program will not compile
2) 10
3) god only knows
4) address of I

Q22)
What would be the output of the following program?
#include
main()
{
char str[]="S\065AB";
printf("\n%d", sizeof(str));
}


1) 7
2) 6
3) 5
4) error

Q23)
What will be the value of `a` after the following code is executed
#define square(x) x*x
a = square(2+3)
1) 25
2) 13
3) 11
4) 10

Q24)
#include
void func()
{
int x = 0;
static int y = 0;
x++; y++;
printf( "%d -- %d\n", x, y );
}

int main()
{
func();
func();
return 0;
}

What will the code above print when it is executed?
1)
1 -- 1
1 -- 1
2)
1 -- 1
2 -- 1
3)
1 -- 1
2 -- 2
4)
1 -- 1
1 -- 2

Q25)

long factorial (long x)
{
????
return x * factorial(x - 1);
}
With what do you replace the ???? to make the function shown above return the correct answer?
1)
if (x == 0) return 0;
2)
return 1;
3)
if (x >= 2) return 2;
4)
if (x <= 1) return 1;

Q 26)

int y[4] = {6, 7, 8, 9};
int *ptr = y + 2; printf("%d\n", ptr[ 1 ] );

What is printed when the sample code above is executed?

1) 6
2) 7
3) 8
4) 9 .

Q27)

int i = 4;

switch (i)
{

default: ;
case 3:
i += 5;
if ( i == 8)
{
i++;
if (i == 9) break;
i *= 2;
}
i -= 4;
break;

case 8:
i += 5;
break;
}
printf("i = %d\n", i);

What will the output of the sample code above be?

1) i = 5
2) i = 8
3) i = 9
4) i = 10


Answers:
1.(a)-37
2.(d)none of them
3.(b)basc
4.(a)0
5.(c)infinite number of time
7.(c)032
8.(d)dbye
9.(b)garbage value
10.(a) error
11.(c) 3
12.(b)0
13.(d) 1 9
14.Error
15.(b)4 3
16.(a) 9
17.(a) 11
18.(d) nothing will be print
19.(3) Error
21.(2)10
22.(2) 6
23.(3) 11
24.(4)1..1,1..2
25.(4)if(x<=1)return 1;
26. (4) 9
27.(1) i=5

C Aptitude Questions and Answers

Predict the output or error(s) for the following:

1.
void main()
{
int const * p=5;
printf("%d",++(*p));
}
Answer:
Compiler error: Cannot modify a constant value.
Explanation:
p is a pointer to a "constant integer".

2.
main()
{
char s[ ]="man";
int i;
for(i=0;s[ i ];i++)
printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
}
Answer:
mmmm
aaaa
nnnn
Explanation:
s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea.

3.
main()
{
float me = 1.1;
double you = 1.1;
if(me==you)
printf("I love U");
else
printf("I hate U");
}
Answer:
I hate U
Explanation:
For floating point numbers (float, double, long double) the values cannot be predicted exactly.

4.
main()
{
static int var = 5;
printf("%d ",var--);
if(var)
main();
}
Answer:
5 4 3 2 1
Explanation:
When static storage class is given, it is initialized once. The change in the value of a static variable is retained even between the function calls. Main is also treated like any other ordinary function, which can be called recursively.

5.

main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf("%d----%d",*p,*q);
}
Answer:
SomeGarbageValue---1
Explanation:
p=&a[2][2][2] you declare only two 2D arrays, but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. Now q is pointing to starting address of a. If you print *q, it will print first element of 3D array.

6.

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 structure variables in declaration.

7.

main()
{
struct xx
{
int x;
struct yy
{
char s;
struct xx *p;
};
struct yy *q;
};
}
Answer:
Compiler Error
Explanation:
The structure yy is nested within structure xx. Hence, the elements are of yy are to be accessed through the instance of structure xx, which needs an instance of yy to be known. If the instance is created after defining the structure the compiler will not know about the instance relative to xx. Hence for nested structure yy you have to declare member.

8.
main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
}
Answer:
hai
Explanation:
\n - newline
\b - backspace
\r - linefeed

9.
main()
{
int i=5;
printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);
}
Answer:
45545
Explanation:
The arguments in a function call are pushed into the stack from left to right. The evaluation is by popping out from the stack. and the evaluation is from right to left, hence the result.

10.
#define square(x) x*x
main()
{
int i;
i = 64/square(4);
printf("%d",i);
}
Answer:
64
Explanation:
the macro call square(4) will substituted by 4*4 so the expression becomes i = 64/4*4 . Since / and * has equal priority the expression will be evaluated as (64/4)*4 i.e. 16*4 = 64

11.
main()
{
char *p="hai friends",*p1;
p1=p;
while(*p!='\0') ++*p++;
printf("%s %s",p,p1);
}
Answer:
ibj!gsjfoet
Explanation:
During the execution of printf p points to last null character and all the content also got incremented.
p1 prints the incremented content.

12.

#define a 10
main()
{
#define a 50
printf("%d",a);
}
Answer:
50
Explanation:
The preprocessor directives can be redefined anywhere in the program. So the most recently assigned value will be taken.

13.

#define clrscr() 100
main()
{
clrscr();
printf("%d\n",clrscr());
}
Answer:
100
Explanation:
Preprocessor executes as a seperate pass before the execution of the compiler. So textual replacement of clrscr() to 100 occurs.The input program to compiler looks like this :
main()
{
100;
printf("%d\n",100);
}
Note:
100; is an executable statement but with no action. So it doesn't give any problem

14.
main()
{
printf("%p",main);
}
Answer:
Some address will be printed.
Explanation:
Function names are just addresses,main() is also a function. So the address of function main will be printed. %p in printf specifies that the argument is an address. They are printed as hexadecimal numbers.

15.

char *someFun1()
{
char temp[ ] = “string";
return temp;
}
main()
{
puts(someFun1());
}
Answer:
Garbage values.

16.

void main()
{
char far *farther,*farthest;
printf("%d..%d",sizeof(farther),sizeof(farthest));
}
Answer:
4..2
Explanation:
the second pointer is of char type and not a far pointer

17.

main()
{
int i=400,j=300;
printf("%d..%d");
}
Answer:
400..300
Explanation:
printf takes the values of the first two assignments of the program. Any number of printf's may be given. All of them take only the first two values. If more number of assignments given in the program,then printf will take garbage values.

18.

main()
{
char *p;
p="Hello";
printf("%c\n",*&*p);
}
Answer:
H

19.

main()
{
int i=1;
while (i<=5) { printf("%d",i); if (i>2)
goto here;
i++;
}
}
fun()
{
here:
printf("PP");
}
Answer:
Compiler error: Undefined label 'here' in function main
Explanation:
Labels have functions scope, in other words The scope of the labels is limited to functions. The label 'here' is available in function fun () Hence it is not visible in function main.

20.

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 .Enumerated types can be used in case statements.

21.

main()
{
int i;
printf("%d",scanf("%d",&i)); // value 10 is given as input here
}
Answer:
1
Explanation:
Scanf returns number of items successfully read and not 1/0. Here 10 is given as input which should have been scanned successfully. So number of items read is 1.

22.

#define f(g,g2) g##g2
main()
{
int var12=100;
printf("%d",f(var,12));
}
Answer:
100

23.

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:
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");

24.
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 shows an error.

25.

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.

26.

main()
{
extern out;
printf("%d", out);
}
int out=100;
Answer:
100
Explanation:
This is the correct way of writing the previous program.

27.

main()
{
show();
}
void show()
{
printf("I'm the greatest");
}
Answer:
Compier error: Type mismatch in redeclaration of show.
Explanation:
When the compiler sees the function show it doesn't know anything about it. So the default return type (ie, int) is assumed. But when compiler sees the actual definition of show mismatch occurs since it is declared as void. Hence the error.

28.
main()
{
int i=-1;
+i;
printf("i = %d, +i = %d \n",i,+i);
}
Answer:
i = -1, +i = -1
Explanation:
Unary + is the only dummy operator in C. Where-ever it comes you can just ignore it just because it has no effect in the expressions (hence the name dummy operator).

29.

What are the files which are automatically opened when a C file is executed?
Answer:
stdin, stdout, stderr (standard input,standard output,standard error).

30.

what will be the position of the file marker?
a: fseek(ptr,0,SEEK_SET);
b: fseek(ptr,0,SEEK_CUR);

Answer :
a: The SEEK_SET sets the file position marker to the starting of the file.
b: The SEEK_CUR sets the file position marker to the current position of the file.

31.

main()
{
char name[10],s[12];
scanf(" \"%[^\"]\"",s);
}
How scanf will execute?
Answer:
First it checks for the leading white space and discards it.Then it matches with a quotation mark and then it reads all character upto another quotation mark.

32.

What is the problem with the following code segment?
while ((fgets(receiving array,50,file_ptr)) != EOF);
Answer & Explanation:
fgets returns a pointer. So the correct end of file check is checking for != NULL.

33.
main()
{
char *cptr,c;
void *vptr,v;
c=10; v=0;
cptr=&c; vptr=&v;
printf("%c%v",c,v);
}
Answer:
Compiler error (at line number 4): size of v is Unknown.
Explanation:
You can create a variable of type void * but not of type void, since void is an empty type. In the second line you are creating variable vptr of type void * and v of type void hence an error.

34.

main()
{
char *str1="abcd";
char str2[]="abcd";
printf("%d %d %d",sizeof(str1),sizeof(str2),sizeof("abcd"));
}
Answer:
2 5 5

35.

main()
{
char not;
not=!2;
printf("%d",not);
}
Answer:
0

36.

#define FALSE -1
#define TRUE 1
#define NULL 0
main() {
if(NULL)
puts("NULL");
else if(FALSE)
puts("TRUE");
else
puts("FALSE");
}
Answer:
TRUE
Explanation:
Preprocessor doesn't replace the values given inside the double quotes. The check by if condition is boolean value false so it goes to else. In second if -1 is boolean value true hence "TRUE" is printed.

37.

main()
{
int k=1;
printf("%d==1 is ""%s",k,k==1?"TRUE":"FALSE");
}
Answer:
1==1 is TRUE
Explanation:
When two strings are placed together (or separated by white-space) they are concatenated (this is called as "stringization" operation). So the string is as if it is given as "%d==1 is %s". The conditional operator( ?: ) evaluates to "TRUE".

38.

main()
{
int *j;
{
int i=10;
j=&i;
}
printf("%d",*j);
}
Answer:
10
Explanation:
The variable i is a block level variable and the visibility is inside that block only. But the lifetime of i is lifetime of the function so it lives upto the exit of main function. Since the i is still allocated space, *j prints the value stored in i since j points i.

39.

main()
{
int i=-1;
-i;
printf("i = %d, -i = %d \n",i,-i);
}
Answer:
i = -1, -i = 1
Explanation:
-i is executed and this execution doesn't affect the value of i. In printf first you just print the value of i. After that the value of the expression -i = -(-1) is printed.

40.
main()
{
register i=5;
char j[]= "hello";
printf("%s %d",j,i);
}
Answer:
hello 5
Explanation:
if you declare i as register compiler will treat it as ordinary integer and it will take integer value. i value may be stored either in register or in memory.

41.

main()
{
int i=5,j=6,z;
printf("%d",i+++j);
}
Answer:
11
Explanation:
the expression i+++j is treated as (i++ + j)

42.

struct aaa{
struct aaa *prev;
int i;
struct aaa *next;
};
main()
{
struct aaa abc,def,ghi,jkl;
int x=100;
abc.i=0;abc.prev=&jkl;
abc.next=&def;
def.i=1;def.prev=&abc;def.next=&ghi;
ghi.i=2;ghi.prev=&def;
ghi.next=&jkl;
jkl.i=3;jkl.prev=&ghi;jkl.next=&abc;
x=abc.next->next->prev->next->i;
printf("%d",x);
}
Answer:
2
Explanation:
above all statements form a double circular linked list;
abc.next->next->prev->next->i
this one points to "ghi" node the value of at particular node is 2.

43.

struct point
{
int x;
int y;
};
struct point origin,*pp;
main()
{
pp=&origin;
printf("origin is(%d%d)\n",(*pp).x,(*pp).y);
printf("origin is (%d%d)\n",pp->x,pp->y);
}

Answer:
origin is(0,0)
origin is(0,0)
Explanation:
pp is a pointer to structure. we can access the elements of the structure either with arrow mark or with indirection operator.
Note:
Since structure pointer is globally declared x & y are initialized as zeroes

44.

main()
{
char *p;
int *q;
long *r;
p=q=r=0;
p++;
q++;
r++;
printf("%p...%p...%p",p,q,r);
}
Answer:
0001...0002...0004
Explanation:
++ operator when applied to pointers increments address according to their corresponding data-types.

45.

aaa()
{
printf("hi");
}
bbb(){
printf("hello");
}
ccc(){
printf("bye");
}
main()
{
int (*ptr[3])();
ptr[0]=aaa;
ptr[1]=bbb;
ptr[2]=ccc;
ptr[2]();
}
Answer:
bye
Explanation:
ptr is array of pointers to functions of return type int.ptr[0] is assigned to address of the function aaa. Similarly ptr[1] and ptr[2] for bbb and ccc respectively. ptr[2]() is in effect of writing ccc(), since ptr[2] points to ccc.

46.

main()
{
int i =0;j=0;
if(i && j++)
printf("%d..%d",i++,j);
printf("%d..%d,i,j);
}
Answer:
0..0
Explanation:
The value of i is 0. Since this information is enough to determine the truth value of the boolean expression. So the statement following the if statement is not executed. The values of i and j remain unchanged and get printed.

47.

main()
{
int i;
i = abc();
printf("%d",i);
}
abc()
{
_AX = 1000;
}
Answer:
1000
Explanation:
Normally the return value from the function is through the information from the accumulator. Here _AH is the pseudo global variable denoting the accumulator. Hence, the value of the accumulator is set 1000 so the function returns value 1000.

48.

int i;
main()
{
int t;
for ( t=4;scanf("%d",&i)-t;printf("%d\n",i))
printf("%d--",t--);
}
// If the inputs are 0,1,2,3 find the o/p
Answer:
4--0
3--1
2--2
Explanation:
Let us assume some x= scanf("%d",&i)-t the values during execution
will be,
t i x
4 0 -4
3 1 -2
2 2 0

49.

main()
{
int a= 0;int b = 20;char x =1;char y =10;
if(a,b,x,y)
printf("hello");
}
Answer:
hello
Explanation:
The comma operator has associativity from left to right. Only the rightmost value is returned and the other values are evaluated and ignored. Thus the value of last variable y is returned to check in if. Since it is a non zero value if becomes true so, "hello" will be printed.

50.

main()
{
unsigned int i;
for(i=1;i>-2;i--)
printf("c aptitude");
}
Explanation:
i is an unsigned integer. It is compared with a signed value. Since the both types doesn't match, signed is promoted to unsigned value. The unsigned equivalent of -2 is a huge value so condition becomes false and control comes out of the loop.

51.

What are the following notations of defining functions known as?
i. int abc(int a,float b)
{
/* some code */
}

ii. int abc(a,b)
int a; float b;
{
/* some code*/
}
Answer:
i. ANSI C notation
ii. Kernighan & Ritche notation

52.

main()
{
char *p;
p="%d\n";
p++;
p++;
printf(p-2,300);
}
Answer:
300
Explanation:
The pointer points to % since it is incremented twice and again decremented by 2, it points to '%d\n' and 300 is printed.

53.

void main()
{
int k=ret(sizeof(float));
printf("\n here value is %d",++k);
}
int ret(int ret)
{
ret += 2.5;
return(ret);
}
Answer:
Here value is 7

54.

void main()
{
unsigned giveit=-1;
int gotit;
printf("%u ",++giveit);
printf("%u \n",gotit=--giveit);
}
Answer:
0 65535

55.

void main()
{
int i;
char a[]="\0";
if(printf("%s\n",a))
printf("Ok here \n");
else
printf("Forget it\n");
}
Answer:
Ok here
Explanation:
Printf will return how many characters does it print. Hence printing a null character returns 1 which makes the if statement true, thus "Ok here" is printed.

56.

void main()
{
void *v;
int integer=2;
int *i=&integer;
v=i;
printf("%d",(int*)*v);
}
Answer:
Compiler Error. We cannot apply indirection on type void*.
Explanation:
Void pointer is a generic pointer type. No pointer arithmetic can be done on it. Void pointers are normally used for,
1. Passing generic pointers to functions and returning such pointers.
2. As a intermediate pointer type.
3. Used when the exact pointer type will be known at a later point of time.

57.

void main()
{
int i=i++,j=j++,k=k++;
printf(“%d%d%d”,i,j,k);
}
Answer:
Garbage values.
Explanation:
An identifier is available to use in program code from the point of its declaration.
So expressions such as i = i++ are valid statements. The i, j and k are automatic variables and so they contain some garbage value. Garbage in is garbage out (GIGO).

58.

void main()
{
static int i=i++, j=j++, k=k++;
printf(“i = %d j = %d k = %d”, i, j, k);
}
Answer:
i = 1 j = 1 k = 1
Explanation:
Since static variables are initialized to zero by default.

59.

main()
{
while(1)
{
if(printf("%d",printf("%d")))
break;
else
continue;
}
}
Answer:
Garbage values
Explanation:
The inner printf executes first to print some garbage value. The printf returns no of characters printed and this value also cannot be predicted. Still the outer printf prints something and so returns a non-zero value. So it encounters the break statement and comes out of the while statement.

60.

main()
{
unsigned int i=10;
while(i-->=0)
printf("%u ",i);

}
Answer:
10 9 8 7 6 5 4 3 2 1 0 65535 65534…..
Explanation:
Since i is an unsigned integer it can never become negative. So the expression i-- >=0 will always be true, leading to an infinite loop.

61.

main()
{
int x,y=2,z,a;
if(x=y%2) z=2;
a=2;
printf("%d %d ",z,x);
}
Answer:
Garbage-value 0
Explanation:
The value of y%2 is 0. This value is assigned to x. The condition reduces to if (x) or in other words if(0) and so z goes uninitialized.

62.

main()
{
int a[10];
printf("%d",*a+1-*a+3);
}
Answer:
4
Explanation:
*a and -*a cancels out. The result is as simple as 1 + 3 = 4 !

63.
main()
{
unsigned int i=65000;
while(i++!=0);
printf("%d",i);
}
Answer:
1
Explanation:
Note the semicolon after the while statement. When the value of i becomes 0 it comes out of while loop. Due to post-increment on i the value of i while printing is 1.

64.

main()
{
int i=0;
while(+(+i--)!=0)
i-=i++;
printf("%d",i);
}
Answer:
-1
Explanation:
Unary + is the only dummy operator in C. So it has no effect on the expression and now the while loop is, while(i--!=0) which is false and so breaks out of while loop. The value –1 is printed due to the post-decrement operator.

65.

Is the following statement a declaration/definition. Find what does it mean?
int (*x)[10];
Answer
Definition.
x is a pointer to array of(size 10) integers.

66.

#ifdef something
int some=0;
#endif

main()
{
int thing = 0;
printf("%d %d\n", some ,thing);
}

Answer:
Compiler error : undefined symbol some
Explanation:
This is a very simple example for conditional compilation. The name something is not already known to the compiler making the declaration int some = 0; effectively removed from the source code.

67.

#if something == 0
int some=0;
#endif

main()
{
int thing = 0;
printf("%d %d\n", some ,thing);
}

Answer
0 0
Explanation
This code is to show that preprocessor expressions are not the same as the ordinary expressions. If a name is not known the preprocessor treats it to be equal to zero.

68.
int swap(int *a,int *b)
{
*a=*a+*b;*b=*a-*b;*a=*a-*b;
}
main()
{
int x=10,y=20;
swap(&x,&y);
printf("x= %d y = %d\n",x,y);
}
Answer
x = 20 y = 10
Explanation
This is one way of swapping two values. Simple checking will help understand this.

69.
main()
{
int i=5;
printf("%d",++i++);
}
Answer:
Compiler error: Lvalue required in function main
Explanation:
++i yields an rvalue. For postfix ++ to operate an lvalue is required.

70.

main()
{
char *p = “ayqm”;
char c;
c = ++*p++;
printf(“%c”,c);
}
Answer:
b
Explanation:
There is no difference between the expression ++*(p++) and ++*p++. Parenthesis just works as a visual clue for the reader to see which expression is first evaluated.

71.

main()
{
int i=5;
printf(“%d”,i=++i ==6);
}

Answer:
1
Explanation:
The expression can be treated as i = (++i==6), because == is of higher precedence than = operator. In the inner expression, ++i is equal to 6 yielding true(1). Hence the result.

72.
void ( * abc( int, void ( *def) () ) ) ();

Answer::
abc is a ptr to a function which takes 2 parameters .(a). an integer variable.(b). a ptr to a funtion which returns void. the return type of the function is void.

73.

main()
{
while (strcmp(“some”,”some\0”))
printf(“Strings are not equal\n”);
}
Answer:
No output
Explanation:
Ending the string constant with \0 explicitly makes no difference. So “some” and “some\0” are equivalent. So, strcmp returns 0 (false) hence breaking out of the while loop.

74.

main()
{
char str1[] = {‘s’,’o’,’m’,’e’};
char str2[] = {‘s’,’o’,’m’,’e’,’\0’};
while (strcmp(str1,str2))
printf(“Strings are not equal\n”);
}
Answer:
“Strings are not equal”
“Strings are not equal”
….
Explanation:
If a string constant is initialized explicitly with characters, ‘\0’ is not appended automatically to the string. Since str1 doesn’t have null termination.

75.

main()
{
int i = 3;
for (;i++=0;) printf(“%d”,i);
}

Answer:
Compiler Error: Lvalue required.

76.

void main()
{
int *mptr, *cptr;
mptr = (int*)malloc(sizeof(int));
printf(“%d”,*mptr);
int *cptr = (int*)calloc(sizeof(int),1);
printf(“%d”,*cptr);
}
Answer:
garbage-value 0
Explanation:
The memory space allocated by malloc is uninitialized, whereas calloc returns the allocated memory space initialized to zeros.

77.

void main()
{
static int i;
while(i<=10) (i>2)?i++:i--;
printf(“%d”, i);
}
Answer:
32767
Explanation:
Since i is static it is initialized to 0. Inside the while loop the conditional operator evaluates to false, executing i--. This continues till the integer value rotates to positive value (32767). The while condition becomes false and hence, comes out of the while loop, printing the i value.


Sunday, March 22, 2009

The OSI Reference Model

Connecting open systems that are open for communication with other system.
Seven layers.
  • Physical layer:
Transmit raw bits from one system to another.
Amount of volts needed to represent 0 or 1.
Type of transmission medium whether Guided or Unguided
Guided(copper wire, fiber optics) and Unguided(laser or radio waves).
  • Data link layer
Accepts the raw bits which are received from the physical layer.Divides the sequence of bit stream received in parts called as frames and recompute the check sum for checking errors.for detecting errors it uses the CRC or Polynomial is used and for error correcting hamming distance is used.
it also performs flow control.
Node to Node transmission takes place.
ARP(Address Resolution Protocol),RARP(Reverse Address Resolution Protocol),
Frame relay(x.25),ISDN,PPP,LLC etc.
  • Network layer
This layer deals with the end to end transmission.
This layer mainly adds source and destination address in the header.
Route the data to different LANs and WANs depending on network Address.
Example : IP,ICMP.

  • Transport layer
This provides efficient reliable and cost effective service to the users.
This ensures the transmission of data to the correct process.
TCP and UDP packets comes under this.
  • Session Layer
This layers allows users on different machines to establish session between them.
This checks two stations do not attempt the same operation at same time.
Critical operation functionality also present here(synchronization).
Starts and stops session and maintains order.
  • Presentation layer
This layer deals with the syntax and semantics of the information to be transmitted.
It encode data in a format so that receiver can easily understand.
This layer also deals with the encryption and compression of the data.
eg: ASCII to EBCDID , Binary to BCD.
  • Application layer
Deals with the protocols that are need for the transfer file,mail etc.
Examples are : SMPT/IMAP4(E-MAIL),Telenet,HTTP(WWW),FTP(File Transfer),
RIP(Route Information Protocol),OSPF(Open Shortest Path First),TFTP (Trivial File Transfer Protocol),DHCP(Dynamic Host Configuration Protocol),BOOTP(Bootstrap protocol).

Names of various PDU in each layer.
Application Protocol: APDU
Presentation Protocol:PPDU
Session protocol:SPDU
Transport Protocol:TPDU
Network : Packet
Datalink: frame
Physical: bit

Friday, March 20, 2009

Preprocessing in C

C's preprocessor provides a facility for defining constant and substitution, which are commonly called macros.
  • #include
The include directive tells the compiler to include all the contents of a specified file in the source file before giving the source file for compiling.

eg: #define TRUE 1
  • #undef
Nullify the effect of define directive.
eg: #undef TRUE
#define TRUE correct

#include
Angle brackets Searches in the default directories of include files.

Quotes specifies search in current directory.
  • #ifdef
ifdef is used to make a substitution depending on whether a certain identifier is defined. If defined returns true else false.

e.g: #ifdef TRUE
#define FALSE 0
#endif
Note: we can easily add multiple macros in between the two macros.
  • #ifndef
eg: #ifndef FALSE
#define WRONG 0
  • #if
#if allows you to define more generalized conditions. Multiple conditions, which are connected by relational operators such as AND(&&), OR(||), are allowed.
  • #error
Used to display error message by preprocessor.

#if !define FALSE
#error "Specify FALSE condition"
  • #line
Mainly used for debugging purpose.
eg: #line100 indicates it is in line 100

C has provided two special identifiers: __FILE__ and __LINE__, which indicate the file name of the source file and the current line number, respectively.

Macros allow replacement of the identifier by using a statement or expression.
eg: #define CUBE(x) x*x*x

Placeholders for Scanf

THE scanf PLACEHOLDERS

The scanf placeholder consists of % at the beginning and a type indicator at the end. Apart from that it can have *, a maximum field-width indicator, and a type indicator modifier, for example,

%10.2f,%10d
  • d, i Used for signed integers; the expected argument should be a pointer to int.

  • o Used for unsigned int expected's value. It should be an integer in octal form.

  • U Unsigned integer in decimal form.

  • X, Unsigned integer in hexadecimal form.

  • E, f, g, G Floating-point values.

  • S Character string. It matches a sequence of non-whitespace characters terminated by an end-of-line or end-of-file character. The additional argument should be a pointer to char and should point to an area that is large enough to hold the input string as well as the NULL terminator.

  • C Matches the number of characters according to a specified field-width. If no width is specified then a single character is assumed. The additional argument must be a pointer to char; the area pointed to should be large enough to hold the specified number of characters.

  • N Does not read any input but writes the number of characters so far in the target variable.

The * is used to suppress input. For example, with %*d, if your input consists of 5 values and you want to ignore the middle 3 values, you can write:

scanf(" %d %*d %*d%*d %d ", &i, &j)

So, if your input is

10 20 30 40 50

it will get the value 10 and j will get the value 50. This is useful when you are getting the input from a file.

Field-width

It indicates the maximum number of characters that are read into the variables.

Explanation

  1. scanf requires two inputs: the first is a string argument and the second is a set of additional arguments.

  2. You can define how the input is to be taken by using placeholders.

Thursday, March 19, 2009

Other Best Links

Introduction - Google Custom Search API - Google Code
How to get Free Linux CD’s DVD’s from Home « Ammasajan’s Weblog
Howstuffworks
The Linux Virtual File-system Layer
Programming Contests, Software Development, and Employment Services at TopCode
Research Projects :: Princeton Computer Science
Ravi Kiran's Homepag
uIP 1.0
Work-Study Abroad in the USA — LearnHub
Study Abroad » Lessons — LearnHub
सरकारी नौकरी - Government Jobs India - Sarkari Naukri
TCP/IP Internetworking Tutorial
Daily Artisan » Open Source E-Books for Linux
VideoTutorials

Device Drivers

Linux Device Drivers, 2nd Edition: In PDF Format
Writing device drivers in Linux: A brief tutorial
Embedded.com - Linux device driver design
Linux Device Driver Template/Skeleton with Interrupt Handler and Device Read Blocking (Kernel Module Example)
Writing Device Drivers: Tutorial
FreeBSD Architecture Handbook
Character devices notes
Linux Device Drivers, 2nd Edition: Online Book
Linux Device Drivers, 3rd Edition
The Linux Kernel Module Programming Guide
LUV: Linux Character Device Drivers
The Linux Kernel: Table of Contents
Writing a Network device driver - Part 1 LG #93
http://www.iana.org/assignments/port-numbers
Serial UART, an in depth tutorial

C Library

System Interfaces & Headers Issue 5 - Index

The GNU C Library

Tutorials

All C functions of UNIX/linux

C Ref Master Index

Programming in C

Linux Kernel

http://www.kernel.org/

PlaceHolders for printf

Placeholders are used to print values of arguments supplied in print. The directives in the placeholders control printing.

Program/Example

The general form of a placeholder is:

  • % flags field-width precision prefix type-identifier.

Type-identifiers

The type-identifiers are as follows:

  • d, i Signed integers

  • o Unsigned integers displayed in octal form.

  • u Unsigned integers in decimal form.

  • x Unsigned integers in hexadecimal form, and the hexadecimal characters a, b, c, d, e, and f printed in lowercase.

  • X Unsigned integer in hexadecimal form, and the hexadecimal characters A, B, C, D, E, and F printed in uppercase.

  • c Any value converted to unsigned char and displayed; c is used mainly for printing characters.

  • s The argument is converted to a character array and is printed; the last null in the string is not printed.

  • f Floating point.

  • e, E Floating point displayed in exponential form. It will have one digit to the left of the decimal point; the number of digits on the right side of the decimal point depends on the required precision.

  • g, G The value can be printed in floating point or exponential form. The exponential form is used if the exponent is less than –1 or if the exponent causes more places than required by the specified precision; the decimal point appears only if it is followed by a digit.

  • n This indicates to print the number of characters that are printed so far by printf.

  • p It indicates an additional argument pointer to void; the value of the pointer is converted to a sequence of characters.

Type prefixes

  • h It can appear before type indicators d, i, o, u, x, and X. It indicates that the value to be displayed should be interpreted as short; for example, short integer (hd) and short unsigned integer (hu).

  • l It can appear before type-identifiers d, i, o, u, x, and X. It indicates that the value to be displayed should be interpreted as long; for example, long integer (hd) and long unsigned integer (hu).

  • l, L Available for type-identifiers e, E, f, g, and G. It indicates that a value should be indicated as long double.

Field-width

  1. Field-width indicates the least number of columns that will be allocated to the output. For example, if you write %4d to i and the value of i is 10, then 4 columns are allocated for i and 2 blank are added on left side of value of i. So the output is bb10. Here, b indicates blank.

  2. If the value is more than the specified column, field-width is ignored and the number of columns used is equal to the number of columns required by the arguments. So if i is 12345 then 5 columns are used, even if %4d is specified.

  3. In any circumstance, the output width is not shortened, because of field-width.

  4. If you specify * instead of field-width then you have to specify additional arguments. For example,

    printf ("%*d\n", 5, 20);     // A
    printf ("%*d\n", 20, 5); // B

    In A, 5 is substituted for * and it indicates putting the value 20 in 5 columns.

    In B, 20 is substituted for * and it indicates putting the value 5 in 20 columns.

Precision

  1. Precision indicates the minimum number of digits printed for type integers d, i, o, u, x, and X. For example,

    i.    printf("%10.4d\n", 35)
  2. Here 10 is the field-width and 4 is the precision, so 10 columns are used for the 4-digit output. To make 35 into 4 digits, two 0s are added to the left side to make it 0035. To print 0035 in 10 columns, blanks are added to make the output bbbbbb0035.

  3. For floating arguments, precision indicates how many digits are printed after decimal points. If precision is more than the number of digits on the right side of the decimal point, 0s are added to the right side.

  4. If precision indicates too few digits, then it is ignored and the number of digits are printed as necessary.

Flags

  1. Flag characters are used to give directives for the output. You can use multiple flag characters in any order.

  2. The flag characters are as follows:

    • Indicates that output is left justified.

      printf("%-10.4d\n", 25)
    • It causes the number to be printed as 0025bbbbbb. Thus, blanks are added to the right side.

    • In the absence of a flag, it is printed as bbbbbb0025.

    • + Indicates that i number is printed using a sign character (+ or —).

      printf("%+d\n", -25);
      printf("%+d\n", 25);
    • It causes printing as

      -25
      +25
    • Indicates a space for positive values so that positive values and negative values are aligned. For example,

      printf("% d\n", 25);
      printf("% d", 25);
    • It causes printing in the form of

      b25
      25
    • In the first case, blank is displayed.

    • # Indicates that the value should be converted to another form before displaying. For example, for hexadecimal values you can indicate 0X; for the floating data type, # indicates that the decimal point should always be included in the output.

    • 0 Used with whole and real numbers, 0 causes 0s to be padded to complete the field width. If the precision is specified as 0, then this flag is ignored; if the 0 and – flags are both specified, the 0 flag is ignored.

    ESCAPE SEQUENCE

Escape sequences are the special directives used to format printing. For example, \n indicates that the next printing should start from the first column of the next line. Following are the escape sequences:

  • \a Alert

  • Produces a beep or flash; the cursor position is not changed.

  • \b Backspace

  • Moves the cursor to the last column of the previous line.

  • \f Form feed

  • Moves the cursor to start of next page.

  • \n New line

  • Moves the cursor to the first column of the next line.

  • \r Carriage Return

  • Moves the cursor to the first column of the current line.

  • \t Horizontal Tab

  • Moves the cursor to the next horizontal tab stop on the line.

  • \v Vertical Tab

  • Moves the cursor to the next vertical tab stop on the line.

  • \\

  • Prints \\.

  • \"

  • Prints "

  • %%

  • Prints %.

Tuesday, March 17, 2009

Facts About Computer and Programming

  • Most applications in a data warehouse consists of transactions.
  • A Transaction consist of one read and write operation.
  • For security purpose we use proxy server along with firewall.
  • Rollback command undo all changes of a transaction.
  • Applet is a dynamic document application program.
  • The speed of a Super Computer is mainly measured in FLOPS.
  • RAID 3 is a single parity drive depends on disk controller for finding out which disk has failed.
  • Propagation time is the time which takes by a signal to transmit from one point of a medium to other end.
  • Sliding window protocol is used in data link layer to store the information about frame sequences and respective acknowledgement.
  • archie is a program to find files in ftp site.
  • website to get kernel source code http://lxr.free-electrons.com/source/
  • The linux kernel mailing list http://www.tux.org/lkml/#s15-3
  • static library has extension .a and dynamic library has .so.
  • files which shown in colors in linux require permissions.
  • ./ is the relative path and starts with / is called absolute path.

Monday, March 16, 2009

Important facts in Writing a C Program

  • Preprocessor can be redefined any where in the Program so that most recently assigned value will be taken.
  • The scope of the labels is limited to functions.
  • The case statement can have only constant expressions (this implies that we cannot use variable names directly). Enumerated types can be used in case statements.
  • Scanf returns number of items successfully read.
  • A variable is available for use from the point of declaration.
  • Pointers give a facility to access the value of a variable indirectly.
  • Prefix/postfix increment(++) and decrement(--) must be used with variables.
  • Precedence is very important in writing a expression.
  • Execution of preprocessor is separate from execution of compiler(Note: we can use any keywords and inbuilt function names).
  • Every function name contains some address. So we can easily print that address using printf("%p",main);.
  • Array names are pointer constants.
  • Character constants are saved in code/data area but not in stack.
  • g1##g2,Here g1 and g2 joined together.
  • The default return value of a function is int. if it is not declared.
  • printf can be implemented using variable length argument list.
  • asserts are used during debugging to make sure that certain conditions are satisfied. If assertion fails, the program will terminate reporting the same. After debugging use, #undef NDEBUG and this will disable all the assertions from the source code. Assertion is a good debugging tool to make use of. if program terminates it shows <> <> of the program.
  • stdin,stdout,stderr these three files are opened automatically when c program executes.
  • SEEK_SET sets the file pointer to beginning of file.
  • SEEK_CUR and SEEK_END are set accordingly by the name.
  • if we want to read input between two quotation marks we should use scanf(" \"%[^\"]\"",s);.
  • fgets always return a pointer,So while reading end of file it returns NULL pointer.
  • If a program is continuously executed without any condition to terminate then its stack will filled completely and abnormally terminates.
  • -1 is a boolean true value,Hence in if statement it executes next instruction of if.
  • When two strings are placed together (or separated by white-space) they are concatenated (this is called as "stringization" operation).
  • For array elements, consecutive memory locations are allocated.
  • When a variable can be resolved by using multiple references, the local definition is given more preference.
  • The variables in C can have static or automatic lifetimes.
  • When a variable has a static lifetime, memory is allocated at the beginning of the program execution and it is reallocated only after the program terminates.
  • When a variable has an automatic lifetime, the memory is allocated to the variable when the function is called and it is deallocated once the function completes its execution.
  • Global variables have static lifetimes.
  • By default, local variables have automatic lifetimes.
  • To make a local variable static, use the storage-class specifier.
  • Extern means that the variable or function is implemented elsewhere but is referred to in the current file.
  • memory is allocated to the global variable at the beginning of the program execution.
  • Register allocation is done for faster access, generally for loop counters.
  • You cannot declare global register variables.
  • The code between opening and closing curly brace called as block.
  • Array elements are Homogeneous(means their elements are of same type).
  • Structure elements are of Heterogeneous type (means their elements are of different type).
  • Never compare or at-least be cautious when using floating point numbers with relational operators (== , >, <, <=, >=,!= ) .

Common Mistakes in C

  • Initializing the structure member variables while declaring.
  • Converting a character Array into String without Appending NULL character.
  • Calling the function without declaring the Prototype.
  • Declared buffer must be initialized before use.
  • Using proper data types when copying functions from one project to another project.
  • Multiple definition of a function some times creates a problem when we are browsing the code through tags in some famous editors like vim etc.(NOTE: Enable the function which is currently in use.Comment the other ones).
  • Avoid same function names which are already defined in system library.

C Operator Precedence

()
[]
.
->
++ --
Parentheses (function call)
Brackets (array subscript)
Member selection via object name
Member selection via pointer
Postfix increment/decrement

left-to-right

++ --
+ -
! ~
(type)
*
&
sizeof
Prefix increment/decrement
Unary plus/minus
Logical negation/bitwise complement
Cast (change type)
Dereference
Address
Determine size in bytes
right-to-left
* / % Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <=
> >=
Relational less than/less than or equal to
Relational greater than/greater than or equal to
left-to-right
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
=
+= -=
*= /=
%= &=
^= |=
<<= >>=
Assignment
Addition/subtraction assignment
Multiplication/division assignment
Modulus/bitwise AND assignment
Bitwise exclusive/inclusive OR assignment
Bitwise shift left/right assignment
right-to-left

,

Comma (separate expressions) left-to-right