You are on page 1of 245

C Language

Interview Training
TYPES OF OPERATORS

2
Interview Question-1
Softway 2015

What will be output of the following program?


#include<stdio.h>
int main()
{
int i=5,j;
j=++i+++i+++i;
printf("%d %d",i,j);
return 0;
}

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

• (1) Declaration statement.


(2) && or operator.
(3) Comma (,) operator etc.
• In the following expression:
• int a=++i + ++i + ++i;
• Here break point is due to declaration .It break after each
increment i.e. (initial value of i=5) after first increment
value 6 assign to variable i then in next increment will
occur and so on. So, a = 6 + 7 + 8;

25
Control Structure

26
Control Structure

• Control Structure are used to alter the


normal sequential flow of control. It
provides the ability to decide the order of
execution. The following are the selection
constructs available in C:
• “ if ” statement
• Conditional / Ternary operator statement (? :)
• “switch” statement
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

What will be the output of following program ?


#include <stdio.h>
int main()
{
int i=1;
while(i<=10 && 1++)
printf("Hello");
}

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

• What will be output of following c code?


#include<stdio.h>
int main(){
int i=2,j=2;
while(i+1?--i:j++)
printf("%d",i);
return 0;
}

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

• Output: Finite times


• Explanation:
• If we will increment the char variable c it
will increment as:
• 126,127,-128,-127,126 . . . . , 3, 2, 1, 0
• When variable c = 0 then loop will
terminate.

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

• C language uses 4 storage classes,


namely:
– Auto
– Static
– Extern
– register

61
Storage Class

• auto: This is the default storage class for


all the variables declared inside a function
or a block.
• Auto variables can be only accessed
within the block/function they have been
declared and not outside the block.

62
Storage Class

• extern: Extern storage class tells the variable is defined


elsewhere and not within the same block where it is
used.
• The value is assigned to it in a different block and this
can be overwritten/changed in a different block as well.
• A normal global variable can be made extern as well by
placing the ‘extern’ keyword before its
declaration/definition in any function/block.
• The main purpose of using extern variables is that they
can be accessed between two different files which are
part of a large program.

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

• register: This storage class declares register


variables which have the same functionality as
that of the auto variables.
• The only difference is that the compiler tries to
store these variables in the register of the
microprocessor if a free register is available.
• An important and interesting point to be noted
here is that we cannot obtain the address of a
register variable using pointers.

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

• After completing this session, you will be able to:


• Explain the concept of Array and memory
organization
• Write program using Single-dimensional arrays
• Write program using Multi-dimensional arrays
• Understand Strings
• Understand String and Character functions
Array

• Array is a derived data type which is used


to store similar data items in contiguous
memory locations under a single name.
• Need for an array
• Many applications require the processing
of multiple data items that have common
characteristics (e.g., set of numbers, set of
names).
Memory organization - Array
• The elements in an array are always
stored in consecutive memory locations. If
an array of 5 integers elements is created,
totally 10 contiguous bytes will be
allocated in memory.
Memory Organization -Array
• Address of an array element is calculated
as below:
• Address of ith location = base address
+ (size of the individual data element *
index i )
• Address of 0th element = 1000 + (2 * 0) =
1000
• Address of 1st element = 1000 + (2 * 1) =
1002 …
Array Declaration

• Arrays are declared with appropriate data


type and size. Arrays can be of single
dimension or of multi dimensions. Array
declaration reserves space in memory.
• General Form:
• datatype arrayname[size] ;
Array Declaration
• Example 7.1
• int x[5];
• Defines an integer array x of 5 integers, starting at x[0], and ending
at x[4].
• char str[16]="qwerty";
• Defines a character array, which is represents a string of maximum
of 16 characters.
• float sales_amt[10];
• Defines a floating point array sales_amt of 10 floating point
numbers, starting at sales_amt[0] and ending at sales_amt[9].
• int matrix[2][2];
• Defines a 2*2 matrix (totally 4 elements) of integers.
Array Accessing
• Accessing Array Elements
• The array elements are accessed by specifying the subscript / index.
• General Form:
• arrayname[index or subscript]
• Example 7.2
• x[0] to access the 1st element in array
• x[4] to access the 5th element in array
• str[2] to access the 3rd character in the string (character
array)
• sales_amt [8] to access the 9th sales amount in the
array
Array Initialization

