P. 1
c puzzles

c puzzles

|Views: 220|Likes:
Published by api-3721375

More info:

Published by: api-3721375 on Oct 19, 2008
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as DOC, PDF, TXT or read online from Scribd
See more
See less

10/14/2015

pdf

text

original

C Puzzles : Questions and Answers - Level 1

Questions
*L1.Q1 : Write the output of the following program
#include #define ABC #define XYZ #define XXX void main() { int 20 10 ABC - XYZ

a;

a = XXX * 10; } printf("%d\n", a);

Solution for L1.Q1

L1.Q2 : Write the output of this program
#include #define calc(a, b) (a * b) / (a - b)

void main() { int a = 20, b = 10; printf("%d\n", calc(a + 4, b -2)); }

Solution for L1.Q2

*L1.Q3 : What will be output of the following program ?
#include void main() { int cnt = 5, a; do { a /= cnt;

} while (cnt --); } printf ("%d\n", a);

Solution for L1.Q3

L1.Q4 : Print the output of this program
#include void main() { int a, b, c, abc = 0; a = b = c = 40; if (c) { int abc; } } abc = a*b+c;

printf ("c = %d, abc = %d\n", c, abc);

Solution for L1.Q4

*L1.Q5 : Print the output of this program
#include main() { int k = 5; if (++k < 5 && k++/5 || ++k <= 8); } printf("%d\n", k);

Solution for L1.Q5

L1.Q6 : What is the output of this program ?
#include void fn(int, int);

main() { int a = 5; %d %d\n", a++, ++a); printf("Main : } fn(a, a++);

void fn(int a, int b) { printf("Fn : a = %d \t b = %d\n", a, b); }

Solution for L1.Q6

Answers
L1.A1 Solution for L1.Q1
a = xxx * 10 which is => a => a => a => a = = = = ABC - XYZ * 10 20 - 10 * 10 20 - 100 -80

L1.A2 Solution for L1.Q2
Actual substitution is like this : calc(20+4, 10 -2) is calculated as follows (20+4 * 10-2) / (20+4 - 10-2) (20+40-2) / 12 58 / 12 = 4.8 it is printed in %d the ans is 4

since

L1.A3 Solution for L1.Q3
This problem will compile properly, but it will give run time error. It will give divide-by-zero error. Look in to the do loop portion do { a /= cnt; } while (cnt --); when the 'cnt' value is 1, it is decremented in 'while ( cnt --)' and on next reference of 'cnt' it becomes zero.

a /= cnt; /* ie. a /= 0 */ which leads to divide-by-zero error.

L1.A4 Solution for L1.Q4
the result will be c = 40 and abc = 0; because the scope of the variable 'abc' inside if(c) {.. is not valid out side that if (.) { .. }. }

L1.A5 Solution for L1.Q5
The answer is 7. it is false (Now (or condition ++k point k value is becomes 7. The first condition ++k < 5 k = 6). So, it checks the <= 8) and (now k = 7) it is incremented by twice, hence is checked and 3rd condition true. At this the value of k

L1.A6 Solution for L1.Q6
The solution depends on the implementation of stack. (Depends on OS) In some machines the arguments are passed from left to right to the stack. In this case the result will be Main : 5 7 Fn : 7 7

Other machines the arguments may be passed from right to left to the stack. In that case the result will be Main : 6 6 Fn : 8 7

C Puzzles : Questions and Answers - Level 2

Questions
*L2.Q1 : Write the output of this program
#include main() {

int *a, *s, i; s = a = (int *) malloc( 4 * sizeof(int)); for (i=0; i<4; i++) *(a+i) = i * 10; printf("%d\n", printf("%d\n", printf("%d\n", printf("%d\n", printf("%d\n", *s++); (*s)++); *s); *++s); ++*s);

}

Solution for L2.Q1

*L2.Q2 : Checkout this program result
#include void fn(int); static int main() { } val = 5;

while (val --) fn(val); printf("%d\n", val);

void fn(int val) { static int val = 0; for (; val < 5; val ++) printf("%d\n", val); }

Solution for L2.Q2

L2.Q3 : Can you predict the output of this program ?
#include main() { typedef union { int a; char b[10]; float c; } Union; Union x, y = { 100 };

x.a = 50; strcpy (x.b, "hello"); x.c = 21.50; printf ("Union 2 : %d %s %f\n", x.a, x.b, x.c); printf ("Union Y : %d %s %f\n", y.a, y.b, y.c); }

Solution for L2.Q3

