programming in c (practice sheet) dilip kumar · pdf fileprogramming in c (practice sheet)...

23
PROGRAMMING IN C (PRACTICE SHEET) Dilip kumar gangwar,Faculty,CS/IT deptt.GEHU(Dehradun) ( [email protected] ) NOTE:1) Solutions are marked in RED colour. 2)You can visit website: geeksforgeeks.org to practice C,c++,java questions and other stuff.(A excellent website for computer science students) ALL THE BEST FOR PLACEMNETS: 1. #include <stdio.h> int main(void) { int x = printf("GeeksQuiz"); printf("%d", x); return 0; } a. GeeksQuiz9 b. GeeksQuiz10 c. GeeksQuizGeeksQuiz d. GeeksQuiz1 2. Which of the following is not a valid declaration in C? 1. short int x; 2. signed short x; 3. short x; 4. unsigned short x

Upload: lydat

Post on 06-Mar-2018

541 views

Category:

Documents


64 download

TRANSCRIPT

PROGRAMMING IN C (PRACTICE SHEET)

Dilip kumar gangwar,Faculty,CS/IT deptt.GEHU(Dehradun)

([email protected])

NOTE:1) Solutions are marked in RED colour.

2)You can visit website: geeksforgeeks.org to practice C,c++,javaquestions and other stuff.(A excellent website for computer sciencestudents)

ALL THE BEST FOR PLACEMNETS:

1. #include <stdio.h>

int main(void) { int x = printf("GeeksQuiz"); printf("%d", x); return 0;}

a. GeeksQuiz9

b. GeeksQuiz10

c. GeeksQuizGeeksQuiz

d. GeeksQuiz1

2. Which of the following is not a valid declaration in C?

1. short int x;

2. signed short x;3. short x;

4. unsigned short x

a.3 b 2 c.1 d.All are valid

3. #include <stdio.h>

int main(){ int x = 1, y = 2, z = 3; printf(" x = %d, y = %d, z = %d \n", x, y, z); { int x = 10; float y = 20; printf(" x = %d, y = %f, z = %d \n", x, y, z); { int z = 100; printf(" x = %d, y = %f, z = %d \n", x, y, z); } } return 0;}

a. x = 1, y = 2, z = 3

x = 10, y = 20.000000, z = 3

x = 1, y = 2, z = 100

b. Compiler Error

c. x = 1, y = 2, z = 3

x = 10, y = 20.000000, z = 3

x = 10, y = 20.000000, z = 100

d. x = 1, y = 2, z = 3

x = 1, y = 2, z = 3

x = 1, y = 2, z = 3

4. Consider the following variable declarations and definitions in C

i) int var_9 = 1;ii) int 9_var = 2;iii) int _ = 3;

Choose the correct statement w.r.t. above variables.a.Both i) and iii) are valid.

b. Both i) and iii) are valid.

c.only i)is valid

d.All are valid

5. Consider the program below in a hypothetical language which allows globalvariable and a choice of call by reference or call by value methods of parameterpassing.

int i ;program main (){ int j = 60; i = 50; call f (i, j); print i, j;}procedure f (x, y){ i = 100; x = 10; y = y + i ;}Which one of the following options represents the correct output of the program for

the two parameter passing mechanisms?

a. Call by value : i = 70, j = 10; Call by reference : i = 60, j = 70

b. Call by value : i = 50, j = 60; Call by reference : i = 50, j = 70

c. Call by value : i = 10, j = 70; Call by reference : i = 100, j = 60

d. Call by value : i = 100, j = 60; Call by reference : i = 10, j = 70

6. #include <stdio.h>

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);}a.

3 1

4 1

4 2

b.

4 2

6 1

6 1

c.

4 2

6 2

2 0

d.

3 1

5 2

5 2

7.

int f(int n) { static int i = 1; if (n >= 5) return n; n = n+i; i++; return f(n); }The value returned by f(1) is

a.5 b.6 c.7 d.8

‘a’ and ‘b’ are global variable. prtFun() also has ‘a’ and ‘b’ as local variables. The

