c sorted queston

Upload: sushilkesharwani

Post on 07-Jan-2016

304 views

Category:

Documents


0 download

DESCRIPTION

n

TRANSCRIPT

PLACES where float should not be used:1 .mod(fmod(x,y)- Calculates x modulo y, the remainder of x/y.This function is the same as the modulus operator. Butfmod()performs2.switch and cCASE3. Bit field type must besigned intorunsigned int.The char type:char scheme:4;is also a valid statement.float category:5; NOT ALLOWED4. printf("%f\n",f a)hereais a float variable and0.7is a double constant. The double constant0.7is greater than the float variable* float a=0.7; printf("%.10f %.10f\n",0.7, a);

0.7000000000 0.6999999881//double is always greater than float

float a=0.7; printf("%.10f %.7f\n",0.7, a);output 0.7000000000 0.7000000// all the vaues have some precision valur above which they will show the value smaller than expected whether it is double or float.but precison valur of float is 7 approx above which its valur will decrease from actual value expectedWhat will be the output of the program if the array begins at 65472 and each integer occupies 2 bytes?

int a[3][4] = {1, 2, 3, 4, 4, 3, 2, 1, 7, 8, 9, 0}; printf("%u, %u\n", a+1, &a+1);65480, 65496

The declarationnum[SIZE]is allowed if SIZE is a macro.

: cannot use static for function parametersSpace is a character ,NULL always represent a pointerIn C and in C++ single quotes identify a single character, while double quotes create a string literal. 'a' is a single a character literal, while "a" is a string literal containing an 'a' and a null terminator (that is a 2 char array).Note that in C, the type of a character literal isint, and notchar, that issizeof 'a'is 4 in an architecture where ints are 32bit (and CHAR_BIT is 8), whilesizeof(char)is 1 everywhere.int main(){ printf("%d, %d\n", sizeof(NULL), sizeof('#')); return 0;}OUTPUT:4, 413.What will be the output of the program?#include

int main(){ int arr[3] = {2, 3, 4}; char *p; p = arr; p = (char*)((int*)(p)); printf("%d, ", *p); p = (int*)(p+1); printf("%d", *p); return 0;}

[A].2, 3[B].2, 0

[C].2, Garbage value[D].0, 0

p = (char*)((int*)(p));// till now the pointer p is type casted to store the variable of type character.

printf("%d, ", *p); // %d means integer value so value at first address i.e. 2 will be printed.

p = (int*)(p+1); // here p is still of type character as type casted in step 1 so p(i.e address) and plus 1 will increase only by one byte so Assuming that integer requires 2 bytes of storage the integer array will be stored in memory asvalue 2 3 4address 00000010 00000000 00000011 00000000 00000100 00000000 pointer p+1 sop+1points to that location which is unfilled as during intialization 2,3,4 were stored in variable of type integer(2 bytes).sop+1will point to00000000.(int*)p+1 // p+1 is type casted again to integerprintf("%d", *p); // this will print 0 as output as by default integer contains 0 as value.Note: The number-sign or "stringizing" operator (#) converts macro parameters to string literals without expanding the parameter definition. It is used only with macros that take arguments## (macro concatenation) operator//#define FUN(i, j) i##j// FUN(First, Second)// FirstSecond.1.printf("Computer","Programming"); ComputerYou might feel that answer of this statement should be Programming because comma operator always returns rightmost operator, in case of printf statement once comma is read then it will consider preceding things as variable or values for format specifier.

2. #define MESS junkprintf("MESS\n");// is no macro calling inside the printf statement occured.B.MESS

What will be the output of the program if the size of pointer is 4-bytes?#include

int main() printf("%d, %d\n", sizeof(NULL), sizeof("")); return 0;}

Note: #ifchecks for thevalueof the symbol, while#ifdefchecks theexistenceof the symbol (regardless of its value). Each#ifdirective in a source file must be matched by a closing#endifdirective. Any number of#elifdirectives can appear between the#ifand#endifdirectives, but at most one#elsedirective is allowed. The#elsedirective, if present, must be the last directive before#endif. The conditional macro#ifmust have an#endif. In this program there is no#endifstatement written. The#ifdefidentifierstatement is equivalent to#if 1whenidentifierhas been defined, and it is equivalent to#if 0whenidentifierhas not been defined or has been undefined with the#undefdirective. These directives check only for the presence or absence of identifiers defined with#define, not for identifiers declared in the C or C++ source code.Note: Macro names should only consist of alphanumeric characters and underscores, i.e.'a-z','A-Z','0-9', and'_', and the first character should not be a digit. Some preprocessors also permit the dollar sign character'$', but you shouldn't use it; unfortunately I can't quote the C standard since I don't have a copy of it.Fill with 1s in the left side for right shift for negative numbers.1. 2. unsigned int a=0xffff;//REPRESENT HEXADECIMAL MAI ffff haiNOTE:CMD NOT DONE DO IT //PAGE 58Note: cannot initialize more than oneunionmember.1.itoa()converts an integer to a string.// itoa(num1, str1, 10); itoa (no,buff,2);// itoa()takes the integer input value input and converts it to a number in base radix. The resulting number a sequence of base-radix digits.