• Array elements can be initialized during


declaration or can be initialized in the program.
• When arrays are initialized during declaration,
partial initialization is allowed.
• In partial initialization, the uninitialized array
elements are initialized to Zero or Null
depending on the data type of the array..
Two-dimensional array

• Two-dimensional arrays are defined in the


same way as one dimensional array,
except that a separate pair of square
brackets is required for second dimension.
• General Form:
• datatype arrayname [row ][column]
• Page
Program-3
ZENQ 2016
• A number is called happy if it leads to 1 after a sequence
of steps where in each step number is replaced by sum
of squares of its digit that is if we start with Happy
Number and keep replacing it with digits square sum, we
reach 1. Help our friends to solve this problem using C.
• Sample Input : 19
1^2 + 9^2 = 82 8^2 + 2^2 = 68 6^2 + 8^2 = 100 1^2 +
0^2 + 0^2 = 1.
20 = 2^2+0^2=4
Sample Output : 1 19 is a Happy Number
4 is a Sad Number(Not Happy Number).
77
Program - 4
OSMOSYS 2016
• Given the grades for each student in a Physics
class of students, store them in a list and print
the grades of any student(s) having the largest
and second largest grade.
• Sample Input
• 5
• 37.21 37.21 37.2 41 39
• Sample Output
• largest 41
• Second largest 39
78
Program - 5
THINK & LEARN 2015
• Implement a program to Merge all the arrays and sort in
ascending order.
• Sample Input
24
5847
15 32 87 65
• Sample Output
4 5 7 8 15 32 65 87

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

• In a library books are arranged one after the


other. One of the student return the book back
which he has taken for reference. Librarian
wants to insert the book at the particular
position. Help librarian to insert the book in
respective shelf.
• Sample Input : 9 2 1
• 10 15 14 12 11 9 7 3 2
• Sample Output
• 10 15 1 14 12 11 9 7 3 2
82
Program - 9
OSMOSYS 2016
• In a backery a pile of biscuits packets are arranged in a
shelf. Like Gooday-1, Parley -2, Britannia-3, ITC-4 and
so on…. . Customer came to the backery and purchased
the ITC biscuits. Help the shop man to rearrange and
display the remaining biscuits in the shelf.
• Sample Input
• 5
• 10 15 17 23 45
• 17
• Sample Output
• 10 15 23 45
83
Program - 10
ZENQ 2014

• Consider an array of n integers,


A=[a0,a1,.......an-1] , where all but one of the
integers occur in pairs. In other words, every
element in A occurs exactly twice except for one
unique element.
• Sample Input
• 3
112
• Sample Output
2
84
Day 2

Strings and Pointer

85
Strings

• Strings are sequence of characters


• String can be represented as a one-
dimensional array of characters.
• A character string is stored in an array of
character type, one ASCII character per
location.
• String should always have a NULL
character (‘\0’) at the end, to represent the
end of string.
86
Strings

• String constants can be assigned to


character array variables.
• String constants are always enclosed
within double quotes and character
constants are enclosed within single
quotes.
Example
• char c[4]={‘s’,’u’,’m’,’\0’);
87
Strings
• char str[16]="qwerty"; /*Creates a string. The
value at str[5] is the character ‘y’. The value
at str[6] is the null character. The values from
str[7] to str[15] are undefined.*/
• char name[5];
• char name[5] = “INDIA” /* Strings are
terminated by the null character, it is
preferred to allocate one extra space to store
null terminator */
88
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

• String can be read either character-by-character or as an