local variables hide the globals (See Scope rules in C). When prtFun() is called first

time, the local ‘b’ becomes 2 and local ‘a’ becomes 4. When prtFun() is called

second time, same instance of local static ‘a’ is used and a new instance of ‘b’ is

created because ‘a’ is static and ‘b’ is non-static. So ‘b’ becomes 2 again and ‘a’

becomes 6. main() also has its own local static variable named ‘a’ that hides the

global ‘a’ in main. The printf() statement in main() accesses the local ‘a’ and prints its

value. The same printf() statement accesses the global ‘b’ as there is no local

variable named ‘b’ in main. Also, the defaut value of static and global int variables is

0. That is why the printf statement in main() prints 0 as value of b.

8. Consider the following C declaration

struct {

short s[5];

union {

float y;

long z;

}u;

} t;

Assume that objects of the type short, float and long occupy 2 bytes, 4 bytes and 8bytes, respectively. The memory requirement for variable t, ignoring alignmentconsiderations, is

a.22 b.14 c.18 d.10

9.

# include <string.h>

struct Test

{

char str[20];

};

int main()

{

struct Test st1, st2;

strcpy(st1.str, "GeeksQuiz");

st2 = st1;

st1.str[0] = 'S';

printf(“%s”, st2.str);

return 0;

}a.segmentation fault

b.seeksQuiz

c.GeeksQuiz

d.compiler error

10. The most appropriate matching for the following pairs (GATE CS 2000)

X: m=malloc(5); m= NULL; 1: using dangling pointersY: free(n); n->value=5; 2: using uninitialized pointersZ: char *p; *p = ’a’; 3. lost memory is:

A X—1 Y—3 Z-2

B (X—2 Y—1 Z-3

C X—3 Y—2 Z-1

D X—3 Y—1 Z-2

X -> A pointer is assigned to NULL without freeing memory so a clear example ofmemory leak Y -> Trying to retrieve value after freeing it so dangling pointer. Z -> Usinguninitialized pointers

11. Consider the following three C functions :

[PI] int * g (void) { int x= 10; return (&x); }

[P2] int * g (void) { int * px; *px= 10; return px; }

[P3] int *g (void) { int *px; px = (int *) malloc (sizeof(int)); *px= 10; return px; }Which of the above three functions are likely to cause problems with pointers?

A Only P3

B Only P1 and P3

C Only P1 and P2

D P1, P2 and P3

12. Which of the following is/are true

A calloc() allocates the memory and also initializes the allocates memory to

zero, while memory allocated using malloc() has random data.

B Both malloc() and calloc() return 'void *' pointer.

C calloc() takes two arguments, but malloc takes only 1 argument.

DAll of the above

13. #include <stdio.h>

#define a 10

int main()

{

printf("%d ",a);

#define a 50

printf("%d ",a);

return 0;

}

A Compiler Error

B 10 50

C 50 50

D 10 10

Preprocessor doesn't give any error if we redefine a preprocessor directive. It may givewarning though. Preprocessor takes the most recent value before use of and put it inplace of a.

14. Which file is generated after pre-processing of a C program?

a) .p b) .i c) .o d) .m

15. What is output?

# include <stdio.h>

void print(int arr[])

{

int n = sizeof(arr)/sizeof(arr[0]);

int i;

for (i = 0; i < n; i++)

printf("%d ", arr[i]);

}

int main()

{

int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};

print(arr);

return 0;

}

A 1, 2, 3, 4, 5, 6, 7, 8

B Compiler Error

C 1

D Run Time Error

16. Consider the following declaration of a ‘two-dimensional array in C:

char a[100][100];

Assuming that the main memory is byte-addressable and that the array is storedstarting from memory address 0, the address of a[40][50] is

A 4040

B 4050

C 5040

D 5050

17.In C, 1D array of int can be defined as follows and both are correct.int array1D[4] = {1,2,3,4};

int array1D[] = {1,2,3,4};But given the following definitions (along-with initialization) of 2D arraysint array2D[2][4] = {1,2,3,4,5,6,7,8}; /* (i) */