L2.Q4 : Print the output of the program
#include main() { struct Data { int a; int b; } y[4] = { 1, 10, 3, 30, 2, 20, 4, 40}; struct Data *x = y; int i; for(i=0; i<4; i++) { x->a = x->b, ++x++->b; printf("%d %d\t", y[i].a, y[i].b); } }

Solution for L2.Q4

L2.Q5 : Write the output of this program
#include main() { typedef struct int int int char int }xyz; { a; b; c; ch; d;

typedef union { xyz X; char y[100]; }abc; printf("sizeof xyz = %d sizeof abc = %d\n",

}

sizeof(xyz), sizeof(abc));

Solution for L2.Q5

L2.Q6 : Find out the error in this code
#include #include #define Error(str) main() { int fd; char str[20] = "Hello! Test me"; if ((fd = open("xx", O_CREAT | O_RDWR)) < 0) Error("open failed"); if (write(fd, str, strlen(str)) < 0) Error("Write failed"); if (read(fd, str, strlen(str)) < 0) Error("read failed"); printf("File read : %s\n", str); close(fd); printf("Error : %s\n", str); exit(1);

}

Solution for L2.Q6

*L2.Q7 : What will be the output of this program ?
#include main() {

int

*a, i;

a = (int *) malloc(10*sizeof(int)); for (i=0; i<10; i++) *(a + i) = i * i; for (i=0; i<10; i++) printf("%d\t", *a++); } free(a);

Solution for L2.Q7

*L2.Q8 :
Write a program to calculate number of 1's (bit) in a given integer number i.e) Number of 1's in the given integer's equivalent binary representation.

Solution for L2.Q8

Answers
L2.A1 Solution for L2.Q1
The output will be : 0 10 11 20 21 *s++ *++s ++*s => *(s++) => *(++s) => ++(*s)

L2.A2 Solution for L2.Q2
Some compiler (ansi) may give warning message, but it will compile without errors. The output will be : 0 1 2 3 4 and -1

L2.A3 Solution for L2.Q3
This is the problem about Unions. Unions are similar to structures but it differs in some ways. Unions can be assigned only with one field at any time. In this case, unions x and y can be assigned with any of the one field a or b or c at one time. During initialisation of unions it takes the value (whatever assigned ) only for the first field. So, The statement y = {100} intialises the union y with field a = 100. In this example, all fields of union x are assigned with some values. But at any time only one of the union field can be assigned. So, for the union x the field c is assigned as 21.50. Thus, The output will be Union 2 : 22 22 21.50 Union Y : 100 22 22 ( 22 refers unpredictable results )

L2.A4 Solution for L2.Q4
The pointer x points to the same location where y is stored. So, The changes in y reflects in x. The output will be : 10 11 30 31 20 21 40 41

L2.A5 Solution for L2.Q5
The output of this program is purely depends on the processor architecuture. If the sizeof integer is 4 bytes and the size of character is 1 byte (In some computers), the output will be sizeof xyz = 20 sizeof abc = 100

The output can be generalized to some extent as follows, sizeof xyz = 4 * sizeof(int) + 1 * sizeof(char) + padding bytes sizeof abc = 100 * sizeof(char) + padding bytes To keep the structures/unions byte aligned, some padding bytes are added in between the sturcture fields. In this example 3 bytes are padded between ' char ch' and 'int d' fields. The unused bytes are called holes. To understand more about padding bytes (holes) try varing the field types of the structures and see the output.

L2.A6 Solution for L2.Q6
Just try to execute this file as such. You can find out that it will exit immediately. Do you know why? With this hint, we can trace out the error. If you look into the macro 'Error', you can easily identify that there are two separete statements without brases '{ ..}'. That is the problem. So, it exits after the calling open(). The macro should be put inside the brases like this. #define Error(str) { printf("Error : %s\n", str); exit(1); }

L2.A7 Solution for L2.Q7
This program will fault (Memory Can you predict Why? fault/segmentation fault).

Remove the statment 'free(a);' from the program, then execute the program. It will run. It gives the results correctly. What causes 'free(a)' to generate fault? Just trace the address location of pointer variable 'a'. The variable 'a' is incremented inside the 'for loop'. Out side the 'for loop' the variable 'a' will point to 'null'. When the free() call is made, it will free the data area from the base_address (which is passed as the argument of the free call) upto the length of the data allocated previously. In this case, free() tries to free the length of 10 *sizeof(int) from the base pointer location passed as the argument to the free call, which is 'null' in this case. Thus, it generates memory fault.