entire string (using %s format specifier). Array name
itself specifies the base address and %s is a format
specifier which will read a string until a white space
character is encountered.
• Example
• char name[20];
• int i=0;
• while((name[i] = getchar ()) != ‘\n’ )
• i++; 91
Strings

• scanf( “%s“ , name);


• printf(“%s” , name);
• Illegal operations on Strings
• C does not allow one array to be assigned to another,
thus statements of the following form are illegal”
• name = “GOOD”; Or name1 = name; -> assignment not
allowed
• name1 = name + “to c “ ->concatenation is not allowed
• if (name1 == name) ->two strings cannot be compared
with the ‘equal to’ operator
92
String Functions

• Strings are manipulated either via pointers or via special


routines available from the standard string library
string.h.

93
Char Function

94
Interview Question -1
DELOITEE 2015

• What is the output of the following code


segment?
char arr[20]="hello world";
printf("%d",sizeof(arr));

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

• abc(char a[]); • abc(char a[])


• main() • {
• { • a++;
• char a[100]; • printf("%c",*a);
• • a++;
a[0]='a';a[1]='b';a[2]='c';a[4]='d';
• printf("%c",*a);
• abc(a);
• }
• }

• 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

• A string is said to be complete if it contains


all the characters from a to z. Given a
string, check if it complete or not.
SAMPLE INPUT
3
Wyyga qwertyuioplkjhgfdsazxcvbnm ejuxggfsts
SAMPLE OUTPUT
NO
YES
NO
100
Program-3
WIPRO 2016
• In this problem the input will consist of a number of lines of English
text consisting of the letters of the English alphabet, the punctuation
marks ' (apostrophe), . (full stop), , (comma), ; (semicolon), : (colon)
and white space characters (blank, newline). Your task is print the
words in the text in lexicographic order (that is, dictionary order).
Each word should appear exactly once in your list. You can ignore
the case (for instance, "The" and "the" are to be treated as the same
word.) There should be no uppercase letters in the output.
• Sample input 2
• This is a sample piece of text to illustrate this problem.
• Sample output 10

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

• Tech Mahindra wanted to automate the


payslip. In the pay slip he want display the
net pay in words. Help the accountant to
convert number into words.
• Sample input
• 45800
• Sample output
• Fourty Five Thousand Eight Hundred only
103
Program - 6
DEIVAM 2016

• Anirudh has a String s consisting of


lowercase alphabetic letter. He has to
remove the duplicate characters in a
string.
Sample Input
i love india
Sample output
love nda

104
Program-7
GGK TECH 2016

• Given a string, find the Second non-


repeating character in it.
Sample Input
StringofString
Sample Output
f

105
Need for user – define Function

• The Program become too large and


complex.
• The user cannot go through at a glance.
• The task of testing and maintenance
becomes difficult.

Precision Infomatic (M) Pvt. Ltd. 106


What is a Function?

• Function is a set of instruction used to


perform specified task.
• Provides Modularity to the software.
• Can divide complex task into manageable
task.

. 107
How Function Works?

• When the Function is called, it takes some


data from the calling function and return
back some value to the called function.
• Whenever the function is called control
passes to the called function and working
of the calling function is temporarily
stopped .
• Execution of called function is completed
the control return backs to calling function.
. 108
Function Example
• # include <stdio.h>
main()
{
message();
Printf(“Main Message”);
}
message()
{
printf(“Function Message\n”);
}

Output :
Function Message
Main Message

109
Function Syntax

• datatype function_name(parameter list)


parameter declaration;
{
local variables declaration;
………….
body of the function;
…………...
return(expression);
}

110
Function Prototype

• While defining user – defined function it is


must to declare its prototype.
• Prototype keep the compiler to check the
return type and arguments types of the
function.
• Function prototype declaration consists of
the function’s return tupe name and
arguments list.

111
Types of Function Prototype

• Function with no argument and no return


value.
• Function with no argument with return
value.
• Function with arguments no return value.
• Function with arguments with return
value.

112
Parameter Passing Methods

