168
‘C’ Programming

C programming

  • View
    21

  • Download
    3

Embed Size (px)

DESCRIPTION

ICT Training

Citation preview

Page 1: C programming

‘C’ Programming

Page 2: C programming

Implement strcpy() function.

Question No : 1

Page 3: C programming

Method1:

Answer

char *mystrcpy(char *dst, const char *src)

{

char *ptr;

ptr = dst;

while(*dst++=*src++);

return(ptr);

}

Page 4: C programming

The strcpy function copies src, including the

terminating null character, to the

location specified by dst.

No overflow checking is performed when strings are

copied or appended.

The behavior of strcpy is undefined if the source and

destination strings overlap.

It returns the destination string.

No return value is reserved to indicate an error.

Answer

Page 5: C programming

The prototype of strcpy as per the C standards is

char *strcpy(char *dst, const char *src);

const for the source, signifies that

the function must not change the

source string

Answer

Page 6: C programming

Method2:

char *my_strcpy(char dest[], const char source[])

{

int i = 0;

while (source[i] != '\0')

{

dest[i] = source[i];

i++;

}

dest[i] = '\0';

return(dest);

}

Answer

Page 7: C programming

Write C programs to implement the toupper() and

the isupper() functions

Question No : 2

Page 8: C programming

toUpper() isUpper()

int toUpper(int ch)

{

if(ch>='a' && ch<='z')

return('A' + ch - 'a');

else

return(ch);

}

int isUpper(int ch)

{

if(ch>='A' && ch <='Z')

return(1); //Yes, its

upper!

else

return(0); // No, its

lower!

}

A-Z - 65-90

a-z - 97-122

Answer

Page 9: C programming

Write a C program to swap two variables without

using a temporary variable

Question No : 3

Page 10: C programming

Answer

Method1: (The XOR)

a ^= b ^= a ^= b;

Method2: (The XOR)

a=a+b;

b=a-b;

a=a-b;

Page 11: C programming

When should a typecast be used?

Question No : 4

Page 12: C programming

Answer

There are two situations in which to use a type cast.

The first use is to change the type of an operand to an

arithmetic operation so that the operation will be performed

properly.

The second case is to cast pointer types to and from void *

in order to interface with functions that expect or return

void pointers.

struct foo *p = (struct foo *) malloc(sizeof(struct foo));

Page 13: C programming

What do lvalue and rvalue mean?

Question No : 5

Page 14: C programming

Answer

An lvalue is an expression that could appear on

the left-hand sign of an assignment (An object

that has a location).

An rvalue is any expression that has a value (and

that can appear on the right-hand sign of an

assignment).

Page 15: C programming

What is the difference between & and &&

operators and | and || operators?

Question No : 6

Page 16: C programming

& and | are bitwise AND and OR operators

respectively. They are usually used to manipulate

the contents of a variable on the bit level.

&& and || are logical AND and OR operators

respectively. They are usually used in

conditionals.

Answer

Page 17: C programming

What is sizeof()?

a. Function

b. Operator

Question No : 7

Page 18: C programming

a. Function

b. Operator

sizeof() is a compile time operator.

To calculate the size of an object, we need the

type information.

Answer

Page 19: C programming

How to declare a pointer to a function?

Question No : 8

Page 20: C programming

Answer

int myfunc(); // The function.

int (*fp)(); // Pointer to that function.

fp = myfunc; // Assigning the address of

the function to the pointer.

(*fp)(); // Calling the function.

fp(); // Another way to call the

function.

Page 21: C programming

What are the common causes of pointer bugs?

Question No : 9

Page 22: C programming

Answer

Uninitialized pointers:

One of the easiest ways to create a pointer bug is to try

to reference the value of a pointer even though the

pointer is uninitialized and does not yet point to a valid

address.

For example: int *p;

*p = 12;

Page 23: C programming

The pointer p is uninitialized and points to a random location

in memory when you declare it.

It could be pointing into the system stack, or the global

variables, or into the program's code space, or into the

operating system.

When you say *p=12;, the program will simply try to write a

12 to whatever random location p points to.

Make sure you initialize all pointers to a valid address before

dereferencing them.

Answer

Page 24: C programming

Invalid Pointer References:

An invalid pointer reference occurs when a pointer's value is

referenced even though the pointer doesn't point to a valid

block.

One way to create this error is to say p=q; when q is