L2.A8 Solution for L2.Q8
#include main(argc, argv) int argc; char *argv[]; { int count = 0, i; int v = atoi(argv[1]); for(i=0; i<8*sizeof(int); i++) if(v &(1<< } count); v, %d='%d\n",' in 1?s of printf(?No count++;>

C Puzzles : Questions and Answers - Level 3

Questions
L3.Q1 :
Write a function revstr() - which reverses the given string in the same string buffer using pointers. (ie) Should not use extra buffers for copying the reverse string.

Solution for L3.Q1

L3.Q2 :
Write a program to print the series 2 power x, where x >= 0 ( 1, 2, 4, 8, 16, .... ) without using C math library and arithmatic operators ( ie. *, /, +, - and math.h are not allowed)

Solution for L3.Q2

L3.Q3 :
Write a program to swap two integers without using integer (ie. Without using any temporary variable) 3rd

Solution for L3.Q3

L3.Q4 :
Write a general swap macro in C : - A macro which can swap any type of data (ie. float, struct, etc..) int, char,

Solution for L3.Q4

L3.Q5 :
Write a program to delete the entry from the doubly linked list without saving any of the entries of the list to the temporary variable.

Solution for L3.Q5

L3.Q6 : What will be the output of this program ?
#include main() { int *a, *savea, i;

savea = a = (int *) malloc(4 * sizeof(int)); for (i=0; i<4; i++) *a++ = 10 * i; for (i=0; i<4; i++) { printf("%d\n", *savea); savea += sizeof(int); }

}

Solution for L3.Q6

LX.Q7 : Trace the program and print the output
#include typedef int abc(int a, char *b); int func2(int a, char *b) { a *= 2; strcat(b, "func2 "); return a; } int func1(int a, char *b) { abc *fn = func2; a *= a; strcat(b, "func1 "); return (fn(a, b)); } main() { abc *f1, *f2; int res; static char str[50] = "hello! "; f1 = func1; res = f1(10, str); f1 = func2; res = f1(res, str); printf("res : %d } str : %s\n", res, str);

Solution for LX.Q7

LX.Q8 :
Write a program to reverse a Linked list within the same list

Solution for LX.Q8

LX.Q9 : What will be the output of this program
#include main() { int a=3, b = 5; printf(&a["Ya!Hello! how is this? %s\n"], &b["junk/super"]); printf(&a["WHAT%c%c%c %c%c %c !\n"], 1["this"], 2["beauty"],0["tool"],0["is"],3["sensitive"],4["CCCCCC"]);

}

Solution for LX.Q9

LX.Q10 : Solution for LX.Q10

Answers
L3.A1 Solution for L3.Q1
#include char *rev_str(char *str) { char *s = str, *e = s + strlen(s) -1; char *t = "junk"; /* to be safe - conforming with ANSI C std */ while (s < e) { *t = *e; *e-- = *s; *s++ = *t; } return(str);

}

/* Another way of doing this */ char *str_rev(char *str) { int len = strlen(str),i=0,j=len/2;

}

len--; while(i < j) { *(str+i)^=*(str+len)^=*(str+i)^=*(str+len); i++; len--; } return(str);

main (int argc, char **argv) { printf("1st method : %s\n", rev_str(argv[1])); printf("2nd method : %s\n", str_rev(argv[1])); }

L3.A2 Solution for L3.Q2
#include void main() { int i; for(i=0; i< 10; i++) printf("%d\t", 2 << i);

}

L3.A3 Solution for L3.Q3
#include main() {

int a, b; printf("Enter two numbers A, B : "); scanf("%d %d", &a, &b); a^=b^=a^=b; /* swap A and B */

}

printf("\nA = %d, B= %d\n", a, b);

L3.A4 Solution for L3.Q4
#include /* Generic Swap macro*/ #define swap(a, b, type) { type t = a; a = b; b = t; }

/* Verification routines */ main() { int a=10, b =20; float e=10.0, f = 20.0; char *x = "string1", *y = "string2"; typedef struct { int a; char s[20]; } st; st s1 = {50, "struct1"}, s2 = {100, "struct2"}; swap(a, b, int); printf("%d %d\n", a, b); swap(e, f, float ); printf("%f %f\n", e, f); swap(x, y, char *); printf("%s %s\n", x, y); swap(s1, s2, st); printf("S1: %d %s \tS2: %d %s\n", s1.a, s1.s, s2.a, s2.s); ptr_swap(); } ptr_swap() { int *a, *b; float *c, *d; a = (int *) malloc(sizeof(int)); b = (int *) malloc(sizeof(int)); *a = 10; *b = 20; swap(a, b, int *); printf("%d %d\n", *a, *b); c = (float *) malloc(sizeof(float)); d = (float *) malloc(sizeof(float)); *c = 10.01; *d = 20.02; swap(c, d, float *); printf("%f %f\n", *c, *d); }