• There are two ways that the parameters


can be passed to a function. They are:

– 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

#define prod(a,b) a*b


main()
{
int x=3,y=4;
printf("%d",prod(x+2,y-1));
}

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

Ans Here value is 7


120
Pointers
Introduction to Pointer

• Pointers are variables that contain the memory


address of another variable.
• Variables can contain the value and pointers can
contain the address of variable which in turn
contains the value.
• Variable directly references the value and
Pointer indirectly references the value.
• Referencing a value through a pointer is called
Indirection.
Introduction to pointer
• Memory is allocated for the variable
according to the data type specified.
• Int a = 5;
• 2 bytes of memory will be allocated for
variable ‘a’.
• printf(“Value = %d”, a); a
• prints the value 5. 1000
• printf(“Address of a = %u”, &a);
• prints the address 1000
Pointer Operator

• &-address operator: Unary operator that


returns the address of its operand.
• *-Indirection or de-referencing operator: It
returns the value of the variable to which
its operand points.
Declaration and Initialization

• A pointer is declared like a normal


variable, but with an asterisk before the
variable name.
• The type-specifiers determine the kind of
variable the pointer points to.
• Syntax:
• data-type *pointer-name;
Declaration

• Example:
int x, *px;
px = &x;
x = 5;
Declaration

• For the example in the preceding slide:printf(“ x


= %d “ , x); /*prints 5*/
• printf(”address of x = %d “ , &x); /*prints 1000*/
• printf(“address pointed by pointer = %u”, px);
/*prints 1000*/
• printf(“address of the pointer = %u”, &px);
/*prints 3000*/
• printf(“content pointed by pointer = %d”, *px);
/*prints 5*/
Initialization

• Pointer variables should be initialized to 0,


NULL, or an address.
• No other constant can be used for
initializing a pointer variable.
• Pointer variable of a particular data type
can only hold the address of the variable
of same data type.
Initialization
• Example:Valid and invalid pointer
assignments:
Pointer Arithmetic

• A pointer variable can be assigned the address of an


ordinary variable or it can be a null pointer.
• A pointer variable can be assigned the value of another
pointer variable.
• An integer quantity can be added to or subtracted from a
pointer variable.
• One pointer can be subtracted from another pointer
variable provided both are pointing to same array.
• Two pointer variables can be compared.
Pointer Arithmetic

• Pointer addition or subtraction is done in


accordance with the associated data type:
• int ->adds 2 for every increment
• Char-> adds 1 for every increment
• Float-> adds 4 for every increment
• long int-> adds 4 for every increment
Pointer Arithmetic

• 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

• Two pointer variables can not be added.

• Pointer variable can not be multiplied or


divided by a constant
Pointer Arrays

• Array addressing is in the form of relative addressing.


• Compiler treats the subscript as a relative offset from the
beginning of the array.
• Pointer addressing is in the form of absolute addressing.
• Exact location of the array elements can be accessed
directly by assigning the starting location of the array to
the pointer variable.
• C treats the name of the array as if it were a pointer to
the first element.
• Thus, if v is an array,*v is the same thing as
v[0]and*(v+0).
Pointer Array Initialization

• Conventional array is declared and pointer


is made to point to the starting location of
the array.
• Syntax:
• ptr_vble = &array_name [starting index];
• OR
• ptr_vble = array_name;
Pointer Array Initialization

• 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

• Character pointer is a pointer, which can hold the


address of a character variable:
• char name[30] = {“C program”};
• Declare a character pointer as follows:
• char *p = NULL;
• Assign the address of the array to pointer:
• p = name;
• String can be represented by either as one-dimensional
character array or a character pointer:
• char *p = “string”;
Function Pointers
• Pointers can be passed to a function as arguments and
a function can also return a pointer back to the calling
program.
• It is possible to pass a portion of an array, rather than an
entire array, to a function using pointers.
• Function will also have a memory address like other
variables.
• A pointer can be used to point to the starting location of
a function.
• Syntax:
• return-type (* fn_ptr_name)(arg list..)
Function Pointer