int array2D[][4] = {1,2,3,4,5,6,7,8}; /* (ii) */

int array2D[2][] = {1,2,3,4,5,6,7,8}; /* (iii) */

int array2D[][] = {1,2,3,4,5,6,7,8}; /* (iv) */Pick the correct statements.A Only (i) is correct.

B Only (i) and (ii) are correct.

C Only (i), (ii) and (iii) are correct.

D All (i), (ii), (iii) and (iv) are correct.

First of all, C language doesn’t provide any true support for 2D array ormultidimensional arrays. A 2D array is simulated via 1D array of arrays. So a 2D arrayof int is actually a 1D array of array of int. Another important point is that array size canbe derived from its initialization but that’s applicable for first dimension only. It meansthat 2D array need to have an explicit size of 2nd dimension. Similarly, for a 3D array,2nd and 3rd dimensions need to have explicit size. That’s why only (i) and (ii) arecorrect. But array2D[2][] and array2D[][] are of incomplete type because their completesize can’t derived even from the initialization.

18. What is the output of following program?

# include <stdio.h>

int main(){ char str1[] = "GeeksQuiz"; char str2[] = {'G', 'e', 'e', 'k', 's', 'Q', 'u', 'i', 'z'}; int n1 = sizeof(str1)/sizeof(str1[0]); int n2 = sizeof(str2)/sizeof(str2[0]); printf("n1 = %d, n2 = %d", n1, n2); return 0;}

A n1 = 10, n2 = 9

B n1 = 10, n2 = 10

C n1 = 9, n2 = 9

D n1 = 9, n2 = 10

The size of str1 is 10 and size of str2 9. When an array is initialized with string in doublequotes, compiler adds a '\0' at the end.

19. What does the following fragment of C-program print?

char c[] = "PLACEMENT2016"; char *p =c; printf("%s", p + p[3] - p[2]) ;

A PLACEMENT2016

B CEMENT2016

C ACEMENT2016

D 011

20. 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);

The output of the program is? A Gnirts

B Gnirt

C String

D no output is printed

21.int main()

{

char str[] = "ALL THE BEST FOR PLACEMENT";

printf("%s", fun(str));

return 0;

}

a. ALL THE BEST FOR PLACEMENT

b. TNEMECALP ROF TSEB EHT LLA

c.Nothing is printed on screen

d.Segmentation Fault

22. The output of following C program is

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

Compiler dependent answer.

23.

Ans:e

24. #include <stdio.h>// Assume base address of "GeeksQuiz" to be 1000int main(){ printf(5 + "PLACEMENTQuiz"); return 0;}

Ans:MENTQuiz

25.

Ans:5

26. main( ){float a = 12.25, b = 12.52 ;if ( a = b )printf ( "\na and b are equal" ) ;}

Ans:a and b are equal27. int main()

{

int i=0,j=0;

for(;i<5;)

printf("%d\n",++i);

for(;j<5;j+1)

printf("%d\n",j);

}

a.1 2 3 4 5 0 1 2 3 4

b.2 3 4 5 0 1 2 3 4

c.1 2 3 4 5 0 0 0 …..infinite loop

d.None of these

28. What is the output of the following code:-

a. 4 c. 5

b. Error d. 2

29. main( ){int a[5], i, b = 16 ;for ( i = 0 ; i < 5 ; i++ )a[i] = 2 * i ;f ( a, b ) ;for ( i = 0 ; i < 5 ; i++ )

void main(){

int a=2;switch(a){

default:a=a+2;break;case 5: a=5+a;case 9: a=a+3;

}printf("%d ",a); }

}

printf ( "\n%d", a[i] ) ;printf( "\n%d", b ) ;}f ( int *x, int y ){int i ;for ( i = 0 ; i < 5 ; i++ )*( x + i ) += 2 ;y += 2 ;}

Ans:

1 4 …1630

Consider cout same as printf()

int main()