uninitialized. The pointer p will then become uninitialized as

well, and any reference to *p is an invalid pointer reference.

The only way to avoid this bug is to draw pictures of each

step of the program and make sure that all pointers point

somewhere.

Answer

Page 25: C programming

Zero Pointer Reference:

A zero pointer reference occurs whenever a pointer pointing to

zero is used in a statement that attempts to reference a block.

For example, if p is a pointer to an integer, the following code is

invalid:

There is no block pointed to by p. Therefore, trying to read or

write anything from or to that block is an invalid zero pointer

reference.

p = 0;*p = 12;

Answer

Page 26: C programming

How to declare an array of N pointers to functions

returning pointers to functions returning pointers

to characters?

Question No : 10

Page 27: C programming

Declare it this way

Answer

char *(*(*a[N])())();

Page 28: C programming

Will C allow passing more or less arguments than

required to a function?

Question No : 11

Page 29: C programming

It will not allow if the prototype is around.

It will ideally throw an error like Too many

arguments or Too few arguments

But if the prototype is not around, the behavior is

undefined.

Answer

Page 30: C programming

Try this out

#include <stdio.h>

int foo(int a);

int foo2(int a, int b);

int main(int a)

{

int (*fp)(int a);

a = foo();

a = foo2(1);

exit(0);

}

int foo(int a)

{

return(a);

}

int foo2(int a, int b)

{

return(a+b);

}

Answer

Page 31: C programming

What does printf() return?

Question No : 12

Page 32: C programming

Upon a successful return, the printf() function returns the number

of characters printed (not including the trailing '\0' used to end

output to strings).

If the output was truncated due to this limit then the return

value is the number of characters (not including the trailing

'\0') which would have been written to the final string if

enough space had been available.

Thus, a return value of size or more means that the output

was truncated. If an output error is encountered, a negative

value is returned.

Answer

Page 33: C programming

Look at the code below.

What should X be replaced with inorder to get the

output as "Hello World"?

Question No : 13

void main()

{

if(X) {

printf("Hello");

}

else {

printf(" World");}

}

Page 34: C programming

Answer

#include <stdio.h>

int main()

{

if(!printf("Hello")) {

printf("Hello");

}

else {

printf(" World");

}

}

Page 35: C programming

Write a C program to count bits set in an integer.

Question No : 14

Page 36: C programming

Answer

#include <stdio.h>

int CountSetBits(int n)

{

int count = 0;

while(n) {

n &= (n-1);

++count;

}

return count;

}

int main(void)

{

int n;scanf("%d",&n);

printf("Number of set

bits in %d is %d \n",

n, CountSetBits(n));

return 0;

}

Page 37: C programming

Write a C Program to calculate pow(x,n)

Question No : 15

Page 38: C programming

Answer

int pow(int x, int y) {

if(y == 1) return x ;

return x * pow(x, y-1) ;

}

Divide and Conquer C program

#include <stdio.h>

int main(int argc,

char*argv[]) {

printf("\n[%d]\n",pow(5,4));

}

printf("\n[%d]\n",pow(5,4));

}

int pow(int x, int n)

{ if(n==0)return(1);

else if(n%2==0) {

return(pow(x,n/2)*pow(x,(n/2)));

}

else {

return(x*pow(x,n/2)*pow(x,(n/2))

);

}

}

Page 39: C programming

Also, the code above can be optimized still by calculating

pow(z, (n/2)) only one time (instead of twice) and using its

value in the two return() expressions above.

Answer

Page 40: C programming

Write a code to return a string from a function

Question No : 16

Page 41: C programming

Answer

char *myfunc()

{

char *temp = "string";

return temp;

}

int main()

{

puts(myfunc ());

}

Page 42: C programming

Write code to evaluate a polynomial.

Question No : 17

Page 43: C programming

Answer

typedef struct node

{

float cf;

float px;

float py;

struct node *next;

}mynode;

float evaluate(mynode *head)

{

float x,y,sum;

sum = 0;

mynode *poly;

for(poly = head->next; poly !=

head; poly = poly->next)

{

sum = sum + poly->cf * pow(x,

poly->px) * pow(y, poly->py);

}

return(sum);

}

Page 44: C programming

Write a C program to convert from decimal to any

base (binary, hex)

Question No : 18

Page 45: C programming

Answer

#include <stdio.h>

#include <conio.h>

void decimal_to_anybase(int,int);