• Example
• void add(int x, int y)
• {
• printf(“Value = %d”, x + y);
• }
– Pointer to this function should be declared as:

• void (*p)(int x, int y);


– Where p is a pointer, which can point to a function, which has two integer arguments and
returning an integer value.

• 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

• p=&a[2][2][2] you declare only two 2D arrays,


but you are trying to access the third 2D(which
you are not declared) it will print garbage values.
*q=***a starting address of a is assigned integer
pointer. Now q is pointing to starting address of
a. If you print *q, it will print first element of 3D
array.

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()
• {

• static char names[5][20]={"pascal","ada","cobol","fortran","perl"};

• 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?

• The structure is a derived data type used to represent


heterogeneous data.
• A structure is an aggregation of components that can be
treated as a single variable. The components are called
members.
• For example, an employee is represented with the
following attributes:employee code (alphanumeric)
• employee name (string)
• department code (integer)
• salary (float)
Structure Declaration

• Structures are defined via a template and


declared with a tag which helps to avoid
repeating the definition.
• structkeyword is used to define structures.
• struct tag_name
• {
– type variable-name, variable-name,........;
– type variable-name, variable-name,........;
– type variable-name, variable-name,........;
• :
• :
– type variable-name, variable-name,........;
• };
Structure- Declaration

• Structure-variables can be declared


anywhere in the program.
• Syntax:
• struct tag_name new-structure-variable;
• Example:
• struct employee
• {
• int code;
• char name[20];
• int dept_code;
• float salary;
• };
• struct employee emp1, emp2;
Structure Declaration

• Structure definition and declaration of


structure variables can be combined
together.
• Example:
• struct employee
• {
• int code;
• char name[20];
• int dept_code;
• float salary;
• } emp1, emp2;
• Note: Tag name is optional in this case.
Structure Initialization

• Structure variables can be initialized at the


time of declaration
• If the structure variable is declared before
the main function, the member variables
are automatically initialized to zero or Null.
• If it is partially initialized, then uninitialized
members will be assigned zero or Null
character.
Accessing the Members

• Members of the structure can be accessed


by using the member access operator
“.”(dot)
• Syntax:
• struct_vble.member-field-name
• Example:
• emp1.code
• emp1.name
• emp1.dept_code
• emp1.salary
Operations on Structures

• Each member of a structure can be


assigned to the corresponding member of
another structure.
• Structure can also be assigned to another
Structure provided they have the same
composition.
• sizeof()operator can be used to find the
size of the structure.
Nested Structure

• Structures can contain members that


themselves are structures.
• struct date
{
int day;
int month;
int year;
};
Nested Structure

• struct employee
{
int code;
char name [20];
struct date doj ;
int dept_code;
float salary;
}emp1,emp2;
Structures and arrays

• The members of structures can be arrays


and the structure can also be an array
• Example: The following example is a array
of structures:
• struct stud
• {
• int rollnum;
• char name[20];
• int semester;
• int avg;
• };
• struct stud student[50];
Structures and Arrays
• Accessing values:
student[1].rollnum, student[1].name,
student[1].semester, student[1].avg

Write a program to store 3 records in one


structures.
Arrays with Structures
• Example:
• struct student-mark
• {
• int rollnumber;
• char name[15];
• int sub_marks[5];
• } student;
• Accessing values:

• student.sub_marks[0],
• student.sub_mark[1], student.name
Self Referential Structure

• A structure containing a member which is a


pointer to the same structure type is called self-
referential structures.
• It is used to build various kinds of linked data
structures.
• Example:
• struct employee
• {
• char name[20];
• char gender;
• float salary;
• struct employee *empptr;
• };
Structures and Function

• Structures can be passed to a function


using call by value and call by address
(reference) methods.
• By default the structure is passed using
call by value approach to a function.
• For calling by reference, structure should
be a array of structures or structure
variable should be pointer variable.
Structures and Function
• Example: Passing structures to a function (call by value):
• struct emp
• {
• int empno;
• char empname[10];
• };
• void main( )
• {
void display(struct emp);
struct emp emp1 = { 101 , “AAAA”} ;
• display(emp1);
• }
void display(struct emp emp2)
• {
printf(“ %d “ , emp2.empno);
printf(“ %s “ , emp2.empname);
• }
Structures and Function
• Example: Passing structures to a function (call by reference):
• struct emp
• {
• int empno;
• char empname[10];
• };
• void main( )
• {
void change(struct emp *);
struct emp emp1 = { 101 , “AAAA”} ;
• change(&emp1);
printf(“%d” , emp1->empno); /*prints 102*/
• }
void change (struct emp *emp2)
• {
• emp2->empno =102;
• }
Interview Question-32
CAPGEMINI 2016
• Is the following code • Answer: Yes.
legal? • Explanation:
• *b is a pointer to type struct a
• struct a and so is legal. The compiler
• { knows, the size of the pointer
to a structure even before the
• int x; size of the structure
• is determined(as you know the
• struct a, *b; pointer to any type is of same
• } size). This type of structures is
known as ‘self-referencing’
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

• Union, like a structure, is a derived data


type
• Unions follow the same syntax as
structures but the only difference is that
members of the union share storage.
• Union differs from structure only in storage
and in initialization.
Union Declearation

• 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

• Union can be initialized only with a value


for the first union member.
• All other member can not be initialized.
• Example:
• union item
• {
• int m;
• float x;
• char c;
• };
union item product = {100};
• 100 will be assigned to union member variable m.
• Write a program to find the size of union and number of bytes reserved for it.
Interview Question-40
CYIENT 2016


#include <stdio.h>
union { • Answer : Compiler


struct {
unsigned char c1:3;
error
• unsigned char c2:3;
• unsigned char c3:2;
• } s;
• unsigned char c;
• } u;

• 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

• Enumeration is a derived data type, similar to


structures or a union.
• Its members are constants that are written as
identifiers, though they have signed integer
values.
• These constants represent values that can be
assigned to corresponding enumeration
variables.
• Enum keyword is used to declare enumerated
variables.
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

• The typedef allows users to define new data


types that are equivalent to existing data types.
• It gives new names to existing data types.
• Syntax:
• typedef datatype new-type;
• Example:
• typedef int numbers;
• Here numbers is the new name given to integer data
type and it can be used to declare integer variables. For
example:
• numbers n1, n2;
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.

double circleArea ( double x )


{ return 3.1415926 * x * x ;
}
• #include <stdio.h>
• #define message_for(a, b) \
• printf(#a " and " #b ": We love you!\n")
• int main(void) {
• message_for(Carole, Debra);
• return 0;
• }

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

• #define getchar() getc ( stdin )


Preprocessor Example
• #include <stdio.h>
• #define PI 3.1415
• int main(){
• int radius;
• float area;
• printf("Enter the radius: ");
• scanf("%d",&radius);
• area=PI*radius*radius;
• printf("Area=%.2f",area);
• return 0;
• }
213
Preprocessor Example

• #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

• A C program is executed by calling its


main()function.
• The main()function is called with one
integer argument indicating how many
words are in the command line and
another argument that is a character array
of pointers containing the command line
words.
Command Line Arguments

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


• {
• :
• }
• argc provides a count of the number of
command line arguments.
• argv is an array of character pointer of undefined
size that can be thought of as an array of pointer
to strings, which are command line strings.
Example

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


• {
• int i;
• printf(“\n Total No. of Arguments =%d”,argc);
• for( i = 0; i < argc; i++)
• printf(“\nArg. No. %d = %s”,i , argv[i]);
• }
Command Line Arguments

• When the following command is given in the


command prompt, for the above program:
• C:\tc\bin> sandhra c cpp ds
• Where:sandhra is program name
• c cpp ds arguments
• The following result is displayed:
• Total No. of Arguments = 4
• Arg. No. 0 = sandhra
• Arg. No. 1 = c
• Arg. No. 2 = cpp
• Arg. No. 3 = ds
Interview Questions-50
COGNIZANT 2016
• main(int argc, char **argv) • Answer: Compiler error.
• {
• Explanation:
• printf("enter the character");
• getchar(); • argv[1] & argv[2] are
• sum(argv[1],argv[2]); strings. They are
• } passed to the function
• sum(num1,num2)
sum without
• int num1,num2;
• {
converting it to integer
• return num1+num2; values.
• }

224
Introduction to File

• A file is a place on the disk where a group


of related data is stored.
• When a large volume of data is involved:
• The input data can be stored on disks
• The program may access the data from
disks for processing
• The results may also be stored on disks
File Operations

• Basic File operations are:


• Opening a File
• Reading from and/or writing into a File
• Closing the File
• In C, FILEis a structure that holds the
description of a file and is defined in
stdio.h
File Operations

• 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

• Using character I/O, one character (byte) can be written


to or read from a file at a time.
• Writing in to a file:To write into a file, the file must be
opened in w mode
• The function putc() is used to write a byte to a file:
• putc(ch, fptr);
• Where:
• ch - character variable
• fptr - file pointer
Character Input

• Reading from a file:The function getc is


used to read a byte from a file:
• ch=getc(fptr);
Program to write into a File
• Example: Program to create a text file (character file):
• main()
• {
• FILE *fp;
• char c;
• if ((fp=fopen(“sample.dat”,”w”)) ==NULL)
• {
• while ((c=getchar()) != EOF)
• putc(c,fp);
• fclose(fp);
• }
• else
• printf(“Error in opening a file”);
• }
Program to read the data from file

• Example: Program to read a character data from file:


• main()
• {
• FILE *fp;
• char c;
• if ((fp=fopen("sample1.doc","r")) !=NULL)
• {
• while ((c=getc(fp)) != EOF)
• putchar(c);
• fclose(fp);
• }
• else
• printf("Error in opening a file");
• }
Interview Questions-51
CGI 2016
• #include<stdio.h> • Answer:contents of zzz.c
followed by an infinite loop
• main()
• { • Explanation:
• FILE *ptr; • The condition is
• char i; checked against EOF,
• ptr=fopen("zzz.c","r"); it should be checked
• while((i=fgetch(ptr))!=EO against NULL
F)
• printf("%c",i);
• }

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

• calloc() is sued to allocate multiple blocks


of memory dynamically during the
execution (run-time) of the program.
• Syntax :
• pointer=(data_type*)calloc(no of memory
blocks, size of each block in bytes);
Example

• #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

• For some applications, it may be


necessary to access any part of the file
directly.
• This can be achieved by using the
functions fseek(), ftell(), and rewind().
Fseek

• Sets the file position to the given offset.


• Syntax:
• fseek( fptr, offset, from_where)
• The argument offsetsignifies the number
of bytes to seek from the given
‘from_where’position.
• On success zero is returned. On error a
nonzero value is returned.
Ftell

• This function takes a file pointer and returns a long


integer, which corresponds to the current file pointer
position.
• If it is a binary stream, then the value is the number of
bytes from the beginning of the file.
• If it is a text stream, then the value is the current file
pointer position.
• On success the current file position is returned.
• On error, the value -1L is returned and error number is
set.
• Syntax:
• n = ftell(fptr);
Rewind

• rewind():Sets the file position to the


beginning of the file.
• The error and end-of-file indicators are
reset
• Syntax:
• rewind(fptr);
Interview Code-54
DEIVAM 2015
• #include<stdio.h> • Answer:
• Compiler Error: We cannot store address of
• #include<stdlib.h> allocated memory in a
• Explanation:
• int main() • We should store the address in a[i]
• {
• int *a[3];
• a = (int*)
malloc(sizeof(int)*3);
• free(a);
• return 0;
• }

246

You might also like