/* 10 radix value */

2.ltoa()converts a long to a string.3.ultoa()converts an unsigned long to a string.4.sprintf()sends formatted output to a string, so it can be used to convert any type of values to string typefflush(FilePointer);fflush(NULL);flushes all streams.printf("%f, %f", floor(i), ceil(i));//IT WORKS WELL WITH FLOAT IDENTIFIERBothceil()andfloor()return the integer found as adouble. doubletointit returns '0'.So, the output is '2.000000, 0'. float i = 2.3; printf("%d\n", floor(i)); printf("%f", ceil(i)); return 0;}OUTPUT:03.000000Directly ceil and floor with int format specifier will result in zero.memcmp(dest, src, 2)// Explanation:memcmpcompares the first 2 bytes of the blocksdestandsrc as unsigned chars. When comparing the arraydestandsrcas unsigned chars, the first 2 bytes are same in both variables.somemcmpreturns '0'.void *memccpy(void *dest, const void *src, int c, size_t n);: Copies a block of n bytes from src to dest p = (char*) memccpy(str2, str1, 'i', strlen(str1));// Withmemccpy(), the copying stops as soon as either of the following occurs:=> the character 'i' is first copied intostr2=> n bytes have been copied intostr2printf("%.#s %2s", str, str);// It prints out a minimum of 2 characters of the character string, str. I don't see an immediate way of limiting the number of characters you want printed if that's what your looking foYou can terminate the string yourself by sticking the'\0'in there yourself:char s[10];char foo = "My hovercraft is full of eels."; // more than 10 chars

strncpy(s, foo, 9); // only copy 9 chars into positions 0-8s[9] = '\0'; // position 9 gets the terminator

. scanf()oratoi()function can be used to convert a string like "436" in to integer. number = atoi("string");int main(){int (*p)[4];p = (int (*) [4])malloc(3*sizeof(*p));

printf("%d, %d\n", sizeof(p), sizeof(*p));return 0;}Output :2,8 //considerint pointer of size 2 bytesNote:union one member is being used at a time.2.What will be the output of the program?

#include#include

union employee{ char name[15]; int age; float salary;};const union employee e1;

int main(){ strcpy(e1.name, "K"); printf("%s %d %f", e1.name, e1.age, e1.salary); return 0;}

OUTPUT:K 75 0.000000Note: in case of constant array modification can ony be done if the is a pointer who tries to do. Aconstvariable can be indirectly modified by a pointer.const int x;// Error:constvariable have been initialised when declared. x=128;in short if substitute name is in small latters then just read it as normal statement wheres for actual definition of typedef to hold it should contain leeter in CAPITAL for alais nameWhat will be the output of the program ?#include