L3.A5 Solution for L3.Q5
#include /* Solution */ typedef struct Link{ int val; struct Link *next; struct Link *prev; } Link;

void DL_delete(Link **, int); void DL_delete(Link **head, int val) { Link **tail; while ((*head)) { if ((*head)->next == NULL) tail = head; if ((*head)->val == val) { *head = (*head)->next; } else head = &(*head)->next; } while((*tail)) { if ((*tail)->val == val) { *tail = (*tail)->prev; } else tail= &(*tail)->prev; } } /* Supporting (Verification) routine */ Link *DL_build(); void DL_print(Link *); main() {

int Link

val; *head;

head = DL_build(); DL_print(head); printf("Enter the value to be deleted from the list : "); scanf("%d", &val); DL_delete(&head, val); DL_print(head); } Link *DL_build() { int val; Link *head, *prev, *next; head = prev = next = while(1) { Link *new; : "); printf("Enter the value for the list element (0 for end) scanf("%d", &val); if (val == 0) break; NULL;

new = (Link *) malloc(sizeof(Link)); new->val = val; new->prev = prev; new->next = next; if (prev) prev->next = new; else head = new; prev = new; } } return (head);

void DL_print(Link *head) { Link *shead = head, *rhead; printf("\n****** Link List values ********\n\n"); while(head) { printf("%d\t", head->val); if (head->next == NULL) rhead = head; head = head->next; } printf("\n Reverse list \n"); while(rhead) { printf("%d\t", rhead->val); rhead = rhead->prev; } printf("\n\n"); }

L3.A6 Solution for L3.Q6
The first value will be 0, the rest of the three values will not be predictable. Actually it prints the values of the following location in each step * savea * (savea + sizeof(int) * sizeof(int)) etc... ie. savea += sizeof(int) => savea = savea + sizeof(savea_type) * sizeof(int) ( by pointer arithmatic) => save = savea + sizeof(int) * sizeof(int) Note: You can verify the above by varing the type of 'savea' variable to char, double, struct, etc. Instead of statement 'savea += sizeof(int)' use savea++ then the values 0, 10, 20 and 30 will be printed. This behaviour is because of pointer arithmatic.

LX.A7 Solution for LX.Q7
Two function pointers f1 and f2 are declared of the type abc. whereas abc is a pointer to a function returns int. func1() which is assigned to f1 is called first. It modifies the values of the parameter 'a' and 'b' to 100, "hello! func1 ". In func1(), func2() is called which further modifies the value of 'a' and 'b' to 200, "hello! func1 func2 " and returns the value of 'a' which is 200 to the main. Main calls f1() again after assigning func2() to f1. So, func2() is called and it returns the following value which will be the output of this program. res : 400 str : hello! func1 func2 func2 called :

The output string shows the trace of the functions func1() and func2() then again func2().

LX.A8 Solution for LX.Q8
#include typedef struct Link { int val; struct Link *next; } Link; /* Reverse List function */ Link *SL_reverse(Link *head) { Link *revlist = (Link *)0; while(head) { Link *tmp; tmp = head; head = head->next; tmp->next = revlist; revlist = tmp;

} }

return revlist; /* Supporting (Verification) routines */ Link *SL_build(); main()

{

Link

*head;

head = SL_build(); head = SL_reverse(head); printf("\nReversed List\n\n"); while(head) { printf("%d\t", head->val); head = head->next; }

}

Link *SL_build() { Link *head, *prev; head = prev = (Link *)0; while(1) { Link int *new; val;

printf("Enter List element [ 0 for end ] : "); scanf("%d", &val); if (val == 0) break; new = (Link *) malloc(sizeof(Link)); new->val = val; if (prev) prev->next = new; else head = new; prev = new;

}

}

prev->next = (Link *)0; return head;

LX.A9 Solution for LX.Q9
In C we can index an array in two ways. For example look in to the following lines int a[3] = {10, 20, 30, 40}; In this example index=3 of array 'a' can be represented in 2 ways. 1) a[3] and 2) 3[a] i.e) a[3] = 3[a] = 40 Extend the same logic to this output as follows Hello! how is this? That is C problem. You will get the

super

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->