Professional Documents
Culture Documents
Interview Training
TYPES OF OPERATORS
2
Interview Question-1
Softway 2015
3
Interview Question-1
• Output:
Turbo C++ 3.0: 8 24
Turbo C ++4.5: Compilation error
Linux GCC: Compilation error
Visual C++: Compilation error
• Explanation:
Rule :- ++ is pre increment operator so in any arithmetic expression it first
increment the value of variable by one in whole expression then starts
assigning the final value of variable in the expression.
Compiler will treat this expression j = ++i+++i+++i; as
i = ++i + ++i + ++i;
Initial value of i = 5 due to three pre increment operator final value of i=8.
Now final value of i i.e. 8 will assigned to each variable as shown in the
following figure:
• 4
Interview Question-2
TECHNICS 2017
What will be output of the following program?
#include<stdio.h>
int main()
{
int a=2,b=7,c=10;
c=a==b;
printf("%d",c);
return 0;
}
5
Interview Question-2
• Output:
Turbo C++ 3.0: 0
Turbo C ++4.5: 0
Linux GCC: 0
Visual C++: 0
• Explanation:
== is relational operator which returns only two values.
0: If a == b is false
1: If a == b is true
Since
a=2
b=7
So, a == b is false hence c=0
6
Interview Question-3
CGI 2016
What will be output of the following program?
#include<stdio.h>
void main()
{
int x;
x=10,20,30;
printf("%d",x);
return 0;
}
7
Interview Question-3
• Output:
Turbo C++ 3.0: 10
Turbo C ++4.5: 10
Linux GCC: 10
Visual C++: 10
• Explanation
Operator Precedence Associative
= More than , Right to left
, Least Left to right
Since assignment operator (=) has more precedence than comma
operator .So = operator will be evaluated first than comma operator.
In the following expression x = 10, 20, 30. First 10 will be assigned
to x then comma operator will be evaluated.
8
Interview Question-4
What will be output of the following program? CAPGEMINI 2014
#include<stdio.h>
int main()
{
int a=0,b=10;
if(a=0){
printf("true");
}
else{
printf("false");
}
return 0; }
9
Interview Question-4
• Output:
Turbo C++ 3.0: false
Turbo C ++4.5: false
Linux GCC: false
Visual C++: false
• Explanation:
As we know = is assignment operator not relation operator. So, a =
0 means zero will assigned to variable a. In c zero represent false
and any non-zero number represents true. So, if(0) means condition
is always false hence else part will execute.
10
Interview Question- 5
Mphasis 2015
What will be output of the following program?
#include<stdio.h>
int main()
{
int a;
a=015 + 0x71 +5;
printf("%d",a);
return 0;
}
11
Interview Question- 5
• Output:
• Turbo C++ 3.0: 131
• Turbo C ++4.5: 131
• Linux GCC: 131
• Visual C++: 131
• Explanation:
015 is octal number its decimal equivalent is = 5 * 8 ^ 0 +
1 * 8 ^ 1 = 5 + 8 = 13
• 0x71 is hexadecimal number (0x is symbol of
hexadecimal) its decimal equivalent is = 1 * 16 ^ 0 + 7 *
16 ^ 1 = 1 + 112 = 113
• So, a = 13 + 113 + 5 = 131 12
Interview Question-6
TECH MAHINDRA 2016
What will be output of the following program?
#include<stdio.h>
int main()
{
printf("%d %d d",sizeof(3.14),sizeof(3.14f),sizeof(3.14L));
return 0;
}
13
Interview Question-6
• Output:
Turbo C++ 3.0: 8 4 10
Turbo C ++4.5: 8 4 10
Linux GCC: 8 4 12
Visual C++: 8 4 8
• Explanation:
3.14f is floating point constant. Its size is 4 byte. 3.14 is
double constant (default). Its size is 8 byte. 3.14L is long
double constant. Its size is 10 byte. sizeof() operator
always return the size of data type which is written inside
the(). It is keyword.
14
Interview Question-7
VIRTUSA 2014
What will be output of the following program?
#include<stdio.h>
int main()
{
int x=100,y=20,z=5;
printf("%d %d %d");
return 0;
}
15
Interview Question-7
• Output:
Turbo C++ 3.0: 5 20 100
Turbo C ++4.5: 5 20 100
Linux GCC: Garbage values
Visual C++: 5 100 20
• By default x, y, z are auto type data which are stored in
stack in memory. Stack is LIFO data structure. So in
stack first stores 100 then 20 then 5 and program
counter will point top stack i.e. 5. Default value of %d in
printf is data which is present in stack. So output is
revere order of declaration. So output will be 5 20 100.
16
Interview Question-8
TECH MAHINDRA 2016
What will be output of the following program?
#include<stdio.h>
int main()
{
int a=2;
a=a++ + ~++a;
printf("%d",a);
return 0;
}
17
Interview Question-8
• Output:
Turbo C++ 3.0: -1
Turbo C ++4.5: 0
Linux GCC: 0
Visual C++: 0
•
18
Interview Question-9
SYNTEL 2014
What will be output of the following program?
#include<stdio.h>
int main()
{
int a;
a=sizeof(!5.6);
printf("%d",a);
return 0;
}
19
Interview Question-9
• Output:
Turbo C++ 3.0: 2
Turbo C ++4.5: 2
Linux GCC: 4
Visual C++: 4
• Explanation:
• ! is negation operator it return either integer 0 or 1.
! Any operand = 0 if operand is non zero.
! Any operand = 1 if operand is zero.
So, !5.6 = 0
• Since 0 is integer number and size of integer data type is
two byte.
20
Interview Question-10
COGNIZANT 2016
What will be output of the following program?
#include<stdio.h>
int main(){
float a;
(int)a= 45;
printf("%d,a);
return 0;
}
21
Interview Question-10
• Output:
Turbo C++ 3.0: Compilation error
Turbo C ++4.5: Compilation error
Linux GCC: Compilation error
Visual C++: Compilation error
• Explanation:
After performing any operation on operand it always return some
constant value. (int) i.e. type casting operator is not exception for
this. (int) a will return one constant value and we cannot assign any
constant value to another constant value in c. (int)a = 45; is
equivalent to 3456 = 45 (Here 3456 in any garbage value of int(a)).
22
Interview Question-11
WIPRO 2016
What will be output of the following program?
#include<stdio.h>
int main()
{
int i=5;
int a=++i + ++i + ++i;
printf("%d",a);
return 0;
}
23
Interview Question-11
• Output:
Turbo C++ 3.0: 21
Turbo C ++4.5: 21
Linux GCC: 22
Visual C++: 24
• Explanation:
• Rule : ++ (in ++i) is pre increment operator so in any
arithmetic expression it first increment the value of
variable by one in whole equation up to break point then
start assigning the value of variable in the equation.
There are many break point operators in. For example:
24
Interview Question-11
25
Control Structure
26
Control Structure
28
Interview Question -12
TECHNOVERT 2015
What will be output when you will execute following c
code?
#include<stdio.h>
void main(){
int a=5,b=10,c=1;
if(a&&b>c){
printf(“Hello Thub");
}
else{
break;
}
} 29
Interview Question -12
• Explanation
• Keyword break is not syntactical part of if-else
statement. So we cannot use break keyword in if-else
statement. This keyword can be use in case of loop or
switch case statement.
• Hence when you will compile above code compiler will
show an error message: Misplaced break.
30
Interview Question-13
SOFTWAY 2016
What will be output when you will execute following c
code?
#define PRINT printf("Star Wars");printf("Godzilla");
#include<stdio.h>
void main(){
int x=1;
if(x--)
PRINT
else
printf(“Titanic");
}
31
Interview Question-13
• If you are not using opening and closing curly bracket in
if clause, then you can write only one statement in the if
clause. So compiler will think:
• (i) if(x--)
• printf("Star Wars");
• It is if statement without any else. It is ok.
• (ii) printf(" Godzilla");
• It is a function call. It is also ok
• (iii) else
• printf(“Titanic");
• You cannot write else clause without any if clause. It is
cause of compilation error. Hence compiler will show an 32
error message: Misplaced else
Interview Question-14
ZENQ 2016
What will be output when you will execute following c
code?
#include<stdio.h>
void main(){
int x=-1,y=-1;
if(++x=++y)
printf(“Abdul Kalam”);
else
printf(“Prathipa Patel”);
}
33
Interview Question-14
• Explanation:
• Consider following statement:
• ++x=++y
• As we know ++ is pre increment operator in the above
statement. This operator increments the value of any integral
variable by one and return that value. After performing pre
increments above statement will be:
• 0=0
• In C language it is illegal to assign a constant value to another
constant. Left side of = operator must be a container i.e. a
variable. So compiler will show an error message: Lvalue
required
34
Interview Question-15
INFOSYS 2016
What will be output when you will execute following c
code?
#include<stdio.h>
void main(){
if(!printf("Aditya Engineering College"))
if(printf(" Sai Aditya Engineering College"));
}
35
Interview Question-15
• Explanation
• Return type of printf function is int. This function return a
integral value which is equal to number of characters a
printf function will print on console. First of all printf
function will: Aditya Engineering College. Since it is
printing 26 character so it will return 26. So,
• !printf("Aditya Engineering College")
• = !26
• =0
• In c language zero represents false. So if(0) is false so
next statement which inside the body of first if statement
will not execute. 36
Programs using Patterns -1
TECHNOVERT 2016
1 *
12 ***
123 *****
1234 *******
12345 *********
*
***
*****
*******
*********
37
Program-2
SOFTWAY 2016
Write a C Program to print the following Pattern
38
Interview Question-16
TECH MAHINDRA 2015
What will be output when you will execute following c
code?
#include<stdio.h>
void main(){
int movie=1;
switch(movie<<2+movie){
default:printf("3 Idiots");
case 4: printf(" Ghajini");
case 5: printf(" Krrish");
case 8: printf(" Race");
}
40
}
Interview Question-16
• Explanation:
• We can write case statement in any order
including the default case. That default
case may be first case, last case or in
between the any case in the switch case
statement.
41
Interview Questions-17
ZENQ 2015
What will be the output of following program ?
#include < stdio.h >
void main()
{ unsigned char var=0;
for(var=0;var<=255;var++)
{
printf("%d ",var);
}
}
42
Interview Questions-17
• Explanation
• 0 1 2 ... 255
• The range of unsigned char is 0 to 255
and when the value of var will cross over
255, value will be 0 and again same
process will happen.
43
Interview Questions-18
TECH MAHINDRA 2016
What will be the output of following program ?
#include <stdio.h>
void main()
{
int i,j,charVal='A';
for(i=5;i>=1;i--)
{
for(j=0;j< i;j++)
printf("%c ",(charVal+j));
printf("\n");
}
} 44
Interview Questions-18
• Answer
ABCDE
ABCD
ABC
AB
A
45
Interview Questions-19
JUST PAY 2016
46
Interview Questions-19
• Answer
• Error: lvalue required as increment
operand.
47
Interview Questions-20
• What will be output of following c code? APTROID 2016
#include<stdio.h>
extern int x;
int main(){
do{
do{
printf("%o",x);
}
while(!-2);
}
while(0);
return 0;
}
int x=8; 48
Interview Questions-20
• Output: 10
• Explanation: Here variable x is extern type. So it will
search the definition of variable x. which is present at the
end of the code. So value of variable x =8. There are two
do-while loops in the above code. AS we know do-while
executes at least one time even that condition is false.
So program control will reach at printf statement at it will
print octal number 10 which is equal to decimal number
8. Note: %o is used to print the number in octal format.
• In inner do- while loop while condition is ! -2 = 0
• In C zero means false. Hence program control will come
out of the inner do-while loop. In outer do-while loop
while condition is 0. That is again false. So program
control will also come out of the outer do-while loop.
Interview Questions-21
ARTECH 2015
50
Interview Questions-21
Output: 1
Explanation:
Consider the while loop condition: i + 1 ? -- i : ++j
In first iteration: i + 1 = 3 (True)
So ternary operator will return -–i i.e. 1
In c 1 means true so while condition is true. Hence printf
statement will print 1. In second iteration:
i+ 1 = 2 (True)
So ternary operator will return -–i i.e. 0 . In c zero means
false so while condition is false. Hence program control will
come out of the while loop.
51
Interview Questions-22
TECH MAHINDRA 2015
What will be output of following c code?
#include<stdio.h>
int main(){
int i,j;
i=j=2,3;
while(--i&&j++)
printf("%d %d",i,j);
return 0;
}
52
Interview Questions-22
• Output: 13
• Explanation:
Initial value of variable
i=2j=2
Consider the while condition : --i && j++ In first iteration:
--i && j++ = 1 && 2 //In c any non-zero number represents true.
= 1 (True)
So while loop condition is true. Hence printf function will print value of i
= 1 and j = 3 (Due to post increment operator)
In second iteration:
--i && j++ = 0 && 3 //In c zero represents false
= 0 //False . So while loop condition is false. Hence program control
will come out of the for loop.
53
Interview Questions-23
DIVAM 2016
What will be output of following c code?
#include<stdio.h>
int r();
int main(){
for(r();r();r()) {
printf("%d ",r());
}
return 0;
}
int r(){
int static num=7;
return num--; 54
Interview Questions-23
• Output: 5 2
• Explanation:
First iteration: Loop initial value: r() = 7
Loop condition: r() = 6
Since condition is true so printf function will print r() i.e. 5
Loop incrimination: r() = 4
Second iteration: Loop condition: r() = 3
Since condition is true so printf function will print r() i.e. 2
Loop incrimination: r() = 1
Third iteration: Loop condition: r() = 0
Since condition is false so program control will come out of the for
loop.
55
Interview Questions-24
HGS 2016
• What will be output of following c code?
#include<stdio.h>
int i=40;
extern int i;
int main(){
do{
printf("%d",i++);
}
while(5,4,3,2,1,0);
return 0;
} 56
Interview Questions-24
• Output: 40
• Explanation:
• Initial value of variable i is 40
• First iteration:
• printf function will print i++ i.e. 40
• do - while condition is : (5,4,3,2,1,0)
• Here comma is behaving as operator and it will
return 0. So while condition is false hence
program control will come out of the for loop.
57
Interview Questions-25
UCERTIFY 2015
• How many times this loop will execute?
#include<stdio.h>
int main(){
char c=125;
do
printf("%d ",c);
while(c++);
return 0;
}
58
Interview Questions-25
59
Storage Class
Storage Classes
• Storage Classes are used to describe
about the scope, visibility and life-time
which help us to trace the existence of a
particular variable during the runtime of a
program.
60
Storage Class
61
Storage Class
62
Storage Class
63
Storage Class
• static: This storage class is used to declare static variables
which are popularly used while writing programs in C
language.
• Static variables have a property of preserving their value
even after they are out of their scope!
• Static variables are initialized only once and exist till the
termination of the program.
• No new memory is allocated because they are not re-
declared.
• Their scope is local to the function to which they were
defined.
• Global static variables can be accessed anywhere in the
program. By default, they are assigned the value 0 by 64 the
compiler.
Storage Class
65
Interview Question 26
GGK TECH 2016
• main() • Answer: 5 4 3 2 1
• { • Explanation:
• static int var = 5; • When static storage class is
given, it is initialized once. The
• printf("%d ",var--); change in the value of a static
variable is retained even
• if(var) between the function calls.
• main(); Main is also treated like any
other ordinary function, which
• } can be called recursively.
66
Interview Question 27
PRATIAN TECH 2016
• main() • Answer: Linker Error :
• { Undefined symbol '_i'
• Explanation: extern storage
• extern int i; class in the following declaration,
• extern int i;
• i=20; • specifies to the compiler that the
• printf("%d",i); memory for i is allocated in some
other program and that address
• } will be given to the current
program at the time of linking. But
linker finds that no other variable
of name i is available in any other
program with memory space
allocated for it. Hence a linker
error has occurred .
67
Arrays and Strings
79
Progam -6
URJANET 2016
• An interview is scheduled for a list of students in T-Hub, and the
candidate list has been shared to the interview panel. But in the last
minute the Team Head came to know the last k students in the
candidate list need to be given priority since they need to catch a
train. Write a program to help the Team Head to shuffle the
candidate list so that last n will come in the first
• Sample Input:
8
5
10 20 30 40 50 60 70 80
• Sample Output:
40 50 60 70 80 10 20 30
80
Program -7
NTT DATA 2015
• Given a sorted array, remove the duplicates in
place such that each element appear only once
and return the new length.
• Sample Input
• 3
• 112
• Sample Output
• 12
81
Program - 8
DELOITTE 2016
85
Strings
• Array of Strings
– Two dimensional character arrays are used to represent array of
strings.
• Declaration
• General Form:
– char arrayname [no. of strings] [max no. of chars in strings];
• Example
• char studname[50][15];
• /* 50 student names each with 15 characters at the
maximum */
89
Strings
• Initialization
• General Form:
• char arrayname [ r ] [ c ]={“values”};
• Example
• char name[3][5] = {“bata” ,”cat” ,”at”}
• char name[3][5] = {{‘b’,’a’,’t’,’a’,’\0’},
{‘c’,’a’,’t’,’\0’}, {‘a’,’t’,’\0’}}
90
Strings
93
Char Function
94
Interview Question -1
DELOITEE 2015
Ans : 20
95
Interview Question-2
NTT DATA 2015
• What is the output of the program segment
below?
• char str[4] = “abe”;
• char c = ‘d’;
• char tmp = ‘f’;
• tmp = str[0];
• str[0] = ‘c’;
• c = tmp;
• printf(“%c%c%c”,str[0],c,tmp);
• Ans :caa
96
Interview Question -3
GLOBAL DATA 2015
main()
{
char string[]=
"Hello World";
display(string);
}
void display(char *string)
{
printf("%s",string);
}
97
Interview Question - 4
ZENQ 2016
• Ans: bc
98
Program-1
URJANET 2016
• Steve has a string s, consisting of lowercase English
alphabetic letters. In one operation, he can delete
duplicate words in a string. For example, string "This is a
life and our life will be full of fun just like the Benn
Steller's Secret life of Walter Mitty" would become “This
is a and our will be full of fun just like the Benn Steller's
Secret of Walter Mitty “. Help Steve out by finding
duplicate words in a string.
• Sample Input “This is a life and our life will be full of fun
just like the Benn Steller's Secret life of Walter Mitty “
• Sample Output : “This is a and our will be full of fun just
like the Benn Steller's Secret of Walter Mitty “
99
Program-2
SOFTWAY 2016
101
Program-4
ARTECH 2015
• Find the frequency of each string in a given string array and arrange
them in their frequency order
• Sample Input:
• 6
• AAA
• BBB
• AAA
• CCC
• AAA
• BBB
• Sample Output:
• AAA 3
• BBB 2
• CCC 1
102
Program - 5
TECH MAHINDRA 2016
104
Program-7
GGK TECH 2016
105
Need for user – define Function
. 107
How Function Works?
Output :
Function Message
Main Message
109
Function Syntax
110
Function Prototype
111
Types of Function Prototype
112
Parameter Passing Methods
– Call by Value
– Call by reference.
113
Interview Questions -5
ACCENTURE 2016
main()
{
int i=abc(10);
printf("%d\n",--i);
}
What will be the output ?
int abc(int i)
{
return(i++);
}
. 114
Interview Questions
Answer:
9
Explanation:
return(i++) it will first return i and then
increments. i.e. 10 will be returned.
115
Interview Questions-6
GGK TECH2016
116
Interview Questions
Answer:
10
Explanation:
The macro expands and evaluates to as:
x+2*y-1 => x+(2*y)-1 => 10
117
Interview Question -7
COGNIZANT 2016
void main()
{
static int i=5;
if(--i){
main();
printf("%d ",i);
}
}
Ans: 0 0 0 0
118
Interview Question
• Explanation:
• The variable "I" is declared as static,
hence memory for I will be allocated for
only once, as it encounters the statement.
The function main() will be called
recursively unless I becomes equal to 0,
and since main() is recursively called, so
the value of static I ie., 0 will be printed
every time the control is returned
119
Interview Question -8
CGI 2016
void main()
{
int k=ret(sizeof(float));
printf("\n Here value is %d",++k);
}
int ret(int ret)
{
ret += 2.5;
return(ret);
}
• Example:
int x, *px;
px = &x;
x = 5;
Declaration
• Example
• int * ptr , i=5;
• ptr= &i; ptr = 1000 (location of i)
• ptr ++; ptr = 1002 (+2 for integers)
• ++*ptr or (*ptr)++ - increments the value of
i by 1
Illegal Operations on pointer
• Example
• Int a[5] = {1,2,3,4,5}, *ptr, i;
• ptr = a ; or ptr = &a[0];
• Assume that array starts at location 1000:
• &a[0] = 1000 a[0] = 1 ptr + 0 = 1000 *(ptr+0) = 1
• &a[1] = 1002 a[1] = 2 ptr + 1 = 1002 *(ptr+1) = 2
• &a[2] = 1004 a[2] = 3 ptr + 2 = 1004 *(ptr+2) = 3
• &a[3] = 1006 a[3] = 4 ptr + 3 = 1006 *(ptr+3) = 4
• &a[4] = 1008 a[4] = 5 ptr + 4 = 1008 *(ptr+4) = 5
Pointers and String
• Example
• void add(int x, int y)
• {
• printf(“Value = %d”, x + y);
• }
– Pointer to this function should be declared as:
• p = add;
• /*makes the pointer to point to the function add()*/
• (*p)(10,20);
• /*will call the function add with parameters 10,20*/
Interview Question - 9
DEIVAM 2016
void main()
{
int const * p=5;
printf("%d",++(*p));
}
Answer : Compiler error: Cannot modify a constant value.
140
Interview Question-10
CSC 2015
main()
{
char s[ ]="man";
int i;
for(i=0;s[ i ];i++)
printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
}
• Answer: mmmm
• aaaa
141
• nnnn
Interview Question -11
ALPHA 2016
main()
{
int c[ ]={2.8,3.4,4,6.7,5};
int j,*p=c,*q=c;
for(j=0;j<5;j++) {
printf(" %d ",*c);
++q; }
for(j=0;j<5;j++){
printf(" %d ",*p);
++p; }
}
• Answer: 2222223465
142
Interview Question -11
• Explanation:
• Initially pointer c is assigned to both p and
q. In the first loop, since only q is
incremented and not c , the value 2 will be
printed 5 times. In second loop p itself is
incremented. So the values 2 3 4 6 5 will
be printed.
143
Interview Question -12
TECHNOVERT 2016
main()
{
char *p;
printf("%d %d ",sizeof(*p),sizeof(p));
}
• Answer: 12
144
Interview Question-12
• Explanation:
• The sizeof() operator gives the number of
bytes taken by its operand. P is a
character pointer, which needs one byte
for storing its value (a character). Hence
sizeof(*p) gives a value of 1. Since it
needs two bytes to store the address of
the character pointer sizeof(p) gives 2.
145
Interview Question-13
WIPRO 2014
main()
{
char string[]="Hello World";
display(string);
}
void display(char *string)
{
printf("%s",string);
}
• Answer: Compiler Error : Type mismatch in redeclaration of function
display
146
Interview Question-13
• Explanation :
• In third line, when the function display is
encountered, the compiler doesn't know
anything about the function display. It assumes
the arguments and return types to be integers,
(which is the default type). When it sees the
actual function display, the arguments and type
contradicts with what it has assumed previously.
Hence a compile time error occurs.
147
Interview Question -14
PATRIAN 2015
• #include<stdio.h>
• main()
• {
• char s[]={'a','b','c','\n','c','\0'};
• char *p,*str,*str1;
• p=&s[3];
• str=p;
• str1=s;
• printf("%d",++*p + ++*str1-32);
• }
• Answer: 77 148
Interview Question -14
• Explanation:
• p is pointing to character '\n'. str1 is pointing to
character 'a' ++*p. "p is pointing to '\n' and that is
incremented by one." the ASCII value of '\n' is
10, which is then incremented to 11. The value
of ++*p is 11. ++*str1, str1 is pointing to 'a' that
is incremented by 1 and it becomes 'b'. ASCII
value of 'b' is 98.
• Now performing (11 + 98 – 32), we get 77("M");
• So we get the output 77 :: "M" (Ascii is 77).
149
Interview Question -15
MINDTREE 2016
#include<stdio.h>
main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf("%d----%d",*p,*q);
}
• Answer: SomeGarbageValue---1
150
Interview Question-15
151
Interview Question - 16
MIRACLE 2016
main()
{
char *p;
p="Hello";
printf("%c\n",*&*p);
}
• Answer: H
152
Interview Question-16
• Explanation:
• * is a dereference operator & is a
reference operator. They can be applied
any number of times provided it is
meaningful. Here p points to the first
character in the string "Hello". *p
dereferences it and so its value is H. Again
& references it to an address and *
dereferences it to the value H.
153
Interview Question-17
AMAZON 2016
• main()
• {
• int i;
• char *t;
• t=names[3];
• names[3]=names[4];
• names[4]=t;
• for (i=0;i<=4;i++)
• printf("%s",names[i]);
• }
154
Interview Question-17
• Answer:
• Compiler error: Lvalue required in function
main
• Explanation:
• Array names are pointer constants. So it
cannot be modified.
155
Interview Question-18
GGK TECH 2016
#include<stdio.h>
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}
156
Interview Question-18
• Answer: M
• Explanation:
• p is pointing to character '\n'.str1 is pointing to character
'a' ++*p meAnswer:"p is pointing to '\n' and that is
incremented by one." the ASCII value of '\n' is 10. then it
is incremented to 11. the value of ++*p is 11. ++*str1
meAnswer:"str1 is pointing to 'a' that is incremented by 1
and it becomes 'b'. ASCII value of 'b' is 98. both 11 and
98 is added and result is subtracted from 32.
• i.e. (11+98-32)=77("M");
157
Interview Question-19
CSC 2016
• main( )
• {
• int a[2][3][2] = {{{2,4},{7,8},{3,4}},{{2,2},{2,3},{3,4}}};
• printf(“%u %u %u %d \n”,a,*a,**a,***a);
• printf(“%u %u %u %d \n”,a+1,*a+1,**a+1,***a+1);
• }
• Answer:
• 100, 100, 100, 2
• 114, 104, 102, 3
158
Interview Question-19
• Explanation:
• The given array is a 3-D one. It can also be viewed as a 1-D array.
• 2
100
4
102
7
104
8
106
3
108
4
110
2
112
2
114
2
116
3
118
3
120
4
122
• thus, for the first printf statement a, *a, **a give address of first
element . since the indirection ***a gives the value. Hence, the first
line of the output.
• for the second printf a+1 increases in the third dimension thus points
to value at 114, *a+1 increments in second dimension thus points to
104, **a +1 increments the first dimension thus points to 102 and
***a+1 first gets the value at first location and then increments it by
1. Hence, the output.
159
Interview Question-20
AMAZON 2016
main( ) p = a;
{ for(j=0; j<5; j++)
int a[ ] = {
{10,20,30,40,50},j,*p; printf(“%d ” ,*p);
for(j=0; j<5; j++) p++;
{ }
printf(“%d” ,*a); }
a++;
}
160
Interview Question-20
• Answer:
• Compiler error: lvalue required.
• Explanation:
• Error is in line with statement a++. The
operand must be an lvalue and may be of
any of scalar type for the any operator,
array name only when subscripted is an
lvalue. Simply array name is a non-
modifiable lvalue.
161
Introduction to Structures and
Union
• Structures and Unions are the main
constructs available in C through which
programmers can define new data type.
• Structures and unions provide a way to
group logically related data items together.
What is Structure?
• struct employee
{
int code;
char name [20];
struct date doj ;
int dept_code;
float salary;
}emp1,emp2;
Structures and arrays
• student.sub_marks[0],
• student.sub_mark[1], student.name
Self Referential Structure
179
Interview Question-33
COGNIZANT 2016
• Is the following code • Answer: No
legal? • Explanation:
• struct a • Is it not legal for a
• { structure to contain a
member that is of the
• int x; same type as in this case.
• struct a, b; Because this will cause
the structure declaration
• } to be recursive without
end.
180
Interview Question-34
• main() CSC 2016
• { • Answer: Compiler Error:
• struct date; Undefined structure date
• struct student • Explanation:
• {
• char name[30]; • Only declaration of struct
• struct date dob; date is available inside
• }stud; the structure definition of
• struct date
• {
‘student’ but to have a
• int day,month,year; variable of type struct
• }; date the definition of the
• scanf("%s%d%d%d", stud.rollno, structure is required.
&student.dob.day,
&student.dob.month,
&student.dob.year);
• }
181
Interview Question-35
APTROID 2016
#include<stdio.h>
• Answer: Compiler
main()
{ Error
struct xx • Explanation:
{
int x; • in the end of nested
struct yy structure yy a
{
member have to be
char s;
struct xx *p; declared.
};
struct yy *q;
};
}
182
Interview Question-36
#include<stdio.h> NTTDATA 2015
• Answer: Compiler Error
main()
• Explanation:
{
• The structure yy is nested
struct xx within structure xx. Hence, the
{ elements are of yy are to be
int x; accessed through the instance
struct yy of structure xx, which needs an
instance of yy to be known. If
{
the instance is created after
char s; defining the structure the
struct xx *p; compiler will not know about
}; the instance relative to xx.
struct yy *q; Hence for nested structure yy
you have to declare member.
};
} 183
Interview Question-37
DEIVAM 2016
#include<stdio.h> • Answer: Compiler
main()
Error
{
struct xx • Explanation: You
{ should not initialize
int x=3; variables in
char name[]="hello"; declaration
};
struct xx *s;
printf("%d",s->x);
printf("%s",s->name);
}
184
Interview Question-38
MPHASIS 2016
• #include<stdio.h> • Answer : Compiler Error
• int main() • Explanation:
• {
• Bit field type must
• struct a
be signed int or unsigned
• {
int.
• float category:5;
• char scheme:4; • The char type: char
• }; scheme:4; is also a valid
• printf("size=%d", statement.
sizeof(struct a));
• return 0;
• }
185
Interview Question-39
ZENQ 2016
•
•
#include<stdio.h>
#include<string.h>
• Answer : Compiler Error
• void modify(struct emp*); • Explanation:
• struct emp
• { • The struct emp is mentioned in
• char name[20]; the prototype of the
• int age; function modify() before
• }; declaring the structure.To
• int main()
solve this problem
• {
• struct emp e = {"Sanjay", 35};
declare struct emp before
• modify(&e); the modify() prototype.
• printf("%s %d", e.name, e.age);
• return 0;
• }
• void modify(struct emp *p)
• {
• p ->age=p->age+2;
• } 186
Unions
• Syntax:
• union tag_name
• {
type variable-name, variable-name,........;
type variable-name, variable-name,........;
type variable-name, variable-name,........;
:
:
type variable-name, variable-name,........;
• }union-variable1, union-variable2...... ;
Union Initialization
• int main()
• {
• u.c = 100;
• printf("%d %d %d\n", u.s.c1, u.s.c2,
u.s.c3);
• return 0;
• }
190
Interview Question-41
CAPGEMINI 2016
#include<stdio.h>
union abc
{
char a,b,c,d,e,f,g,h; int i;
}abc;
main()
{
printf( "%d", sizeof( abc
)); }
191
Interview Question-42
CALIBER 2016
#include<stdio.h>
• Answer : 3 2 515
int main() • The system will allocate 2 bytes
{ for the union.
union a • The statements u.ch[0]=3;
{
u.ch[1]=2; store data in memory
int i;
as given below.
char ch[2];
};
union a u;
u.ch[0]=3;
u.ch[1]=2;
printf("%d, %d, %d\n", u.ch[0], u.ch[1], u.i);
return 0;
}
192
Enumeration
• Syntax:
• enum tag {member1,member2,…member n};
• Tag is a name that identifies
enumerations.
• Members represent the identifiers
• Enumerated variables can be declared as
follows:
• storage-class enum tag var1,var2,……
varn;
Enumeration
• Example:
• enum escapes {bell=`\a', backspace=`\b', tab=`\t’,
newline=`\n', vtab=`\v', return=`\r'}
• main()
• {
• enum escapes e1;
• e1 = getch();
• if (e1 == newline)
• printf("newline");
• }
Interview Questions-43
ARTECH 2016
• #include<stdio.h> • Answer : -1, 0, 6, 7, 8, 9
• int main()
• {
• enum days {MON=-1,
TUE, WED=6, THU, FRI,
SAT};
• printf("%d, %d, %d, %d,
%d, %d\n", MON, TUE,
WED, THU, FRI, SAT);
• return 0;
• }
196
Interview Questions-44
CGI 2016
• #include <iostream> • Answer : If you were cat,
• enum cat { you would be 2
• temp = 7 • Explanation:
• };
• Explanation: The age will
• int main()
be divided by using
• {
compound assignment
• int age = 14;
operator and so it will
• age /= temp;
return the age of the cat
• printf("If you were cat, you
would be %d”,age ); according to your age.
• return 0;
• }
197
Interview Questions-45
ACCENTURE 2016
• #include <iostream> • Answer: Compiler Error
• int main() • Explanation :
• {
• enumartion variable ‘star’
• enum channel {star, sony,
zee}; appears two times in
• enum symbol {hash, star}; main() which causes the
• int i = 0; error. An enumaration
• for (i = star; i <= zee; i++) constant must be unique
{ within the scope.
• printf("%d ", i);
• }
• return 0;
• }
198
Interview Questions-46
AD3i 2015
• enum colors • Answer : 0..1..2
{BLACK,BLUE,GREEN}
• main() • Explanation :
• { • enum assigns numbers
• starting from 0, if not
• explicitly defined.
printf("%d..%d..%d",BLACK,BL
UE,GREEN);
•
• return(1);
• }
199
Typedef
• Example:
• typedef struct
• {
• int empno;
char empname[10];
• }employee;
employee emp1, emp2;
• No need to use struct keyword when
declaring structure variables.
Interview Questions-47
APTROID 2016
• Is the following code • Answer: No
legal? • Explanation:
• typedef struct a • The typename aType is
not known at the point of
• {
declaring the structure
• int x; (forward references are
• aType *b; not made for typedefs).
• }aType
202
Interview Questions-48
URJANET 2016
• Is the following code legal? • Answer: Yes
• typedef struct a • Explanation:
aType;
• The typename aType
• struct a is known at the point
• { of declaring the
• int x; structure, because it
• aType *b; is already
typedefined.
• };
203
Interview Questions-49
WIPRO 2015
• Is the following code legal? • Answer: No
• void main()
• Explanation:
• {
• When the declaration,
• typedef struct a aType;
typedef struct a
• aType someVariable;
aType;is encountered
• struct a
body of struct a is not
• {
known. This is known
• int x;
as ‘incomplete types’.
• aType *b;
• };
• }
204
Preprocessor Directories
• Preprocessing
– Occurs before a program is compiled
– Inclusion of other files
– Definition of symbolic constants and macros
– Conditional compilation of program code
– Conditional execution of preprocessor directives
• Format of preprocessor directives
– Lines begin with #
– Only whitespace characters before directives on a
line
The #include Preprocessor Directive
• #include
– Copy of a specified file included in place of the directive
#include <filename> -
• Searches standard library for file
• Use for standard library files
#include "filename"
• Use for user-defined files
• Used for
• Searches current directory, then standard library
– Loading header files (#include <iostream>)
– Programs with multiple source files to be compiled together
– Header file - has common declarations and definitions (classes,
structures, function prototypes)
• #include statement in each file
The #define Preprocessor Directive:
Symbolic Constants
• #define
– Preprocessor directive used to create symbolic constants
and macros.
• Symbolic constants
– When program compiled, all occurrences of symbolic
constant replaced with replacement text
• Format
#define identifier replacement-text
– Example: #define PI 3.14159
– everything to right of identifier replaces text
#define PI = 3.14159
• replaces "PI" with " = 3.14159", probably results in an error
– Cannot redefine symbolic constants with more #define
statements
The #define Preprocessor Directive:
Macros
• Macro
– Operation defined in #define
– Macro without arguments: treated like a symbolic
constant
– Macro with arguments: arguments substituted for
replacement text, macro expanded
– Performs a text substitution - no data type checking
Example:
#define CIRCLE_AREA( x ) ( (PI) * ( x ) * ( x ) )
area = CIRCLE_AREA( 4 );
is expanded to
area = ( 3.14159 * ( 4 ) * ( 4 ) );
The #define Preprocessor Directive:
Macros
• Use parenthesis
– Without them:
#define CIRCLE_AREA( x ) ((PI) * ( x ) * ( x ))
#define CIRCLE_AREA( x ) PI * x * x
area = CIRCLE_AREA( c + 2 );
becomes
area = 3.14159 * c + 2 * c + 2;
• Evaluates incorrectly
• Macor’s advantage is that avoiding function overhead
– Macro inserts code directly.
• Macro’s disadvantage is that its argument may be evaluated more than
once.
210
The #define Preprocessor Directive:
Macros
• Multiple arguments
#define RECTANGLE_AREA( x, y ) ( ( x ) * ( y ) )
rectArea = RECTANGLE_AREA( a + 4, b + 7 );
becomes
rectArea = ( ( a + 4 ) * ( b + 7 ) );
The #define Preprocessor Directive:
Macros
• #undef
– Undefines a symbolic constant or macro,
which can later be redefined
• #include<stdio.h>
• #define max 10+2
• int main() {
• int a;
• a = max * max;
• printf("%d",a);
• return 0;
• }
214
Preprocessor Example
• #include<stdio.h>
• #if -2
• int main(){
• printf("HELLO WORLD");
• return 0;
• }
• #else
• int main(){
• printf("errorandexception.blogspot.com");
• return 0;
• }
• #endif
215
Preprocessor Example
• #include<stdio.h>
• #define var 10
• int main(){
• #if var
• printf("Aditya Engineering College");
• #else
• printf("Aditya College of Engineering");
• #endif
• return 0;
• }
216
Preprocessor Example
• #include<stdio.h>
• #define ABC 25
• #define PQR "Exact Help“
• int main(){
• int num = 3;
• #ifdef ABC
• printf("%d",ABC * ABC);
• #else
• printf("%s",PQR);
• #endif
• return 0;
• }
217
Preprocessor Example
• #include<stdio.h>
• int main(){
•
• #ifdef __DATE__
• printf("%s",__DATE__);
• #else
• printf("First define the __DATE__");
• #endif
• return 0;
• }
218
Preprocessor Example
• #include<stdio.h>
• #define ABC 25
• #ifdef ABC
• #undef ABC
• #define ABC 50
• #else
• #define ABC 100
• #endif
• int main(){
• printf("%d",ABC);
• return 0;
• }
219
Command line Argument
224
Introduction to File
• Example:
• FILE *fp;
– fp = fopen(“name”, “mode”);
– fscanf(fp, "format string", variable list);
– fprintf(fp, "format string", variable list);
• fclose(fp);
• The fp is a file pointer
• The name is to represent filename
• The mode argument in the fopen() specifies the
purpose/positioning in opening the file
Files Mode
Character I/O File
233
Interview Questions-52
NTTDATA 2016
• What will happen if you execute • //test.txt
following program? • I Love T shape Engineering Course
• #include<stdio.h> • Answer: It will print NULL.
• Explanation: As we know \ has special
• int main(){ meaning in c programming. To store \
• char *str; in a string data type there
requirements of two forward slash i.e.
• FILE *fp; \\. In this case fopen function will
• return NULL value due to wrong URL.
fp=fopen("c:\tc\bin\test.txt","r"); • Right way to write that URL is:
c:\\tc\\bin\\test.txt
•
while(fgets(str,15,fp)!=NULL)
• printf("%s",str);
• fclose(fp);
• return 0;
• } 234
Interview Questions-53
CGI 2015
•
•
What will be output of following program?
#include<stdio.h>
• Answer: Who a
• int main(){ • Explanation: It will
• FILE *fp;
print only first five
• char *str;
• character of including
fp=fopen("c:\\tc\\bin\\world.txt","r"); blank space of file
• while(fgets(str,5,fp)!=NULL)
• puts(str);
word.txt
• fclose(fp);
• return 0;
• }
• //word .txt
• Who are you? 235
Dynamic Memory Allocation
• Malloc :
• malloc() is used to allocate memory space
in bytes for variables of any valid C data
type.
• Syntax :
• pointer= (data_type*)malloc(user_defined_size);
Example
• #include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int a,*ptr;
a=10;
ptr=(int*)malloc(a*sizeof(int));
ptr=a;
printf("%d",ptr);
free(ptr);
getch(); Output : 10
}
Calloc
• #include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int *ptr,a[6]={1,2,3,4,5,6};
int i;
ptr=(int*)calloc(a[6]*sizeof(int),2);
Example Contd.
• for(i=0;i<7;i++)
{
printf("\n %d",*ptr+a[i]); Output :
1
} 2
3
4
5
free(ptr); 6
getch(); 2293544
}
Random File Operations
246