‘C’ Programming
Implement strcpy() function.
Method1:char *mystrcpy(char *dst, const char *src){ char *ptr;ptr = dst; while(*dst++=*src++);  return(ptr);}
The strcpy function copies src, including the terminating null character, to thelocation 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.
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
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);}
Write C programs to implement the toupper() and the isupper() functions
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!}
Write a C program to swap two variables without using a temporary variable
Method1: (The XOR)a ^= b ^= a ^= b;Method2: (The XOR)a=a+b;b=a-b;a=a-b;
When should a typecast be used?
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.structfoo *p = (structfoo *) malloc(sizeof(structfoo));
What do lvalue and rvalue mean?
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).
What is the difference between & and && operators and | and || operators?
& 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.
What is sizeof()? FunctionOperator
FunctionOperatorsizeof() is a compile time operator. To calculate the size of an object, we need the type information.
How to declare a pointer to a function?
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.
What are the common causes of pointer bugs?
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;
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.
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.
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;
How to declare an array of N pointers to functions returning pointers to functions returning pointers to characters?
Declare it this waychar *(*(*a[N])())();
Will C allow passing more or less arguments than required to a function?
It will not allow if the prototype is around.  It will ideally throw an error like Too many arguments  or Too few argumentsBut if the prototype is not around, the behavior is undefined.
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);}
What does printf() return?
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.
Look at the code below. What should X be replaced with inorder to get the output as "Hello World"? void main(){   if(X) { printf("Hello");}else { printf(" World");}}
#include <stdio.h>int main() { if(!printf("Hello")) { printf("Hello");}else { printf(" World"); }}
Write a C program to count bits set in an integer.
#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;}
Write a C Program to calculate pow(x,n)
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))); }}
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.
Write a code to return a string from a function
char *myfunc(){ char *temp = "string"; return temp;}int main(){ puts(myfunc ());}
Write code to evaluate a polynomial.
typedefstruct 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);}
Write a C program to convert from decimal to any base (binary, hex)
#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);
while(n) { m=n%base; digits[i]="0123456789abcdefghijklmnopqrstuvwxyz"[m]; n=n/base; i++;}//Eliminate any leading zeroesfor(i--;i>=0;i--) { if(!flag && digits[i]!='0')flag=1; if(flag)printf("%c",digits[i]); }}
How to fast multiply a number by 7?
(num<<3 - num)Same as, num*8 - num = num * (8-1) = num * 7
How can we sum the digits of a given number in single statement?
# 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);}
Given two strings A and B, how would you find out if the characters in B were a subset of the characters in A?
#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); }
// 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);}
Write a program to print numbers from 1 to 100 without using loops!
void printUp(int startNumber, int endNumber){ if (startNumber > endNumber)  return; printf("[%d]\n", startNumber++);printUp(startNumber, endNumber);}
Write code to round numbers
(int)(num < 0 ? (num - 0.5) : (num + 0.5))
How to swap the two nibbles in a byte?
#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; }
Write a C program to reverse the words in a sentence in place.Like, Input: I am a good girlOutput: should be: lrigdoog a ma I
First reverse the whole string and then individually reverse the words#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);
// 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;}  }
// 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;} }
Write a C program to multiply two matrices.
// 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]; }}
Is there something we can do in C but not in C++? Declare variable names that are keywords in C++ but not C.
 #include <stdio.h>int main(void){  int old, new=3;return 0;}