{

char k='m';

char t=10;

char a[]="hello";

char *p="fine";

cout<<a<<" "<<p<<" "<<a[0]<<" "<<p[0]<<" "<<a[1]<<" "<<p[1]<<endl;

a++;

p++;

cout<<a<<" "<<p<<" "<<a[1]<<" "<<p[1]<<" "<<a[0]<<" "<<p[0]<<endl;

a[2]='k';

p[2]='t';

cout<<a[2]<<" "<<p[2]<<endl;

p=&k;

cout<<p<<" "<<*p;

a=&t;

cout<<a<<" "<<*a;

}

include<iostream>

#include<iomanip>

using namespace std;

int main()

{

char k='m';

char t=10;

char a[]="hello";

char *p="fine";

cout<<a<<" "<<p<<" "<<a[0]<<" "<<p[0]<<" "<<a[1]<<" "<<p[1]<<endl;

//a++;

p++;

cout<<a<<" "<<p<<" "<<a[1]<<" "<<p[1]<<" "<<a[0]<<" "<<p[0]<<endl;

a[2]='k';

//p[2]='t';

cout<<a[2]<<" "<<p[2]<<endl;

p=&k;

cout<<p<<" "<<*p;

//a=&t;

cout<<a<<" "<<*a;

}

After commenting green lines the output is:

hello fine h f e i

hello ine e n h i

k e

m▼■" mheklo h

1)

In char *p=”fine”

fine is string constant so no character in it can be changed as it is stored in read onlyarea part of program.But p can be changed to store some other address.

In char a[] =”hello”

Any character in hello can be changed as it is like

H e l l o \0

a[0] a[1] ………………………………………………………. a[5]

Name of array is constant pointer so it cannot be changed ,so a++ is wrong

2)

Here m▼■" is the answer given by cout<<p after p=&k. But why ?? shouldn’t itgive only m

For this,

ed

First, you need to understand how "strings" work in C.

"Strings" are stored as an array of characters in memory. Since there is no way ofdetermining how long the string is, a NUL character, '\0', is appended after the string sothat we know where it ends.So for example if you have a string "foo", it may look like this in memory:

--------------------------------------------| 'f' | 'o' | 'o' | '\0' | 'k' | 'b' | 'x' | ...--------------------------------------------The things after '\0' are just stuff that happens to be placed after the string, which mayor may not be initialised.When you assign a "string" to a variable of type char *, what happens is that the variablewill point to the beginning of the string, so in the above example it will point to 'f'. (Inother words, if you have a string str, then str == &str[0] is always true.) When you

assign a string to a variable of type char *, you are actually assigning the addressof the zeroth character of the string to the variable.

When you pass this variable to printf(), it starts at the pointed address, then goesthrough each char one by one until it sees '\0' and stops. For example if we have:

char *str = "foo";and you pass it to printf(), it will do the following:1. Dereference str (which gives 'f')2. Dereference (str+1) (which gives 'o')3. Dereference (str+2) (which gives another 'o')4. Dereference (str+3) (which gives '\0' so the process stops).

char k='m';char *p=”fine”;…………p=&k; //or p=’m’;cout<<k;

so p has the starting address i.e address of m.Cout will print the characters from here tillit finds ‘\0’ so may be we get m or mgarbage (as we are getting here)

cout<<*p; //dereference just the zeroth address so we get m

31. main(){extern int i;i=20;printf("%d",i);}Answer:Linker Error : Undefined symbol '_i'Explanation:extern storage class in the following declaration,extern int i;specifies to the compiler that the memory for i is allocated in some other programand that address will be given to the current program at the time of linking. Butlinker finds that no other variable of name i is available in any other program withmemory space allocated for it. Hence a linker error has occurred .

32. #define square(x) x*x

main()

{

int i;

i = 64/square(4);

printf("%d",i);

}

a.4 b.64 c.16. None

Answer:64

33.

D

34. 26. main( ){int k, num = 30 ;k = ( num > 5 ? ( num <= 10 ? 100 : 200 ) : 500 ) ;printf ( "\n%d %d", k,num ) ;}Ans:200 30