void main() {

decimal_to_anybase(10, 2);

decimal_to_anybase(255, 16);

getch();

}

void decimal_to_anybase(int n, int base) {

int i, m, digits[1000], flag;

i=0;

printf("\n\n[%d] converted to base [%d] : ", n, base);

Page 46: C programming

Answer

while(n) {

m=n%base;

digits[i]="0123456789abcdefghijklmnopqrstuvwxyz"[m];

n=n/base;

i++;

}

//Eliminate any leading zeroes

for(i--;i>=0;i--) {

if(!flag && digits[i]!='0')flag=1;

if(flag)printf("%c",digits[i]);

}

}

Page 47: C programming

How to fast multiply a number by 7?

Question No : 19

Page 48: C programming

(num<<3 - num)

Same as, num*8 - num = num * (8-1) = num * 7

Answer

Page 49: C programming

How can we sum the digits of a given number in

single statement?

Question No : 20

Page 50: C programming

Answer

# include<stdio.h>

void main()

{

int num=123456;

int sum=0;

for(;num>0;sum+=num%10,num/=10); // This is

the "single line".

printf("\nsum = [%d]\n", sum);

}

Page 51: C programming

Given two strings A and B, how would you find

out if the characters in B were a subset of the

characters in A?

Question No : 21

Page 52: C programming

Answer

#include <stdio.h>

#include <conio.h>

int isSubset(char *a, char *b);