Write a C program for calculating the factorial of a number (use recursive function)
Here is a recursive C programint 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
If a character string is to be received through the keyboard which function would work faster? getsscanf
gets
Consider the following piece of code and predict the output1004299void main() { int i=100;clrscr(); printf("%d", sizeof(sizeof(i))); getch(); }
2
Choose the correct output from the following code snippet.It prints "God is Great“Run time errorCompilation errorNo outputvoid main() { static int a,b; if(a & b) printf("\nGod is Great"); }
No Output
Which of the following header file is required for strcpy () function?string.hstrings.hstdio.hfile.h
string.h
Choose the correct answerMain cannot be printed%p is an invalid control stringSome address will be printedCompile time errormain(){ Printf(“%p”,main);}
Some address will be printed
What error will the below function give on compilation?The function should be defined as int f(int a, int b)Redeclaration of aMissing parentheses in returnf(int a, int b){ int a; a = 20; return a;}
Redeclaration of a
Choose the correct output for the below code123,201121,200120,201120,199main() { int x=45,y=78;clrscr(); x = y-- + x--; y = ++y + ++x; printf ("%d %d\n", x, y); }
123,201
Consider the code snippet and choose the correct output0No OutputNull1void main() { static int i; i = i+1; printf("%d", i); getch(); }
1
What is the output of the below code? main(){  int a=10,*j; void *k;  j=k=&a; j++;  k++; printf("\n %u %u ",j,k);}
Compiler error: Cannot increment a void pointerExplanation: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
What is the output of the below code?main(){ float i = 1.5; switch(i) {  case 1: printf(“1”);  case 2: printf(“2”);  default: printf(“0”);}}
Compiler Error: switch expression not integralExplanation: Switch statements can be applied only to integral types.
What is the output of the below code?void main(){ static int i; while(i<=10)  (i>2)?i++:i--; printf(“%d”, i);}
32767Explanation: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.
What is the output of the below code?main(){ char str1[] = ”some”; char str2[] =”some”; if (strcmp(str1,str2))   printf(“Strings are not equal\n”);}
No output
What is the output of the below code?main(){ char p[ ]="%d\n"; p[1] = 'c'; printf(p,65);}
AExplanation: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.
What is the output of the below code?void main(){ int i=5; printf(“%d”,i=++i ==6);}
1Explanation: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.
What is the output of the following code?main(){ int a[5] = {2,3}; printf(" "\n%d %d d"",a[2],a[3],a[4]);}
0 0 0
What will be the output of the below program?43No output0#include<stdio.h>#define MIN(x,y)(x<y)?x:yvoid main() { int x = 3, y = 4,z; z = MIN(x+y/2,y-1); if(z>0)  printf("%d",z);}
3
Which of the following is correct about the statement given below?structure engine is nested within structure marutistructure maruti is nested within structure enginestructure maruti is nested within structure boltsstructure engine is nested within structure enginemaruti.engine.bolts = 25;
structure engine is nested within structure maruti
Which of the following is the correct output for the program given below?1254int fun(int);void main(){ int i = 3; fun(i = fun(fun(i))); printf("%d",i);}fun(int i){ i++; return(i);}
5
Recursions works slower than loopsTrueFalse
True
Choose the correct answer based on output from following piece of code16, 259,49Error in code6,7#define PRODUCT(x) (x*x)main(){ int i = 3,j,k; j = PRODUCT (i++); k = PRODUCT(++i); printf(“\n%d %d”, j,k);}
9,49
Which of the following is the correct output for the given program?dAbcdefgheCompile time errorvoid main(){printf("%c","abcdefgh"[4]);}
e
Which of the following is the correct output for the program given below?2010300#include<stdio.h>void main() { union var  {  int a, b; }; union var v;v.a = 10;v.b = 20; printf("%d",v.a); }
20
On opening a file for reading which of the following activities are performed?A pointer is set up which points to the first character in the fileThe disk is searched for existence of the fileThe file is brought into memory
a, b and c
The assignment operation X=Y means?l-value of Y is stored in l-value of Xr-value of Y is stored in r- value of Xr-value of Y is stored in l-value of Xl-value of Y is stored in r-value of X
r-value of Y is stored in l-value of X
Which of the following statement is/are true?A char data type variable always occupies one byte independent of the system architecture.The sizeof operator is used to determine the amount of memory occupied by a variable.Only iOnly iiBoth i & iiNeither i nor ii
Only ii
Write down the equivalent pointer expression for referring element a[i][j][k][l] ?
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)Hence Final output is *(*(*(*(a+i)+j)+k)+l)
The preprocessor can trap the simple errors like missing declarations, nested comments or mismatch of braces.TrueFalse
False
What is the output of the below code?Syntax ErrorNo OutputCompiler Errorhello#include main(){ struct xx {  int x=3; char name[]=”hello”; };struct xx *s;
Compiler Error
What is the output of the below code?HSyntax errorCompiler errorEvoid main(){ char *p; p=”Hello”; printf(“%c\n”,*&*p);}
H
In the following codefp points toA Structure which contains a char pointer which points to the first character in the fileThe name of the fileThe First character in the file#include<stdio.h>main() {FILE *fp;fp=fopen("trail","r");}
A Structure which contains a char pointer which points to the first character in the file
#include<stdio.h>main(){char line[80];scanf("%[^n]",line);printf("%s",line);}what will scanf do ?Compiler errorterminates reading input into variable line after newlineterminates reading input into variable line after entering ^n
Terminates reading input into variable line after newline
What is the output of the below code?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]);}
WWWWeeeellllccccoooommmmeeee
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].
What does the following program do?#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); }
It will print the list of all primary numbers less than or equal to a given number n
You have given 1000 integers to sort. But, your RAM accommodates maximum of 100 integers only. How do your sort them?
We have to use external sorting (by tapes, disks etc.) mechanism. We can use merge sort for internal sorting iterations.
How to allocate and deallocate memory for char** ?
In the order, first construct the main objects, and then construct the internal objectsAllocationchar** pp = new char*[10];   for(int i=0;i<10;i++)       char*[i]=new char[100];
In the reverse order, first destruct the internal objects, then destruct the main objectDeallocation   for(int i=0;i<10;i++)   delete [] char*[i];    delete[] pp;
What are the best data structures for insertion, deletion and search operations?
For Insertion and deletion - Linked listFor search - Map (it is a height balanced Red-black tree. We can search in O(log n))
Describe two scenarios where an application will crash due to stack overflow.
The two most common causes  for a stack overflow is:(i) An infinite recursion int f1(){ f2();}int f2() { f1();  }f1() calls f2(), which in turn calls f1() and so on. Eventually, the stack overflows.
(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
Can main function be overloaded? Explain.
No, only one type of calling is allowed in a program (with out arguments/with two arguments/ with three arguments)
How to count the number of set bits of an integer using that many number of iterations of for loop?
unsigned int v; // count the number of bits set in vunsigned int c; // c accumulates the total bits set in vfor (c = 0; v; c++){  v &= v - 1; // clear the least significant bit set}
What is the output of this program?#include <stdio.h>void main()  {       char s[20];      char *str = "SachinTendulker";      sscanf(str, "%s", s);       printf("%s", s);      sscanf(str+7, "%[duenTlk]", s);       printf("%s", s);      sscanf(str+15, "%[^Ganguly]", s);       printf("%s\n", s);  }
SachinTendulkerExplanation: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);
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.sscanf(str+15, "%[^Ganguly]", s);
What is the output of the following program?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);  }
-1Explanation:By default, X is signed and has sign bit 1. Therefore, it is stored in 2’s complement form.
Consider the following code:What is the scope difference between i and j?int i;static int j;main( )               { }
Both i and j have global scope, but j cannot be accessed in the other modules(files)
How many times the following program would print India?main( ){ printf(" \n India"); main();}
Till stack does not overflow (Infinite loop)
What is heap?
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.
What would be the output of the following program if the array begins at the location 65472?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);}
65488, 65520
Provide simple implementation of   int atoi(char* pStr)
int atoi(char* pStr) { int iRetVal=0; if (pStr){  while (*pStr && *pStr<= ‘9’ && *pStr>=’0’)  {iRetval = (iRetval*10) + (*pStr – ‘0’);pStr++;  } } return iRetval;}
What is the output of the below statement?printf(“%d”);
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.