int main(){ struct value { int bit1:1; int bit3:4; int bit4:4;//IF BIT FIELD IS LARGE EX.40 IT WIL DISPLAY ERROR }bit={1, 2, 13};

printf("%d, %d, %d\n", bit.bit1, bit.bit3, bit.bit4); return 0;}

A.1, 2, 13B.1, 4, 4

C.-1, 2, -3D.-1, -2, -13

Answer & ExplanationAnswer:OptionCExplanation:Note the below statement inside the struct:

int bit1:1;--> 'int' indicates that it is a SIGNED integer.

For signed integers the leftmost bit will be taken for +/- sign.

If you store 1 in 1-bit field:

The left most bit is 1, so the system will treat the value as negative number.

The 2's complement method is used by the system to handle the negative values.

Therefore, the data stored is 1. The 2's complement of 1 is also 1 (negative).

Therefore-1is printed.

If you store 2 in 4-bits field:

Binary 2: 0010 (left most bit is 0, so system will treat it as positive value)

0010 is 2

Therefore2is printed.

If you store 13 in 4-bits field:

Binary 13: 1101 (left most bit is 1, so system will treat it as negative value)

Find 2's complement of 1101:

1's complement of 1101 : 00102's complement of 1101 : 0011 (Add 1 to the result of 1's complement)

0011 is 3 (but negative value)

Therefore-3is printed.1. Bit fields be used in union ALSO.2. ALLcombination of nesting is possible between strut and union

ENUM PROPERTIES: enum assigns to it's variable component sequential integer values.Enum values are constant.r++ not alloowedNote: char arr[]="\0"; if(printf("%s",arr)) printf("not empty"); else printf("empty")char arr[]="\0";Here, thechararrayarrhas two elements, both of them are\0. When you use:printf("%s",arr)%sin format specifier tellsprintfto look for a string. Andprintffound it, but it stops printing after seeing the first\0, which is the first characterNote:i++[s] is equivalent to s[i]; i=i+1;

++i[s] is equivalent to ++(s[i]);

18.What will be the output of the program assuming that the array begins at location 1002?#include

int main(){ int a[2][3][4] = { {1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 1, 2}, {2, 1, 4, 7, 6, 7, 8, 9, 0, 0, 0, 0} }; printf("%u, %u, %u, %d\n", a, *a, **a, ***a); return 0;}

[A].1002, 2004, 4008, 2[B].2004, 4008, 8016, 1

[C].1002, 1002, 1002, 1

[D].Error

a' holds the starting address of 3d array here. So it will be 1002,In a[][][], the first bracket represents the z-direction view. Second bracket represents rows(X-direction). 3rd brackets represents columns (Y-direction).

*a is nothing but a[][] is the starting address of 2d array in xy-direction.

**a is nothing but a[] is the starting address of 1d array in y-direction.

***a is value at stating of 3d array a

So answers will be: *a=1002, **a=1002, ***a=1.4.Will the program compile in Turbo C?#includeint main(){ int a=10, *j; void *k; j=k=&a; j++; k++; printf("%u %u\n", j, k); return 0;}

A.YesB.No

Answer & ExplanationAnswer:OptionBExplanation:Error in statementk++. We cannot perform arithmetic onvoidpointers.Note:There is compiler error in line "printf("%d", *ptr);". void * type pointers cannot be de-referenced. We must type cast them before de-referencing. The following program works fine and prints 12.

Note: In C, when an intger value is compared with an unsigned it, the int is promoted to unsigned. Negative numbers are stored in 2's complement form and unsigned value of the 2's complement form is much higher than the sizeof int.

free(p);///in thisorder it must be used otherwise memory leakage happens p = NULL;Consider the following program, where are i, j and k are stored in memory?int i;int main(){int j;int *k = (int *) malloc (sizeof(int));}

NOTE:i is global variable and it is uninitialized so it is stored on BSS part of Data Segment (http://en.wikipedia.org/wiki/.bss) j is local in main() so it is stored in stack frame (http://en.wikipedia.org/wiki/Call_stack) k is dynamically allocated so it is stored on Heap Segment. Seeint a[][3] = {1, 2, 3, 4, 5, 6};int (*ptr)[3] = a;printf("%d %d ", (*ptr)[1], (*ptr)[2]);output : 2 3note: int x = 10; static int y = x; In, C static variables can only be initialized using constant literals.static int i = initializer();//false way#include int a, b, c = 0;void prtFun (void);int main (){static int a = 1; /* line 1 */prtFun();a += 1;prtFun();printf ( "\n %d %d " , a, b) ;}void prtFun (void){static int a = 2; /* line 2 */int b = 1;a += ++b;printf (" \n %d %d " , a, b);}Output4 26 22 0Note:Static variable will exist till the program exit ,but its scope will be within function wher e it is definedPoints:On extern1. Declaration can be done any number of times but definition only once.2. extern keyword is used to extend the visibility of variables/functions().3. Since functions are visible through out the program by default. The use of extern is not needed in function declaration/definition. Its use is redundant.4. When extern is used with a variable, its only declared not defined.5. As an exception, when an extern variable is declared with initialization, it is taken as definition of the variable as well.2. http://www.geeksforgeeks.org/understanding-extern-keyword-in-c/3. http://www.geeksforgeeks.org/understanding-register-keyword/4. #include 5. char *fun()6. {7. static char arr[1024];8. return arr;9. }10. 11. int main()12. {13. char *str = "geeksforgeeks";14. strcpy(fun(), str);str = fun();15. strcpy(str, "geeksquiz");16. printf("%s", fun());17. return 0;}Question 19 Explanation:Note that arr[] is static in fun() so no problems of returning address, arr[] will stay there even after the fun() returns and all calls to fun() share the same arr[]. strcpy(fun(), str); // Copies "geeksforgeeks" to arr[] str = fun(); // Assigns address of arr to str strcpy(str, "geeksquiz"); // copies geeksquiz to str which is address of arr[] printf("%s", fun()); // prints "geeksquiz"

Predict the output#include #include #include void fun(char** str_ref){str_ref++;}int main(){char *str = (void *)malloc(100*sizeof(char));strcpy(str, "GeeksQuiz");fun(&str);puts(str);free(str);return 0;}

OutputGeeksQuizQuestion 5 Explanation:Note that str_ref is a local variable to fun(). When we do str_ref++, it only changes the local variable str_ref. We can change str pointer using dereference operator *. For example, the following program prints "eeksQuiz"#include #include #include

void fun(char** str_ref){ (*str_ref)++;}

int main(){ char *str = (void *)malloc(100*sizeof(char)); strcpy(str, "GeeksQuiz"); fun(&str); puts(str); free(str); return 0;}Output of following program#include int fun(int arr[]) {arr = arr+1; printf("%d ", arr[0]);}int main(void) {int arr[2] = {10, 20};fun(arr);printf("%d", arr[0]);return 0;}

Output20 10Question 9 Explanation:In C, array parameters are treated as pointers (See http://www.geeksforgeeks.org/why-c-treats-array-parameters-as-pointers/ for details). So the variablearrrepresents an array in main(), but a pointer in fun().

What is the output of the following C code? Assume that the address of x is 2000 (in decimal) and an integer requires four bytes of memory.#include int main(){ unsigned int x[4][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};printf("%u, %u, %u", x+3, *(x+3), *(x+2)+3);}

x= 2000

Since x is considered as a pointer to an array of 3 integers and an integer takes 4bytes, value of x + 3 = 2000 + 3*3*4 = 2036

The expression, *(x + 3) also prints same address as x is 2D array.

The expression *(x + 2) + 3 = 2000 + 2*3*4 + 3*4 = 2036

int * g (void) { int x = 10; return (&x); } pointer variable x is a local variable to g(), and g() returns pointer to this variable. x may vanish after g() has returned as x exists on stack. So, &x may become invalid

1. Consider the following C program segment:char p[20];char *s = "string";int length = strlen(s);int i;for (i = 0; i < length; i++)p[i] = s[length i];printf("%s",p);

Run on IDEThe output of the program is (GATE CS 2004)a) gnirtsb) gnirtc) stringd) no output is printedAnswer(d)Let us consider below line inside the for loopp[i] = s[length i];For i = 0, p[i] will be s[6 0] and s[6] is \0So p[0] becomes \0. It doesnt matter what comes in p[1], p[2].. as P[0] will not change for i >0. Nothing is printed if we print a string with first character \0

