The document discusses C programming concepts like strcpy() function implementation, data types, operators, functions, pointers, arrays, strings and more. It provides code snippets to demonstrate various C programming techniques like implementing string copy functions, converting numbers to different bases, evaluating polynomials, swapping variables, reversing strings, matrix multiplication and more. It also answers questions about common C programming topics to test understanding.
4. 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.
5. 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
6. Method2: char *my_strcpy(char dest[], const char source[]) { int i = 0; while (source[i] != '') { dest[i] = source[i]; i++; } dest[i] = ''; return(dest); }
7. Write C programs to 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 C program 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;
12. 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));
14. 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).
15. What is the difference 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.
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.
22. 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;
23. 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.
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 declare an array of N pointers to functions returning pointers to functions returning pointers to characters?
28. Will C allow passing more or less arguments than required to a function?
29. 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.
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); }
32. Upon a successful return, the printf() function returns the number of characters printed (not including the trailing '' 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 '') 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 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");} }
35. Write a C program to count bits set in an integer.
36. #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, CountSetBits(n)); return 0; }
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("[%d]",pow(5,4)); } printf("[%d]",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 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.
44. Write a C program to convert from decimal to any base (binary, hex)
45. #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("[%d] converted to base [%d] : ", n, base);
46. 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]); } }
48. (num<<3 - num) Same as, num*8 - num = num * (8-1) = num * 7
49. How can we sum 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("sum = [%d]", sum); }
51. Given two strings A 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> int isSubset(char *a, char *b); int main(){ char str1[]="defabc"; char str2[]="abcfed"; if(isSubset(str1, str2)==0){ printf("Yes, characters in B=[%s] are a subset of characters in A=[%s]",str2,str1); } else { printf("No, characters in B=[%s] are not a subset of characters in A=[%s]",str2,str1); } getch(); return(0); }
53. // 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]!=''; i++) letterPresent[a[i]]++; for(i=0; b[i]!=''; i++) if(!letterPresent[b[i]]) return(1); return(0); }
54. Write a program to print numbers from 1 to 100 without using loops!
55. void printUp(int startNumber, int endNumber) { if (startNumber > endNumber) return; printf("[%d]", startNumber++); printUp(startNumber, endNumber); }
59. #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("The exchanged value is %x",swap_nibbles(ch)); return 0; }
60. Write a C program to reverse the words in a sentence in place. Like, Input: I am a good girl Output: should be: lrigdoog a ma I
61. 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);
62. // Now swap each word within sentence... x = buf-1; y = buf; while(x++ < end) { if(*x == '' || *x == ' ') { rev(y,x-1); y = x+1;} }
63. // Now print the final string.... printf("%s",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; } }
68. Write a C program for calculating the factorial of a number (use recursive function)
69. Here is a recursive C program 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
70.
71. If a character string is to be received through the keyboard which function would work faster? gets scanf
73. Consider the following piece of code and predict the output 100 4 2 99 void main() { int i=100; clrscr(); printf("%d", sizeof(sizeof(i))); getch(); }
75. Choose the correct output from the following code snippet. It prints "God is Great“ Run time error Compilation error No output void main() { static int a,b; if(a & b) printf("God is Great"); }
79. Choose the correct answer Main cannot be printed %p is an invalid control string Some address will be printed Compile time error main() { Printf(“%p”,main); }
81. What error will the below function give on compilation? The function should be defined as int f(int a, int b) Redeclaration of a Missing parentheses in return f(int a, int b) { int a; a = 20; return a; }
87. What is the output of the below code? main(){ int a=10,*j; void *k; j=k=&a; j++; k++; printf(" %u %u ",j,k); }
88. 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
89. 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”); }}
90. Compiler Error: switch expression not integral Explanation: Switch statements can be applied only to integral types.
91. What is the output of the below code? void main() { static int i; while(i<=10) (i>2)?i++:i--; printf(“%d”, i); }
92. 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.
93. What is the output of the below code? main(){ char str1[] = ”some”; char str2[] =”some”; if (strcmp(str1,str2)) printf(“Strings are not equal”); }
95. What is the output of the below code? main(){ char p[ ]="%d"; p[1] = 'c'; printf(p,65);}
96. A Explanation: Due to the assignment p[1] = ‘c’ the string becomes, “%c”. Since this string becomes the format string for printf and ASCII value of 65 is ‘A’, the same gets printed.
97. What is the output of the below code? void main() { int i=5; printf(“%d”,i=++i ==6); }
98. 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.
99. What is the output of the following code? main() { int a[5] = {2,3}; printf(" "%d %d d"",a[2],a[3],a[4]); }
101. What will be the output of the below program? 4 3 No output 0 #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); }
103. Which of the following is correct about the statement given below? structure engine is nested within structure maruti structure maruti is nested within structure engine structure maruti is nested within structure bolts structure engine is nested within structure engine maruti.engine.bolts = 25;
105. Which of the following is the correct output for the program given below? 1 2 5 4 int fun(int); void main(){ int i = 3; fun(i = fun(fun(i))); printf("%d",i); } fun(int i){ i++; return(i); }
109. Choose the correct answer based on output from following piece of code 16, 25 9,49 Error in code 6,7 #define PRODUCT(x) (x*x) main() { int i = 3,j,k; j = PRODUCT (i++); k = PRODUCT(++i); printf(“%d %d”, j,k); }
113. Which of the following is the correct output for the program given below? 20 10 30 0 #include<stdio.h> void main() { union var { int a, b; }; union var v; v.a = 10; v.b = 20; printf("%d",v.a); }
115. 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 file The disk is searched for existence of the file The file is brought into memory
117. The assignment operation X=Y means? l-value of Y is stored in l-value of X r-value of Y is stored in r- value of X r-value of Y is stored in l-value of X l-value of Y is stored in r-value of X
119. 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 i Only ii Both i & ii Neither i nor ii
125. What is the output of the below code? Syntax Error No Output Compiler Error hello #include main(){ struct xx { int x=3; char name[]=”hello”; }; struct xx *s;
129. In the following code fp points to A Structure which contains a char pointer which points to the first character in the file The name of the file The First character in the file #include<stdio.h> main() { FILE *fp; fp=fopen("trail","r"); }
130. A Structure which contains a char pointer which points to the first character in the file
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 the following program do? #include "math.h" main(){ int n,i,j,m; printf("Enter any number "); 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", 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 print the list of all primary numbers less than or equal to a given number n
138. You have given 1000 integers to sort. But, your RAM accommodates maximum of 100 integers only. How do your sort them?
139. We have to use external sorting (by tapes, disks etc.) mechanism. We can use merge sort for internal sorting iterations.
141. In the order, first construct the main objects, and then construct the internal objects Allocation char** pp = new char*[10]; for(int i=0;i<10;i++) char*[i]=new char[100];
142. In the reverse order, first destruct the internal objects, then destruct the main object Deallocation for(int i=0;i<10;i++) delete [] char*[i]; delete[] pp;
143. What are the best data structures for insertion, deletion and search operations?
144. For Insertion and deletion - Linked list For search - Map (it is a height balanced Red-black tree. We can search in O(log n))
146. 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.
147. (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
149. No, only one type of calling is allowed in a program (with out arguments/with two arguments/ with three arguments)
150. How to count the 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 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 }
152. 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", s); }
153. 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);
154. 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);
155. 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); }
156. -1 Explanation: By default, X is signed and has sign bit 1. Therefore, it is stored in 2’s complement form.
157. Consider the following code: What is the scope difference between i and j? int i; static int j; main( ) { }
158. Both i and j have global scope, but j cannot be accessed in the other modules(files)
159. How many times the following program would print India? main( ) { printf(" India"); main(); }
162. 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.
163. 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( " %u %u ",a+1, &a+1); }
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 the output 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.