C programming

  • 1.
  • 2.
  • 3.
    Method1:char *mystrcpy(char *dst,const char *src){ char *ptr;ptr = dst; while(*dst++=*src++); return(ptr);}
  • 4.
    The strcpy functioncopies src, including the terminating null character, to thelocation 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.
  • 5.
    The prototype ofstrcpy 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
  • 6.
    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);}
  • 7.
    Write C programsto implement the toupper() and the isupper() functions
  • 8.
    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!}
  • 9.
    Write a Cprogram to swap two variables without using a temporary variable
  • 10.
    Method1: (The XOR)a^= b ^= a ^= b;Method2: (The XOR)a=a+b;b=a-b;a=a-b;
  • 11.
    When should atypecast be used?
  • 12.
    There are twosituations 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.structfoo *p = (structfoo *) malloc(sizeof(structfoo));
  • 13.
    What do lvalueand rvalue mean?
  • 14.
    An lvalue isan 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).
  • 15.
    What is thedifference between & and && operators and | and || operators?
  • 16.
    & 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.
  • 17.
    What is sizeof()?FunctionOperator
  • 18.
    FunctionOperatorsizeof() is acompile time operator. To calculate the size of an object, we need the type information.
  • 19.
    How to declarea pointer to a function?
  • 20.
    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.
  • 21.
    What are thecommon causes of pointer bugs?
  • 22.
    Uninitialized pointers: Oneof 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;
  • 23.
    The pointer pis 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.
  • 24.
    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.
  • 25.
    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;
  • 26.
    How to declarean array of N pointers to functions returning pointers to functions returning pointers to characters?
  • 27.
    Declare it thiswaychar *(*(*a[N])())();
  • 28.
    Will C allowpassing more or less arguments than required to a function?
  • 29.
    It will notallow if the prototype is around. It will ideally throw an error like Too many arguments or Too few argumentsBut if the prototype is not around, the behavior is undefined.
  • 30.
    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);}
  • 31.
  • 32.
    Upon a successfulreturn, 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.
  • 33.
    Look at thecode below. What should X be replaced with inorder to get the output as "Hello World"? void main(){ if(X) { printf("Hello");}else { printf(" World");}}
  • 34.
    #include <stdio.h>int main(){ if(!printf("Hello")) { printf("Hello");}else { printf(" World"); }}
  • 35.
    Write a Cprogram to count bits set in an integer.
  • 36.
    #include <stdio.h>int CountSetBits(intn) { 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;}
  • 37.
    Write a CProgram to calculate pow(x,n)
  • 38.
    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))); }}
  • 39.
    Also, the codeabove 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.
  • 40.
    Write a codeto return a string from a function
  • 41.
    char *myfunc(){ char*temp = "string"; return temp;}int main(){ puts(myfunc ());}
  • 42.
    Write code toevaluate a polynomial.
  • 43.
    typedefstruct node{ floatcf; 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);}
  • 44.
    Write a Cprogram to convert from decimal to any base (binary, hex)
  • 45.
    #include <stdio.h>#include <conio.h>voiddecimal_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);
  • 46.
    while(n) { m=n%base;digits[i]="0123456789abcdefghijklmnopqrstuvwxyz"[m]; n=n/base; i++;}//Eliminate any leading zeroesfor(i--;i>=0;i--) { if(!flag && digits[i]!='0')flag=1; if(flag)printf("%c",digits[i]); }}
  • 47.
    How to fastmultiply a number by 7?
  • 48.
    (num<<3 - num)Sameas, num*8 - num = num * (8-1) = num * 7
  • 49.
    How can wesum the digits of a given number in single statement?
  • 50.
    # 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);}
  • 51.
    Given two stringsA and B, how would you find out if the characters in B were a subset of the characters in A?
  • 52.
    #include <stdio.h>#include <conio.h>intisSubset(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); }
  • 53.
    // Function tocheck 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);}
  • 54.
    Write a programto print numbers from 1 to 100 without using loops!
  • 55.
    void printUp(int startNumber,int endNumber){ if (startNumber > endNumber) return; printf("[%d]\n", startNumber++);printUp(startNumber, endNumber);}
  • 56.
    Write code toround numbers
  • 57.
    (int)(num < 0? (num - 0.5) : (num + 0.5))
  • 58.
    How to swapthe two nibbles in a byte?
  • 59.
    #include <stdio.h>unsigned charswap_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; }
  • 60.
    Write a Cprogram to reverse the words in a sentence in place.Like, Input: I am a good girlOutput: should be: lrigdoog a ma I
  • 61.
    First reverse thewhole string and then individually reverse the words#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);
  • 62.
    // Now swapeach word within sentence... x = buf-1; y = buf; while(x++ < end) { if(*x == '\0' || *x == ' ') { rev(y,x-1); y = x+1;} }
  • 63.
    // Now printthe 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;} }
  • 64.
    Write a Cprogram to multiply two matrices.
  • 65.
    // 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]; }}
  • 66.
    Is there somethingwe can do in C but not in C++? Declare variable names that are keywords in C++ but not C.
  • 67.
    #include <stdio.h>intmain(void){ int old, new=3;return 0;}
  • 68.
    Write a Cprogram for calculating the factorial of a number (use recursive function)
  • 69.
    Here is arecursive C programint 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
  • 71.
    If a characterstring is to be received through the keyboard which function would work faster? getsscanf
  • 72.
  • 73.
    Consider the followingpiece of code and predict the output1004299void main() { int i=100;clrscr(); printf("%d", sizeof(sizeof(i))); getch(); }
  • 74.
  • 75.
    Choose the correctoutput from the following code snippet.It prints "God is Great“Run time errorCompilation errorNo outputvoid main() { static int a,b; if(a & b) printf("\nGod is Great"); }
  • 76.
  • 77.
    Which of thefollowing header file is required for strcpy () function?string.hstrings.hstdio.hfile.h
  • 78.
  • 79.
    Choose the correctanswerMain cannot be printed%p is an invalid control stringSome address will be printedCompile time errormain(){ Printf(“%p”,main);}
  • 80.
  • 81.
    What error willthe below function give on compilation?The function should be defined as int f(int a, int b)Redeclaration of aMissing parentheses in returnf(int a, int b){ int a; a = 20; return a;}
  • 82.
  • 83.
    Choose the correctoutput for the below code123,201121,200120,201120,199main() { int x=45,y=78;clrscr(); x = y-- + x--; y = ++y + ++x; printf ("%d %d\n", x, y); }
  • 84.
  • 85.
    Consider the codesnippet and choose the correct output0No OutputNull1void main() { static int i; i = i+1; printf("%d", i); getch(); }
  • 86.
  • 87.
    What is theoutput of the below code? main(){ int a=10,*j; void *k; j=k=&a; j++; k++; printf("\n %u %u ",j,k);}
  • 88.
    Compiler error: Cannotincrement a void pointerExplanation: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
  • 89.
    What is theoutput of the below code?main(){ float i = 1.5; switch(i) { case 1: printf(“1”); case 2: printf(“2”); default: printf(“0”);}}
  • 90.
    Compiler Error: switchexpression not integralExplanation: Switch statements can be applied only to integral types.
  • 91.
    What is theoutput of the below code?void main(){ static int i; while(i<=10) (i>2)?i++:i--; printf(“%d”, i);}
  • 92.
    32767Explanation:Since i isstatic 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.
  • 93.
    What is theoutput of the below code?main(){ char str1[] = ”some”; char str2[] =”some”; if (strcmp(str1,str2)) printf(“Strings are not equal\n”);}
  • 94.
  • 95.
    What is theoutput of the below code?main(){ char p[ ]="%d\n"; p[1] = 'c'; printf(p,65);}
  • 96.
    AExplanation:Due to theassignment 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.
  • 97.
    What is theoutput of the below code?void main(){ int i=5; printf(“%d”,i=++i ==6);}
  • 98.
    1Explanation:The expression canbe 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.
  • 99.
    What is theoutput of the following code?main(){ int a[5] = {2,3}; printf(" "\n%d %d d"",a[2],a[3],a[4]);}
  • 100.
  • 101.
    What will bethe output of the below program?43No output0#include<stdio.h>#define MIN(x,y)(x<y)?x:yvoid main() { int x = 3, y = 4,z; z = MIN(x+y/2,y-1); if(z>0) printf("%d",z);}
  • 102.
  • 103.
    Which of thefollowing is correct about the statement given below?structure engine is nested within structure marutistructure maruti is nested within structure enginestructure maruti is nested within structure boltsstructure engine is nested within structure enginemaruti.engine.bolts = 25;
  • 104.
    structure engine isnested within structure maruti
  • 105.
    Which of thefollowing is the correct output for the program given below?1254int fun(int);void main(){ int i = 3; fun(i = fun(fun(i))); printf("%d",i);}fun(int i){ i++; return(i);}
  • 106.
  • 107.
    Recursions works slowerthan loopsTrueFalse
  • 108.
  • 109.
    Choose the correctanswer based on output from following piece of code16, 259,49Error in code6,7#define PRODUCT(x) (x*x)main(){ int i = 3,j,k; j = PRODUCT (i++); k = PRODUCT(++i); printf(“\n%d %d”, j,k);}
  • 110.
  • 111.
    Which of thefollowing is the correct output for the given program?dAbcdefgheCompile time errorvoid main(){printf("%c","abcdefgh"[4]);}
  • 112.
  • 113.
    Which of thefollowing is the correct output for the program given below?2010300#include<stdio.h>void main() { union var { int a, b; }; union var v;v.a = 10;v.b = 20; printf("%d",v.a); }
  • 114.
  • 115.
    On opening afile for reading which of the following activities are performed?A pointer is set up which points to the first character in the fileThe disk is searched for existence of the fileThe file is brought into memory
  • 116.
  • 117.
    The assignment operationX=Y means?l-value of Y is stored in l-value of Xr-value of Y is stored in r- value of Xr-value of Y is stored in l-value of Xl-value of Y is stored in r-value of X
  • 118.
    r-value of Yis stored in l-value of X
  • 119.
    Which of thefollowing statement is/are true?A char data type variable always occupies one byte independent of the system architecture.The sizeof operator is used to determine the amount of memory occupied by a variable.Only iOnly iiBoth i & iiNeither i nor ii
  • 120.
  • 121.
    Write down theequivalent pointer expression for referring element a[i][j][k][l] ?
  • 122.
    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)Hence Final output is *(*(*(*(a+i)+j)+k)+l)
  • 123.
    The preprocessor cantrap the simple errors like missing declarations, nested comments or mismatch of braces.TrueFalse
  • 124.
  • 125.
    What is theoutput of the below code?Syntax ErrorNo OutputCompiler Errorhello#include main(){ struct xx { int x=3; char name[]=”hello”; };struct xx *s;
  • 126.
  • 127.
    What is theoutput of the below code?HSyntax errorCompiler errorEvoid main(){ char *p; p=”Hello”; printf(“%c\n”,*&*p);}
  • 128.
  • 129.
    In the followingcodefp points toA Structure which contains a char pointer which points to the first character in the fileThe name of the fileThe First character in the file#include<stdio.h>main() {FILE *fp;fp=fopen("trail","r");}
  • 130.
    A Structure whichcontains a char pointer which points to the first character in the file
  • 131.
    #include<stdio.h>main(){char line[80];scanf("%[^n]",line);printf("%s",line);}what willscanf do ?Compiler errorterminates reading input into variable line after newlineterminates reading input into variable line after entering ^n
  • 132.
    Terminates reading inputinto variable line after newline
  • 133.
    What is theoutput of the below code?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]);}
  • 134.
  • 135.
    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].
  • 136.
    What does thefollowing program do?#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); }
  • 137.
    It will printthe list of all primary numbers less than or equal to a given number n
  • 138.
    You have given1000 integers to sort. But, your RAM accommodates maximum of 100 integers only. How do your sort them?
  • 139.
    We have touse external sorting (by tapes, disks etc.) mechanism. We can use merge sort for internal sorting iterations.
  • 140.
    How to allocateand deallocate memory for char** ?
  • 141.
    In the order,first construct the main objects, and then construct the internal objectsAllocationchar** pp = new char*[10]; for(int i=0;i<10;i++) char*[i]=new char[100];
  • 142.
    In the reverseorder, first destruct the internal objects, then destruct the main objectDeallocation for(int i=0;i<10;i++) delete [] char*[i]; delete[] pp;
  • 143.
    What are thebest data structures for insertion, deletion and search operations?
  • 144.
    For Insertion anddeletion - Linked listFor search - Map (it is a height balanced Red-black tree. We can search in O(log n))
  • 145.
    Describe two scenarioswhere an application will crash due to stack overflow.
  • 146.
    The two mostcommon causes for a stack overflow is:(i) An infinite recursion int f1(){ f2();}int f2() { f1(); }f1() calls f2(), which in turn calls f1() and so on. Eventually, the stack overflows.
  • 147.
    (ii) An attemptto 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
  • 148.
    Can main functionbe overloaded? Explain.
  • 149.
    No, only onetype of calling is allowed in a program (with out arguments/with two arguments/ with three arguments)
  • 150.
    How to countthe number of set bits of an integer using that many number of iterations of for loop?
  • 151.
    unsigned int v;// count the number of bits set in vunsigned int c; // c accumulates the total bits set in vfor (c = 0; v; c++){ v &= v - 1; // clear the least significant bit set}
  • 152.
    What is theoutput of this program?#include <stdio.h>void main() { char s[20]; char *str = "SachinTendulker"; sscanf(str, "%s", s); printf("%s", s); sscanf(str+7, "%[duenTlk]", s); printf("%s", s); sscanf(str+15, "%[^Ganguly]", s); printf("%s\n", s); }
  • 153.
    SachinTendulkerExplanation:The above statementcaptures 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);
  • 154.
    The above statementcaptures 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.sscanf(str+15, "%[^Ganguly]", s);
  • 155.
    What is theoutput of the following program?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); }
  • 156.
    -1Explanation:By default, Xis signed and has sign bit 1. Therefore, it is stored in 2’s complement form.
  • 157.
    Consider the followingcode:What is the scope difference between i and j?int i;static int j;main( ) { }
  • 158.
    Both i andj have global scope, but j cannot be accessed in the other modules(files)
  • 159.
    How many timesthe following program would print India?main( ){ printf(" \n India"); main();}
  • 160.
    Till stack doesnot overflow (Infinite loop)
  • 161.
  • 162.
    The heap iswhere 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.
  • 163.
    What would bethe output of the following program if the array begins at the location 65472?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);}
  • 164.
  • 165.
    Provide simple implementationof int atoi(char* pStr)
  • 166.
    int atoi(char* pStr){ int iRetVal=0; if (pStr){ while (*pStr && *pStr<= ‘9’ && *pStr>=’0’) {iRetval = (iRetval*10) + (*pStr – ‘0’);pStr++; } } return iRetval;}
  • 167.
    What is theoutput of the below statement?printf(“%d”);
  • 168.
    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.