int main(){

char str1[]="defabc";

char str2[]="abcfed";

if(isSubset(str1, str2)==0){

printf("\nYes, characters in B=[%s] are a subset of characters in

A=[%s]\n",str2,str1); }

else {

printf("\nNo, characters in B=[%s] are not a subset of characters

in A=[%s]\n",str2,str1); }

getch();

return(0); }

Page 53: C programming

Answer

// Function to check if characters in "b" are a subset

// of the characters in "a“

int isSubset(char *a, char *b) {

int letterPresent[256];

int i;

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

letterPresent[i]=0;

for(i=0; a[i]!='\0'; i++)

letterPresent[a[i]]++;

for(i=0; b[i]!='\0'; i++)

if(!letterPresent[b[i]])

return(1);

return(0);

}

Page 54: C programming

Write a program to print numbers from 1 to 100

without using loops!

Question No : 22

Page 55: C programming

Answer

void printUp(int startNumber, int endNumber)

{

if (startNumber > endNumber)

return;

printf("[%d]\n", startNumber++);

printUp(startNumber, endNumber);

}

Page 56: C programming

Write code to round numbers

Question No : 23

Page 57: C programming

(int)(num < 0 ? (num - 0.5) : (num + 0.5))

Answer

Page 58: C programming

How to swap the two nibbles in a byte?

Question No : 24

Page 59: C programming

Answer

#include <stdio.h>

unsigned char swap_nibbles(unsigned char c) {

unsigned char temp1, temp2;

temp1 = c & 0x0F;

temp2 = c & 0xF0;

temp1=temp1 << 4;

temp2=temp2 >> 4;

return(temp2|temp1); //adding the bits }

int main(void) {

char ch=0x34;

printf("\nThe exchanged value is

%x",swap_nibbles(ch));

return 0;

}

Page 60: C programming

Write a C program to reverse the words in a

sentence in place.

Like,

Input: I am a good girl

Output: should be: lrig doog a ma I

Question No : 25

Page 61: C programming

Answer

#include <stdio.h>

void rev(char *l, char *r);

int main(int argc, char *argv[]){

char buf[] = "the world will go on forever";

char *end, *x, *y;

// Reverse the whole sentence first..

for(end=buf; *end; end++);

rev(buf,end-1);

First reverse the whole string and then

individually reverse the words

Page 62: C programming

Answer

// Now swap each word within sentence...

x = buf-1;

y = buf;

while(x++ < end)

{

if(*x == '\0' || *x == ' ')

{

rev(y,x-1);

y = x+1;}

}

Page 63: C programming

Answer

// Now print the final string....

printf("%s\n",buf);

return(0); }

// Function to reverse a string in place...

void rev(char *l,char *r) {

char t;while(l<r) {

t = *l;

*l++ = *r;

*r-- = t;

} }

Page 64: C programming

Write a C program to multiply two matrices.

Question No : 26

Page 65: C programming

Answer

// Matrix A (m*n)

// Matrix B (n*k)

// Matrix C (m*k)

for(i=0; i<m; i++) {

for(j=0;j<k;j++) {

c[i][j]=0;

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

c[i][j] += a[i][l] * b[l]

[j];

}

}

Page 66: C programming

Is there something we can do in C but not in C+

+?

Declare variable names that are keywords in C++

but not C.

Question No : 27

Page 67: C programming

Answer

#include <stdio.h>

int main(void)

{

int old, new=3;return 0;

}

This will compile in C, but not in C++!

Page 68: C programming

Write a C program for calculating the factorial of

a number (use recursive function)

Question No : 28

Page 69: C programming

Here is a recursive C program

Answer

int fact(int n)

{

int fact;

if(n==1)

return(1);

else

fact = n * fact(n-1);

return(fact);

} Please note that there is

no error handling added to

this function

Page 70: C programming

Too much error handling and standard compliance results

in a lot of clutter making it difficult to concentrate on the

crux of the solution.

You must of course add as much error handling and

comply to the standards of your compiler when you

actually write the code to implement these algorithms.

Answer

Page 71: C programming

If a character string is to be received through the

keyboard which function would work faster?

a. gets

b. scanf

Question No : 29

Page 72: C programming

a. gets

Answer

Page 73: C programming

Consider the following piece of code and predict the output

a. 100

b. 4

c. 2

d. 99

Question No : 30

void main() {

int i=100;

clrscr();

printf("%d",

sizeof(sizeof(i)));

getch();

}

Page 74: C programming

c. 2

Answer

Page 75: C programming

Choose the correct output from the following

code snippet.

a. It prints "God is Great“

b. Run time error

c. Compilation error

d. No output

void main() {

static int a,b;

if(a & b)

printf("\nGod is Great"); }

Question No : 31

Page 76: C programming

d. No Output

Answer

Page 77: C programming

Which of the following header file is required for

strcpy () function?

a. string.h

b. strings.h

c. stdio.h

d. file.h

Question No : 32

Page 78: C programming

a. string.h

Answer

Page 79: C programming

Choose the correct answer

a. Main cannot be printed

b. %p is an invalid control string

c. Some address will be printed

d. Compile time error

Question No : 33

main()

{

Printf(“%p”,main);

}

Page 80: C programming

c. Some address will be printed

Answer

Page 81: C programming

What error will the below function give on

compilation?

a. The function should be defined as int f(int a, int b)

b. Redeclaration of a

c. Missing parentheses in return

Question No : 34

f(int a, int b)

{

int a;

a = 20;

return a;

}

Page 82: C programming

b. Redeclaration of a

Answer

Page 83: C programming

Choose the correct output for the below code

a. 123,201

b. 121,200

c. 120,201

d. 120,199

Question No : 35

main()

{

int x=45,y=78;

clrscr();

x = y-- + x--;

y = ++y + ++x;

printf ("%d %d\n", x, y);

}

Page 84: C programming

a. 123,201

Answer

Page 85: C programming

Consider the code snippet and choose the correct

output

a. 0

b. No Output

c. Null

d. 1

Question No : 36

void main() {

static int i;

i = i+1;

printf("%d", i);

getch();

}

Page 86: C programming

d. 1

Answer

Page 87: C programming

What is the output of the below code?

Question No : 37

main()

{

int a=10,*j;

void *k;

j=k=&a;

j++;

k++;

printf("\n %u %u ",j,k);

}

Page 88: C programming

Compiler error: Cannot increment a void pointer

Explanation:

Void pointers are generic pointers and they can be used

only when the type is not known and as an intermediate

address storage type.

No pointer arithmetic can be done on it and you cannot

apply indirection operator (*) on void pointers

Answer

Page 89: C programming

What is the output of the below code?

Question No : 38

main()

{

float i = 1.5;

switch(i)

{

case 1: printf(“1”);

case 2: printf(“2”);

default: printf(“0”);

}}

Page 90: C programming

Compiler Error: switch expression not integral

Explanation:

Switch statements can be applied only to integral types.

Answer

Page 91: C programming

What is the output of the below code?

Question No : 39

void main()

{

static int i;

while(i<=10)

(i>2)?i++:i--;

printf(“%d”, i);

}

Page 92: C programming

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.

Answer

Page 93: C programming

What is the output of the below code?

Question No : 40

main()

{

char str1[] = ”some”;

char str2[] =”some”;

if (strcmp(str1,str2))

printf(“Strings are not

equal\n”);

}

Page 94: C programming

No output

Answer

Page 95: C programming

What is the output of the below code?

Question No : 41

main()

{

char p[ ]="%d\n";

p[1] = 'c';

printf(p,65);

}

Page 96: C programming

A

Explanation:

Due to the assignment p[1] = ‘c’ the string becomes,

“%c\n”.

Since this string becomes the format string for printf and

ASCII value of 65 is ‘A’, the same gets printed.

Answer

Page 97: C programming

What is the output of the below code?

Question No : 42

void main()

{

int i=5;

printf(“%d”,i=++i ==6);

}

Page 98: C programming

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.

Answer

Page 99: C programming

What is the output of the following code?

Question No : 43

main()

{

int a[5] = {2,3};

printf(" "\n%d %d d"",a[2],a[3],a[4]);

}

Page 100: C programming

0 0 0

Answer

Page 101: C programming

What will be the output of the below program?

a. 4

b. 3

c. No output

d. 0

Question No : 44

#include<stdio.h>

#define MIN(x,y)(x<y)?

x:y

void main() {

int x = 3, y = 4,z;

z = MIN(x+y/2,y-1);

if(z>0)

printf("%d",z);

}

Page 102: C programming

b. 3

Answer

Page 103: C programming

Which of the following is correct about the

statement given below?

a. structure engine is nested within structure maruti

b. structure maruti is nested within structure engine

c. structure maruti is nested within structure bolts

d. structure engine is nested within structure engine

Question No : 45

maruti.engine.bolts = 25;

Page 104: C programming

a. structure engine is nested within structure

maruti

Answer

Page 105: C programming

Which of the following is the correct output for the

program given below?

a. 1

b. 2

c. 5

d. 4

Question No : 46

int fun(int);

void main(){

int i = 3;

fun(i = fun(fun(i)));

printf("%d",i);

}

fun(int i){

i++;

return(i);

}

Page 106: C programming

c. 5

Answer

Page 107: C programming

Recursions works slower than loops

a. True

b. False

Question No : 47

Page 108: C programming

a. True

Answer

Page 109: C programming

Choose the correct answer based on output from

following piece of code

a. 16, 25

b. 9,49

c. Error in code

d. 6,7

Question No : 48

#define PRODUCT(x) (x*x)

main()

{

int i = 3,j,k;

j = PRODUCT (i++);

k = PRODUCT(++i);

printf(“\n%d %d”, j,k);

}

Page 110: C programming

b. 9,49

Answer

Page 111: C programming

Which of the following is the correct output for

the given program?

a. d

b. Abcdefgh

c. e

d. Compile time error

Question No : 49

void main()

{

printf("%c","abcdefgh"[4]);

}

Page 112: C programming

c. e

Answer

Page 113: C programming

Which of the following is the correct output for

the program given below?

a. 20

b. 10

c. 30

d. 0

Question No : 50

#include<stdio.h>

void main() {

union var {

int a, b;

};

union var v;

v.a = 10;

v.b = 20;

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

Page 114: C programming

a. 20

Answer

Page 115: C programming

On opening a file for reading which of the

following activities are performed?

a. A pointer is set up which points to the first character in

the file

b. The disk is searched for existence of the file

c. The file is brought into memory

Question No : 51

Page 116: C programming

a, b and c

Answer

Page 117: C programming

The assignment operation X=Y means?

a. l-value of Y is stored in l-value of X

b. r-value of Y is stored in r- value of X

c. r-value of Y is stored in l-value of X

d. l-value of Y is stored in r-value of X

Question No : 52

Page 118: C programming

c. r-value of Y is stored in l-value of X

Answer

Page 119: C programming

Which of the following statement is/are true?

i. A char data type variable always occupies one byte

independent of the system architecture.

ii. The sizeof operator is used to determine the amount of

memory occupied by a variable.

a. Only i

b. Only ii

c. Both i & ii

d. Neither i nor ii

Question No : 53

Page 120: C programming

b. Only ii

Answer

Page 121: C programming

Write down the equivalent pointer expression for

referring element a[i][j][k][l] ?

Question No : 54

Page 122: C programming

Hence Final output is *(*(*(*(a+i)+j)+k)+l)

Answer

a[i] == *(a+i)

a[i][j] == *(*(a+i)+j)

a[i][j][k] == *(*(*(a+i)+j)+k)

a[i][j][k][l] == *(*(*(*(a+i)

+j)+k)+l)

Page 123: C programming

The preprocessor can trap the simple errors like

missing declarations, nested comments or

mismatch of braces.

a. True

b. False

Question No : 55

Page 124: C programming

b. False

Answer

Page 125: C programming

What is the output of the below code?

a. Syntax Error

b. No Output

c. Compiler Error

d. hello

Question No : 56

#include main(){

struct xx {

int x=3;

char name[]=”hello”;

};

struct xx *s;

Page 126: C programming

c. Compiler Error

Answer

Page 127: C programming

What is the output of the below code?

a. H

b. Syntax error

c. Compiler error

d. E

Question No : 57

void main()

{

char *p;

p=”Hello”;

printf(“%c\n”,*&*p);

}

Page 128: C programming

a. H

Answer

Page 129: C programming

In the following code

fp points to

a. A Structure which contains a char pointer which points to the first character

in the file

b. The name of the file

c. The First character in the file

Question No : 58

#include<stdio.h>

main() {

FILE *fp;

fp=fopen("trail","r");

}

Page 130: C programming

a. A Structure which contains a char pointer which

points to the first character in the file

Answer

Page 131: C programming

what will scanf do ?

a. Compiler error

b. terminates reading input into variable line after newline

c. terminates reading input into variable line after entering ^n

Question No : 59

#include<stdio.h>

main()

{

char line[80];

scanf("%[^n]",line);

printf("%s",line);

}

Page 132: C programming

b. Terminates reading input into variable line after

newline

Answer

Page 133: C programming

What is the output of the below code?

Question No : 60

void main()

{

char s[ ]="Welcome";

int i;

for(i=0;s[ i ];i++)

printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);

}

Page 134: C programming

WWWWeeee

llll

cccc

oooo

mmmm

eeee

Answer

Page 135: C programming

Explanation:

s[i], *(i+s), *(s+i), i[s] are all different ways of expressing

the same idea.

Generally array name is the base address for that array.

Here s is the base address.

i is the index number/displacement from the base

address.

So, indirecting it with * is same as s[i]. i[s] may be

surprising. But in the case of C it is same as s[i].

Answer

Page 136: C programming

What does the following program do?

Question No : 50

#include "math.h"

main(){

int n,i,j,m;

printf("Enter any number \n");

scanf("%d", &n);

for(i=1;i<=n;i++) {

m=(int)(sqrt(i));

for(j=1; j<=m;j++)

if(func(i,j)!=1)

break;

if(j==m+1)

printf("%d\t", i);

}

}

int func(int u, int v){

int min,i,val;

min = (u<v?u:v);

for(i=1;i<min;i++)

if(u%i==0&&v%i==0)

val = i;

return(val);

}

Page 137: C programming

It will print the list of all primary numbers less

than or equal to a given number n

Answer

Page 138: C programming

You have given 1000 integers to sort. But, your

RAM accommodates maximum of 100 integers

only. How do your sort them?

Question No : 62

Page 139: C programming

We have to use external sorting (by tapes, disks

etc.) mechanism.

We can use merge sort for internal sorting

iterations.

Answer

Page 140: C programming

How to allocate and deallocate memory for

char** ?

Question No : 63

Page 141: C programming

Answer

char** pp = new char*[10];

for(int i=0;i<10;i++)

char*[i]=new char[100];

Allocation

In the order, first construct

the main objects, and then

construct the internal

objects

Page 142: C programming

for(int i=0;i<10;i++)

delete [] char*[i];

delete[] pp;

Deallocation

In the reverse order, first

destruct the internal objects,

then destruct the main

object

Answer

Page 143: C programming

What are the best data structures for insertion,

deletion and search operations?

Question No : 64

Page 144: C programming

For Insertion and deletion - Linked list

For search - Map (it is a height balanced Red-

black tree. We can search in O(log n))

Answer

Page 145: C programming

Describe two scenarios where an application will

crash due to stack overflow.

Question No : 65

Page 146: C programming

The two most common causes for a stack

overflow is:(i) An infinite recursion

Answer

int f1(){

f2();

}

int f2() {

f1();

} f1() calls f2(), which in turn

calls f1() and so on.

Eventually, the stack

overflows.

Page 147: C programming

(ii) An attempt to create a large array on the stack,

for example:int main()

{

int a[100000000]; // array is too

large

int b =0; //b's address exceeds the

stack's limits, error

}If our program crashes due to a

stack overflow, we need to

check for infinite recursion or

too large local objects

Answer

Page 148: C programming

Can main function be overloaded? Explain.

Question No : 66

Page 149: C programming

No, only one type of calling is allowed in a

program (with out arguments/with two

arguments/ with three arguments)

Answer

Page 150: C programming

How to count the number of set bits of an integer

using that many number of iterations of for loop?

Question No : 67

Page 151: C programming

Answer

unsigned int v; // count the number of bits

set in v

unsigned int c; // c accumulates the total

bits set in v

for (c = 0; v; c++)

{

v &= v - 1; // clear the least significant

bit set

}

Page 152: C programming

What is the output of this program?

Question No : 68

#include <stdio.h>

void main() {

char s[20];

char *str = "Sachin Tendulker";

sscanf(str, "%s", s);

printf("%s", s);

sscanf(str+7, "%[duenTlk]", s);

printf("%s", s);

sscanf(str+15, "%[^Ganguly]", s);

printf("%s\n", s); }

Page 153: C programming

SachinTendulker

Explanation:

The above statement captures Sachin only into S, because of white space

character.

The above statement captures Tendulker into S freshly. Because the format

specifier has wildcard character [duenTlk], which means the scanning of

string would be done as long as the character is one among the list of

characters(starting from str+7).

when it encounters a new character which is not there in the list the

reading stops.

sscanf(str, "%s", s);

sscanf(str+7, "%[duenTlk]", s);

Page 154: C programming

The above statement captures r into S freshly. Because

the format specifier has wildcard character [^Ganguly],

which means the scanning of string would be done as

long as the character is not one among the list of

characters(starting from str+15).

when it encounters a new character which is there in the

list(or when the null character occurs) the reading stops.

Answer

sscanf(str+15, "%[^Ganguly]", s);

Page 155: C programming

What is the output of the following program?

Question No :69

main() {

union abc {

int a:1;

int b:1;

int c:1;

int d:1;

int e:1;

int f:1;

int g:1;

int h:1;

};

abc X;

abc.a = abc.b = abc.c

= abc.d = abc.e =

abc.f =abc.g = abc.h =

1;

printf("%d",X);

}

Page 156: C programming

-1

Explanation:

By default, X is signed and has sign bit 1. Therefore, it is

stored in 2’s complement form.

Answer

Page 157: C programming

Consider the following code:

What is the scope difference between i and j?

Question No : 70

int i;

static int j;

main( )

{

}

Page 158: C programming

Both i and j have global scope, but j cannot be

accessed in the other modules(files)

Answer

Page 159: C programming

How many times the following program would

print India?

Question No : 71

main( )

{

printf(" \n India");

main();

}

Page 160: C programming

Till stack does not overflow (Infinite loop)

Answer

Page 161: C programming

What is heap?

Question No : 72

Page 162: C programming

The heap is where malloc(), calloc(), and realloc() get memory.

Getting memory from the heap is much slower than getting it

from the stack.

On the other hand, the heap is much more flexible than the

stack. Memory can be allocated at any time and deallocated in

any order.

Such memory is not deallocated automatically; you have to

call free().

Recursive data structures are almost always implemented with

memory from the heap.

Answer

Page 163: C programming

What would be the output of the following

program if the array begins at the location

65472?

Question No : 73

main( ) {

int a[3][4] = {

1,2,3, 4,

4,3,2,1,

7,8,9,0

};

printf( "\n %u %u ",a+1, &a+1);

}

Page 164: C programming

65488, 65520

Answer

Page 165: C programming

Provide simple implementation of int atoi(char*

pStr)

Question No : 74

Page 166: C programming

Answer

int atoi(char* pStr) {

int iRetVal=0;

if (pStr){

while (*pStr && *pStr<= ‘9’ && *pStr>=’0’)

{

iRetval = (iRetval*10) + (*pStr – ‘0’);

pStr++;

}

}

return iRetval;

}

Page 167: C programming

What is the output of the below statement?

Question No : 75

printf(“%d”);

Page 168: C programming

Garbage Value.

Because, when we write printf("%d",x); this means

compiler will print the value of x.

But as here, there is nothing after %d so garbage value is

given as an output.

Answer