5. Consider the following C programmain(){int x, y, m, n;scanf ("%d %d", &x, &y);/* x > 0 and y > 0 */m = x; n = y;while (m != n){ if(m>n)m = m - n;elsen = n - m;}printf("%d", n);}

Run on IDEThe program computes (GATE CS 2004)a) x + y using repeated subtractionb) x mod y using repeated subtractionc) the greatest common divisor of x and yd) the least common multiple of x and yAnswer(c)This is an implementation ofEuclids algorithmto find GCD

2. Consider the C program shown below.# include # define print(x) printf ("%d", x) int x; void Q(int z) { z += x;print(z); } void P(int *y) { int x = *y+2; Q(x); *y = x-1; print(x);} main(void) { x=5; P(&x); print(x); getchar();}

Run on IDEThe output of this program is (GATE CS 2003)a) 1276b) 22 12 11c) 14 6 6d) 766Answer (a)Note that main() and Q() are accessing the global variable x. Inside P(), pointer variable y also holds address of global variable x, but x in P() is its Ps own local variable.

int f1(int n){if(n == 0 || n == 1)return n;elsereturn (2*f1(n-1) + 3*f1(n-2));}f1(8) a(A) 1661 and

(B) 59 and(C) 1640 an(D) Both functions perform same operation, so output is same, means either (B) or (C) is correct.f1(2) = 2*f1(1) + 3*f1(0) = 2f1(3) = 2*f1(2) + 3*f1(1) = 2*2 + 3*1 = 7f1(4) = 2*f1(3) + 3*f1(2) = 2*7 + 3*2 = 20f1(5) = 2*f1(4) + 3*f1(3) = 2*20 + 3*7 = 40 + 21 = 61We can skip after this as the only remaining choice is (C)f1(6) = 2*f1(5) + 3*f1(4) = 2*61 + 3*20 = 122 + 60 = 182f1(7) = 2*f1(6) + 3*f1(5) = 2*182 + 3*61 = 364 + 183 = 547f1(8) = 2*f1(7) + 3*f1(6) = 2*547 + 3*182 = 1094 + 546 = 1640

Following is the declaration for putchar() function.int putchar(int char) char-- This is the character to be written. This is passed as its int promotion. Following is the declaration for getchar() function. int getchar(void)Return ValueThis function returns the character written as an unsigned char cast to an int or EOF on error.2. What is the value printed by the following C program?#includeint f(int *a, int n){if(n