0% found this document useful (2 votes)
4K views

FAQs in C Language

The document discusses data types in C language. It describes basic data types like integer and floating point types. It provides the storage size and value ranges of standard integer and floating point types. It also discusses user defined data types like typedef and enum. The document ends with multiple choice questions related to data types in C.

Uploaded by

Shrinivas A B
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (2 votes)
4K views

FAQs in C Language

The document discusses data types in C language. It describes basic data types like integer and floating point types. It provides the storage size and value ranges of standard integer and floating point types. It also discusses user defined data types like typedef and enum. The document ends with multiple choice questions related to data types in C.

Uploaded by

Shrinivas A B
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 256

FAQ in C Language - Prepared by Ms.P.

Edreena

CHAPTER 1

DATATYPES

Data types refer to an extensive system used for declaring variables or functions of
different types. The type of a variable determines how much space it occupies in storage and
how the bit pattern stored is interpreted.
The types in C can be classified as follows:
1. Basic Types:
They are arithmetic types and consists of the two types: (a) integer types and
(b) floating-point types.
2. Enumerated types:
They are again arithmetic types and they are used to define variables that can
only be assigned certain discrete integer values throughout the program.
3. The type void:
The type specifier void indicates that no value is available.
4. Derived types:
They include
(a) Pointer types,
(b) Array types,
(c) Structure types,
(d) Union types and
(e) Function types.
Integer Types
Following table gives you details about standard integer types with its storage sizes and value
ranges:
Storage
Type Value range
size

char 1 byte -128 to 127 or 0 to 255

unsigned char 1 byte 0 to 255

signed char 1 byte -128 to 127

int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647


PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
1
FAQ in C Language - Prepared by Ms.P.Edreena

unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

short 2 bytes -32,768 to 32,767

unsigned short 2 bytes 0 to 65,535

long 4 bytes -2,147,483,648 to 2,147,483,647

unsigned long 4 bytes 0 to 4,294,967,295

Floating-Point Types
Following table gives you details about standard floating-point types with storage sizes and
value ranges and their precision:
Type Storage size Value range Precision

float 4 byte 1.2E-38 to 3.4E+38 6 decimal places

double 8 byte 2.3E-308 to 1.7E+308 15 decimal places

long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

User Defined Datatypes

1.typedef

typedef is used to give a new name to an existing datatype.

Syntax:

typedef type new-name;

2. enum

An enumerated type declares an optional type name and a set of zero or more
identifiers that can be used as values of the type. Each enumerator is a constant whose type is
the enumeration.
To create an enumeration requires the use of the keyword enum. The general form of
an enumeration type is:
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
2
FAQ in C Language - Prepared by Ms.P.Edreena

Syntax:

enum enum-name { list of names } var-list;

MULTIPLE CHOICE QUESTIONS:

1. The real constant in C can be expressed in which of the following forms:


A) Fraction form only
B) Exponential form only
C) ASCII form only
D) Both fractional and exponential forms.
Answer: D

2. A character variable can at a time store


A) 1 character
B) 8 characters
C) 254 characters
D) None of the above
Answer: A

3. The statement char ch= ‘Z’ would store in ch


A) The character Z
B) ASCII value of Z
C) Z along with the single inverted commas
D) Both a & b
Answer: B

4. Which of the following is not a character constant


A) ’Thank you’
B) ‘Enter values of P,N,R’
C) ’23.56E-03’
D) All the above
Answer: All the above
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
3
FAQ in C Language - Prepared by Ms.P.Edreena

5. The maximum value that an integer constant can have is


A) -32767
B) 32767
C) 1.7014e+38
D) -1.0714e+38
Answer: B

6. If a is an integer variable a= 5/2; will return a value


A) 2.5
B) 3
C) 2
D) 0
Answer: C

7. An integer constant in C must have


A) Atleast one digit
B) Atleast one decimal point
C) A comma along with digits
D) Digits separated by commas
Answer: A

8. What will be the value of d (assume d to be float) after the operation? d=2/7.0
A) 0
B) 0.2857
C) Cannot be determined
D) None of the above
Answer: B

9. What will be the output of the following program


#include <stdio.h>
void main()
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
4
FAQ in C Language - Prepared by Ms.P.Edreena

{
int i;
for(i=0; i<=50000 ; i++)
printf(“ \n %d”, i);
}

Answer: The program gets struck in a infinite loop.

10. What will be the output of the following program


#include <stdio.h>
void main()
{
float a=13.5;
double b=13.5;
printf(“\n %f %lf”,a,b);
}

Answer: 13.500000 , 13.500000

11. What will be output when you will execute following c code?
#include<stdio.h>
int main()
{
printf("%d\t",sizeof(6.5));
printf("%d\t",sizeof(90000));
printf("%d",sizeof('A'));
return 0;
}
Choose all that apply:
A) 421
B) 821
C) 441
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
5
FAQ in C Language - Prepared by Ms.P.Edreena

D) 841
E) 842
Answer: E
Explanation:
By default data type of numeric constants is:
6.5 : double 90000: long int ‘A’: char
In C size of data type varies from compiler to compiler.
In TURBO C 3.0 (16 bit compilers) size of:
double is 8 byte
Long int is 4 byte
Character constant is 2 byte (size of char data type is one byte)

12. Consider on following declaring of enum.


(i) enum cricket {Gambhir,Smith,Sehwag}c;
(ii) enum cricket {Gambhir,Smith,Sehwag};
(iii) enum {Gambhir,Smith=-5,Sehwag}c;
(iv) enum c {Gambhir,Smith,Sehwag};
Choose correct one:
A)Only (i) is correct declaration
B) Only (i) and (ii) is correct declaration
C) Only (i) and (iii) are correct declaration
D) Only (i),(ii) and are correct declaration
E) All four are correct declaration
Answer: E

13. What will be output when you will execute following c code?
#include<stdio.h>
int main()
{
signed x;
unsigned y;
x = 10 +- 10u + 10u +- 10;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
6
FAQ in C Language - Prepared by Ms.P.Edreena

y = x;
if(x==y)
printf("%d %d",x,y);
else if(x!=y)
printf("%u %u",x,y);
return 0;
}
Choose all that apply:
A) 00
B) 65536 -10
C) 0 65536
D) 65536 0
E) Compilation error
Answer: A

14. What will be output when you will execute following c code?
#include<stdio.h>
int main(){
double num=5.2;
int var=5;
printf("%d\t",sizeof(!num));
printf("%d\t",sizeof(var=15/2));
printf("%d",var);
return 0;
}
Choose all that apply:
A) 427
B) 445
C) 225
D) 247
Answer: C
Explanation:
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
7
FAQ in C Language - Prepared by Ms.P.Edreena

sizeof(Expr) operator always returns the an integer value which represents the size of
the final value of the expression expr.
Consider on the following expression:
!num
=!5.2
=0
0 is int type integer constant and it size is 2 by in TURBO C 3.0 Consider on the
following expression:
var = 15/2
=> var = 7
=> 7
7 is int type integer constant.
Any expression which is evaluated inside the sizeof operator its scope always will be
within the sizeof operator. So value of variable var will remain 5 in the printf statement.

15. What will be output when you will execute following c code?
#include<stdio.h>
int main()
{
const int *p;
int a=10;
p=&a;
printf("%d",*p);
return 0;
}
Choose all that apply:
A) 0
B) 10
C) Garbage value
D) Error: Cannot modify const object
Answer: B

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


8
FAQ in C Language - Prepared by Ms.P.Edreena

16. Consider on following declaration:


(i) short i=10;
(ii) static i=10;
(iii) unsigned i=10;
(iv) const i=10;
Choose correct one:
A) Only (iv) is incorrect
B) Only (ii) and (iv) are incorrect
C) Only (ii),(iii) and (iv) are correct
D) All are correct declaration
Answer: D

17. What will be output when you will execute following c code?
#include<stdio.h>
int main(){
int a= sizeof(signed) +sizeof(unsigned);
int b=sizeof(const)+sizeof(volatile);
printf("%d",a+++b);
return 0;
}
Choose all that apply:
A) 10
B) 9
C) 8
D) Error: Cannot find size of modifiers
Answer: C

18. Which of the following is integral data type?


A) void
B) char
C) float
D) None of these
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
9
FAQ in C Language - Prepared by Ms.P.Edreena

Answer: B

19. What will be output when you will execute following c code?
#include<stdio.h>
int main()
{
volatile int a=11;
printf("%d",a);
return 0;
}
Choose all that apply:
A) 11
B) Garbage
C) We cannot predict
D) Compilation error
Answer: C

20. What is the range of signed int data type in that compiler in which size of int is two byte?
A) -255 to 255
B) -32767 to 32767
C) -32768 to 32768
D) -32768 to 32767
Answer: D

21. What will be output when you will execute following c code?
#include<stdio.h>
const enum Alpha{
X,
Y=5,
Z
}p=10;
int main()
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
10
FAQ in C Language - Prepared by Ms.P.Edreena

{
enum Alpha a,b;
a= X;
b= Z;
printf("%d",a+b-p);
return 0;
}
Choose all that apply:
A) -4
B) -5
C) 10
D) 11
Answer: A
Explanation:
Default value of enum constant X is zero and
Z=Y+1=5+1=6
So, a + b – p
=0 + 6 -10 = -4

22. What will be output when you will execute following c code?
#include<stdio.h>
int main(){
char a=250;
int expr;
expr= a+ !a + ~a + ++a;
printf("%d",expr);
return 0;
}
Choose all that apply:
A) 249
B) 250
C) 0
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
11
FAQ in C Language - Prepared by Ms.P.Edreena

D) -6
Answer: D

23. Consider on order of modifiers in following declaration:


(i)char volatile register unsigned c;
(ii)volatile register unsigned char c;
(iii)register volatile unsigned char c;
(iv)unsigned char volatile register c;
Choose correct one:
A) Only (ii) is correct declaration
B) Only (i) is correction declaration
C) All are incorrect
D) All are correct and same
Answer: D

24. What will be output when you will execute following c code?
#include<stdio.h>
int main()
{
int a=-5;
unsigned int b=-5u;
if(a==b)
printf("Avatar");
else
printf("Alien");
return 0;
}
Choose all that apply:
A) Avatar
B) Alien
C) Run time error
D) Error: Illegal assignment
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
12
FAQ in C Language - Prepared by Ms.P.Edreena

Answer: A
Explanation:
int a=-5;
unsigned int b=-5u;
Constant -5u will convert into unsigned int. Its corresponding unsigned int value will
be :
65536 – 5 + 1= 65532
So, b = 65532
In any binary operation of dissimilar data type for example: a == b.Lower data type
operand always automatically type casted into the operand of higher data type before
performing the operation and result will be higher data type.
In c signed int is higher data type than unsigned int. So variable b will automatically
typecast into signed int. So corresponding signed value of 65532 is -5. Hence, a==b.

25. Which of the following is not derived data type in c?


A) Function
B) Pointer
C) Enumeration
D) Array
E) All are derived data type
Answer: C

26. What will be output when you will execute following c code?
#include<stdio.h>
enum A{
x,y=5,
enum B{
p=10,q
}varp;
}varx;
int main(){
printf("%d %d",x,varp.q);
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
13
FAQ in C Language - Prepared by Ms.P.Edreena

return 0;
}
Choose all that apply:
A) 0 11
B) 5 10
C) 4 11
D) 0 10
E) Compilation error
Answer: E

27. Consider on following declaration in c:


(i)short const register i=10;
(ii)static volatile const int i=10;
(iii)unsigned auto long register i=10;
(iv)signed extern float i=10.0;
Choose correct one:
A) Only (iv)is correct
B) Only (ii) and (iv) is correct
C) Only (i) and (ii) is correct
D) Only (iii) correct
Answer: C

28. Comment on the output of this C code?


#include <stdio.h>
int main()
{
int a[5] = {1, 2, 3, 4, 5};
int i;
for (i = 0; i < 5; i++)
if ((char)a[i] == '5')
printf("%d\n", a[i]);
else
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
14
FAQ in C Language - Prepared by Ms.P.Edreena

printf("FAIL\n");
}
A) The compiler will flag an error
B) Program will compile and print the output 5
C) Program will compile and print the ASCII value of 5
D) Program will compile and print FAIL for 5 times
Answer: D
Explanation:The ASCII value of 5 is 53, the char type-casted integral value 5 is 5 only.

29. The format identifier ‘%i’ is also used for _____ data type?
A) char
B) int
C) float
D) double
Answer: B

30. Which data type is most suitable for storing a number 65000 in a 32-bit system?
A) short
B) int
C) long
D) double
Answer: A

31. Which of the following is a User-defined data type?


A) typedef int Boolean;
B) typedef enum {Mon, Tue, Wed, Thu, Fri} Workdays;
C) struct {char name[10], int age};
D) all of the mentioned
Answer: D

32. What is the size of an int data type?


A) 4 Bytes
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
15
FAQ in C Language - Prepared by Ms.P.Edreena

B) 8 Bytes
C) Depends on the system/compiler
D) Cannot be determined
Answer: C

33. What is the output of this C code?


#include <stdio.h>
int main()
{
char chr;
chr = 128;
printf("%d\n", chr);
return 0;
}
A) 128
B) -128
C) Depends on the compiler
D) None of the mentioned
Answer: B

34. What is short int in C programming?


A) Basic datatype of C
B) Qualifier
C) short is the qualifier and int is the basic datatype
D) All of the mentioned
Answer: C

35. What is the output of this C code?


#include <stdio.h>
int main()
{
enum {ORANGE = 5, MANGO, BANANA = 4, PEACH};
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
16
FAQ in C Language - Prepared by Ms.P.Edreena

printf("PEACH = %d\n", PEACH);


}
A) PEACH = 3
B) PEACH = 4
C) PEACH = 5
D) PEACH = 6
Answer: C

36. What is the output of this C code?


#include <stdio.h>
#define a 10
int main()
{
const int a = 5;
printf("a = %d\n", a);
return 0;
}
A) a = 5
B) a = 10
C) Compilation error
D) Runtime error
Answer: C

37. What is the output of this C code?


#include <stdio.h>
int main()
{
int var = 010;
printf("%d", var);
}
A) 2
B) 8
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
17
FAQ in C Language - Prepared by Ms.P.Edreena

C) 9
D) 10
Answer: B
Explanation:010 is octal representation of 8.

38. What is the output of this C code?


#include <stdio.h>
#define MAX 2
enum bird {SPARROW = MAX + 1, PARROT = SPARROW + MAX};
int main()
{
enum bird b = PARROT;
printf("%d\n", b);
return 0;
}
A) Compilation error
B) 5
C) Undefined value
D) 2
Answer: B

39. enum types are processed by


A) Compiler
B) Preprocessor
C) Linker
D) Assembler
Answer: A

40. What is the output of this C code?


#include <stdio.h>
int main()
{
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
18
FAQ in C Language - Prepared by Ms.P.Edreena

const int p;
p = 4;
printf("p is %d", p);
return 0;
}
A) p is 4
B) Compile time error
C) Run time error
D) p is followed by a garbage value
Answer: B

41. What is the output of the following program?


int x= 0x65;
main()
{
char x;
printf("%d\n",x)
}
A) Compilation error
B) 'A'
C) 65
D) Unidentified
Answer: C

42. What can be said of the following program?


void main()
{
enum Months {JAN =1,FEB,MAR,APR};
Months X = JAN;
if(X==1)
{
printf("Jan is the first month");
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
19
FAQ in C Language - Prepared by Ms.P.Edreena

}
}
A) Does not print anything
B) Prints : Jan is the first month
C) Generates compilation error
D) Results in runtime error
Answer: B

43. What is the output of the following program?


enum colors {BLACK,BLUE,GREEN}
main()
{
printf("%d..%d..%d",BLACK,BLUE,GREEN);
return(1);
}
Answer: 0..1..2
44. Given the following statement enum day = { jan = 1 ,feb=4, april, may} .
What is the value of may?
A) 4
B) 5
C) 6
D) 11
Answer: C

45. What is the output of the following program?


void main()
{
int d=5;
printf("%f",d);
}
Answer: Undefined

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


20
FAQ in C Language - Prepared by Ms.P.Edreena

CHAPTER 2

STORAGE CLASSES

In C language, each variable has a storage class which decides scope, visibility and lifetime
of that variable. The following storage classes are most oftenly used in C programming,

1. Automatic variables (auto)


2. External variables (extern)

3. Static variables (static)

4. Register variables (register)

auto - Storage Class

A variable declared inside a function without any storage class specification, is by default
an automatic variable. They are created when a function is called and are
destroyed automatically when the function exits. Automatic variables can also be called
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
21
FAQ in C Language - Prepared by Ms.P.Edreena

local variables because they are local to a function. By default they are assigned garbage
value by the compiler.

{
int Count;
auto int Month;
}
The example above defines two variables with the same storage class. auto can only be used
within functions, i.e. local variables.

register - Storage Class


register is used to define local variables that should be stored in a register instead of
RAM. This means that the variable has a maximum size equal to the register size
(usually one word) and can’t have the unary '&' operator applied to it (as it does not
have a memory location).
{
register int Miles;
}
Register should only be used for variables that require quick access - such as counters. It
should also be noted that defining 'register' goes not mean that the variable will be stored in a
register. It means that it MIGHT be stored in a register - depending on hardware and
implementation restrictions.

static - Storage Class


static is the default storage class for global variables. The two variables below (count
and road) both have a static storage class.
static int Count;
int Road;
{
printf("%d\n", Road);
}

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


22
FAQ in C Language - Prepared by Ms.P.Edreena

static can also be defined within a function. If this is done the variable is initialised at run
time but is not reinitialized when the function is called. This inside a function static variable
retains its value during various calls.

extern - Storage Class


extern is used to give a reference of a global variable that is visible to ALL the
program files. When you use 'extern' the variable cannot be initialized as all it does is point
the variable name at a storage location that has been previously defined.
When you have multiple files and you define a global variable or function which will
be used in other files also, then extern will be used in another file to give reference of defined
variable or function. Just for understanding extern is used to declare a global variable or
function in other files.
File 1: main.c
int count=5;
main()
{
write_extern();
}
File 2: write.c
void write_extern(void);
extern int count;
void write_extern(void)
{
printf("count is %i\n", count);
}
Here extern keyword is being used to declare count in another file.

MULTIPLE CHOICE QUESTIONS:

1. What is the output for the following program?


void main()
{
static int var = 5; printf(“%d”,var--);

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


23
FAQ in C Language - Prepared by Ms.P.Edreena

if(var)
main();
}
A) Prints 5 infinite times C) Runtime error E) 4 3 2 1
B) Compilation error D) 5 4 3 2 1
Answer: D
static storage class is given, it is initialized only once. The change in the value of a
static variable is retained even between the function calls. The function main () is also treated
like any other ordinary function, which can be called recursively.

2. What is the output for the following program?


void 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]);
}
Answer:
Compiler error: Lvalue required in function main
Explanation:
Array names are pointer constants. So it cannot be modified.
3. What is the output for the following program?
main()
{
extern int i;
i=20;
printf("%d",i);
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
24
FAQ in C Language - Prepared by Ms.P.Edreena

}
A) 0 C) 20
B) Error D) garbage value

Answer: B
Explanation:
extern storage class in the following declaration,
extern int i;
specifies to the compiler that the 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.

4. What is the output for the following program?


main()
{
extern int i;
i=20;
printf("%d",sizeof(i));
}
Answer: Linker error: undefined symbol '_i'.
Explanation:
extern declaration specifies that the variable i is defined somewhere else. The
compiler passes the external variable to be resolved by the linker. So compiler doesn't find an
error. During linking, the linker searches for the definition of i. Since it is not found the linker
flags an error.

5. What is the output for the following program?


void main()
{
extern out;
printf("%d", out);
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
25
FAQ in C Language - Prepared by Ms.P.Edreena

}
int out=100;
Answer: 100
Explanation:
This is the correct way of writing the previous program (Q.4).

6. What is the output for the following program?


int i=10;
void main()
{
extern int i;
{
int i=20;
{
const volatile unsigned i=30;
printf("%d",i);
}
printf("%d",i);
}
printf("%d",i);
}
Answer: 30,20,10
Explanation:
'{', Introduces new block and thus new scope. In the innermost block i is declared as,
const volatile unsigned which is a valid declaration. i is assumed of type int. So printf prints
30. In the next block, i have value 20 and so printf prints 20. In the outermost block, i is
declared as extern, so no storage space is allocated for it. After compilation is over the linker
resolves it to global variable i (since it is the only variable visible there). So it prints i's value
as 10.

7. What is the output of the following C program?


# include <stdio.h>
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
26
FAQ in C Language - Prepared by Ms.P.Edreena

void main( )
{
int a, b=0;
static int c [10]={1,2,3,4,5,6,7,8,9,0};
for (a=0; a<10;+ + a)
if ((c[a]%2)= = 0) b+ = c [a];
printf (“%d”, b);
}
A) 20 C) 25
B) 45 D) 90

Answer: A
printf statement will print b which is sum of the those values from array c which get
divided by 2, that is 2+4+6+8=20.

8. If storage class is missing in the array definition, by default it will be taken to be


A) Automatic Variable
B) External Variable
C) Static Variable
D) Either automatic or external depending on the place of occurrence.
Answer: A
A variable declared inside inside a function without storage class specification is, by
default, an automatic variable.

9. What is the output of the following C program?


void main()
{
extern out;
printf("%d", out);
}
int out=100;
Answer: 100
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
27
FAQ in C Language - Prepared by Ms.P.Edreena

Explanation:
This is the correct way of writing the previous program.

10. What is the output of the following C program?


#include<stdio.h>
int main()
{
register i=5;
char j[]= "hello";
printf("%s %d",j,i);
return 0;
}
Answer: hello 5
Explanation:
If variable ‘i’ is initialized with register keyword, it will be treated as ordinary integer
and it will take integer value. ‘i’ value may be stored either in register or in memory.

11. What is the output of the following C program?


void main()
{
static int i=5;
if(--i)
{
main();
printf("%d ",i);
}
}
Answer: 0000
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

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


28
FAQ in C Language - Prepared by Ms.P.Edreena

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.

12. What is the output of the following C program?


void main()
{
static int i=i++, j=j++, k=k++;
printf(“i = %d j = %d k = %d”, i, j, k);
}
A) i=0 j=0 k=0.
B) i=1 j=1 k=1.
C) Garbagevalues for i,j,k.
D) Compilation error.
Answer: B
Explanation:
Since static variables are initialized to zero by default.

13. What is the output of the following C program?


void main()
{
register int a=2;
printf("Address of a = %d",&a);
printf("Value of a = %d",a);
}
Answer: Compiler Error: '&' on register variable
Rule to Remember:
& (address of) operator cannot be applied on register variables.

14. What is the output of the following C program?


void main()
{
extern i;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
29
FAQ in C Language - Prepared by Ms.P.Edreena

printf("%d\n",i);
{
int i=20;
printf("%d\n",i);
}
}
Answer: Linker Error: Unresolved external symbol i
Explanation:
The identifier i is available in the inner block and so using extern has no use in
resolving it.

15. A variable which is visible only in the function in which it is defined, is called
A) Static variable
B) Auto variable
C) External variable
D) Local variable
Answer: D

16. What is the output of this C code?


#include <stdio.h>
void main()
{
m();
m();
}
void m()
{
static int x = 5;
x++;
printf("%d", x);
}
A) 6 7 B) 6 6 C) 5 5 D) 5 6
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
30
FAQ in C Language - Prepared by Ms.P.Edreena

Answer: A

17. What is the output of this C code?


#include <stdio.h>
void main()
{
static int x;
printf("x is %d", x);
}
A) 0 B) 1 C) Junk value D) Run time error
Answer: A
The default value for static variable is 0.

18. What is the output of this C code?


#include <stdio.h>
static int x;
void main()
{
int x;
printf("x is %d", x);
}
A) 0 B) Junkvalue C) Run time error D) Nothing
Answer: B

19. What is the output of this C code?


#include <stdio.h>
void main()
{
static int x;
if (x++ < 2)
main();
}
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
31
FAQ in C Language - Prepared by Ms.P.Edreena

A) Infinite calls to main


B) Run time error
C) Depends on the compiler
D) main is called twice
Answer: D

20. Which of following is not accepted in C?


A) static a = 10; //static as
B) static int func (int); //parameter as static
C) static static int a; //a static variable prefixed with static
D) All of the mentioned
Answer: C

21. Which of the following cannot be static in C?


A) Variables
B) Functions
C) Structures
D) None of the mentioned
Answer: D

22. Automatic variables are allocated space in the form of a:


A) stack
B) queue
C) priority queue
D) random
Answer: A

23. Which of the following is a storage specifier?


A) enum
B) union
C) auto
D) volatile
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
32
FAQ in C Language - Prepared by Ms.P.Edreena

Answer: C

24. Default storage class if not any is specified for a local variable, is auto
A) true
B) false
C) Depends on the standard
D) None of the mentioned
Answer: A
Default storage classes for the locally declared variables are auto.

25. What is the output of this C code?


#include <stdio.h>
void foo(auto int i);
int main()
{
foo(10);
}
void foo(auto int i)
{
printf("%d\n", i );
}
A) 10
B) Compile time error
C) Depends on the standard
D) None of the mentioned
Answer: B
In a function prototype, the storage class specifier is simply ignored.
A note on register variables: This is the only storage class specifier that may be used in a
function prototype or function definition.

26. Array sizes are optional during array declaration by using ______ keyword.
A) auto
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
33
FAQ in C Language - Prepared by Ms.P.Edreena

B) static
C) extern
D) register
Answer: C

27. What is the output of this C code?


#include <stdio.h>
int main()
{
auto i = 10;
const auto int *p = &i;
printf("%d\n", i);
}
A) 10
B) Compile time error
C) Depends on the standard
D) Depends on the compiler
Answer: A

28. What is the output of this C code?


#include <stdio.h>
int main()
{
register int i = 10;
int *p = &i;
*p = 11;
printf("%d %d\n", i, *p);
}
A) Depends on whether i is actually stored in machine register
B) 10 10
C) 11 11
D) Compile time error
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
34
FAQ in C Language - Prepared by Ms.P.Edreena

Answer: D
& (Address of) should not be used with register variable.

29. What is the output of this C code?


#include <stdio.h>
int main()
{
register static int i = 10;
i = 11;
printf("%d\n", i);
}
A) 10
B) Compile time error
C) Undefined behaviour
D) 11
Answer: B
Combination of storage class keywords is not allowed.

30. What is the output of this C code?


#include <stdio.h>
register int x;
void main()
{
printf("%d", x);
}
A) Depending on the compiler.
B) 0
C) Junk value
D) Compile time error
Answer: DOriginally, register variables were meant to be stored in processor registers, but
global variables have to be stored in the data or the BSS section to be accessible from every
function. Therefore global scope register variables aren't allowed.
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
35
FAQ in C Language - Prepared by Ms.P.Edreena

CHAPTER 3

OPERATORS

• An operator is a symbol that specifies an operation to be performed on the operands.


• The data items that operators act upon are called operands.
• Some operators require two operands. They are called binary operators.
• Some operators require one operand. They are called unary operator.

Types of operators
1. Arithmetic Operator
2. Relational Operator
3. Logical Operator
4. Assignment Operator
5. Increment & decrement Operator
6. Conditional Operator
7. Bitwise Operator
8. Special Operator

Arithmetic Operators
The following table shows all the arithmetic operators supported by the C
language. Assume variable A holds 10 and variable B holds 20 then :

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B /A= 2

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


36
FAQ in C Language - Prepared by Ms.P.Edreena

% Modulus Operator and remainder of after an integer division. B %A= 0

++ Increment operator increases the integer value by one. A++ = 11

-- Decrement operator decreases the integer value by one. A-- = 9

Difference between ++ and -- operator as postfix and prefix


When i++ is used as (like: var++), operator will return the value of operand first and then
only increment prefix(like: ++var), ++var will increment the value of varand then return it
but, if ++ is used as postfix it. This can be demonstrated by an example:
Example:
#include <stdio.h>
int main()
{
int c=2,d=2;
printf("%d\n",c++); //this statement displays 2 then, only c incremented by 1 to 3.
printf("%d",++c); //this statement increments 1 to c then, only c is displayed.
return 0;
}
Output:
2
4
Relational Operators:

Relational Operator

Relational operators checks relationship between two operands. If the relation is true, it
returns value 1 and if the relation is false, it returns value 0. For example:

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


37
FAQ in C Language - Prepared by Ms.P.Edreena

a>b

Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then, it returns 0.

Relational operators are used in decision making and loops in C programming.

Operator Meaning of Operator Example

== Equal to 5==3 returns false (0)

> Greater than 5>3 returns true (1)

< Less than 5<3 returns false (0)

!= Not equal to 5!=3 returns true(1)

>= Greater than or equal to 5>=3 returns true (1)

<= Less than or equal to 5<=3 return false (0)

Logical Operators

Logical operators are used to combine expressions containing relation operators. In C, there
are 3 logical operators:

Meaning of
Operator Example
Operator

If c=5 and d=2 then,((c==5) && (d>5))


&& Logial AND
returns false.

|| Logical OR If c=5 and d=2 then, ((c==5) || (d>5)) returns

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


38
FAQ in C Language - Prepared by Ms.P.Edreena

Meaning of
Operator Example
Operator

true.

! Logical NOT If c=5 then, !(c==5) returns false.

Explanation

For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is
false in the given example. So, the expression is false. For expression ((c==5) || (d>5)) to be
true, either the expression should be true. Since, (c==5) is true. So, the expression is
true. Since, expression (c==5) is true, !(c==5) is false.

Conditional Operator

Conditional operator takes three operands and consists of two symbols ? and : . Conditional
operators are used for decision making in C. For example:

c=(c>0)?10:-10;

If c is greater than 0, value of c will be 10 but, if c is less than 0, value ofc will be -10.

Bitwise Operators

A bitwise operator works on each bit of data. Bitwise operators are used in bit level
programming.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


39
FAQ in C Language - Prepared by Ms.P.Edreena

Operators Meaning of operators

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

Other Operators:

1) Comma Operator

Comma operators are used to link related expressions together. For example:

int a,c=5,d;

2) The sizeof operator

It is a unary operator which is used in finding the size of data type, constant, arrays, structure
etc. For example:

#include <stdio.h>
int main(){
int a;
float b;
double c;
char d;
printf("Size of int=%d bytes\n",sizeof(a));
printf("Size of float=%d bytes\n",sizeof(b));

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


40
FAQ in C Language - Prepared by Ms.P.Edreena

printf("Size of double=%d bytes\n",sizeof(c));


printf("Size of char=%d byte\n",sizeof(d));
return 0;
}

Output

Size of int=4 bytes

Size of float=4 bytes

Size of double=8 bytes

Size of char=1 byte

3) Conditional operators (?:)

Conditional operators are used in decision making in C programming, i.e, executes different
statements according to test condition whether it is either true or false.

Syntax of conditional operators

conditional_expression?expression1:expression2

If the test condition is true, expression1 is returned and if false expression2 is returned.

Example of conditional operator

#include <stdio.h>
int main(){
char feb;
int days;
printf("Enter l if the year is leap year otherwise enter 0: ");
scanf("%c",&feb);
days=(feb=='l')?29:28;

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


41
FAQ in C Language - Prepared by Ms.P.Edreena

/*If test condition (feb=='l') is true, days will be equal to 29.


*/
/*If test condition (feb=='l') is false, days will be equal to
28. */
printf("Number of days in February = %d",days);
return 0;
}

Output

Enter l if the year is leap year otherwise enter n: l

Number of days in February = 29

Operator Associativity & Precedence:

Category Operator Associativity


Postfix () [ ] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


42
FAQ in C Language - Prepared by Ms.P.Edreena

Example program for operator precedence


#include <stdio.h>
main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = (a + b) * (c / d); // (30) * (15/5)
printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0;
}
Output:
Value of (a + b) * c / d is : 90

Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50

Rules for evaluation of expression


• Any expression within the parenthesis is evaluated first.
• Arithmetic expression is evaluated from left to right using the rule of precedence.
• Within the parenthesis, highest precedence operator is evaluated first.
• If the operators have the same precedence, associativity is to be applied.
• If the parenthesis is nested, the innermost sub-expression is evaluated first.

Operators Categories:
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
43
FAQ in C Language - Prepared by Ms.P.Edreena

All the operators can be categorised into following categories:


• Postfix operators, which follow a single operand.
• Unary prefix operators, which precede a single operand.
• Binary operators, which take two operands and perform a variety of arithmetic and
logical operations.
• The conditional operator (a ternary operator), which takes three operands and
evaluates either the second or third expression, depending on the evaluation of the
first expression.
• Assignment operators, which assign a value to a variable.
• The comma operator, which guarantees left-to-right evaluation of comma-separated
expressions.

MULTIPLE CHOICE QUESTIONS:

1. What is the value of i in the following expression?


#include<stdio.h>
void main()
{
int i=1;
i << 1%2;
printf(“%d”,i);
}
A) 2 B) -2 C) 1 D) 0
Answer: A
Explanation:
Step 1: i= 1 (i.e., 0001)
Step 2:1%2= 1 (Higher precedence)
Step 3: i << 1
Step 4: left shift i by 1 bit (0010)
So value of I is 2.

2. For the following statements find the values generated for p and q.
#include<stdio.h>
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
44
FAQ in C Language - Prepared by Ms.P.Edreena

void main()
{
int p=0, q=1;
p=q++;
p=++q;
p=q--;
p=--q;
}
A) 1, 1 B) 0, 0 C) 3, 2 D) 1, 2
Answer : A
Explanation:
• Step 1: p=1 & q=2
• Step 2: p=3 & q=3
• Step 3: p=3 & q=2
• Step 4: p=1 & q=1

3.What are the values for variable, a & b when compiled without error?
#include<stdio.h>
#define MAX(x,y) ((x) > (y)) ? (x) : (y)
void main()
{
int a, b;
a = 3;
b = MAX (3, a++);
printf(“%d \t %d”, a, b);
}
Answer:
a = 5, b = 4
Explanation:
• b = ((3) > (a++)) ? (3) : (a++);
• i.e., if(3>3) // a=a+1; (a=4)
b=3;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
45
FAQ in C Language - Prepared by Ms.P.Edreena

else
b=4; // a=a+1; (a=5)
In the end values are a = 5, b = 4

4. What will be the output of the following program?


void main()
{
int i=-1, j=-1, k=0, l=2, m;
m=i++ && j++ && k++ || l++;
printf("%d %d %d %d %d", i, j, k, l, m);
}
Answer: 00131
Explanation :
Logical operations always give a result of 1 or 0. And also the logical AND (&&)
operator has higher priority over the logical OR (||) operator.
So the expression ‘i++ && j++ && k++’ is executed first. The result of this
expression is 0 (-1 && -1 && 0 = 0).
Now the expression is 0 || 2 which evaluates to 1 (because OR operator always
gives 1 except for ‘0 || 0’ combination- for which it gives 0).
So the value of m is 1. The values of other variables are also incremented by 1.

5. What will be the output of the following program?


void main()
{
int c=- -2;
printf("c=%d",c);
}
Answer:
c=2;
Explanation:
Here unary minus (or negation) operator is used twice. Same maths rules applies, i.e.
minus * minus= plus.
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
46
FAQ in C Language - Prepared by Ms.P.Edreena

Note:
However you cannot give like --2. Because, -- operator can be applied to variables as
a decrement operator (e.g., i--). Value, 2 is a constant and not a variable.

6. What will be output of the following program?


#include<stdio.h>
int main(){
int i=1;
i=2+2*i++;
printf("%d",i);
return 0;
}
Answer: 5
Explanation:
i++ i.e. when postfix increment operator is used any expression the it first assign the
its value in the expression the it increments the value of variable by one. So,
• i=2+2*1
• i=4
Now i will be incremented by one so i = 4 + 1 = 5

7. What will be output of the following program?


void main()
{
int i=10;
i=!i>14;
printf("i=%d",i);
}
Answer: i=0
Explanation:
In the expression !i>14 , NOT (!) operator has more precedence than ‘ >’ symbol. ! is a
unary logical operator. !i (!10) is 0 (not of true is false). 0>14 is false (zero).

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


47
FAQ in C Language - Prepared by Ms.P.Edreena

8. 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;
}
Answer: 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 b=0

9. What will be output of the following program?


#define square(x) x*x
void main()
{
int i;
i = 64/square(4);
printf("%d",i);
}
Answer: 64
Explanation:
The macro call square(4) will substituted by 4*4 so the expression becomes i =
64/4*4. Since / and * has equal priority the expression will be evaluated as (64/4)*4 i.e. 16*4
= 64
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
48
FAQ in C Language - Prepared by Ms.P.Edreena

10. What will be output of the following program?


#include<stdio.h>
void main()
{
int x;
x=10, 20, 30;
printf("%d",x);
return 0;
}
Answer: 10
Explanation :

• 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

11. What will be output of the following program?


#include<stdio.h>
int main()
{
int a=0,b=10;
if(a=0)
printf("true");
else
printf("false");
return 0;

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


49
FAQ in C Language - Prepared by Ms.P.Edreena

}
Answer: 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.
• Note: if (a=10), o/p: true

12. What will be output of the following program?


#include<stdio.h>
int main()
{
int a;
a=015 + 0x71 +5;
printf("%d",a);
return 0;
}
Answer: 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
Note:
★ To write numbers in octal, precede the value with a 0. Thus, 023 is 238 (which is 19 in
base 10).
★ To write numbers in hexadecimal, precede the value with a 0x or 0X. Thus, 0x23 is
2316 (which is 35 in base 10).

13. What will be output of the following program?


void main()
{
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
50
FAQ in C Language - Prepared by Ms.P.Edreena

int i=-1;
+i;
printf("i = %d, +i = %d \n",i,+i);
}
Answer:
i = -1, +i = -1
Explanation:
Unary + is the only dummy operator in C. Where-ever it comes you can just ignore it
just because it has no effect in the expressions (hence the name dummy operator).

14. The output of the code below is


#include <stdio.h>
void main()
{
int k = 8;
int m = 7;
k < m ? k++ : m = k;
printf("%d", k);
}
A) 7 B) 8 C) Compile time error D) Run time error
Answer: C
Explanation:
Throws compile time error stating Lvalue is required, because assignment of an
expression should be done to the left hand side of the expression.

15. What is the output of the following program?


#include <stdio.h>
void main()
{
int k = 8;
int m = 7;
k= k < m ? k++ : m;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
51
FAQ in C Language - Prepared by Ms.P.Edreena

printf("%d", k);
}
Output: 7

16. What is the output of the following program?


void main()
{
printf("%x",-1<<4);
}
Answer: fff0
Explanation :
-1 is internally represented as all 1's. When left shifted four times the least
significant 4 bits are filled with 0's.The %x format specifier specifies that the integer value be
printed as a hexadecimal value.

As Decimal: 65520
As Hexadecimal: FFF0 (0xFFF0)
As Binary: 1111111111110000
Note:
Decimal :15 => hex: f =>binary:1111
As Decimal: 65528 //( i.e.,6552=fff)
As Hexadecimal: FFF8 (0xFFF8)
As Binary: 1111111111111000
As Decimal: 65530
As Hexadecimal: FFFA (0xFFFA)
As Binary: 1111111111111010

17. Print the output of this program


void main()
{ int a, b, c, abc = 0;
a = b = c = 40;
if (c) {
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
52
FAQ in C Language - Prepared by Ms.P.Edreena

int abc;
abc = a*b+c;
}
printf ("c = %d, abc = %d ", c, abc);
}
Answer:
c = 40 and abc = 0;
Explanation:
Because the scope of the variable 'abc' inside if(c) {.. } is not valid outside that if (.) { .. }.

18. Print the output of this program


void main()
{
int k = 5;
if (++k < 5 && k++/5 || ++k <= 8);
printf("%d ", k);
}
Answer: 7
Explanation:
The first condition ++k < 5 is checked and it is false (Now k = 6). So, it checks the
3rd condition (or condition ++k <= 8) and (now k = 7) it is true. At this point k value is
incremented by twice; hence the value of k becomes 7.

19. What is the output of this program?


void fn(int, int);
main()
{ int a = 5;
printf("Main : %d %d ", a++, ++a);
fn(a, a++);

}
void fn(int a, int b)
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
53
FAQ in C Language - Prepared by Ms.P.Edreena

{
printf("Fn : a = %d b = %d ", a, b);
}
Answer: The solution depends on the implementation of stack. (Depends on OS). In some
machines the arguments are passed from left to right to the stack. In this case the result will
be,

Main : 5 7 Fn : 7 7
Other machines the arguments may be passed from right to left to the stack. In that case
the result will be
Main : 6 6 Fn : 8 7

20. Which of the following statement is correct about the code snippet given below?
#include < stdio.h>
int main()
{
float z = 12.35, c = 10;
if( ++z%10 -z)
c += z;
else
c - = z;
printf( “%f %f”, z, c);
return 0;
}
A) The program will result in compile time error
B) The program will print 12.35 22.35
C) The program will print 13.35 22.35
D) The program will print 1.35 11.35
Answer: A

21. What is the output of the following program?

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


54
FAQ in C Language - Prepared by Ms.P.Edreena

#include < stdio.h>


int main()
{
int max =123, min = 10, *maxptr = &max, *minptr = &min;
int **nptr = &minptr, **mptr = &maxptr;
*maxptr = ++*mptr % **nptr;
max - = ( *minptr -**nptr && *maxptr || *minptr);
printf( “ %d %d”, ++**mptr, *minptr);
return 0;
}
A) 4 10 B) 3 11 C) 3 10 D) 4 11
Answer: A

22. What is the value of x after executing the following statement?


void main()
{
int x = 011 | 0x10;
printf(“%d”, i);
}
A) 13 B) 19 C) 25 D) 27
Answer: C

23. Which of the following statement is correct about the code snippet given below?
#include < stdio.h>
int main()
{
int a = 10, b = 2, c;
a = !( c = c == c) && ++b;
c += ( a + b- -);
printf( “ %d %d %d”, b, c, a);
return 0;
}
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
55
FAQ in C Language - Prepared by Ms.P.Edreena

A) The program will print the output 1 3 0


B) The program will print the output 0 1 3
C) The program will results in expression syntax error
D) The program will print the output 0 3 1

Answer: A

24. What will be output of the following program?


#include<stdio.h>
int main(){
float a=0.7;d
if(a<0.7){
printf("C");
}
else{
printf("C++");
}
return 0;
}
Answer: C
Explanation:
0.7 is double constant (Default). Its binary value is written in 64 bit.

Binary value of 0.7 = (0.1011 0011 0011 0011 0011 0011 0011 0011 0011 0011 0011)
Now here variable a is a floating point variable while 0.7 is double constant. So variable a
will contain only 32 bit value i.e.

a = 0.1011 0011 0011 0011 0011 0011 0011 0011 while


0.7 = 0.1011 0011 0011 0011 0011 0011 0011 0011 0011 0011 0011....
It is obvious a < 0.7

25. What will be output if you will compile and execute the following c code?
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
56
FAQ in C Language - Prepared by Ms.P.Edreena

void main()
{
int i=4,x;
x=++i + ++i + ++i;
printf("%d",x);
}

(A) 21 (B) 18 (C) 12 (D) Compiler error (E) None of


above

Answer: A
Explanation:
In ++a, ++ is pre increment operator. In any mathematical expression pre increment
operator first increment the variable up to break point then starts assigning the final value to
all variable.

Step 1: Increment the variable ‘i' up to break point.


x=++i + ++i + ++i;
x= 5 + 6 + 7

Step 2: Start assigning final value 7 to all variable ‘i' in the expression.
x=++i + ++i + ++i;
x= 7 + 7 + 7
So, x=7+7+7=21

26. What will be output if you will compile and execute the following c code?
void main()
{
int a=10;
printf("%d %d %d",a,a++,++a);
}
(A) 12 11 11 (B) 12 10 10 (C) 11 11 12
(D) 10 10 12 (E) Compiler error
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
57
FAQ in C Language - Prepared by Ms.P.Edreena

Answer: A
Explanation:
In c printf function follows cdecl parameter passing scheme. In this scheme parameter
is passed from right to left direction.
printf("%d %d %d",a,a++,++a);
3 2 1
So first ++a will pass and value of variable will be a=10 then a++ will pass now value
variable will be a=10 and at the end a will pass and value of a will be a=12.

27. What will be output if you will compile and execute the following c code?
#define call(x,y) x##y
void main()
{
int x=5,y=10,xy=20;
printf("%d",xy+call(x,y));
}
(A) 35 (B) 510 (C) 15 (D) 40 (E) None of above
Answer: D
Explanation:
## is concatenation c preprocessor operator. It only concatenates the operands i.e.
a##b=ab
If you will see intermediate file then you will find code has converted into following
intermediate code before the start of actual compilation.
Intermediate file:

void main()
{
int x=5,y=10,xy=20;
printf("%d",xy+xy);
}

It is clear call(x, y) has replaced by xy.


PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
58
FAQ in C Language - Prepared by Ms.P.Edreena

28. Which of the following is the correct order if calling functions in the below code?
a = f1(23, 14) * f2(12/4) + f3();
A) f1, f2, f3
B) f3, f2, f1
C) Order may vary from compiler to compiler
D) None of above
Answer: C
Explanation:
Here, Multiplication will happen before the addition, but in which order the functions would
be called is undefined. In an arithmetic expression the parenthesis tell the compiler which
operands go with which operators but do not force the compiler to evaluate everything within
the parenthesis first.

29. Which of the following are unary operators in C?


1. !
2. sizeof
3. ~
4. &&

A) 1, 2 B) 1, 3 C) 2, 4 D) 1, 2, 3
Answer: D
Explanation:
An operation with only one operand is called unary operation.
Unary operators:
! Logical NOT operator.
~ bitwise NOT operator.
sizeof Size-of operator.
&& Logical AND is a logical operator.
Therefore, 1, 2, 3 are unary operators.
30. In which order do the following gets evaluated

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


59
FAQ in C Language - Prepared by Ms.P.Edreena

1. Relational
2. Arithmetic
3. Logical
4. Assignment
A) 2134 B) 1234 C) 4321 D) 3214
Answer: A
Explanation:
2. Arithmetic operators: *, /, %, +, -
1. Relational operators: >, <, >=, <=, ==, !=
3. Logical operators : !, &&, ||
4. Assignment operators: =

CHAPTER 4

FLOW CONTROL STATEMENTS

C provides two sytles of flow control:


i) Branching
ii) Looping
Branching is deciding what actions to take and looping is deciding how many times to take a
certain action.

Branching:
1) if statement
✓ This is the most simple form of the branching statements.
✓ It takes an expression in parenthesis and an statement or block of statements.
✓ if the expression is true then the statement or block of statements gets executed
otherwise these statements are skipped.

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


60
FAQ in C Language - Prepared by Ms.P.Edreena

NOTE: Expression will be assumed to be true if its evaulated value is non-zero.


Syntax:
if (expression)
statement;
or
if (expression)
{
Block of statements;
}

or

if (expression)
{
Block of statements;
}
else
{
Block of statements;
}
or
if (expression)
{
Block of statements;
}
else if(expression)
{
Block of statements;
}
else
{
Block of statements;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
61
FAQ in C Language - Prepared by Ms.P.Edreena

2) ? : Operator
✓ The ? : operator is just like an if ... else statement except that because it is an operator
you can use it within expressions.
✓ ? : is a ternary operator in that it takes three values, this is the only ternary operator C
has.
✓ ? : takes the following form:
Syntax:
if condition is true ? then X return value : otherwise Y value;
(OR)
cond ? X : Y

3) switch statement:
✓ The switch statement is much like a nested if .. else statement.
✓ Its mostly a matter of preference which you use, switch statement can be slightly
more efficient and easier to read.
Syntax:
switch( expression )
{
case constant-expression1: statements1;
[case constant-expression2: statements2;]
[case constant-expression3: statements3;]
[default : statements4;]
}
Using break keyword:
If a condition is met in switch case then execution continues on into the next case
clause also if it is not explicitly specified that the execution should exit the switch statement.
This is achieved by using break keyword.

Looping

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


62
FAQ in C Language - Prepared by Ms.P.Edreena

Loops provide a way to repeat commands and control how many times they are
repeated. C provides a number of looping way.
1) while loop
✓ A while statement is like a repeating if statement.
✓ Like an If statement, if the test condition is true: the statments get executed.
✓ The difference is that after the statements have been executed, the test condition is
checked again. If it is still true the statements get executed again.
✓ This cycle repeats until the test condition evaluates to false.
Syntax:
while ( expression )
{
Single statement
or
Block of statements;
}
2) for loop
✓ for loop is similar to while, it's just written differently.
✓ for statements are often used to process lists such a range of numbers:
Syntax:
for( expression1; expression2; expression3)
{
Single statement
or
Block of statements;
}
i) expression1 - Initializes variables.
ii) expression2 - Conditional expression, as long as this condition is true, loop
will keep executing.
iii) expression3 - expression3 is the modifier which may be simple increment of a
variable.
3) do...while loop

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


63
FAQ in C Language - Prepared by Ms.P.Edreena

✓ do ... while is just like a while loop except that the test condition is checked at the end
of the loop rather than the start.
✓ This has the effect that the content of the loop are always executed at least once.
Syntax:
do
{
Single statement
or
Block of statements;
}while(expression);

break and continue statements


C provides two commands to control how we loop:
● break -- exit form loop or switch.
● continue -- skip 1 iteration of loop.

MULTIPLE CHOICE QUESTIONS

1. What will be output when you will execute following c code?


#include<stdio.h>
void main()
{
int check=2;
switch(check)
{
case 1: printf("D. Abiram");
case 2: printf(" M.G.George");
case 3: printf(" Mohammad Abdul");
default: printf(" M.Vijay");
}
}

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


64
FAQ in C Language - Prepared by Ms.P.Edreena

A) M.G.George B) M.Muralidaran
C) M.G.George Mohammad Abdul M.Vijay
D) Compilation error E) None of the above
Answer: C
Explanation:
If we don’t use break keyword in each case the program control passes to next
consecutive statements inside the switch condition.

2. What will be output when you will execute following c code?


#include<stdio.h>
#define X 10
void main()
{
auto m=10;
switch(m,m*2)
{
case X: printf("William");
break;
case X*2:printf("Cathy");
break;
case X*3:printf("Charles");
break;
default: printf("Lawrence");
case X*4:printf("Abhinav");
break;
}
}

A) William B) Cathy C) Lawrence Abhinav


D) Compilation error: Misplaced defaultE) None of the above
Answer: B
Explanation:
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
65
FAQ in C Language - Prepared by Ms.P.Edreena

In C, comma is an operator which has least precedence. So, if x = (a , b); Then x = b.


Note: Case expression can be macro constant.

3. What will be output when you will execute following c code?


#include<stdio.h>
void main()
{
switch(*(1+"AB" "CD"+1))
{
case 'A':printf("Friction");
break;
case 'B':printf("Angry Bird");
break;
case 'C':printf("Black Berry");
break;
case 'D':printf("BlueDiamond");
}
}
A) Friction B) Angry Bird C) Black Berry
D) BlueDiamond E) Compilation error
Answer: C
Explanation:
Consider on the expression:
*(1+"AB" "CD"+1)
= *(2+"AB" "CD")
= *(2+"ABCD")
=*("CD")
='C'
Note: Case expression can be character constant.

4. What will be output when you will execute following c code?


#include<stdio.h>
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
66
FAQ in C Language - Prepared by Ms.P.Edreena

void main()
{
switch(5||2|1)
{
case 3&2:printf("Anatomy of a Murder");
break;
case -~11:printf("Planet of Apes");
break;
case 6-3<<2:printf("The conversation");
break;
case 5>=5:printf("Shaun of the Dead");
}
}

A) Anatomy of a Murder B) Planet of Apes C) The conversation


D) Shaun of the Dead E) Compilation error

Answer: E
Explanation:
Consider on the expression:
5||2|1
=5|| (2|1) //Bitwise or has higher precedence
=5||3
=1
Now, value of each case expression:
3&2 = 2
-~11 = -(-12) =12
6-3<<2 = 3 <<2 = 12
5>=5 = 1
case -~11 and case 6-3<<2 have same constant expression i.e. case 12
In c duplicate case is not possible.

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


67
FAQ in C Language - Prepared by Ms.P.Edreena

5. What will be output when you will execute following c code?


#include<stdio.h>
void main()
{
static int i;
int j;
for(j=0;j<=5;j+=2)
switch(j)
{
case 1: i++;break;
case 2: i+=2;
case 4: i%=2;j=-1; continue;
default: --i; continue;
}
printf("%d",i);
}
(A) 0 (B) 1 (C) 2 (D) Compilation error (E)
None of the above

Answer: A
Explanation:
In first iteration of for loop: j = 0
So, control will come to default,
i = -1
Due to continue keyword program control will move to beginning of for loop
In second iteration of for loop: j =2
So, control will come to case 2,
i+=2
i = i+2 = -1 +2 =1
Then come to case 4,
i%=2
i = i%2 = 1%2 = 1
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
68
FAQ in C Language - Prepared by Ms.P.Edreena

j= -1
Due to continue keyword program control will move to beginning of for loop. In third
iteration of for loop:
j = -1 +2 =1
So, control will come to case 1
i=2
In the fourth iteration of for loop:
j = 1+ 2 =3
So, control will come to default,
So i=1
In the fifth iteration of for loop:
j = 3 + 2 =5
So, control will come to default,
So i=0
In the sixth iteration of for loop:
j = 5 + 2 =7
Since loop condition is false. So control will come out of the for loop.

6. What will be output when you will execute following c code?


#include<stdio.h>
void main()
{
char *str="cquestionbank.blogspot.com";
int a=2;
switch('A')
{
case 97:
switch(97)
{
default: str+=1;
}
case 65:
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
69
FAQ in C Language - Prepared by Ms.P.Edreena

switch(97)
{
case 'A':str+=2;
case 'a':str+=4;
}
default:
for(;a;a--)
str+=8;
}
printf("%s",str);
}
A) cquestionbank.blogspot.com B) blogspot.com C) com
D) Compilation error E) None of the above
Answer: E
Explanation:
ASCII value of the character constant 'A' is 65 and 'a' is 97. Nesting of switch case is
possible in c.

7. What will be output when you will execute following c code?


#include<stdio.h>
void main()
{
int a=3,b=2;
a=a==b==0;
switch(1)
{
a=a+10;
}
sizeof(a++);
printf("%d",a);
}

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


70
FAQ in C Language - Prepared by Ms.P.Edreena

A) 10 B) 11 C) 12 D) 1 E) Compilation error
Answer: D
Explanation:
Consider on the expression:
a=a==b==0;
a=(a==b)==0; //Since associate is right to left
a =(3==2)==0
a=0==0
a=1
switch case will not affect the value of variable a.
Also sizeof operator doesn't affect the value of the any variable

8. In a for loop, if the condition is missing, then?


A) It is assumed to be present and taken to be false
B) It is assumed to be present and taken to be true
C) It result in the syntax error
D) Execution will be terminated abruptly
Answer: B

9. 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("cquestionbank");
}
else
{
break;
}
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
71
FAQ in C Language - Prepared by Ms.P.Edreena

}
A) cquestionbank B) It will print nothing C) Run time error
D) Compilation error E) None of the above
Answer: D
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 used in case of loop or switch case
statement.
Hence when you will compile above code compiler will show an error message:
Misplaced break.

10. What is the output of the following?


void main()
{
int ones, twos, threes, others;
int c;
ones = twos = threes = others = 0;
while( ( c = getchar() != ‘\n’) )
{
switch( c )
{
case ‘1’ : ++ones;
case ‘2’ : ++twos;
case ‘3’ : ++threes;
break;
default: ++others;
break;
}
}
printf( “%d%d ”, ones, others);
}

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


72
FAQ in C Language - Prepared by Ms.P.Edreena

If the input is “1a1b1c” what is the output?


A) 13 B) 34 C) 33 D) 31
Answer: C

11. In a for loop, if the condition is missing, then infinite looping cannot be avoided by a
A) continue statement B) goto statement
C) return statement D) break statement
Answer: A

12. What is the output of the following code?


void main()
{
int I = 3;
while( I --)
{
int I = 100;
i- -;
printf(“%d. .”, i);
}
}
A) Infinite loop B) Error C) 99..99..99.. D) 3..2..1..
Answer: C

13. What will be output when you will execute following c code?
#define PRINT printf("Star Wars");
printf(" Psycho");
#include<stdio.h>
void main()
{
int x=1;
if(x--)
PRINT
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
73
FAQ in C Language - Prepared by Ms.P.Edreena

else
printf("The Shawshank Redemption");
}
A) Stars Wars Psycho B) The Shawshank Redemption
C) Warning: Condition is always trueD) Warning: Condition is always false
E) Compilation error
Answer: E
Explanation:
PRINT is macro constant. Macro PRINT will be replaced by its defined statement just
before the actual compilation starts. Above code is converted as:

void main()
{
int x=1;
if(x--)
printf("Star Wars");
printf(" Psycho");
else
printf("The Shawshank Redemption");
}
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(" Psycho");
It is a function call. It is also ok
(iii) else
printf("The Shawshank Redemption");
You cannot write else clause without any if clause. It is cause of compilation error.
Hence compiler will show an error message: Misplaced else

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


74
FAQ in C Language - Prepared by Ms.P.Edreena

14. How many times the loop executes?


void main()
{
unsigned char c;
for( c = 0; c != 256; c+2 )
printf(“%d”, c);
}
A) 127 B) 128 C) 256 D) Infinitely
Answer: D

15. Which of the following comments about for loop are not correct?
A) Index value is retained outside the loop
B) Index value can be changed from within the loop
C) goto can be used to jump,out of loop
D) Body of the loop cannot be empty
Answer: D

16. What will be printed when the following code is executed?


void main()
{
int a = 2, b = 4, c = 8, x = 4;
if ( x == b)
x = a;
else
x = b;
if( x != b)
c = c + b;
else
c = c + a;
printf(“c = %d\n”,c);
}
A) c = 4 B) c = 8 C) c = 10 D) c = 12
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
75
FAQ in C Language - Prepared by Ms.P.Edreena

Answer: D

17. What will be printed when the following code is executed?


void main()
{
int x = 0;
for (; ;)
{
if ( x++ == 4) break;
continue;
}
printf(“x = %d\n”, x);
}
A) x = 0 B) x = 1 C) x = 4 D) x = 5
Answer: D

18. What is the output of the code?


#include <stdio.h>
void main()
{
int x = 5;
if (x < 1)
printf("hello");
if (x == 5)
printf("hi");
else
printf("no");
}
A) hi B) hello C) no D) None of the mentioned
Answer: A

19. What is the output of the code?


PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
76
FAQ in C Language - Prepared by Ms.P.Edreena

#include <stdio.h>
int x;
void main()
{
if (x)
printf("hi");
else
printf("how are u");
}
A) hi B) how are you C) Compile time error D) None of the mentioned
Answer: B

20. Predict the output of the code


#include <stdio.h>
void main()
{
int x = 0;
if (x == 0)
printf("hi");
else
printf("how are u");
printf("hello");
}
A) hi B) how are you C) hello D) hihello
Answer: D

21. What is the output of the code (When 1 is entered)?


#include <stdio.h>
void main()
{
char *ch;
printf("enter a value btw 1 to 3:");
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
77
FAQ in C Language - Prepared by Ms.P.Edreena

scanf("%s", ch);
switch (ch)
{
case "1":
printf("1");
break;
case "2":
printf("2");
break;
}
}
A) 1 B) 2 C) Compile time error D) No Compile time error
Answer: C

22. When 1 is entered, what will be the output of the code?


#include <stdio.h>
void main()
{
int ch;
printf("enter a value btw 1 to 2:");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("1\n");
default:
printf("2\n");
}
}
A) 1 B) 2 C) 1 2 D) Run time error
Answer: C

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


78
FAQ in C Language - Prepared by Ms.P.Edreena

23. When 2 are entered, what is the output of the code?


#include <stdio.h>
void main()
{
int ch;
printf("enter a value btw 1 to 2:");
scanf("%d", &ch);
switch(ch)
{
case 1:
printf("1\n");
break;
printf("Hi");
default:
printf("2\n");
}
}
A) 1 B) Hi 2 C) Run time error D) 2
Answer: D

24. What is the output of this C code?


#include <stdio.h>
const int a = 1, b = 2;
void main()
{
int x = 1;
switch (x)
{
case a:
printf("yes ");
case b:
printf("no\n");
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
79
FAQ in C Language - Prepared by Ms.P.Edreena

break;
}
}
A) yes no B) yes C) no D) Compile time error
Answer: D

25. 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("XYZ");
else
printf("ABC");
}
Choose all that apply:
A) XYZ B) ABC
C) Warning: x and y are assigned a value that is never used
D) Warning: Condition is always true E) Compilation error
Answer: C, E
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

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


80
FAQ in C Language - Prepared by Ms.P.Edreena

In C if you assign any value to variable but you don’t perform any operator or
perform operation only using unary operator on the variable the compiler will show a
warning message: Variable is assigned a value that is never used

26. What will be the final values of I and j when the following code terminates?
void main()
{
static int I , j = 5;
for ( I = 0; I < 3; I ++)
{
printf(“%d%d\n”, I, j);
if( j > 1)
{
j - -;
main ();
}
}
}
A) 02 B) 11 C) 21 D) Error, because main cannot be called recursively
Answer: C

27. What will be output of following C code?


#include<stdio.h>
extern int x;
int main()
{
do
{
do
{
printf("%o",x);
}
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
81
FAQ in C Language - Prepared by Ms.P.Edreena

while(!-2);
}
while(0);
return 0;
}
int x=8;
Answer: 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.

28. How many x are printed?


void main()
{
int I, j;
for( I = 0, j = 10; I < j; I ++, j --)
printf(“x”);
}

A) 10 B) 5 C) 4 D) None
Answer: B

29. What will be output of following c code?


#include<stdio.h>
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
82
FAQ in C Language - Prepared by Ms.P.Edreena

int main()
{
int i=2,j=2;
while(i+1?--i:j++)
printf("%d",i);
return 0;
}
Answer: 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.

30. What will be output of following c code?


#include<stdio.h>
int main()
{
static int i;
for(++i;++i;++i)
{
printf("%d ",i);
if(i==4) break;
}
return 0;
}
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
83
FAQ in C Language - Prepared by Ms.P.Edreena

Answer: 24
Explanation:
Default value of static int variable in c is zero. So, initial value of variable i = 0
First iteration:
For loop starts value: ++i i.e. i = 0 + 1 = 1
For loop condition: ++i i.e. i = 1 + 1 = 2 i.e. loop condition is true. Hence printf
statement will print 2
Loop incrimination: ++I i.e. i = 2 + 1 =3
Second iteration:
For loop condition: ++i i.e. i = 3 + 1 = 4 i.e. loop condition is true. Hence printf
statement will print 4.
Since is equal to for so if condition is also true. But due to break keyword program
control will come out of the for loop.

31. 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--;
}

Answer: 5 2
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
84
FAQ in C Language - Prepared by Ms.P.Edreena

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.

32. What will be output of following c code?


#include<stdio.h>
char _x_(int,...);
int main()
{
char (*p)(int,...)=&_x_;
for(;(*p)(0,1,2,3,4); )
printf("%d",!+2);
return 0;
}
char _x_(int a,...)
{
static i=-1;
return i+++a;
}
Answer: 0
Explanation:
In c three continuous dot represents variable number of arguments.
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
85
FAQ in C Language - Prepared by Ms.P.Edreena

p is the pointer to the function _x_


First iteration of for loop:
Initial value: Nothing // In c it is optional
Loop condition: (*p)(0,1,2,3,4)
= *(&_x_)(0,1,2,3,4) // p = &_x_
= _x_(0,1,2,3,4) //* and & always cancel to each other
= return i+++a
= return i+ ++a
= return -1 + 1
=0
Since condition is false. But printf function will print 0. It is bug of c language.

33. What will be output when you will execute following C code?
#include<stdio.h>
void main()
{
int x=1,y=2;
if(--x && --y)
printf("x=%d y=%d",x,y);
else
printf("%d %d",x,y);
}

A) 1 2 B) x=1 y=2 C) 0 2 D) x=0 y=1 E) 0 1


Answer: C
Explanation:
Consider the following expression:
--x && --y
In this expression && is Logical AND operator. Two important properties of this
operator are:
Property 1:
(Expression1) && (Expression2)
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
86
FAQ in C Language - Prepared by Ms.P.Edreena

&& operator returns 1 if and only if both expressions return a non-zero value
otherwise it && operator returns 0.
Property 2:
To optimize the execution time there is rule, Expression2 will only evaluate if and
only if Expression1 return a non-zero value.
In this program initial value of x is 1. So –x will be zero. Since -–x is returning zero
so -–y will not execute and if condition will be false. Hence else part will be executed.

34. What will be output if you will compile and execute the following c code?
void main()
{
float a=5.2;
if(a==5.2)
printf("Equal");
else if(a<5.2)
printf("Less than");
else
printf("Greater than");
}
(A) Equal (B) Less than (C) Greater than
(D) Compiler error (E) None of above

Answer: B
Explanation:
5.2 is double constant in c. In c size of double data is 8 byte while a is float variable.
Size of float variable is 4 byte.
So double constant 5.2 is stored in memory as:
101.00 11001100 11001100 11001100 11001100 11001100 11001101
Content of variable a will store in the memory as:
101.00110 01100110 01100110
It is clear variable a is less than double constant 5.2.

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


87
FAQ in C Language - Prepared by Ms.P.Edreena

Since 5.2 is recurring float number so it different for float and double. Number likes
4.5, 3.25, 5.0 will store same values in float and double data type.
Note: In memory float and double data is stored in completely different way.

35. What will be output if you will compile and execute the following c code?
void main()
{
int x;
for(x=1;x<=5;x++);
printf("%d",x);
}

(A) 4 (B) 5 (C) 6 (D) Compiler error (E) None of above


Answer: C
Explanation:
Body of for loop is optional. In this question for loop will execute until value of
variable x became 6 and condition became false

36. What will be output if you will compile and execute the following c code?
void main()
{
int i=10;
static int x=i;
if(x==i)
printf("Equal");
else
if(x>i)
printf("Greater than");
else
printf("Less than");
}

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


88
FAQ in C Language - Prepared by Ms.P.Edreena

(A) Equal (B) Greater than (C) Less than


(D) Compiler error (E) None of above
Answer: D
Explanation:
static variables are load time entity while auto variables are run time entity. We cannot
initialize any load time variable by the run time variable. In this example i is run time
variable while x is load time variable.

CHAPTER 5

FUNCTIONS

A function is a group of statements that together perform a task. Every C program has
at least one function, which is main(), and all the most trivial programs can define additional
functions.
You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division usually is so each function
performs a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can
call. For example, function strcat() to concatenate two strings, function memcpy() to copy
one memory location to another location and many more functions.
A function is known with various names like a method or a sub-routine or a
procedure, etc.

Defining a Function:
The general form of a function definition in C programming language is as follows:
return_type function_name( parameter list )
{
body of the function
}

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


89
FAQ in C Language - Prepared by Ms.P.Edreena

A function definition in C programming language consists of a function header and


a function body. Here are all the parts of a function:
● Return Type: A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
● Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
● Parameters: A parameter is like a placeholder. When a function is invoked, you pass
a value to the parameter. This value is referred to as actual parameter or argument.
The parameter list refers to the type, order, and number of the parameters of a
function. Parameters are optional; that is, a function may contain no parameters.
● Function Body: The function body contains a collection of statements that define
what the function does.

Example:
Following is the source code for a function called max(). This function takes two
parameters num1 and num2 and returns the maximum between the two:
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

Function Declarations:
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration has the following parts:
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
90
FAQ in C Language - Prepared by Ms.P.Edreena

return_type function_name( parameter list );


For the above defined function max(), following is the function declaration:
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required,
so following is also valid declaration:
int max(int, int);
Function declaration is required when you define a function in one source file and you
call that function in another file. In such case you should declare the function at the top of the
file calling the function.

Calling a Function:
While creating a C function, you give a definition of what the function has to do. To
use a function, you will have to call that function to perform the defined task.
When a program calls a function, program control is transferred to the called function.
A called function performs defined task and when its return statement is executed or when its
function-ending closing brace is reached, it returns program control back to the main
program.
To call a function, you simply need to pass the required parameters along with
function name, and if function returns a value, then you can store returned value. For
example:
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %d\n", ret );

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


91
FAQ in C Language - Prepared by Ms.P.Edreena

return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
max() function is kept along with main() function and compiled the source code.
While running final executable, it would produce the following result:
Max value is: 200

Function Arguments:
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a
function:

Call Type Description


This method copies the actual value of an argument into the formal parameter
Call by
of the function. In this case, changes made to the parameter inside the function
value
have no effect on the argument.
This method copies the address of an argument into the formal parameter.
Call by
Inside the function, the address is used to access the actual argument used in
reference
the call. This means that changes made to the parameter affect the argument.

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


92
FAQ in C Language - Prepared by Ms.P.Edreena

By default, C uses call by value to pass arguments. In general, this means that code
within a function cannot alter the arguments used to call the function and above mentioned
example while calling max() function used the same method.

Call by Value: Program


#include <stdio.h>
void swap( int p1, int p2 ); // function declaration
int main()
{
int a = 10;
int b = 20;
printf("Before: Value of a = %d and value of b = %d\n", a, b );
swap( a, b ); // function call
printf("After: Value of a = %d and value of b = %d\n", a, b );
}
void swap( int p1, int p2 ) // function definition
{
int t;
t = p2;
p2 = p1;
p1 = t;
printf("Value of a (p1) = %d and value of b(p2) = %d\n", p1, p2 );
}
Output:
Before: Value of a = 10 and value of b = 20
Value of a (p1) = 20 and value of b(p2) = 10
After: Value of a = 10 and value of b = 20

Call by Reference: Program


#include <stdio.h>
void swap( int *p1, int *p2 ); // function declaration
int main()
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
93
FAQ in C Language - Prepared by Ms.P.Edreena

{
int a = 10;
int b = 20;
printf("Before: Value of a = %d and value of b = %d\n", a, b );
swap( &a, &b ); // function call
printf("After: Value of a = %d and value of b = %d\n", a, b );
}
void swap( int *p1, int *p2 ) // function definition
{
int t;
t = *p2;
*p2 = *p1;
*p1 = t;
printf("Value of a (p1) = %d and value of b(p2) = %d\n", *p1, *p2 );
}
Output:
Before: Value of a = 10 and value of b = 20
Value of a (p1) = 20 and value of b(p2) = 10
After: Value of a = 20 and value of b = 10

MULTIPLE CHOICE QUESTIONS:

1. What is the following function computing? Assume a and b are positive integers.
int fn( int a, int b)
{
if (b == 0)
return b;
else
return (a * fn(a, b - 1));

}
A) Output will be 0 always B) Output will always be b

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


94
FAQ in C Language - Prepared by Ms.P.Edreena

C) Computing ab D) Computing a + b
Answer: A
The output is always be 0 because b is decremented in recursive function fn each time
by 1 till the terminating condition b==0 where it will return 0.

2. A possible output of the following program fragment, when the input is “mix’, is
for (i=getchar();; i=get.char())
if (i==‘x’)
break;
else
putchar(i);
A) mi B) mix
C) mixx D) none of the above

Answer: D
Explanation:
As it is wrong syntax it is compiler error. Suppose if, i=get.char() is replaced by
getchar(), then the output will be ‘mi’.

3. In a for loop, if the condition is missing, then,


A) It is assumed to be present and taken to be false.
B) It is assumed to be present and taken to be true.
C) It results in a syntax error.
D) Execution will be terminated abruptly.
Answer: B

4. What will be the output of the program?


#include<stdio.h>
void fun(int*, int*);
int main()
{
int i=5, j=2;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
95
FAQ in C Language - Prepared by Ms.P.Edreena

fun(&i, &j);
printf("%d, %d", i, j);
return 0;
}
void fun(int *i, int *j)
{
*i = *i**i;
*j = *j**j;
}
A) 5, 2 B) 10, 4 C) 2, 5 D) 25, 4

Answer: D
Explanation:
Step 1: int i=5, j=2; Here variable i and j are declared as an integer type and initialized to 5
and 2 respectively.
Step 2: fun(&i, &j); Here the function fun() is called with two parameters &i and &j (The &
denotes call by reference. So the address of the variable i and j are passed. )
Step 3: void fun(int *i, int *j) This function is called by reference, so we have to use * before
the parameters.
Step 4: *i = *i**i; Here *i denotes the value of the variable i. Here 5*5 is multiplied and
storing the result 25 in same variable, i.
Step 5: *j = *j**j; Here *j denotes the value of the variable j. We are multiplying 2*2 and
storing the result 4 in same variable j.
Step 6: Then the function void fun(int *i, int *j) return back the control back to main()
function.
Step 7: printf("%d, %d", i, j); It prints the value of variable i and j.
Hence the output is 25, 4.

5. What is the name of built-in function for finding square roots?


A) square(x) B) sqr(x) C) sqrt(x) D) No built-in fn
Answer: C
sqrt(x) is a built-in function for finding square roots.
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
96
FAQ in C Language - Prepared by Ms.P.Edreena

6. What is the output of following statement?


for(i=1; i<4; i++)
printf(“%d”,(i%2) ? i : 2*i);
A) 1 4 3 B) 1 2 3
C) 2 4 6 D) 2 2 6

Answer: A
for i=1, (i%2) is true so the statement will print 1; for for i=2, (i%2) is false so the
statement will print 2*i=2*2=4; for for i=3, (i%2) is again true so the statement will print 3;
for i=4, the statement is out from the loop.

7. Which of the following statement is true about a function?


A) An invoking function must pass arguments to the invoked function.
B) Every function returns a value to the invoker.
C) A function may contain more than one return statement.
D) Every function must be defined in its own separate file.
Answer: A
An invoking function must pass arguments to the invoked function.

8. For implementing recursive function the data structure used is:


A) Queue B) Stack
C) Linked List D) Tree
Answer: B
For implementing recursive function, stack is used as a data structure.

9. How many times the following code prints the string “hello”.
for(i=1; i<=1000; i++);
printf(“hello”);
A) 1 B) 1000
C) Zero D) Syntax error
Answer: A
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
97
FAQ in C Language - Prepared by Ms.P.Edreena

The “for” loop is terminated by a semicolon so the next statement is execute that is
printing hello.

10. The function used to read a character from a file that has been opened in read mode is
A) putc B) getc
C) getchar D) putchar
Answer: B
getc is used to read a character from a file that has been opened in read mode.

11. The function that allocates requested size of bytes and returns a pointer to the first byte
of the allocated space is -
A) realloc B) malloc
C) calloc D) none of the above
Answer: B
malloc allocates requested size of bytes and returns a pointer to the first byte of the
allocated space.

12. What is the output for the following program?


void main()
{
int i=0;
for(;i++;printf("%d",i)) ;
printf("%d",i);
}
Answer: 1
Before entering into for loop, checking condition is "evaluated". Here it evaluates to
0 (false) and comes out of the loop, and i is incremented (note the semicolon after the
for loop).

13. In the following pgm add a stmt in the function fun such that the address of 'a' gets
stored in 'j'.
void main()
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
98
FAQ in C Language - Prepared by Ms.P.Edreena

{
int * j;
void fun(int **);
fun(&j);
}
void fun(int **k)
{
int a =0;
/* add a stmt here*/
}
Answer: *k = &a
The argument of the function is a pointer to a pointer.

14. What are the following notations of defining functions known as?
i. int abc(int a,float b)
{
/* some code */
}
ii. int abc(a,b)
int a; float b;
{
/* some code*/
}

Answer:
i. ANSI C notation
ii. Kernighan & Ritche notation

15. What are the following notations of defining functions known as?
void main()
{
int k=ret(sizeof(float));
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
99
FAQ in C Language - Prepared by Ms.P.Edreena

printf("\n here value is %d",++k);


}
int ret(int ret)
{
ret += 2.5;
return(ret);
}
A) 6 B) 7 C) 8 D) Runtime Error
Answer: B
Explanation:
The int ret(int ret), ie., the function name and the argument name can be same. Firstly,
the function ret() is called in which the sizeof(float) ie., 4 is passed, after the first
expression the value in ret will be 6, as ret is integer hence the value stored in ret will have
implicit type conversion from float to int. The ret is returned in main() it is printed after pre
incrementing the value.

16. What is the output of this C code?


#include <stdio.h>
int main()
{
void foo();
printf("1 ");
foo();
}
void foo()
{
printf("2 ");
}
A)1 2
B)Compile time error
C)1 2 1 2
D)Depends on the compiler
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
100
FAQ in C Language - Prepared by Ms.P.Edreena

E) 2 1 2
Answer: A

17. What is the output of this C code?


#include <stdio.h>
int main()
{
void foo(), f();
f();
}
void foo()
{
printf("2 ");
}
void f()
{
printf("1 ");
foo();
}
A) Compile time error as foo is local to main
B) 1 2
C) 2 1
D) 2 1 2 1 2
E) Compile time error due to declaration of functions inside main
Answer: B

18. What is the output of this C code?


#include <stdio.h>
void foo(int*);
int main()
{
int i = 10;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
101
FAQ in C Language - Prepared by Ms.P.Edreena

foo((&i)++);
}
void foo(int *p)
{
printf("%d\n", *p);
}
A)10
B)Some garbage value
C)Compile time error
D)Segmentation fault/code crash

Answer: C

19. What is the output of this C code?


#include <stdio.h>
void foo(int*);
int main()
{
int i = 10, *p = &i;
foo(p++);
}
void foo(int *p)
{
printf("%d\n", *p);
}
A)10
B)Some garbage value
C)Compile time error
D)Segmentation fault

Answer: A

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


102
FAQ in C Language - Prepared by Ms.P.Edreena

20. What is the output of this C code?


#include <stdio.h>
int main()
{
int i = 97, *p = &i;
foo(&i);
printf("%d ", *p);
}
void foo(int *p)
{
int j = 2;
p = &j;
printf("%d ", *p);
}
A) 2 97
B)2 2
C)Compile time error
D)Segmentation fault/code crash

Answer: A

21. What is the output of this C code?


#include <stdio.h>
int main()
{
int i = 97, *p = &i;
foo(&p);
printf("%d ", *p);
return 0;
}
void foo(int **p)
{
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
103
FAQ in C Language - Prepared by Ms.P.Edreena

int j = 2;
*p = &j;
printf("%d ", **p);
}
A)2 2
B)2 97
C)Undefined behaviour
D)Segmentation fault/code crash

Answer: A

22. Which of the following can never be sent by call-by-value?


A) Variable
B) Array
C) Structures
D) Both (B) and (C)
Answer: B

23. Which type of variables can have same name in different function:
A) global variables
B) static variables
C) Function arguments
D) Both (B) and (C)

Answer: D

24. Arguments that take input by user before running a program are called?
A) main function arguments
B) main arguments
C) Command-Line arguments
D) Parameterized arguments

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


104
FAQ in C Language - Prepared by Ms.P.Edreena

Answer: C

25. The maximum number of arguments that can be passed in a single function
are_____________
A) 127
B) 253
C) 361
D) No limits in number of arguments

Answer: B

26. What is the output of this C code?


#include <stdio.h>
void m(int *p, int *q)
{
int temp = *p; *p = *q; *q = temp;
}
void main()
{
int a = 6, b = 5;
m(&a, &b);
printf("%d %d\n", a, b);
}
A)5 6 B) 6 5 C) 5 5 D) 6 6

Answer: A

27. What is the output of this C code?


#include <stdio.h>
void m(int *p)
{
int i = 0;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
105
FAQ in C Language - Prepared by Ms.P.Edreena

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


printf("%d\t", p[i]);
}
void main()
{
int a[5] = {6, 5, 3};
m(&a);
}
A)0 0 0 0 0
B)6 5 3 0 0
C)Run time error
D)6 5 3 junk junk

Answer: B

28. What is the output of this C code?


#include <stdio.h>
void m(int p, int q)
{
int temp = p;
p = q;
q = temp;
}
void main()
{
int a = 6, b = 5;
m(a, b);
printf("%d %d\n", a, b);
}
A) 5 6 B) 5 5 C) 6 5 D) 6 6

Answer: C
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
106
FAQ in C Language - Prepared by Ms.P.Edreena

29. What is the output of this C code?


#include <stdio.h>
void m(int p, int q)
{
printf("%d %d\n", p, q);
}
void main()
{
int a = 6, b = 5;
m(a);
}
A)6 C) 6 5
B)6 junk value D) Compile time error

Answer: D

30. What is the output of this C code?


#include <stdio.h>
void m(int p)
{
printf("%d\n", p);
}
void main()
{
int a = 6, b = 5;
m(a, b);
printf("%d %d\n", a, b);
}
A) 6 B) 6 5
C) 6 junk value D) Compile time error
Answer: D
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
107
FAQ in C Language - Prepared by Ms.P.Edreena

CHAPTER 6

ARRAYS

❖ An array is a data structure, which can store a fixed-size sequential collection of


elements of the same type.

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


108
FAQ in C Language - Prepared by Ms.P.Edreena

❖ An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
❖ All arrays consist of contiguous memory locations.
❖ The lowest address corresponds to the first element and the highest address to the last
element.

Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows:
type arrayName [ arraySize ];
This is called a single-dimensional array.
where
arraySize must be an integer constant greater than zero and
type can be any valid C data type.
For example, to declare a 10-element array called balance of type double, use this statement:
double balance[10];

Initializing Arrays
❖ You can initialize array in C either one by one or using a single statement as follows:
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
❖ The number of values between braces { } cannot be larger than the number of
elements that we declare for the array between square brackets [ ].
❖ If you omit the size of the array, an array just big enough to hold the initialization is
created. Therefore, if you write:
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
❖ You will create exactly the same array as you did in the previous example. Following
is an example to assign a single element of the array:
balance[4] = 50.0;
❖ The above statement assigns element number 5th in the array with a value of 50.0.
❖ All arrays have 0 as the index of their first element which is also called base index and
last index of an array will be total size of the array minus 1.

Accessing Array Elements

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


109
FAQ in C Language - Prepared by Ms.P.Edreena

❖ An element is accessed by indexing the array name.


❖ This is done by placing the index of the element within square brackets after the name
of the array.
❖ For example:
double salary = balance[9];
❖ The above statement will take 10th element from the array and assign the value to
salary variable.

MULTIPLE CHOICE QUESTIONS:

1. Which of the following correctly declares an array?


A) int anarray[10]; B) int anarray;
C) anarray{10}; D) array anarray[10];
Answer: A

2. What is the index number of the last element of an array with 29 elements?
A) 29 B) 28
C) 0 D) Programmer-defined
Answer: B

3. Which of the following is a two-dimensional array?


A) array anarray[20][20]; B) int anarray[20][20];
C) int array[20, 20]; D) char array[20];
Answer: B

4. Which of the following correctly accesses the seventh element stored in foo, an array with
100 elements?
A) foo[6]; B) foo[7];
C) foo(7); D) foo;
Answer: A

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


110
FAQ in C Language - Prepared by Ms.P.Edreena

5. Which of the following gives the memory address of the first element in array foo, an array
with 100 elements?
A) foo[0]; B) foo;
C) &foo; D) foo[1];
Answer: B

6. What will happen if in a C program you assign a value to an array element whose subscript
exceeds the size of array?
A) The element will be set to 0.
B) The compiler would report an error.
C) The program may crash if some important data gets overwritten.
D) The array size would appropriately grow.
Answer: C

7. What does the following declaration mean?


int (*ptr)[10];
A) ptr is array of pointers to 10 integers
B) ptr is a pointer to an array of 10 integers
C) ptr is an array of 10 integers
D) ptr is an pointer to array
Answer: B

8. In C, if you pass an array as an argument to a function, what actually gets passed?


A) Value of elements in array
B) First element of the array
C) Base address of the array
D) Address of the last element of array
Answer: C

9. What will be the output of the program?


#include<stdio.h>
int main()
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
111
FAQ in C Language - Prepared by Ms.P.Edreena

{
int a[5] = {5, 1, 15, 20, 25};
int i, j, m;
i = ++a[1];
j = a[1]++;
m = a[i++];
printf("%d, %d, %d", i, j, m);
return 0;
}
A) 2, 1, 15 B) 1, 2, 5
C) 3, 2, 15 D) 2, 3, 20
Answer: C

10. What will be the output of the program ?


#include<stdio.h>
int main()
{
void fun(int, int[]);
int arr[] = {1, 2, 3, 4};
int i;
fun(4, arr);
for(i=0; i<4; i++)
printf("%d,", arr[i]);
return 0;
}
void fun(int n, int arr[])
{
int *p=0;
int i=0;
while(i++ < n)
p = &arr[i];
*p=0;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
112
FAQ in C Language - Prepared by Ms.P.Edreena

}
A) 2, 3, 4, 5 B) 1, 2, 3, 4
C) 0, 1, 2, 3 D) 3, 2, 1 0
Answer: B

11. What will be the output of the program ?


#include <stdio.h>
int main()
{
int arr[5];
// assume that base address of arr is 2000 and size of integer is 32 bit
arr++;
printf("%u", arr);
return 0;
}
A) 2002 B) 2004
C) 2020 D) lvalue required
Answer: D
Explanation: Array name in C is implemented by a constant pointer. It is not possible to
apply increment and decrement on constant types.

12. What will be the output of the program ?


#include <stdio.h>
int main()
{
int arr[5];
// Assume base address of arr is 2000 and size of integer is 32 bit
printf("%u %u", arr + 1, &arr + 1);
return 0;
}
A) 2004 2020 B) 2004 2004
C) 2004 Garbage value
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
113
FAQ in C Language - Prepared by Ms.P.Edreena

D) The program fails to compile because Address-of operator cannot be used with array name
Answer: A
Explanation: Name of array in C gives the address (except in sizeof operator) of the first
element. Adding 1 to this address gives the address plus the sizeof type the array has.
Applying the Address-of operator before the array name gives the address of the whole array.
Adding 1 to this address gives the address plus the sizeof whole array.

13. What is output of the following C program?


#include<stdio.h>
int main()
{
int a[] = {1, 2, 3, 4, 5, 6};
int *ptr = (int*)(&a+1);
printf("%d ", *(ptr-1) );
return 0;
}

A) 1 B) 2
C) 6 D) Runtime Error

Answer: C
Explanation: &a is address of the whole array a[]. If we add 1 to &a, we get “base address of
a[] + sizeof(a)”. And this value is typecasted to int *. So ptr points the memory just after 6 is
stored. ptr is typecasted to “int *” and value of *(ptr-1) is printed. Since ptr points memory
after 6, ptr – 1 points to 6.

14. What is output of the following C program?


int main()
{
int i;
int arr[5] = {1};
for (i = 0; i < 5; i++)

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


114
FAQ in C Language - Prepared by Ms.P.Edreena

printf("%d ", arr[i]);


return 0;
}
A) 1 followed by four garbage values B) 1 0 0 0 0
C) 1 1 1 1 1 D) 0 0 0 0 0
Answer: B
Explanation: In C/C++, if we initialize an array with fewer members, all remaining members
are automatically initialized as 0.
For example, the following statement initializes an array of size 1000 with values as
0.
int arr[1000] = {0};

15. What will be the output of the program in Turbo C (under DOS)?
#include<stdio.h>
int main()
{
int arr[5], i=0;
while(i<5)
arr[i]=++i;
for(i=0; i<5; i++)
printf("%d, ", arr[i]);
return 0;
}
A) 1, 2, 3, 4, 5, B) Garbage value, 1, 2, 3, 4,
C) 0, 1, 2, 3, 4, D) 2, 3, 4, 5, 6,
Answer: B
Explanation:
Since C is a compiler dependent language, it may give different outputs at different
platforms. We have given the TurboC Compiler (Windows) output.

MULTI DIMENSIONAL ARRAYS:

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


115
FAQ in C Language - Prepared by Ms.P.Edreena

The general form of a multidimensional array declaration:


type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array:
int threedim[5][10][4];

Two-Dimensional Arrays:
❖ The simplest form of the multidimensional array is the two-dimensional array.
❖ A two-dimensional array is, in essence, a list of one-dimensional arrays.
❖ To declare a two-dimensional integer array of size x,y you would write something as
follows:
type arrayName [ x ][ y ];
where
type can be any valid C data type and
arrayName will be a valid C identifier.
❖ A two-dimensional array can be thought as a table which will have x number of rows
and y number of columns.

MULTIPLE CHOICE QUESTIONS :

1. What is the output of this C code?


#include <stdio.h>
void main ()
{
int a[2][3] = {1, 2, 3, 4, 5};
int i = 0, j = 0;
for (i = 0; i < 2; i++)
for (j = 0; j < 3; j++)
printf("%d", a[i][j]);
}
A) 1 2 3 4 5 0 B) 1 2 3 4 5 junk
C) 1 2 3 4 5 5 D) Run time error
Answer: A

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


116
FAQ in C Language - Prepared by Ms.P.Edreena

2. What is the output of this C code?


#include <stdio.h>
void main()
{
int a[2][3] = {1, 2, 3, , 4, 5};
int i = 0, j = 0;
for (i = 0; i < 2; i++)
for (j = 0; j < 3; j++)
printf("%d", a[i][j]);
}
A) 1 2 3 junk 4 5 B) Compile time error
C) 1 2 3 0 4 5 D) 1 2 3 3 4 5
Answer: B

3. What is the output of this C code?


#include <stdio.h>
void f(int a[][3])
{
a[0][1] = 3;
int i = 0, j = 0;
for (i = 0; i < 2; i++)
for (j = 0; j < 3; j++)
printf("%d", a[i][j]);
}
void main()
{
int a[2][3] = {0};
f(a);
}
A) 0 3 0 0 0 0 B) Junk 3 junk junk junk junk
C) Compile time error D) All junk values
Answer: A
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
117
FAQ in C Language - Prepared by Ms.P.Edreena

4. Comment on the following statement:


int (*a)[7];
A) An array “a” of pointers. B) A pointer “a” to an array.
C) A ragged array. D) None of the mentioned
Answer: B

5. Comment on the 2 arrays regarding P and Q:


int *a1[8];
int *(a3[8]);
P. Array of pointers
Q. Pointer to an array
A) a1 is P, a2 is Q B) a1 is P, a2 is P
C) a1 is Q, a2 is P D) a1 is Q, a2 is Q
Answer: B

6. Which of the following is not possible statically in C?


A) Jagged Array B) Rectangular Array
C) Cuboidal Array D) Multidimensional Array
Answer: A

7. What is the correct syntax to send a 3-dimensional array as a parameter?


(Assuming declaration int a[5][4][3];)
A) func(a); B) func(&a);
C) func(*a); D) func(**a);
Answer: A

8. Applications of multidimensional array are?


A) Matrix-Multiplication B) Minimum Spanning Tree
C) Finding connectivity between nodes D) All of the mentioned
Answer: D

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


118
FAQ in C Language - Prepared by Ms.P.Edreena

9. What is the output of this C code?


#include <stdio.h>
int main()
{
int ary[2][3];
foo(ary);
}
void foo(int *ary[])
{
int i = 10, j = 2, k;
ary[0] = &i;
ary[1] = &j;
*ary[0] = 2;
for (k = 0;k < 2; k++)
printf("%d\n", *ary[k]);
}
A) 2 2 B) Compile time error
C) Undefined behavior D) 10 2
Answer: A

10. What is the output of this C code?


#include <stdio.h>
int main()
{
int ary[2][3];
foo(ary);
}
void foo(int (*ary)[3])
{
int i = 10, j = 2, k;
ary[0] = &i;
ary[1] = &j;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
119
FAQ in C Language - Prepared by Ms.P.Edreena

for (k = 0;k < 2; k++)


printf("%d\n", *ary[k]);
}
A) Compile time error B) 10 2
C) Undefined behavior D) segmentation fault/code crash
Answer: A
11. What is the output of this C code?
#include <stdio.h>
int main()
{
int ary[2][3][4], j = 20;
ary[0][0] = &j;
printf("%d\n", *ary[0][0]);
}
A) Compile time error B) 20
C) Address of j D) Undefined behaviour
Answer: A

12. What is the output of this C code?


#include <stdio.h>
int main()
{
int ary[2][3];
ary[][] = {{1, 2, 3}, {4, 5, 6}};
printf("%d\n", ary[1][0]);
}
A) Compile time error B) 4
C) 1 D) 2
Answer: A

13. Assume the following C variable declaration

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


120
FAQ in C Language - Prepared by Ms.P.Edreena

int *A [10], B[10][10];


Of the following expressions
I ) A[2]
II) A[2][3]
III ) B[1]
IV) B[2][3]
which will not give compile-time errors if used as left hand sides of assignment
statements in a C program
A) I, II, and IV only B) II, III, and IV only
C) II and IV only D) IV only
Answer: A

14. Consider the following declaration of a ‘two-dimensional array in C:


char a[100][100];
Assuming that the main memory is byte-addressable and that the array is stored
starting from memory address 0, the address of a[40][50] is
A) 4040 B) 4050
C) 5040 D) 5050
Answer: B
Explanation:
Address of a[40][50] = Base address + 40*100*element_size + 50*element_size
= 0 + 4000*1 + 50*1
= 4050

15. What is the output of the following program?

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


121
FAQ in C Language - Prepared by Ms.P.Edreena

#include <stdio.h>
int main()
{
int a[][] = {{1,2},{3,4}};
int i, j;
for (i = 0; i < 2; i++)
for (j = 0; j < 2; j++)
printf("%d ", a[i][j]);
return 0;
}
A) 1 2 3 4 B) Compiler Error in line ” int a[][] = {{1,2},{3,4}};
C) 4 garbage values D) 4 3 2 1
Answer: B
Explanation: There is compilation error in the declaration ” int a[][] = {{1,2},{3,4}};”.
Except the first dimension, every other dimension must be specified.
int arr[] = {5, 6, 7, 8} //valid
int arr[][5] = {}; //valid
int arr[][] = {}; //invalid
int arr[][10][5] = {}; //valid
int arr[][][5] = {}; //invalid

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


122
FAQ in C Language - Prepared by Ms.P.Edreena

CHAPTER 7

POINTERS

❖ A pointer is a value that designates the address (i.e., the location in memory), of some
value.
❖ Pointers are variables that hold a memory location.
❖ There are four fundamental things you need to know about pointers:
1) How to declare them (with the address operator '&': int *pointer =
&variable;)
2) How to assign to them (pointer = NULL;)
3) How to reference the value to which the pointer points (known
as dereferencing, by using the dereferencing operator '*': value =
*pointer;)

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


123
FAQ in C Language - Prepared by Ms.P.Edreena

4) How they relate to arrays (the vast majority of arrays in C are simple
lists, also called "1 dimensional arrays")
How to use Pointers?
There are few important operations, which we will do with the help of pointers very
frequently.
(a) Define a pointer variable
(b) Assign the address of a variable to a pointer and
(c) finally access the value at the address available in the pointer variable.
This is done by using unary operator * that returns the value of the variable located at
the address specified by its operand.
Following example makes use of these operations:
#include <stdio.h>
int main ()
{
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x\n", &var );
/* address stored in pointer variable */
printf("Address stored in ip variable: %x\n", ip );
/* access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
● Address of var variable: bffd8b3c
● Address stored in ip variable: bffd8b3c
● Value of *ip variable: 20

NULL Pointers in C

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


124
FAQ in C Language - Prepared by Ms.P.Edreena

❖ It is always a good practice to assign a NULL value to a pointer variable in case you
do not have exact address to be assigned. This is done at the time of variable
declaration. A pointer that is assigned NULL is called a null pointer.
❖ The NULL pointer is a constant with a value of zero defined in several standard
libraries. Consider the following program:
#include <stdio.h>
int main ()
{
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}
★ When the above code is compiled and executed, it produces the following result:
★ The value of ptr is 0
★ On most of the operating systems, programs are not permitted to access memory at
address 0 because that memory is reserved by the operating system. However, the
memory address 0 has special significance; it signals that the pointer is not intended to
point to an accessible memory location. But by convention, if a pointer contains the
null (zero) value, it is assumed to point to nothing.
★ To check for a null pointer you can use an if statement as follows:
★ if(ptr) /* succeeds if p is not null */
★ if(!ptr) /* succeeds if p is null */

C Pointers in Detail:
Pointers have many but easy concepts and they are very important to C programming.
There are following few important pointer concepts which should be clear to a C
programmer:

Concept Description
C - Pointer There are four arithmetic operators that can be used on pointers: ++,
arithmetic --, +, -
C - Array of pointers You can define arrays to hold a number of pointers.

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


125
FAQ in C Language - Prepared by Ms.P.Edreena

C - Pointer to pointer C allows you to have pointer on a pointer and so on.


Passing pointers to Passing an argument by reference or by address both enable the past
functions in C argument to be changed in the calling function by the called function.
Return pointer from C allows a function to return a pointer to local variable, static variable
functions in C and dynamically allocated memory as well.

MULTIPLE CHOICE QUESTIONS:

1. If x is one dimensional array, then pick up the correct answer


A) *(x + i) is same as &x[i] B) *&x[i] is same as x + i
C) *(x + i) is same as x[i] +1 D) *(x + i) is same as *x[i]
Answer: A
= > num[i] is same as *(num+i)

2. Consider the following declaration


int a, *b = &a, **c = &b;
The following program fragment
a = 4;
**c = 5;
A) Does not change the value of a B) Assigns address of c to a
C) assigns the value of b to a D) Assigns 5 to a

Answer: D
The value of a = 4, b = address of a and c = Address of b. The statement **c can be
defined as *(*(Address of b)) = > *(Address of a) = > a.
Note:
*(Address of b) = Value of b (i.e.) Address of a
*(Address of a) = a

3. Consider the following code segment:


int a[10], *p1, *p2;

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


126
FAQ in C Language - Prepared by Ms.P.Edreena

p1 = &a[4];
p2 = &a[6];
Which of the following statement is an incorrect w.r.t. pointer?
A) p1 + 2 B) p2 – 2
C) p2 + p1 D) p2 – p1

Answer: C
= > Addition of two pointers is not allowed.

4. If a function is declared as void fn(int *p), then which of the following statements is
valid to call function fn?
A) fn(x) where x is defined as int x;
B) fn(x) where x is defined as int *x;
C) fn(&x) where x is defined as int *x;
D) fn(*x) where x is defined as int *x;

Answer: B
Function void fn(int *p) needs pointer to int as argument. When x is defined as int
*x, then x is pointer to integer and not *x.

5. What is the output of following program?


void main()
{
int q, *p, n;
q = 176; //if the address of q is 2801 and p is 2600
p = &q;
n = *p;
printf(“%d”, n);
}
A) 2801 B) 176
C) 2600 D) None of the above
Answer: B
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
127
FAQ in C Language - Prepared by Ms.P.Edreena

The statement n=*p can be defined as n=*(address of q) (i.e.) n=176.


q 176
p 2801
n *(2801) (i.e.) The value from the address 2801 is 176

6. Predict the output or error(s) for the following:


void main()
{
int const * p=5;
printf("%d",++(*p));
}
Answer: Compiler error: Cannot modify a constant value.
The variable, p is a pointer to a "constant integer". An attempt is made to change the
value of the “constant integer", which will end up with compilation error.

7. What is the output for the following program?


void 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
nnnn
Explanation:
s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea. Generally
array name is the base address for that array. Variable, s is the base address.

8. What is the output for the following code?


void main()
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
128
FAQ in C Language - Prepared by Ms.P.Edreena

{
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
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.

9. What is the output for the following program?


void main()
{
char *p;
printf("%d %d ",sizeof(*p),sizeof(p));
}
A) 2 1 B) 1 1 C) 1 2 D) Error
Answer: C
Explanation:
The sizeof() operator gives the number of bytes taken by its operand. Variable, p is a
character pointer, which needs one byte for storing its value (a character). Hence sizeof(*p)

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


129
FAQ in C Language - Prepared by Ms.P.Edreena

gives a value of 1. As it needs two bytes to store the address of the character pointer sizeof(p)
gives 2 as output.

10. What is the output for the following code?


#include<stdio.h>
void main()
{
char string[]="Hello World";
display(string);
}
void display(char *string)
{
printf("%s",string);
}
Answer: Compiler Error: Type mismatch in redeclaration of function display
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.

11. What is the output for the following program?


#include<stdio.h>
void 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
Explanation:
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
130
FAQ in C Language - Prepared by Ms.P.Edreena

Variable, p is pointing to character '\n'. Variable, str1 is pointing to character 'a'. For
++*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 as 77. Suppose
if the format specifier used is %C the output would have been M.

12. What is the output for the following code?


#include<stdio.h>
void 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: Garbage Value---10
Explanation:
Only two 2D arrays has been initialized, but the statement, p=&a[2][2][2] tries to
access the element from the third 2D array (which is not declared) so the output is garbage
value. For the statement, *q=***a; starting address of a is assigned to the integer pointer, q.
Now q is pointing to starting address of a. If you print *q, it will print first element of 3D
array.

13. What is the output for the following code?


void main()
{
char *p="hai friends",*p1;
p1=p;
while(*p!='\0')
++*p++;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
131
FAQ in C Language - Prepared by Ms.P.Edreena

printf("%s %s",p,p1);
}
Answer: ibj!gsjfoet
Explanation:
The statement, ++*p++ will parse in the given order:
Step 1: *p = > denotes the value at the address currently pointed by p.
Step 2: ++*p = > the retrieved value will be incremented.
Step 3: When, the end of the statement (;) is encountered the location will be incremented
(i.e.) p++ will be executed.
Hence, in the while loop initial value pointed by p is ‘h’, which is changed to ‘i’ by
executing ++*p. Pointer moves to point the second character, ‘a’ which is similarly changed
to ‘b’ and so on. Similarly blank space is converted to ‘!’. Thus, value in p becomes “ibj!
gsjfoet” and since p reaches ‘\0’ and p1 points to p so, p1doesnot print anything.

14. What is the output for the following code?


void main()
{
char far *farther,*farthest;
printf("%d..%d",sizeof(farther),sizeof(farthest));
}
Answer: 4..2
Explanation:
The character pointer variable stores the address of another variable so it takes the
size of integer variable (2 bytes). The second pointer is of char type and not a far pointer. Far
pointers will double the size of the variable.

15. What is the output of the following C code?


void main()
{
char *p;
p="Hello";
printf("%c\n",*&*p);
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
132
FAQ in C Language - Prepared by Ms.P.Edreena

return 0;
}
Answer: H
Explanation:
* is a dereference operator and & 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.
Note: If * and & comes together it can be just ignored.

16. What is the output for the following program?


void 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]);
}
Answer: Compiler error: Lvalue required in function main
Explanation:
Array names are pointer constants. So it cannot be modified. (i.e.) two dimensional
arrays cannot be modified/accessed using single dimensional array.

17. What is the output for the following program? Assume the base address of ‘a’ as 100.
void 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);
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
133
FAQ in C Language - Prepared by Ms.P.Edreena

}
Answer:
100, 100, 100, 2
114, 104, 102, 3
Explanation:
The given array is a 3-D one. It can also be viewed as a 1-D array.

2 4 7 8 3 4 2 2 2 3 3 4
100 102 104 106 108 110 112 114 116 118 120 122
Thus, for the variables a, *a and **a in the first printf statement the address of first
element is displayed as output. The pointer variable, ***a displays the value at the base
address.
The expression, a+1 in the second printf statement, increments 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.

18. What is the output for the following program?


void main( )
{
int a[ ] = {10,20,30,40,50},j,*p;
for(j=0; j<5; j++)
{
printf(“%d” ,*a);
a++;
}
p = a;
for(j=0; j<5; j++)
{
printf(“%d ” ,*p);
p++;
}

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


134
FAQ in C Language - Prepared by Ms.P.Edreena

}
A) 10 20 30 40 50 10 20 30 40 50 B) 10 10 10 10 10 10 20 30 40 50
C) Compilation Error D) 10 20 30 40 50
Answer: C (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.

19. What is the output for the following program?


void main( )
{
static int a[ ] = {0,1,2,3,4};
int *p[ ] = {a,a+1,a+2,a+3,a+4};
int **ptr = p;
ptr++;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
*ptr++;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
}

A) 0 1 2 B) 0 0 0 C) 1 1 1 D) Compilation error
123 111 222
Answer: C
Explanation:
Let us consider the array and the two pointers with some address
a
0 1 2 3 4
100 102 104 106 108

p
100 102 104 106 108

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


135
FAQ in C Language - Prepared by Ms.P.Edreena

1000 1002 1004 1006 1008


ptr
1000
2000
After execution of the instruction ptr++, value in ptr becomes 1002, if scaling factor
for integer is 2 bytes. Now ptr – p is value in ptr – starting location of array p, (1002 –
1000) / (scaling factor) = 1, *ptr – a = value at address pointed by ptr – starting value of
array a, 1002 has a value 102 so the value is (102 – 100)/(scaling factor) = 1, **ptr is the
value stored in the location pointed by the pointer of ptr = value pointed by value pointed by
1002 = value pointed by 102 = 1. Hence the output of the firs printf is 1, 1,1.
After execution of *ptr++ the value in ptr is incremented by scaling factor, so it
becomes1004. Hence, the outputs for the second printf are ptr – p = 2, *ptr – a = 2, **ptr = 2.

20) What is the output for the following program?


void main ( )
{
static char *s[ ] = {“black”, “white”, “yellow”, “violet”};
char **ptr[ ] = {s+3, s+2, s+1, s}, ***p;
p = ptr;
**++p;
printf(“%s”,*--*++p + 3);
}
A) Compilation Error C) ck E) black
B) Garbage Value D) ack
Answer: C
In this problem an array of char pointers is pointing to 4th strings. Then ptr is a pointer
to a pointer of type char and a variable p which is a pointer to a pointer to a pointer of type
char. p hold the initial value of ptr, i.e. p = s+3. The next statement increment value in p by 1,
thus now value of p = s+2. In the printf statement the expression, *++p gets the value of s+1
then the pre decrement is executed and we get s+1 – 1 = s. The indirection operator now gets
the value from the array of s and adds 3 to the starting address. The string is printed starting
from this position. Thus, the output is ‘ck’.
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
136
FAQ in C Language - Prepared by Ms.P.Edreena

21. What will be output of following program?


#include<stdio.h>
int main()
{
int a = 320;
char *ptr;
ptr =( char *)&a;
printf("%d ",*ptr);
return 0;
}
A) 2 B) 64 C) 320 D) Compilation Error
Answer: C
As we know int is two byte data byte while char is one byte data byte. char pointer
can keep the address one byte at time.
Binary value of 320 is 00000001 01000000 (In 16 bit)

Memory representation of int a = 320 is:

So ptr is pointing only


first 8 bit and the Decimal value is 64.

22. What is the output for the following program?


void main()
{
int i, n;
char *x = “You”;
n = strlen(x);
*x = x[n];
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
137
FAQ in C Language - Prepared by Ms.P.Edreena

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


{
printf(“%s\t”,x);
x++;
}
}
A) Compilation error C) You ou u
B) Infinite Loop D) (blank space) ou u
Answer: D
Explanation:
Here a string (a pointer to char) is initialized with a value “You”. The strlen function
returns the length of the string, thus n has a value 3. The next statement assigns value at the
nth location (‘\0’) to the first location. Now the string becomes “\0ou”. Now the printf
statement prints the string after each iteration it increments it starting position. Loop starts
from 0 to 3. The first time x[0] = ‘\0’ hence it prints nothing and pointer value is incremented.
The second time it prints from x[1] i.e “ou” and the third time it prints “u”and the loop
terminates.

23. What si the output for the following program?


void main()
{
int *j;
{
int i=10;
j=&i;
}
printf("%d",*j);
}
A)10 B) Address of i C) Garbage Value D) Error

Answer: A

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


138
FAQ in C Language - Prepared by Ms.P.Edreena

The variable i is a block level variable and the visibility is inside that block only. But
the lifetime of i is lifetime of the function so it lives up to the exit of main function. *j prints
the value stored in i since j points i.

24. What is the output for the following program?


#include<stdio.h>
void 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);
}
A) 8 8 B) 10 8 C) Garbagevalue Garbagevalue D) Garbagevalue
10
Answer: D
Explanation:
The statement, p=&a[2][2][2] has declared only two 2D arrays. But the third 2D
(which is not declared) is tried to access so it will print garbage value. The statement,
*q=***a points to the starting address of a so q is pointing to starting address of a. So for, *q
first element of 3D array is displayed.

25. What is the output for the following program?


void main()
{
char *p;
int *q;
long *r;
p=q=r=0;
p++;
q++;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
139
FAQ in C Language - Prepared by Ms.P.Edreena

r++;
printf("%p...%p...%p",p,q,r);
}
Answer: 0001...0002...0004
Explanation:
++ operator when applied to pointers increments address according to their
corresponding data-types.

26. What is the output for the following program?


#include <stdio.h>
int main()
{
int i = 10;
void *p = &i;
printf("%d\n", (int)*p);
return 0;
}
A) Compile time error
B) Segmentation fault/runtime crash.
C) 10
D) Undefined behavior.
Answer: A

27. What is the output for the following program?


#include <stdio.h>
int *f();
int main()
{
int *p = f();
printf("%d\n", *p);
}
int *f()
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
140
FAQ in C Language - Prepared by Ms.P.Edreena

{
int j = 10;
return &j;
}
A) 10
B) Compile time error
C) Segmentation fault/runtime crash
D) Undefined behavior.
Answer: A

28. What is the output for the following program?


#include <stdio.h>
int main()
{
int *ptr, a = 10;
ptr = &a;
*ptr += 1;
printf("%d,%d/n", *ptr, a);
}
A) 10,10 B) 10,11 C) 11,10 D) 11,11
Answer: D
The statement *ptr+=1 => (*ptr = *ptr + 1) => *ptr = 10+1 => *ptr = 11.

29. Comment on the following?


const int *ptr;

A) You cannot change the value pointed by ptr.


B) You cannot change the pointer ptr itself.
C) Both (a) and (b).
D) You can change the pointer as well as the value pointed by it.
Answer: A

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


141
FAQ in C Language - Prepared by Ms.P.Edreena

30. What is the output for the following program?


#include <stdio.h>
void foo(int*);
int main()
{
int i = 10, *p = &i;
foo(p++);
}
void foo(int *p)
{
printf("%d\n", *p);
}
A) 10 B) Some garbage value
C) Compile time error D) Segmentation fault

Answer: A
If suppose the statement, foo(p++); is written as foo((&i)++); then it will end up with
compile time error.

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


142
FAQ in C Language - Prepared by Ms.P.Edreena

CHAPTER 8

STRINGS

❖ The string in C programming language is actually a one-dimensional array of


characters which is terminated by a null character '\0'.
❖ The following declaration and initialization create a string consisting of the word
"Hello".
❖ To hold the null character at the end of the array, the size of the character array
containing the string is one more than the number of characters in the word "Hello."
❖ greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
❖ If you follow the rule of array initialization then you can write the above statement as
follows:
❖ char greeting[] = "Hello";
C supports a wide range of functions that manipulate null-terminated strings:
● strcpy(s1, s2);
Copies string s2 into string s1.
● strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
● strlen(s1);
Returns the length of string s1.
● strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
● strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
● strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
MULTIPLE CHOICE QUESTIONS:
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
143
FAQ in C Language - Prepared by Ms.P.Edreena

1. Which of the following function sets first n characters of a string to a given character?
A) strinit() B) strnset()
C) strset() D) strcset()
Answer: B

2. If the two strings are identical, then strcmp() function returns


A) -1 B) 1
C) 0 D) Yes
Answer: C
Explanation:
The strcmp return an int value that is
● if s1 < s2 returns a value < 0
● if s1 == s2 returns 0
● if s1 > s2 returns a value > 0

3. How will you print \n on the screen?


A) printf("\n"); B) echo "\\n";
C) printf('\n'); D) printf("\\n");
Answer: D

4. The library function used to find the last occurrence of a character in a string is
A) strnstr() B) laststr()
C) strrchr() D) strstr()
Answer: C

5. Which of the following function is used to find the first occurrence of a given string in
another string?
A)strchr() B)strrchr()
C)strstr() D)strnset()
Answer : C

6. Which of the following function is more appropriate for reading in a multi-word string?
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
144
FAQ in C Language - Prepared by Ms.P.Edreena

A) printf(); B) scanf();
C) gets(); D)puts();
Answer: C

7. What will be the output of the program ?


#include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "Hello", str2[20] = " World";
printf("%s\n", strcpy(str2, strcat(str1, str2)));
return 0;
}
A) Hello B) World
C) Hello World D)WorldHello
Answer: C
Explanation:
printf("%s\n", strcpy(str2, strcat(str1, str2)));
● strcat(str1, str2)) appends the string str2 to str1. The result will be stored in str1.
Therefore str1 contains "Hello World".
● strcpy(str2, "Hello World") it copies the "Hello World" to the variable str2.
Hence it prints "Hello World".

8. What will be the output of the program ?


#include<stdio.h>
int main()
{
char p[] = "%d\n";
p[1] = 'c';
printf(p, 65);
return 0;
}
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
145
FAQ in C Language - Prepared by Ms.P.Edreena

A) A B) a
C) c D) 65
Answer: A
Explanation:
● char p[] = "%d\n"; The variable p is declared as an array of characters and initialized
with string "%d".
● p[1] = 'c'; Here, we overwrite the second element of array p by 'c'. So array p becomes
"%c"
● printf(p, 65); becomes printf("%c", 65);
Therefore it prints the ASCII value of 65. The output is 'A'.

9. What will be the output of the program ?


#include<stdio.h>
#include<string.h>
int main()
{
printf("%d\n", strlen("123456"));
return 0;
}
A) 6 B) 12
C) 7 D) 2
Answer: A
Explanation:
The function strlen returns the number of characters in the given string. Therefore,
strlen("123456") returns 6.

10. What will be the output of the program ?


#include<stdio.h>
int main()
{
printf(5+"Good Morning\n");
return 0;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
146
FAQ in C Language - Prepared by Ms.P.Edreena

}
A) Good Morning B) Good
C) M D) Morning
Answer: D
Explanation:
printf(5+"Good Morning\n"); It skips the 5 characters and prints the given string.
Hence the output is "Morning"

11. What will be the output of the program ?


#include<stdio.h>
#include<string.h>
int main()
{
char str[] = "India\0\Blue\0";
printf("%s\n", str);
return 0;
}
A) Blue B) India
C) India Blue D) India\0Blue
Answer: B
Explanation:
printf("%s\n", str) displays the string str till it encounters a null character.

12. What will be the output of the program ?


#include<stdio.h>
int main()
{
int i;
char a[] = "\0";
if (printf("%s", a))
printf("The string is empty\n");
else
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
147
FAQ in C Language - Prepared by Ms.P.Edreena

printf("The string is not empty\n");


return 0;
}
A) The string is empty B) The string is not empty
C) No output D) 0
Answer: B
Explanation:
The function printf() returns the number of charecters printed on the console.
● char a[] = "\0"; The variable a is declared as an array of characters and it initialized
with "\0". It denotes that the string is empty.
● if(printf("%s", a)) The printf() statement does not print anything, so it returns
'0'(zero). Hence the if condition is failed.
In the else part it prints "The string is not empty".

13. What will be output when you will execute following c code?
#include<stdio.h>
void main()
{
char arr[7]="Network";
printf("%s",arr);
}
A) Network B) N
C) Garbage value D) Compilation error
Answer: C
Explanation:
Size of a character array should be one greater than the total number of characters in
any string which it stores. In c every string has one terminating null character. This represents
end of the string.
So in the string “Network” , there are 8 characters and they are
‘N’,’e’,’t’,’w’,’o’,’r’,’k’ and ‘\0’. Size of array arr is seven. So array arr will store only first
seven characters and it will note store a null character.

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


148
FAQ in C Language - Prepared by Ms.P.Edreena

%s in printf statement prints the stream of characters until it gets the first null
character. Since array arr has not stored any null character so it will print garbage value.

14. What will be output when you will execute following c code?
#include<stdio.h>
void main()
{
char arr[11]="The African Queen";
printf("%s",arr);
}
A) The African Queen B) The
C) The African D) Compilation error
Answer: D
Explanation:
Size of any character array cannot be less than the number of characters in any string
which it has assigned. Size of an array can be equal (excluding null character) or greater than
but never less than.

15. What will be output when you will execute following c code?
#include<stdio.h>
void main()
{
int const SIZE=5;
int expr;
double value[SIZE]={2.0,4.0,6.0,8.0,10.0};
expr=1|2|3|4;
printf("%f",value[expr]);
}
A) 2.000000 B) 4.000000
C) 8.000000 D) Compilation error
Answer: D
Explanation:
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
149
FAQ in C Language - Prepared by Ms.P.Edreena

Size of any array in c cannot be constantan variable.

16. What will be output when you will execute following c code?
#include<stdio.h>
void main()
{
char *ptr="cquestionbank";
printf("%d",-3[ptr]);
}
A) Garbage value B) -300
C) -101 D) Compilation error
Answer: C
Explanation:
-3[ptr]
=-*(3+ptr)
=-*(ptr+3)
=-ptr[3]
=-103 //ASCII value of character ‘e’ is 103

17. What does the following fragment of C-program print?


char c[] = "GATE2011";
char *p =c;
printf("%s", p + p[3] - p[1]) ;
A) GATE2011 B) E2011
C) 2011 D) 011
Answer: C
Explanation:
char c[] = "GATE2011";
● p now has the base address string "GATE2011"
char *p = c;
● p[3] is 'E' and p[1] is 'A'.
● p[3] - p[1] = ASCII value of 'E' - ASCII value of 'A' = 4
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
150
FAQ in C Language - Prepared by Ms.P.Edreena

● So the expression p + p[3] - p[1] becomes p + 4 which is


● base address of string "2011"
printf("%s", p + p[3] - p[1]);
● prints 2011

18. In below program, what would you put in place of “?” to print “Quiz”?
#include <stdio.h>
int main()
{
char arr[] = "GeeksQuiz";
printf("%s", ?);
return 0;
}
A) arr B) (arr+5)
C) (arr+4) D) Not possible
Answer: B
Explanation:
Since %s is used, the printf statement will print everything starting from arr+5 until it
finds ‘\0’

19. Consider the following C program segment:


char p[20];
char *s = "string";
int length = strlen(s);
int i;
for (i = 0; i < length; i++)
p[i] = s[length — i];
printf("%s", p);
The output of the program is?
A) gnirts B) gnirt
C) string D) no output is printed
Answer: D
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
151
FAQ in C Language - Prepared by Ms.P.Edreena

Explanation:
Let us consider the line below the for loop
● p[i] = s[length — i];
For i = 0, p[i] will be s[6 — 0] and s[6] is ‘\0′
So p[0] becomes ‘\0’. It doesn’t matter what comes in p[1], p[2]….. as P[0] will not change
for i >0. Nothing is printed if we print a string with first character ‘\0′

19. Assume that a character takes 1 byte. What is the output of the following program?
#include<stdio.h>
int main()
{
char str[20] = "GeeksQuiz";
printf ("%d", sizeof(str));
return 0;
}
A) 9 B) 10
C) 20 D) Garbage Value
Answer: C
Explanation:
The sizeof() operator would return the size of the array. To get size of the string stored
in array, we need to use strlen().

20. Consider the following C program segment.


# include <stdio.h>
int main( )
{
char s1[7] = "1234", *p;
p = s1 + 2;
*p = '\0' ;
printf ("%s", s1);
}
What will be printed by the program?
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
152
FAQ in C Language - Prepared by Ms.P.Edreena

A) 12 B) 120400
C) 1204 D) 1034
Answer: A
Explanation:
char s1[7] = "1234", *p;
p = s1 + 2; // p holds address of character 3
*p = '\0' ; // memory at s1 now becomes "12\034"
printf ("%s", s1); // All characters till \0 are printed

21. Output of following C program? Assume that all necessary header files are included
int main()
{
char *s1 = (char *)malloc(50);
char *s2 = (char*) malloc(50);
strcpy(s1, "strings");
strcpy(s2, "Quiz");
strcat(s1, s2);
printf("%s", s1);
return 0;
}
A) stringsQuiz B) stringss
C) strings Quiz D) Quiz
Answer: A

22. What will be the output of the program?


#include<stdio.h>
#include<string.h>
int main()
{
static char str1[] = "dills";
static char str2[20];
static char str3[] = "Daffo";
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
153
FAQ in C Language - Prepared by Ms.P.Edreena

int i;
i = strcmp(strcat(str3, strcpy(str2, str1)), "Daffodills");
printf("%d\n", i);
return 0;
}
A) 0 B) 1 C) 2 D) 4
Answer: A

23. What will be the output of the program?


#include<stdio.h>
int main()
{
static char s[25] = "The cocaine man";
int i=0;
char ch;
ch = s[++i];
printf("%c", ch);
ch = s[i++];
printf("%c", ch);
ch = i++[s];
printf("%c", ch);
ch = ++i[s];
printf("%c", ch);
return 0;
}
A) hhe! B) he c C) The c D) Hhec
Answer: A

24. If the size of pointer is 4 bytes then What will be the output of the program?
#include<stdio.h>
int main()
{
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
154
FAQ in C Language - Prepared by Ms.P.Edreena

char *str[] = {"Frogs", "Do", "Not", "Die", "They", "Croak!"};


printf("%d, %d", sizeof(str), strlen(str[0]));
return 0;
}
A) 22, 4 B) 25, 5 C) 24, 5 D) 20, 2
Answer: C
Explanation:
Step 1: char *str[] = {"Frogs", "Do", "Not", "Die", "They", "Croak!"}; The variable str is
declared as an pointer to the array of 6 strings.
Step 2: printf("%d, %d", sizeof(str), strlen(str[0]));
sizeof(str) denotes 6 * 4 bytes = 24 bytes. Hence it prints '24'
strlen(str[0])); becomes strlen(Frogs)). Hence it prints '5';
Hence the output of the program is 24, 5

Hint: If you run the above code in 16 bit platform (Turbo C under DOS) the output will be
12, 5, because the pointer occupies only 2 bytes. If you run the above code in Linux (32 bit
platform), the output will be 24, 5 (because the size of pointer is 4 bytes).

25. Which of the following statements are correct about the program below?
#include<stdio.h>
int main()
{
char str[20], *s;
printf("Enter a string\n");
scanf("%s", str);
s=str;
while(*s != '\0')
{
if(*s >= 97 && *s <= 122)
*s = *s-32;
s++;
}
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
155
FAQ in C Language - Prepared by Ms.P.Edreena

printf("%s",str);
return 0;
}
A) The code converts a string in to an integer
B) The code converts lower case character to upper case
C) The code converts upper case character to lower case
D) Error in code
Answer: B

CHAPTER 9

STRUCTURES AND UNIONS

STRUCTURE
Structure is the collection of variables of different types under a single name for better
handling.
For example: You want to store the information about person about his/her name,
citizenship number and salary.

Structure Definition in C:
Keyword struct is used for creating a structure.
Syntax of Structure:
struct structure_name
{
data_type member1;
data_type member2;

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


156
FAQ in C Language - Prepared by Ms.P.Edreena

..
data_type memeber;
};
Example:
struct person
{
char name[50];
int cit_no;
float salary;
};

UNIONS
Unions are quite similar to the structures in C. Union is also a derived type as
structure. Union can be defined in same manner as structures just the keyword used in
defining union in union where keyword used in defining structure was struct.
Example:
union car
{
char name[50];
int price;
};

Difference Between Structure and Union:


Structure Union
1.The keyword struct is used to define a 1. The keyword union is used to define a
structure union.
2. When a variable is associated with a structure, 2. When a variable is associated with a
the compiler allocates the memory for each union, the compiler allocates the
member. The size of structure is greater than or memory by considering the size of the
equal to the sum of sizes of its members. The largest memory. So, size of union is equal
smaller members may end with unused slack to the size of largest member.
bytes.
3. Each member within a structure is assigned 3. Memory allocated is shared by
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
157
FAQ in C Language - Prepared by Ms.P.Edreena

unique storage area of location. individual members of union.


4. The address of each member will be in 4. The address is same for all the
ascending order This indicates that memory for members of a union. This indicates that
each member will start at different offset values. every member begins at the same offset
value.
5 Altering the value of a member will not affect 5. Altering the value of any of the
other members of the structure. member will alter other member values.
6. Individual member can be accessed at a time 6. Only one member can be accessed at a
time.
7. Several members of a structure can initialize at 7. Only the first member of a union can
once. be initialized.

MULTIPLE CHOICE QUESTIONS:

1. Which of the following are themselves a collection of different data types?


A. string
B. structures
C. char
D. All of the mentioned
Answer: B

2. User-defined data type can be derived by___________.


A. struct
B. enum
C. typedef
D. All of the mentioned
Answer: D

3. Which operator connects the structure name to its member name?


A. -
B. <-
C. .
D. Both (b) and (c)
Answer: C
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
158
FAQ in C Language - Prepared by Ms.P.Edreena

4. Which of the following cannot be a structure member?


A. Another structure
B. Function
C. Array
D. None of the mentioned
Answer: B

5. Which of the following structure declaration will throw an error?


A. struct temp{}s;
main(){}
B. struct temp{};
struct temp s;
main(){}
C. struct temp s;
struct temp{};
main(){}
D. None of the mentioned
Answer: D

6. What is the output of this C code?


#include <stdio.h>
struct student
{
int no;
char name[20];
}
void main()
{
struct student s;
s.no = 8;
printf("hello");
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
159
FAQ in C Language - Prepared by Ms.P.Edreena

}
A. Compile time error
B. Nothing
C. hello
D. Varies
Answer: A
Explanation: diff struct variables should not be assigned using "=" operator.

7. What is the output of the program?


#include<stdio.h>
void main()
{
struct s1 {int i; };
struct s2 {int i; };
struct s1 st1;
struct s2 st2;
st1.i =5;
st2 = st1;
printf(" %d " , st2.i);
}
Answer : nothing (error)
Explanation: diff struct variables should not be assigned using "=" operator.

8. What is the output of the program?


#include‹stdio.h›
int main()
{
struct site
{
char name[] = "GeeksQuiz";
int no_of_pages = 200;
};
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
160
FAQ in C Language - Prepared by Ms.P.Edreena

struct site *ptr;


printf("%d ", ptr->no_of_pages);
printf("%s", ptr->name);
getchar();
return 0;
}
A. 200 GeeksQuiz
B. 200
C. Runtime Error
D. Compiler Error
Answer: D

Explanation: When we declare a structure or union, we actually declare a new data type
suitable for our purpose. So we cannot initialize values as it is not a variable declaration but a
data type declaration.

9. What is the output of the following C program?


#include<stdio.h>
struct Point
{
int x, y, z;
};
int main()
{
struct Point p1 = {.y = 0, .z = 1, .x = 2};
printf("%d %d %d", p1.x, p1.y, p1.z);
return 0;
}
A. Compiler Error
B. 2 0 1
C. 0 1 2
D. 2 1 0
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
161
FAQ in C Language - Prepared by Ms.P.Edreena

Answer: B
Explanation: This type of initialization is called as Designated Initialization, which allows
the structure members to be initialized in any order. This feature is not available in C++ and
works only in C.

10. What is the output of the following C program?


Assume that the size of an integer is 4 bytes and size of character is 1 byte. Also
assume that there is no alignment needed.
union test
{
int x;
char arr[4];
int y;
};
int main()
{
union test t;
t.x = 0;
t.arr[1] = 'G';
printf("%s", t.arr);
return 0;
}
A. Nothing is printed
B. G
C. Garbage character followed by ‘G’
D. Garbage character followed by ‘G’, followed by more garbage characters

Answer: A
Explanation: Since x and arr[4] share the same memory, when we set x = 0, all characters of
arr are set as 0. O is ASCII value of ‘\0′. When we do “t.arr[1] = ‘G'”, arr[] becomes
“\0G\0\0″. When we print a string using “%s”, the printf function starts from the first

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


162
FAQ in C Language - Prepared by Ms.P.Edreena

character and keeps printing till it finds a \0. Since the first character itself is \0, nothing is
printed.

11. What is the output of the following C program?


Assume that the size of an integer is 4 bytes and size of character is 1 byte. Also
assume that there is no alignment needed.
union test
{
int x;
char arr[8];
int y;
};
int main()
{
printf("%d", sizeof(union test));
return 0;
}
A. 12
B. 16
C. 8
D. Compiler Error

Answer: C
Explanation:
When we declare a union, memory allocated for a union variable of the type is equal
to memory needed for the largest member of it, and all members share this same memory
space. In above example, “char arr[8]” is the largest member. Therefore size of union test is 8
bytes.

12. Which of the following operators can be applied on structure variables?


A. Equality comparison ( = = )
B. Assignment ( = )
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
163
FAQ in C Language - Prepared by Ms.P.Edreena

C. Both of the above


D. None of the above
Answer: B
Explanation:
A structure variable can be assigned to other using =, but cannot be compared with
other using = =.

13. What is the output of the following program?


#include<stdio.h>
struct st
{
int x;
struct st next;
};
int main()
{
struct st temp;
temp.x = 10;
temp.next = temp;
printf("%d", temp.next.x);
return 0;
}
A. Compiler Error
B. 10
C. Runtime Error
D. Garbage Value

Answer: A
Explanation:
A structure cannot contain a member of its own type because if this is allowed then it
becomes impossible for compiler to know size of such struct. Although a pointer of same type

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


164
FAQ in C Language - Prepared by Ms.P.Edreena

can be a member because pointers of all types are of same size and compiler can calculate
size of struct.

14. Consider the following C declaration

Struct
{
short s[5];
union
{
float y;
long z;
}u;
} t;
Assume that objects of the type short, float and long occupy 2 bytes, 4 bytes and 8
bytes, respectively. The memory requirement for variable t, ignoring alignment
considerations, is
A. 22 bytes
B. 14 bytes
C. 18 bytes
D. 10 bytes
Answer: C
Explanation:
Short array s[5] will take 10 bytes as size of short is 2 bytes. When we declare a
union, memory allocated for the union is equal to memory needed for the largest member of
it, and all members share this same memory space. Since u is a union, memory allocated to u
will be max of float y(4 bytes) and long z(8 bytes). So, total size will be 18 bytes (10 + 8).

15. struct node


{
int i;
float j;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
165
FAQ in C Language - Prepared by Ms.P.Edreena

};
struct node *s[10];

The above C declaration define ‘s’ to be


A. An array, each element of which is a pointer to a structure of type node
B. A structure of 2 fields, each field being a pointer to an array of 10 elements
C. A structure of 3 fields: an integer, a float, and an array of 10 elements
D. An array, each element of which is a structure of type node.
Answer: A

16. Assume that size of an integer is 32 bit. What is the output of following program?
#include<stdio.h>
struct st
{
int x;
static int y;
};
int main()
{
printf("%d", sizeof(struct st));
return 0;
}
A. 4
B. 8
C. Compiler Error
D. Runtime Error
Answer: C
Explanation: In C, struct and union types cannot have static members.

17. What will be output of following c code?


void main()
{
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
166
FAQ in C Language - Prepared by Ms.P.Edreena

struct world
{
int a;
char b;
struct india
{
char c;
float d;
}p;
};
struct world st ={1,'A','i',1.8};
clrscr();
printf("%d\t%c\t%c\t%f",st.a,st.b,st.p.c,st.p.d);
getch();
}
Answer: 1 A I 1.800000
Explanation:
Nesting of structure is possible i.e. we can declare a structure within another structure
but it is necessary that an inner structure must declare a structure variable otherwise we can
not access the data member of the inner structure.

18. What will be output of following c code?


void main()
{
struct india
{
char c;
float d;
};
struct world
{
int a[3];
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
167
FAQ in C Language - Prepared by Ms.P.Edreena

char b;
struct india orissa;
};
struct world st ={{1,2,3},'P','q',1.4};
clrscr();
printf("%d\t%c\t%c\t%f",st.a[1],st.b,st.orissa.c,st.orissa.d);
getch();
}
Answer: 2 p q 1.400000

19. Which of the following comment about the usage of structures in true?
A. Storage class can be assigned to individual member
B. Individual members can be initialized within a structure type declaration
C. The scope of the member name is confined to the particular structure, within which it
is defined.
D. None of above
Answer: C
Explanation:
Structure is user defined data type which is used to store heterogeneous data under
unique name.

20. Which of the following comment about Union is false?


A. Union is a structure whose members share same memory area
B. The compiler will keep track of what type of information is currently stored
C. Only one of the members of union can be assigned a value at particular time
D. Size allocated for Union is the size of its member needing the maximum storage
Answer: B
Explanation:
Union is similar to structure the only difference is the way the memory allocated to
structure and union

21. Which of the following is a collection of different data types?


PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
168
FAQ in C Language - Prepared by Ms.P.Edreena

A. String
B. Array
C. Structure
D. Files
Answer: C
Explanation:
Structure is a user defined data type which contains the variables of different data
types.

22. For accessing a structure element using a pointer,you must use?


A. Pointer operator (&)
B. Dot operators(.)
C. Pointer operator(*)
D. Arrow operator(->)
Answer: D
Explanation:
For accessing the structure element using pointers arrow operator is used otherwise
dot operator is used.
23. Which operator is used to connect structure name to its member name?
A. dot operator(.)
B. logical operator(&&)
C. pointer operator(&)
D. Arrow operator(->)
Answer: A
24. A bit field is
A. A pointer variable in a structure.
B. One bit or a set of adjacent bits within a word
C. A pointer variable in a union
D. Not used in C
Answer: B
25. Union differs from structure in the following way
A. All members are used at a time
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
169
FAQ in C Language - Prepared by Ms.P.Edreena

B. Only one member can be used at a time


C. Union cannot have more members
D. Union initialized all members as structure
Answer: B
26. struct
{
int x;
int y;
}abc;

You cannot access x by the following.


1.. abc -> x
2. abc[0] ->x
3. abc.x
4. (abc) ->x
A. Option 1,2 and 4
B. Option 2 and 3
C. Option 1 and 3
D. Option 1,3 and 4
Answer: A
27. struct customer *ptr = malloc( sizeof( struct customer));
Given the sample allocation for the pointer ”ptr” found, which statement would be
used to reallocate ptr to be an array of 10 element?

A. ptr = realloc( ptr, 10 * sizeof( sizeof customer));


B. ptr = realloc( ptr, 9 * sizeof( struct customer) );
C. realloc(ptr, 9 * sizeof(struct customer));
D. realloc( ptr, 10 * sizeof( struct customer));
Answer: A

28. About structure which of the following is true.


1. Structure members are aligned in memory depending on their data type.
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
170
FAQ in C Language - Prepared by Ms.P.Edreena

2. The size of a structure may not be equal to the sum of the size of its members.
A. Only option 1
B. Only option 2
C. Both option 1 and 2
D. Neither option 1 nor 2
Answer: C

CHAPTER 10

FREQUENTLY ASKED PROGRAMS

1. Fibonacci series:
We assume first two Fibonacci are 0 and 1. A series of numbers in which each
sequence number is sum of its two previous numbers is known as Fibonacci series and each
numbers are called Fibonacci numbers. So Fibonacci numbers is
Algorithm for Fibonacci series
Fn = Fn-2 + Fn-1
Example of Fibonacci series:
0 , 1 ,1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 ...
5 is Fibonacci number since sum of its two previous number i.e. 2 and 3 is 5
8 is Fibonacci number since sum of its two previous number i.e. 3 and 5 is 8 and so on.
Code 1:
#include<stdio.h>
int main()
{
int k,r;
long int i=0l, j=1, f;
//Taking maximum numbers form user
printf("Enter the number range:");
scanf("%d",&r);
printf("FIBONACCI SERIES: ");

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


171
FAQ in C Language - Prepared by Ms.P.Edreena

printf("%ld %ld",i,j); //printing first two values.


for(k=2;k<r;k++)
{
f=i+j;
i=j;
j=f;
printf(" %ld",j);
}
return 0;
}

Sample output:
Enter the number range: 15
FIBONACCI SERIES: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Code 2: Using Arrays


#include<stdio.h>
int main()
{
int i,range;
long int arr[40];
printf("Enter the number range: ");
scanf("%d",&range);
arr[0]=0;
arr[1]=1;
for(i=2;i<range;i++)
{
arr[i] = arr[i-1] + arr[i-2];
}
printf("Fibonacci series is: ");
for(i=0;i<range;i++)
printf("%ld ",arr[i]);
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
172
FAQ in C Language - Prepared by Ms.P.Edreena

return 0;
}
Sample output:
Enter the number range: 20
Fibonacci series is: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
610 987 1597 2584 4181

2. Check given number is prime number or not using c program


Prime number:
A natural number greater than 1 has not any other divisors except 1 and itself. In other
word we can say which has only two divisors 1 and number itself.
For example: 5
Their divisors are 1 and 5.
Note: 2 is only even prime number.
Logic for prime number in c
We will take a loop and divide number from 2 to number/2. If the number is not
divisible by any of the numbers then we will print it as prime number.
Example of prime numbers : 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163,
167, 173, 179, 181, 191, 193, 197, 199 etc.

Code 1:
#include<stdio.h>
int main()
{
int num,i,count=0;
printf("Enter a number: ");
scanf("%d",&num);
for(i=2;i<=num/2;i++)
{
if(num%i==0)
{
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
173
FAQ in C Language - Prepared by Ms.P.Edreena

count++;
break;
}
}
if(count==0 && num!= 1)
printf("%d is a prime number",num);
else
printf("%d is not a prime number",num);
return 0;
}

Sample output:
Enter a number: 5
5 is a prime number

Code 2:
#include<stdio.h>
int main()
{
int num,i,count,n;
printf("Enter max range: ");
scanf("%d",&n);
for(num = 1;num<=n;num++)
{
count = 0;
for(i=2;i<=num/2;i++)
{
if(num%i==0)
{
count++;
break;
}
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
174
FAQ in C Language - Prepared by Ms.P.Edreena

}
if(count==0 && num!= 1)
printf("%d ",num);
}
return 0;
}

Sample output:
Enter max range: 50
2 3 5 7 11 13 17 19 23 29 31 37 41 43
47

3. Factorial value
Factorial of number is defined as:
Factorial (n) = 1*2*3 … * n
For example: Factorial of 5 = 1*2*3*4*5 = 120
Note: Factorial of zero = 1
Code 1:
#include<stdio.h>
int main()
{
int i,f=1,num;
printf("Enter a number: ");
scanf("%d",&num);
for(i=1;i<=num;i++)
f=f*i;
printf("Factorial of %d is: %d",num,f);
return 0;
}

Sample output:
Enter a number: 5
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
175
FAQ in C Language - Prepared by Ms.P.Edreena

Factorial of 5 is: 120

Code 2: Using Functions


#include<stdio.h>
int findFactorial(int);
int main()
{
int i,factorial,num;
printf("Enter a number: ");
scanf("%d",&num);
factorial = findFactorial(num);
printf("Factorial of %d is: %d",num,factorial);
return 0;
}
int findFactorial(int num)
{
int i,f=1;
for(i=1;i<=num;i++)
f=f*i;
return f;
}

Sample output:
Enter a number: 8
Factorial of 8 is: 40320

4. Palindrome number
A number is called palindrome number if it is remain same when its digits are
reversed. For example 121 is palindrome number. When we will reverse its digit it will
remain same number i.e. 121

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


176
FAQ in C Language - Prepared by Ms.P.Edreena

Examples: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121,
131, 141, 151, 161, 171, 181, 191 etc.
#include<stdio.h>
int main()
{
int num,r,sum=0,temp;
printf("Enter a number: ");
scanf("%d",&num);
temp=num;
while(num)
{
r=num%10;
num=num/10;
sum=sum*10+r;
}
if(temp==sum)
printf("%d is a palindrome",temp);
else
printf("%d is not a palindrome",temp);
return 0;
}

Sample output:
Enter a number: 131
131 is a palindrome

Code 2: Using recursion


#include<stdio.h>
int checkPalindrome(int);
int main()
{
int num,sum;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
177
FAQ in C Language - Prepared by Ms.P.Edreena

printf("Enter a number: ");


scanf("%d",&num);
sum = checkPalindrome(num);
if(num==sum)
printf("%d is a palindrome",num);
else
printf("%d is not a palindrome",num);
return 0;
}
int checkPalindrome(int num)
{
static int sum=0,r;
if(num!=0)
{
r=num%10;
sum=sum*10+r;
checkPalindrome(num/10);
}
return sum;
}

Sample output:
Enter a number: 25
25 is not a palindrome

5. Reverse any number


#include<stdio.h>
int main()
{
int num,r,reverse=0;
printf("Enter any number: ");
scanf("%d",&num);

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


178
FAQ in C Language - Prepared by Ms.P.Edreena

while(num)
{
r=num%10;
reverse=reverse*10+r;
num=num/10;
}
printf("Reversed of number: %d",reverse);
return 0;
}

Sample output:
Enter any number: 12
Reversed of number: 21

Code 2: Using Recursion


#include<stdio.h>
int main()
{
int num,reverse;
printf("Enter any number: ");
scanf("%d",&num);
reverse=rev(num);
printf("Reverse of number: %d",reverse);
return 0;
}
int rev(int num)
{
static sum,r;
if(num)
{
r=num%10;
sum=sum*10+r;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
179
FAQ in C Language - Prepared by Ms.P.Edreena

rev(num/10);
}
else
return 0;
return sum;
}

Sample output:
Enter any number: 456
Reverse of number: 654

6. Sum of Digits of a number


#include<stdio.h>
int main()
{
int num,sum=0,r;
printf("Enter a number: ");
scanf("%d",&num);
while(num)
{
r=num%10;
num=num/10;
sum=sum+r;
}
printf("Sum of digits of number: %d",sum);
return 0;
}

Sample output:
Enter a number: 123
Sum of digits of number: 6

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


180
FAQ in C Language - Prepared by Ms.P.Edreena

Code 2: Using recursion


#include<stdio.h>
int getSum(int);
int main()
{
int num,sum;
printf("Enter a number: ");
scanf("%d",&num);
sum = getSum(num);
printf("Sum of digits of number: %d",sum);
return 0;
}
int getSum(int num)
{
static int sum =0,r;
if(num!=0)
{
r=num%10;
sum=sum+r;
getSum(num/10);
}
return sum;
}

Sample output:
Enter a number: 45
Sum of digits of number: 9

7. Reverse String
Code 1:
#include<stdio.h>
int main()

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


181
FAQ in C Language - Prepared by Ms.P.Edreena

{
char str[50];
char rev[50];
int i=-1,j=0;
printf("Enter any string : ");
scanf("%s",str);
while(str[++i]!='\0');
while(i>=0)
rev[j++] = str[--i];
rev[j]='\0';
printf("Reverse of string is : %s",rev);
return 0;
}

Sample output:
Enter any string : cquestionbank.blogspot.com
Reverse of string is : moc.topsgolb.knabnoitseuqc

Code 2: Using Pointers


#include<stdio.h>
int main()
{
char str[50];
char rev[50];
char *sptr = str;
char *rptr = rev;
int i=-1;
printf("Enter any string : ");
scanf("%s",str);
while(*sptr)
{
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
182
FAQ in C Language - Prepared by Ms.P.Edreena

sptr++;
i++;
}
while(i>=0)
{
sptr--;
*rptr = *sptr;
rptr++;
--i;
}
*rptr='\0';
printf("Reverse of string is : %s",rev);
return 0;
}

Sample output:
Enter any string : Pointer
Reverse of string is : retnioP

8. Largest Among n numbers


#include<stdio.h>
int main()
{
int n,num,i;
int big;
printf("Enter the values of n: ");
scanf("%d",&n);
printf("Number %d",1);
scanf("%d",&big);
for(i=2;i<=n;i++)
{
printf("Number %d: ",i);
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
183
FAQ in C Language - Prepared by Ms.P.Edreena

scanf("%d",&num);
if(big<num)
big=num;
}
printf("Largest number is: %d",big);
return 0;
}

Sample Output:
Enter the values of n: 3
Number 1: 12
Number 2: 32
Number 3: 35
Largest number is: 35

9. Program to print “hello world” without using semicolon


Code 1:
#include<stdio.h>
void main()
{
if(printf("Hello world"))
{
}
}

Code 2:
#include<stdio.h>
void main()
{
while(!printf("Hello world"))
{
}
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
184
FAQ in C Language - Prepared by Ms.P.Edreena

Code 3:
#include<stdio.h>
void main()
{
switch(printf("Hello world"))
{
}
}

10. Armstrong number


Those numbers which sum of the cube of its digits is equal to that number are known
as Armstrong numbers.
For example 153 since 1^3 + 5^3 + 3^3 = 1+ 125 + 9 =153
Other armstrong numbers: 370,371,407 etc.

Example 1: 153
Total digits in 153 is 3
AND 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
Example 2: 1634
Total digits in 1634 is 4
And 1^4 + 6^4 + 3^4 +4^4 = 1 + 1296 + 81 + 64 =1634

Examples of Armstrong numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208,


9474, 54748, 92727, 93084, 548834, 1741725

#include<stdio.h>
int main()
{
int num,r,sum=0,temp;
printf("Enter a number: ");
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
185
FAQ in C Language - Prepared by Ms.P.Edreena

scanf("%d",&num);
temp=num;
while(num!=0)
{
r=num%10;
num=num/10;
sum=sum+(r*r*r);
}
if(sum==temp)
printf("%d is an Armstrong number",temp);
else
printf("%d is not an Armstrong number",temp);
return 0;
}

Sample output:
Enter a number: 153
153 is an Armstrong number

Program for finding Armstrong number


#include<stdio.h>
int main()
{
int num,r,sum,temp;
for(num=1;num<=500;num++)
{
temp=num;
sum = 0;
while(temp!=0)
{
r=temp%10;
temp=temp/10;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
186
FAQ in C Language - Prepared by Ms.P.Edreena

sum=sum+(r*r*r);
}
if(sum==num)
printf("%d ",num);
}
return 0;
}

Output:
1 153 370 371 407

11. Concatenation of 2 strings using Pointers


#include<stdio.h>
int main()
{
int i=0,j=0;
char *str1,*str2,*str3;
puts("Enter first string");
gets(str1);
puts("Enter second string");
gets(str2);
printf("Before concatenation the strings are\n");
puts(str1);
puts(str2);
while(*str1)
{
str3[i++]=*str1++;
}
while(*str2)
{
str3[i++]=*str2++;
}
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
187
FAQ in C Language - Prepared by Ms.P.Edreena

str3[i]='\0';
printf("After concatenation the strings are\n");
puts(str3);
return 0;
}

12. Program for sorting of strings


#include<stdio.h>
int main()
{
int i,j,n;
char str[20][20],temp[20];
puts("Enter the no. of string to be sorted");
scanf("%d",&n);
for(i=0;i<=n;i++)
gets(str[i]);
for(i=0;i<=n;i++)
for(j=i+1;j<=n;j++)
{
if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
printf("The sorted string\n");
for(i=0;i<=n;i++)
puts(str[i]);
return 0;
}

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


188
FAQ in C Language - Prepared by Ms.P.Edreena

13. Counting different characters in a string


#include <stdio.h>
int isvowel(char chk);
int main()
{
char text[1000], chk;
int count;
count = 0;
while((text[count] = getchar()) != '\n')
count++;
text[count] = '\0';
count = 0;
while ((chk = text[count]) != '\0')
{
if (isvowel(chk))
{
if((chk = text[++count]) && isvowel(chk))
{
putchar(text[count -1]);
putchar(text[count]);
putchar('\n');
}
}
else
++count;
}
return 0;
}
int isvowel(char chk)
{
if(chk == 'a' || chk == 'e' || chk == 'i' || chk == 'o' || chk == 'u')
return 1;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
189
FAQ in C Language - Prepared by Ms.P.Edreena

return 0;
}

14. LCM (Least Common Multiple)


LCM of two integers is a smallest positive integer which is multiple of both integers
that it is divisible by the both of the numbers.
Example: LCM of two integers 2 and 5 is 10 since 10 is the smallest positive numbers which
is divisible by both 2 and 5.
#include<stdio.h>
int main()
{
int n1,n2,x,y;
printf("\nEnter two numbers:");
scanf("%d %d",&n1,&n2);
x=n1,y=n2;
while(n1!=n2)
{
if(n1>n2)
n1=n1-n2;
else
n2=n2-n1;
}
printf("L.C.M=%d",x*y/n1);
return 0;
}

15. HCF (Highest common factor):


HCF is also called greatest common divisor (gcd). HCF of two numbers is a largest
positive numbers which can divide both numbers without any remainder.
Example: HCF of two numbers 4 and 8 is 2 since 2 is the largest positive number which can
dived 4 as well as 8 without a remainder.
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
190
FAQ in C Language - Prepared by Ms.P.Edreena

In HCF we try to find any largest number which can divide both the number.
For example: HCF or GCD of 20 and 30
Both number 20 and 30 are divisible by 1, 2,5,10.
HCF=max (1, 2, 3, 4, 10) =10

Logic for writing program:


It is clear that any number is not divisible by greater than number itself. In case of
more than one numbers, a possible maximum number which can divide all of the numbers
must be minimum of all of that numbers.

For example: 10, 20, and 30


Min (10, 20, 30) =10 can divide all three numbers. So we will take one for loop which
will start form min of the numbers and will stop the loop when it became one, since all
numbers are divisible by one. Inside for loop we will write one if conditions which will check
divisibility of both the numbers.

Code 1:
#include<stdio.h>
int main()
{
int x,y,m,i;
printf("Insert any two number: ");
scanf("%d%d",&x,&y);
if(x>y)
m=y;
else
m=x;
for(i=m;i>=1;i--)
{
if(x%i==0&&y%i==0)
{
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
191
FAQ in C Language - Prepared by Ms.P.Edreena

printf("\nHCF of two number is : %d",i) ;


break;
}
}
return 0;
}

Code 2:
#include<stdio.h>
int main()
{
int n1,n2;
printf("\nEnter two numbers:");
scanf("%d %d",&n1,&n2);
while(n1!=n2)
{
if(n1>=n2-1)
n1=n1-n2;
else
n2=n2-n1;
}
printf("\nGCD=%d",n1);
return 0;
}

16. Selection Sort


#include<stdio.h>
int main()
{
int s,i,j,temp,a[20];
printf("Enter total elements: ");
scanf("%d",&s);
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
192
FAQ in C Language - Prepared by Ms.P.Edreena

printf("Enter %d elements: ",s);


for(i=0;i<s;i++)
scanf("%d",&a[i]);
for(i=0;i<s;i++)
{
for(j=i+1;j<s;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("After sorting is: ");
for(i=0;i<s;i++)
printf(" %d",a[i]);
return 0;
}

Output:
Enter total elements: 5
Enter 5 elements: 4 5 0 2 1 7
The array after sorting is: 0 4 5 7 2 1

17. Quick Sort


QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the
given array around the picked pivot. There are many different versions of quickSort that pick
pivot in different ways.

 Always pick first element as pivot.


 Always pick last element as pivot (implemented below)
 Pick a random element as pivot.
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
193
FAQ in C Language - Prepared by Ms.P.Edreena

 Pick median as pivot.

The key process in quickSort is partition(). Target of partitions is, given an array and an
element x of array as pivot, put x at its correct position in sorted array and put all smaller
elements (smaller than x) before x, and put all greater elements (greater than x) after x. All
this should be done in linear time.

Working of Quick sort:

Program:
#include<stdio.h>
void quicksort(int [10],int,int);
int main()
{
int x[20],size,i;
printf("Enter size of the array: ");
scanf("%d",&size);
printf("Enter %d elements: ",size);
for(i=0;i<size;i++)
scanf("%d",&x[i]);
quicksort(x,0,size-1);
printf("Sorted elements: ");
for(i=0;i<size;i++)
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
194
FAQ in C Language - Prepared by Ms.P.Edreena

printf(" %d",x[i]);
return 0;
}
void quicksort(int x[10],int first,int last)
{
int pivot,j,temp,i;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(x[i]<=x[pivot]&&i<last)
i++;
while(x[j]>x[pivot])
j--;
if(i<j)
{
temp=x[i];
x[i]=x[j];
x[j]=temp;
}
}
temp=x[pivot];
x[pivot]=x[j];
x[j]=temp;
quicksort(x,first,j-1);
quicksort(x,j+1,last);
}
}
Output:
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
195
FAQ in C Language - Prepared by Ms.P.Edreena

Enter size of the array: 5


Enter 5 elements: 3 8 0 1 2
Sorted elements: 0 1 2 3 8

Complexity Analysis:
Worst Case Time Complexity : O(n2)
Best Case Time Complexity : O(n log n)
Average Time Complexity : O(n log n)
Space Complexity : O(n log n)

18. Insertion Sort

It is a simple Sorting algorithm which sorts the array by shifting elements one by one.
Following are some of the important characteristics of Insertion Sort.

1. It has one of the simplest implementation


2. It is efficient for smaller data sets, but very inefficient for larger lists.

3. Insertion Sort is adaptive, that means it reduces its total number of steps if given a
partially sorted list, hence it increases its efficiency.

4. It is better than Selection Sort and Bubble Sort algorithms.

5. Its space complexity is less, like Bubble Sorting, inerstion sort also requires a single
additional memory space.

6. It is Stable, as it does not change the relative order of elements with equal keys

Program:

#include<stdio.h>
int main()
{
int i,j,s,temp,a[20];
printf("Enter total elements: ");
scanf("%d",&s);
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
196
FAQ in C Language - Prepared by Ms.P.Edreena

printf("Enter %d elements: ",s);


for(i=0;i<s;i++)
scanf("%d",&a[i]);
for(i=1;i<s;i++)
{
temp=a[i];
j=i-1;
while((temp<a[j])&&(j>=0))
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=temp;
}
printf("After sorting: ");
for(i=0;i<s;i++)
printf(" %d",a[i]);
return 0;
}

Working of Insertion sort:

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


197
FAQ in C Language - Prepared by Ms.P.Edreena

Output:
Enter total elements: 5
Enter 5 elements: 3 7 9 0 2
After sorting: 0 2 3 7 9

Complexity Analysis:

Worst Case Time Complexity : O(n2)

Best Case Time Complexity : O(n)

Average Time Complexity : O(n2)

Space Complexity : O(1)

19. Bubble Sort

Bubble Sort is an algorithm which is used to sort N elements that are given in a memory for
eg: an Array withN number of elements. Bubble Sort compares all the element one by one
and sort them based on their values.

It is called Bubble sort, because with each iteration the smaller element in the list bubbles up
towards the first place, just like a water bubble rises up to the water surface.

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


198
FAQ in C Language - Prepared by Ms.P.Edreena

Sorting takes place by stepping through all the data items one-by-one in pairs and comparing
adjacent data items and swapping each pair that is out of order.

Program:
#include<stdio.h>
int main()
{
int s,temp,i,j,a[20];
printf("Enter total numbers of elements: ");
scanf("%d",&s);
printf("Enter %d elements: ",s);
for(i=0;i<s;i++)
scanf("%d",&a[i]);
//Bubble sorting algorithm
for(i=s-2;i>=0;i--)
{
for(j=0;j<=i;j++)
{
if(a[j]>a[j+1])
{
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
199
FAQ in C Language - Prepared by Ms.P.Edreena

temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("After sorting: ");
for(i=0;i<s;i++)
printf(" %d",a[i]);
return 0;
}
Output:
Enter total numbers of elements: 5
Enter 5 elements: 6 2 0 11 9
After sorting: 0 2 6 9 11

Complexity Analysis:

Complexity of Bubble Sort is O(n2).

Space complexity for Bubble Sort is O(1)

Best-case Time Complexity will be O(n), it is when the list is already sorted.

20. Merge Sort

Merge Sort follows the rule of Divide and Conquer. But it doesn't divides the list into two
halves. In merge sort the unsorted list is divided into N sublists, each having one element,
because a list of one element is considered sorted. Then, it repeatedly merge these sublists, to
produce new sorted sublists, and at lasts one sorted list is produced.

Merge Sort is quite fast, and has a time complexity of O(n log n). It is also a stable sort,
which means the "equal" elements are ordered in the same order in the sorted list.

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


200
FAQ in C Language - Prepared by Ms.P.Edreena

Program:

#include<stdio.h>
#define MAX 50
void mergeSort(int arr[],int low,int mid,int high);
void partition(int arr[],int low,int high);
int main()
{
int merge[MAX],i,n;
printf("Enter the total number of elements: ");
scanf("%d",&n);
printf("Enter the elements which to be sort: ");
for(i=0;i<n;i++)
{
scanf("%d",&merge[i]);
}
partition(merge,0,n-1);

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


201
FAQ in C Language - Prepared by Ms.P.Edreena

printf("After merge sorting elements are: ");


for(i=0;i<n;i++)
{
printf("%d ",merge[i]);
}
return 0;
}
void partition(int arr[],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
partition(arr,low,mid);
partition(arr,mid+1,high);
mergeSort(arr,low,mid,high);
}
}
void mergeSort(int arr[],int low,int mid,int high)
{
int i,m,k,l,temp[MAX];
l=low;
i=low;
m=mid+1;
while((l<=mid)&&(m<=high))
{
if(arr[l]<=arr[m])
{
temp[i]=arr[l];
l++;
}
else
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
202
FAQ in C Language - Prepared by Ms.P.Edreena

{
temp[i]=arr[m];
m++;
}
i++;
}
if(l>mid)
{
for(k=m;k<=high;k++)
{
temp[i]=arr[k];
i++;
}
}
else
{
for(k=l;k<=mid;k++)
{
temp[i]=arr[k];
i++;
}
}
for(k=low;k<=high;k++)
{
arr[k]=temp[k];
}
}
Sample output:
Enter the total number of elements: 5
Enter the elements which to be sort: 2 5 0 9 1
After merge sorting elements are: 0 1 2 5 9
Complexity Analysis:
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
203
FAQ in C Language - Prepared by Ms.P.Edreena

Worst Case Time Complexity : O(n log n)

Best Case Time Complexity : O(n log n)

Average Time Complexity : O(n log n)

Space Complexity : O(n)

21. Linear Search


A linear search is the basic and simple search algorithm. A linear search searches an element
or value from an array till the desired element or value is not found and it searches in a
sequence order. It compares the element with all the other elements given in the list and if the
element is matched it returns the value index else it return -1. Linear Search is applied on the
unsorted or unordered list when there are fewer elements in a list.
Program:
#include<stdio.h>
int main()
{
int a[10],i,n,m,c=0;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i=0;i<=n-1;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the number to be search: ");
scanf("%d",&m);
for(i=0;i<=n-1;i++)
{
if(a[i]==m)
{
c=1;
break;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
204
FAQ in C Language - Prepared by Ms.P.Edreena

}
}
if(c==0)
printf("The number is not in the list");
else
printf("The number is found");
return 0;
}

Sample output:
Enter the size of an array: 5
Enter the elements of the array: 4 6 8 0 3
Enter the number to be search: 0
The number is found

22. Binary Search

Binary Search is applied on the sorted array or list. In binary search, we first compare the
value with the elements in the middle position of the array. If the value is matched, then we
return the value. If the value is less than the middle element, then it must lie in the lower half
of the array and if it's greater than the element then it must lie in the upper half of the array.
We repeat this procedure on the lower (or upper) half of the array. Binary Search is useful
when there are large numbers of elements in an array.

To search an element 13 from the sorted array or list.

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


205
FAQ in C Language - Prepared by Ms.P.Edreena

Program:
#include<stdio.h>
int main()
{
int a[10],i,n,m,c=0,l,u,mid;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements in ascending order: ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the number to be search: ");
scanf("%d",&m);
l=0,u=n-1;
while(l<=u)
{
mid=(l+u)/2;
if(m==a[mid])
{

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


206
FAQ in C Language - Prepared by Ms.P.Edreena

c=1;
break;
}
else if(m<a[mid])
{
u=mid-1;
}
else
l=mid+1;
}
if(c==0)
printf("The number is not found.");
else
printf("The number is found.");
return 0;
}

Sample output:
Enter the size of an array: 5
Enter the elements in ascending order: 4 7 8 11 21
Enter the number to be search: 11
The number is found.

23. Swapping of Strings


#include<stdio.h>
int main()
{
int i=0,j=0,k=0;
char str1[20],str2[20],temp[20];
puts("Enter first string");
gets(str1);
puts("Enter second string");
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
207
FAQ in C Language - Prepared by Ms.P.Edreena

gets(str2);
printf("Before swaping the strings are\n");
puts(str1);
puts(str2);
while(str1[i]!='\0')
{
temp[j++]=str1[i++];
}
temp[j]='\0';
i=0,j=0;
while(str2[i]!='\0')
{
str1[j++]=str2[i++];
}
str1[j]='\0';
i=0,j=0;
while(temp[i]!='\0')
{
str2[j++]=temp[i++];
}
str2[j]='\0';
printf("After swaping the strings are\n");
puts(str1);
puts(str2);
return 0;
}

24. Swapping of two arrays


#include<stdio.h>
int main()
{
int a[10],b[10],c[10],i;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
208
FAQ in C Language - Prepared by Ms.P.Edreena

printf("Enter First array->");


for(i=0;i<10;i++)
scanf("%d",&a[i]);
printf("\nEnter Second array->");
for(i=0;i<10;i++)
scanf("%d",&b[i]);
printf("Arrays before swapping");
printf("\nFirst array->");
for(i=0;i<10;i++)
{
printf("%d",a[i]);
}
printf("\nSecond array->");
for(i=0;i<10;i++)
{
printf("%d",b[i]);
}
for(i=0;i<10;i++)
{
//write any swapping technique
c[i]=a[i];
a[i]=b[i];
b[i]=c[i];
}
printf("\nArrays after swapping");
printf("\nFirst array->");
for(i=0;i<10;i++)
{
printf("%d",a[i]);
}
printf("\nSecond array->");
for(i=0;i<10;i++)
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
209
FAQ in C Language - Prepared by Ms.P.Edreena

{
printf("%d",b[i]);
}
return 0;
}

25. Swap two variables without using third using c program variable
#include<stdio.h>
int main()
{
int a=5,b=10;
//process one
a=b+a;
b=a-b;
a=a-b;
printf("a= %d b= %d",a,b);
//process two
a=5;b=10;
a=a+b-(b=a);
printf("\na= %d b= %d",a,b);
//process three
a=5;b=10;
a=a^b;
b=a^b;
a=b^a;
printf("\na= %d b= %d",a,b);
//process four
a=5;b=10;
a=b-~a-1;
b=a+~b+1;
a=a+~b+1;
printf("\na= %d b= %d",a,b);
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
210
FAQ in C Language - Prepared by Ms.P.Edreena

//process five
a=5,b=10;
a=b+a,b=a-b,a=a-b;
printf("\na= %d b= %d",a,b);
return 0;
}

26. Binary to Decimal conversion


Binary number system: It is base 2 number system which uses the digits from 0 and 1.
Decimal number system: It is base 10 number system which uses the digits from 0 to
9
Conversion:
For this we multiply each digit separately from right side by 1, 2, 4, 8, 16 …
respectively then add them.
Example: convert binary number 101111 to decimal:
Step1: 1 * 1 = 1
Step2: 1 * 2 = 2
Step3: 1 * 4 = 4
Step4: 1 * 8 = 8
Step5: 0 * 16 = 0
Step6: 1 * 32 = 32
Its decimal value: 1 + 2 + 4+ 8+ 0+ 32 = 47
That is (101111)2 = (47)10

#include<stdio.h>
int main()
{
long int binaryNumber,decimalNumber=0,j=1,remainder;
printf("Enter any number any binary number: ");
scanf("%ld",&binaryNumber);
while(binaryNumber!=0)
{
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
211
FAQ in C Language - Prepared by Ms.P.Edreena

remainder=binaryNumber%10;
decimalNumber=decimalNumber+remainder*j;
j=j*2;
binaryNumber=binaryNumber/10;
}
printf("Equivalent decimal value: %ld",decimalNumber);
return 0;
}

Sample output:
Enter any number any binary number: 1101
Equivalent decimal value: 13

27. Stack operations:


Stack is an abstract data type with a bounded(predefined) capacity. It is a simple data
structure that allows adding and removing elements in a particular order. Every time an
element is added, it goes on the top of the stack, the only element that can be removed is the
element that was at the top of the stack, just like a pile of objects.

1. Stack is an ordered list of similar data type.


2. Stack is a LIFO structure. (Last in First out).

3. push() function is used to insert new elements into the Stack and pop() is used to
delete an element from the stack. Both insertion and deletion are allowed at only one end
of Stack called Top.
4. Stack is said to be in Overflow state when it is completely full and is said to be
in Underflow state if it is completely empty.

Position of Top Status of Stack

-1 Stack is Empty

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


212
FAQ in C Language - Prepared by Ms.P.Edreena

0 Only one element in Stack

N-1 Stack is Full

N Overflow state of Stack

Analysis of Stack:

Below mentioned are the time complexities for various operations that can be performed on the
Stack data structure.

 Push Operation : O(1)


 Pop Operation : O(1)

 Top Operation : O(1)

 Search Operation : O(n)

Program:

#include <stdio.h>
#define MAXSIZE 5
struct stack
{
int stk[MAXSIZE];
int top;
};
typedef struct stack STACK;
STACK s;
void push(void);
int pop(void);
void display(void);

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


213
FAQ in C Language - Prepared by Ms.P.Edreena

void main ()
{
int choice;
int option = 1;
s.top = -1;
printf ("STACK OPERATION\n");
while (option)
{
printf (" 1 --> PUSH \n");
printf (" 2 --> POP \n");
printf (" 3 --> DISPLAY \n");
printf (" 4 --> EXIT \n");
printf ("Enter your choice\n");
scanf ("%d", &choice);
switch (choice)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
return;
}
fflush (stdin);
printf ("Do you want to continue(Type 0 or 1)?\n");
scanf ("%d", &option);
}
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
214
FAQ in C Language - Prepared by Ms.P.Edreena

}
/* Function to add an element to the stack */
void push ()
{
int num;
if (s.top == (MAXSIZE - 1))
{
printf ("Stack is Full\n");
return;
}
else
{
printf ("Enter the element to be pushed\n");
scanf ("%d", &num);
s.top = s.top + 1;
s.stk[s.top] = num;
}
return;
}
/* Function to delete an element from the stack */
int pop ()
{
int num;
if (s.top == - 1)
{
printf ("Stack is Empty\n");
return (s.top);
}
else
{
num = s.stk[s.top];
printf ("poped element is = %dn", s.stk[s.top]);
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
215
FAQ in C Language - Prepared by Ms.P.Edreena

s.top = s.top - 1;
}
return(num);
}
/* Function to display the status of the stack */
void display ()
{
int i;
if (s.top == -1)
{
printf ("Stack is empty\n");
return;
}
else
{
printf ("\n The status of the stack is \n");
for (i = s.top; i >= 0; i--)
{
printf ("%d\n", s.stk[i]);
}
}
printf ("\n");
}

28. Queue Operations

Queue is also an abstract data type or a linear data structure, in which the first element is
inserted from one end called REAR(also called tail), and the deletion of exisiting element
takes place from the other end called as FRONT(also called head). This makes queue as
FIFO data structure, which means that element inserted first will also be removed first.

The process to add an element into queue is called Enqueue and the process of removal of an
element from queue is called Dequeue.

Analysis of Queue:
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
216
FAQ in C Language - Prepared by Ms.P.Edreena

 Enqueue : O(1)
 Dequeue : O(1)

 Size : O(1)

Implementation of Queue

Queue can be implemented using an Array, Stack or Linked List. The easiest way of
implementing a queue is by using an Array. Initially the head(FRONT) and the tail(REAR)
of the queue points at the first index of the array (starting the index of array from 0). As we
add elements to the queue, the tail keeps on moving ahead, always pointing to the position
where the next element will be inserted, while the head remains at the first index.

Program:
#include<stdio.h>
#include<conio.h>
#define MAX 10
int queue[MAX],front=-1,rear=-1;
void insert_element();
void delete_element();
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
217
FAQ in C Language - Prepared by Ms.P.Edreena

void display_queue();
int main()
{
int option;
printf(">>> c program to implement queue operations <<<");
do
{
printf("\n\n 1.Insert an element");
printf("\n 2.Delete an element");
printf ("\n 3.Display queue");
printf("\n 4.Exit");
printf("\n Enter your choice: ");
scanf("%d",&option);
switch(option)
{
case 1: insert_element();
break;
case 2: delete_element();
break;
case 3: display_queue();
break;
case 4: return 0;
}
}while(option!=4);
}
void insert_element()
{
int num;
printf("\n Enter the number to be inserted: ");
scanf("%d",&num);
if(front==0 && rear==MAX-1)
printf("\n Queue OverFlow Occured");
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
218
FAQ in C Language - Prepared by Ms.P.Edreena

else if(front==-1&&rear==-1)
{
front=rear=0;
queue[rear]=num;
}
else if(rear==MAX-1 && front!=0)
{
rear=0;
queue[rear]=num;
}
else
{
rear++;
queue[rear]=num;
}
}
void delete_element()
{
int element;
if(front==-1)
{
printf("\n Underflow");
}
element=queue[front];
if(front==rear)
front=rear=-1;
else
{
if(front==MAX-1)
front=0;
else
front++;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
219
FAQ in C Language - Prepared by Ms.P.Edreena

printf("\n The deleted element is: %d",element);


}
}
void display_queue()
{
int i;
if(front==-1)
printf("\n No elements to display");
else
{
printf("\n The queue elements are:\n ");
for(i=front;i<=rear;i++)
{
printf("\t %d",queue[i]);
}
}
}
29. Creating a Linked List & displaying the elements of the list .
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
void main()
{
struct node
{
int num;
struct node *ptr;
};
typedef struct node NODE;
NODE *head, *first, *temp = 0;
int count = 0;
int choice = 1;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
220
FAQ in C Language - Prepared by Ms.P.Edreena

first = 0;
while (choice)
{
head = (NODE *)malloc(sizeof(NODE));
printf("Enter the data item\n");
scanf("%d", &head-> num);
if (first != 0)
{
temp->ptr = head;
temp = head;
}
else
{
first = temp = head;
}
fflush(stdin);
printf("Do you want to continue(Type 0 or 1)?\n");
scanf("%d", &choice);
}
temp->ptr = 0;
/* reset temp to the beginning */
temp = first;
printf("\n status of the linked list is\n");
while (temp != 0)
{
printf("%d=>", temp->num);
count++;
temp = temp -> ptr;
}
printf("NULL\n");
printf("No. of nodes in the list = %d\n", count);
}
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
221
FAQ in C Language - Prepared by Ms.P.Edreena

30. Read a linked list in reverse


#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node *next;
};
void create(struct node **);
void reversedisplay(struct node *);
void release(struct node **);
void display(struct node *);
int main()
{
struct node *p = NULL;
struct node_occur *head = NULL;
int n;
printf("Enter data into the list\n");
create(&p);
printf("Displaying the nodes in the list:\n");
display(p);
printf("Displaying the list in reverse:\n");
reversedisplay(p);
release(&p);

return 0;
}
void reversedisplay(struct node *head)
{
if (head != NULL)
{
reversedisplay(head->next);
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
222
FAQ in C Language - Prepared by Ms.P.Edreena

printf("%d\t", head->num);
}
}
void create(struct node **head)
{
int c, ch;
struct node *temp, *rear;
do
{
printf("Enter number: ");
scanf("%d", &c);
temp = (struct node *)malloc(sizeof(struct node));
temp->num = c;
temp->next = NULL;
if (*head == NULL)
{
*head = temp;
}
else
{
rear->next = temp;
}
rear = temp;
printf("Do you wish to continue [1/0]: ");
scanf("%d", &ch);
} while (ch != 0);
printf("\n");
}
void display(struct node *p)
{
while (p != NULL)
{
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
223
FAQ in C Language - Prepared by Ms.P.Edreena

printf("%d\t", p->num);
p = p->next;
}
printf("\n");
}

void release(struct node **head)


{
struct node *temp = *head;
*head = (*head)->next;
while ((*head) != NULL)
{
free(temp);
temp = *head;
(*head) = (*head)->next;
}
}
31. Program to add the sum of the elements in the matrix.

# include <stdio.h>
# include <conio.h>
void main()
{
int mat[10][10] ;
int i, j, row, col, sum = 0 ;
clrscr() ;
printf("Enter the order of the matrix : ") ;
scanf("%d %d", &row, &col) ;
printf("\nEnter the elements of the matrix : \n\n") ;
for(i = 0 ; i < row ; i++)
for(j = 0 ; j < col ; j++)
scanf("%d", &mat[i][j]) ;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
224
FAQ in C Language - Prepared by Ms.P.Edreena

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


for(j = 0 ; j < col ; j++)
sum = sum + mat[i][j] ;
printf("\nThe sum of the elements in the matrix is : %d", sum) ;
getch() ;
}
Output of above program -

Enter the order of the matrix : 3 3


Enter the elements of the matrix :
1 2 3
4 5 6
7 8 9
The sum of the elements in the matrix is : 45
32. Program to add the diagonal elements in a matrix
# include <stdio.h>
# include <conio.h>
void main()
{
int mat[10][10] ;
int i, j, size, sum = 0 ;
clrscr() ;
printf("Enter size of the square matrix : ") ;
scanf("%d", &size) ;
printf("\nEnter the elements of the matrix : \n\n") ;
for(i = 0 ; i < size ; i++)
for(j = 0 ; j < size ; j++)
scanf("%d", &mat[i][j]) ;
for(i = 0 ; i < size ; i++)
sum = sum + mat[i][i] ;
printf("\nThe sum of diagonal elements in the matrix is : %d",
sum) ;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
225
FAQ in C Language - Prepared by Ms.P.Edreena

getch() ;
}

Output of the above program -

Enter size of the square matrix : 3


Enter the elements of the matrix :
1 2 3
4 5 6
7 8 9
The sum of diagonal elements in the matrix is : 15

CHAPTER 11
COMPANIES CRITICAL SOLVED QUESTIONING PAPERS

Here are few solved questions of major companies who go for engineering colleges
recruitment drive.
1) Hexaware
2) CSC

HEXAWARE PLACEMENT PAPER

1. What error would the following function give on compilation?


f( int a, int b)
{

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


226
FAQ in C Language - Prepared by Ms.P.Edreena

int a;
a=20;
return a;
}
a) Missing parantheses in return statement
b) The function should be defined as int f(int a, int b)
c) Redeclaration of a
d) None of these
Ans: c

2. What is the output of the following c program?


main()
{
Char Str1[]=”Hello”;
Char Str2[]=”Hello”;
if (str1==str2)
printf(“\n equal”);
else
printf(“\n unequal”);

a) Equal
b) unequal
c) error
d) None Ans: b

3. What is the output of the following c program ?


main()
{
char ch=’A’;
printf(“%d%d”,sizeof(ch), sizeof(‘A’));
}

a) 1 1
b) 1 2
c) 2 2
d) 2 1
Ans: b

4. If the following program(myprog) is run from the command line as “myprog 1 2 3”


without quotes, what would be the output?
main(int argc, char *argv[])
{
int I;
i=argv[1]+argv[2]+argv[3];
printf(“%d”,i);
}

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


227
FAQ in C Language - Prepared by Ms.P.Edreena

a) 1 2 3
b) 6
c) error
d) ”123”
Ans:c

5. What is the output of the following c program?


main()
{
unsigned int m=32;
printf(“%x”,~m);
}

a) ffff
b) 0000
c) ffdf
d) ddff
Ans:c

6. What is the output of the following c program?


main()
{
int y=128;
const int x=y;
printf(“%d”,x);
}

a) 128
b) Garbage value
c) error
d) 0
Ans:a

7. In a c program constant is defined


a) Before main
b) After main
c) Anywhere but starting on a new line
d) None of these
Ans:c

8. Which of the following statements is incorrect?


a) C provides no I/O features
b) C provides no file access features
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
228
FAQ in C Language - Prepared by Ms.P.Edreena

c) Provides no features to manipulate composite objects


d) All the above
Ans:d

9. If y of integer type, then the expression 3*(y-8)/9 and (y-8)/9*3 yields the same value
if
a) y is an even number
b) y is a odd number
c) (y-8) is an integer multiple of 9
d) (y-8) is an integer multiple of 3
Ans: c

10. In c programming language x-= y+1; means


a) x=x-y+1
b) x=-x-y-1
c) x=-x+y+1
d) x=x-y-1
Ans:a
11. The decimal equilvalent for the hexadecimal number E5 is
a) 279 b) 229 c.) 427 d.)3000
Ans:b

12. The greatest negative number which can be stored in computer that has 8 bit word
length and uses 2’s compliment arithematic is
a) -256 b) -255 c) -128 d) -127
Ans:c

13. Which of the following pairs of regular expression are not equivalent?
a) (ab)*a and a(ba)*
b) (a+b)* and (a*+b)*
c) b*ab*a(a+b)*
d) all of these
Ans:d

14. which of the following is not possible algorithmically?


a) Regular grammar to CFG
b) Non deterministic FSA to deterministic FSA
c) Non deterministic PDA to deterministic PDA
d) Non deterministic turing machine to deterministic turing machine
Ans: d

15. If the address of the 8th element in a linked list of integers is 1022 then the address of
the 10th element is
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
229
FAQ in C Language - Prepared by Ms.P.Edreena

a) 1024 b) 1026 c) 1023 d) none


Ans: d

16. If max is a function that returns the larger of the two integers, given as arguments then
which of the following statements finds the largest of the three given numbers?
a) max (max(a,b), max(a,c))
b) max (max(a,b), max(b,c))
c) max (b,max(a,c))
d) all of these.
Ans:c

17. What is the output of the following program?


main()
{
int x=2, y=5;
if (x<y) return(x=x+y);
else printf(“z1”);
printf(“z2”);
}
a) z2 b) z1z2 c)compilation error d) none
Ans: d

18. Which of the following class constructor will be invoked first?


a) Base class
b) Virtual base class
c) Abstract class
d) Derived class
Ans: a

19. A function that can access private members of a class even though it is not a member
of the class itself is
a) A friend
b) An inline function
c) A private function
d) Never allowed in oops
Ans: a

20. The feature that allows the same operations to be carried out differently depending on
the objects is
a) Polymorphism
b) Polygamy
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
230
FAQ in C Language - Prepared by Ms.P.Edreena

c) Inheritance
d) Multitasking

21. The algorithm design technique used in the quick sort algorithm is
a) Dynamic programming
b) Backtracking
c) Divide and conquer
d) Greedy method

22. In a circular linked list organization, insertion of a record involves the modification of
a) No pointer
b) 1 pointer
c) 2 pointers
d) 3 pointers

23. The worst case time required to search a given element in a sorted linked list of length
n is
a) 0(1) b) 0(log2n) c) 0(n) d)0(n log2n)
Ans: c

24. The five items A,B,C,D and E are pushed in a stack, one after the other starting from
A. The stack is popped four times and each element is inserted in a queue. Then the
two elements are deleted from the queue and pushed back on the stack. Now one item
is popped from the stack. The popped item is
a) A b) B c) C d) D
Ans: d

Consider a logical address space of 8 pages of 1024 words mapped into memory of 32
frames
Ques 25 & 26 based on above assumptions

25. How many bits are there in the logical address?


a) 9 bits b) 11 bits c)13 bits d) 15 bits
Ans:c

26. How many bits are there in the physical address?


a) 9 bits b) 11 bits c)13 bits d) 15 bits
Ans:d

27. Communication between computers is almost always


a) Serial
b) parallel

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


231
FAQ in C Language - Prepared by Ms.P.Edreena

c) seriesparallel
d) direct
Ans:a

28. Which layer functions as a liaison between user support layers and network support
layers?
a) Network layer
b) Physical layer
c) Transport layer
d) Session layer
Ans:c

29. In session layer during data transfer the data stream responsible for the control
purpose is
a) Regular data
b) Typed data
c) Capability data
d) Extended data Ans:c
30. Which of the following requires a device driver?
a) Register
b) Cache
c) Main memory
d) Disk
Ans: d

31. Consider a machine with 64MB physical memory and 32 bit virtual address space. If
the page size is 4kb then the approximate size of the page table will be
a) 16MB
b) 8MB
c) 2MB
d) 24MB
Ans: c

32. The performance of the pipelined processor suffers if


a) The pipeline stages have different delays
b) Consecutive instruction are dependend on each other
c) The pipeline stages share hardware resources.
d) All of these
Ans:d

33. The optimal page replacement algorithm will select the page that
a) Has not been used for the longest time in the past
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
232
FAQ in C Language - Prepared by Ms.P.Edreena

b) Will not be used for the longest time in the future


c) Has been used for least number of times
d) Has been used most number of times.
Ans:

34. A processor needs software interrupt to


a) Test the interrupt system of the processor
b) Implement co-routines
c) Obtain system services which need execution ofpriviledged instructions
d) Return from subroutine.
Ans:

35. When a subroutine is called the address of the instruction following the CALL
instruction is stored in/on the
a) Stack pointer
b) Accumulator
c) Program counter
d) Stack
Ans: d

36. The depth of the complete binary tree with n nodes is


a) log(n+1)-1
b) log(n)
c) log(n-1+1
d) log(n)+1
Ans:a

37. The postfix equivalent of the prefix *+ab-cd is


a) ab+cd-*
b) abcd+-*
c) ab+cd*-
d) ab+-cd*
Ans:a

38. The minimum number of interchanges needed to convert the array 89, 19, 40, 17, 12,
10, 2, 5, 7, 11, 6, 9, 70 into a heap with maximum element at the root is
a) 1
b) 2
c) 3
d) None
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
233
FAQ in C Language - Prepared by Ms.P.Edreena

Ans:b

39. Heap allocation is required for languages


a) That supports recursion
b) That supports dynamic data structures
c) That uses dynamic scope rules
d) None
Ans:b

40. If each address space represents one byte of storage space how many address lines are
needed to access RAM chips arranged in 4*6 array where each chip is 8k*4bits
a) 13
b) 15
c) 16
d) 17 Ans:d

41. Consider a disk with the following characteristics:


Track size:10,000 bytes
Rotational latency: 10 ms/revolution
Block size: 1000 bytes
What is the maximum transfer rate per track measured in bits per second as is
conventional for this disk unit?
a) 400 Mbps
b) 8 Mbps
c) 6,400 Mbps
d) 4.250 Mbps
Ans: b

42. The ring counter is analogous to


a) Toggle switch
b) Latch
c) Stepping switch
d) S-R flip flop
Ans: c

43. Which of the following is termed as minimum error code?


a) Binary code
b) Gray code
c) Excess code
d) Octal code
Ans: b
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
234
FAQ in C Language - Prepared by Ms.P.Edreena

44. Which of the following four 4 bit numbers equal its 1 compliment?
a) 1010
b) 1000
c) No such number exists
d) None
Ans:d

45. The binary equivalent of decimal number 0.4375 is


a) 0.0111
b) 0.1011
c) 0.1100
d) 0.1010
Ans:a

46. A designer wants to design a point to point sub network with 10 routers of full duplex
line. Then the total number of lines among them would be
a) 10
b) 20
c) 45
d) 95
Ans: d

47. Which of the following is user defined function in c?


a) sqrt()
b) printf()
c) main()
d) none

48. the value of an automatic variable that is declared but not initialized will be
a) 0
b) -1
c) Garbage
d) 2

49. What will be the length of the following string using strlen()?
char str[20]=”Hello\rWorld”;
a) 5
b) 6
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
235
FAQ in C Language - Prepared by Ms.P.Edreena

c) 10
d) 11

50. What is the output of the following c program?


Void main()
{
const int x=get();
printf(“%d”,x);
}
int get()
{
return(20);
}
a) 20
b) Garbage value
c) Compile error
d) 0

51. What happens when an integer pointer (int *ptr) is increment (ptr=ptr+1)?
a) Its value incremented by 1
b) Pointer cannot be incremented
c) Segmentation fault
d) Pointer to the next element
Ans:a

52. The most appropriate matching for the following pairs


A) Indirect addressing 1. Loops
B) Immediate addressing 2. Pointers
C) Auto decrement addressing 3. Constants
A B C

a) 3 2 1
b) 1 3 2
c) 2 3 1
d) 3 1 2
Ans:c

53. Consider the statement int val[2][4]={1,2,3,4,5,6,7,8} 4 will be the value of


a) Val[1][4]
b) Val[0][4]
c) Val[1][1]
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
236
FAQ in C Language - Prepared by Ms.P.Edreena

d) None
Ans:d

54. Consider the following declaration:


int a, *b=&a, **c=&b;
The following program segment
a=4;
**c=5
a) Does not change the value of a
b) Assigns the address of c to a
c) Assign the value of b to a
d) Assign the value of 5 to a
Ans:d

55. What is the output of the program segment?


for(i=1;i<5;i++)
if(i===3)
continue;
else
printf(“%d”,i);
a) 1 2 4 5
b) 1 2 4
c) 2 4 5
d) None
Ans:b

56. Consider a set of n tasks with known runtime r1,r2,…rn. To be run on a uniprocessor
machine. Which of the following processor scheduling algorithm will result in the
maximum throughput?
a) Round robin
b) Shortest job first
c) Highest response ratio next
d) FCFS
Ans: b

57. What is the output of the following c program?


main()
{
int i=5;
if(i==5)
return 0;
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
237
FAQ in C Language - Prepared by Ms.P.Edreena

else
printf(“I is not five”);
printf(“over”);
}
a) Syntax error
b) Execution error
c) Prints over
d) Execution termination without printing anything

58. The following program


main()
{
inc(); inc(); inc();
}
inc()
{
static int x;
printf(“%d”,++x);
}
a) Print 0 1 2
b) Prints 1 2 3
c) Prints 3 consecutive but unpredictable numbers
d) Prints 1 1 1

59. The slowest transmission speeds are those of


a) twisted pair wire
b) Coaxial cable
c) Fiber optic cable
d) Microwaves
Ans:a

60. A central computer surrounded by one or more satellite computers is called a


a) Bus network
b) Ring network
c) Star network
d) Tri network
Ans:c

61. A distributed network configuration in which all data/information pass through a


central computer is
a) Bus network
b) Star network
c) Duplex
d) Multiplex
Ans:b

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


238
FAQ in C Language - Prepared by Ms.P.Edreena

62. Which of the following is a wrong example of a network layer?


a) X.25 level-2-ISO
b) Usenet
c) X.25 packet level protocol-ISO
d) IP
Ans: a

63. The data rate of the ISDN basic access B channel is


a) 32 kbps
b) 64 kbps
c) 144 kbps
d) 192 mbps
Ans:b

64. Which of the following data structure is mainly used during shift reduce parsing?
a) Pointers
b) Arrays
c) Tokens
d) Queues
Ans:d

65. Which sentence can be generated by


aas/bA, Ad/ccA
a) bccddd
b) abbbd
c) aabccd
d) ababccd
Ans:c

66. Hidden files in unix always begin with a character


a) $
b) .
c) #
d) #
Ans: b

67. Usage of index/indexes will improve the performance


a) Searching
b) Insertion
c) Sorting
d) Deletion
Ans: a

68. Give a situation where there is a list of grocery items out of which only one item can
be chosen. Which among the following uI element is the best choice?
a) Push button
b) Checkbox

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


239
FAQ in C Language - Prepared by Ms.P.Edreena

c) Text field
d) Drop down list
Ans: b

69. By default the vi editor opens up in which mode


a) Command mode
b) Insert mode
c) Escape mode
d) Depends on the file type
Ans: a

CSC(Computer Software Corporation)

1. ------- is associated with web services.


a) WSDL b) WML c) web sphere d) web logic
Ans: a

2. Any large single block of data stored in a database, such as a


picture or sound file, which does not include record fields, and
cannot be directly searched by the database's search engine.
a) TABLE
b) BLOB
c) VIEW
d) SCHEME
Ans: b

3.A reserved area of the immediate access memory used to increase the
running speed of the computer program.
a) session memory
b) bubble memory
c) cache memory
d) shared memory
Ans: c

4.A small subnet that sit between a trusted internal network and an
untruster external network, such as the public internet.
a) LAN
b) MAN
c) WAN
d) DMZ
Ans: d

5. Technologies that use radio waves to automatically identify people


or objects, which is very similar to the barcode identification
PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.
240
FAQ in C Language - Prepared by Ms.P.Edreena

systems, seen in retail stores everyday.


a) BLUETOOTH
b) RADAR
c) RSA SECURE ID
d) RFID
Ans: d

6.main(){
float fl = 10.5;
double dbl = 10.5
if(fl ==dbl)
printf("UNITED WE STAND");
else
printf("DIVIDE AND RULE")
}

What is the output?


a) compilation error
b) UNITED WE STAND
c) DIVIDE AND RULE
d) Linkage error.
Ans: c

7.main(){
static int ivar = 5;
printf("%d",ivar--);
if(ivar)
main();
}

What is the output?


a)1 2 3 4 5
b) 5 4 3 2 1
c)5
d) Compiler error:main cannot be recursive function.
Ans: b

8.main()
{
extern int iExtern;
iExtern = 20;
printf("%d",iExtern);
}

What is the output?


a)2
b) 20

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


241
FAQ in C Language - Prepared by Ms.P.Edreena

c) compile error
d) linker error
Ans: d

9..#define clrscr() 100


main(){
clrscr();
printf("%d\n\t", clrscr());
}

What is the output?


a)100 b)10 c)compiler errord)linkage error
Ans: a

10.main()
{
void vpointer;
char cHar = 'g', *cHarpointer = "GOOGLE";
int j = 40;
vpointer = &cHar;
printf("%c",*(char*)vpointer);
vpointer = &j;
printf("%d",*(int *)vpointer);
vpointer = cHarpointer;
printf("%s",(char*)vpointer +3);
}

What is the output?


a) g40GLE
b) g40GOOGLE
c) g0GLE
d) g4GOO
Ans: a

11.#define FALSE -1
#define TRUE 1
#define NULL 0
main() {
if(NULL)
puts("NULL");
else if(FALSE)
puts("TRUE");
else
puts("FALSE");
}

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


242
FAQ in C Language - Prepared by Ms.P.Edreena

What is the output?


a) NULL
b) TRUE
c) FALSE
d)0
Ans: b

12.main() {
int i =5,j= 6, z;
printf("%d",i+++j);
}

What is the output?


a)13
b)12
c)11
d) Compiler error
Ans: c

13.main() {
int i ;
i = accumulator();
printf("%d",i);
}
accumulator(){
_AX =1000
}

What is output?
a)1
b)10
c)100
d)1000
Ans: d

14.main() {
int i =0;
while(+(+i--)!= 0)
i- = i++;
printf("%d",i);
}

What is the output?


a) -1
b) 0
c) 1

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


243
FAQ in C Language - Prepared by Ms.P.Edreena

d) Will go in an infinite loop


Ans: a

15.main(){
int i =3;
for(; i++=0;)
printf(("%d",i);
}

What is the output?


a) 1
b) 2
c) 1 2 3
d) Compiler error : L value required.
Ans: d

16. main(){
int i = 10, j =20;
j = i ,j?(i,j)?i :j:j;
printf("%d%d",i,j);
}

What is the output?


a) 20 20
b) 20 10
c) 10 20
d) 10 10
Ans: d

17.main(){
extern i;
printf("%d\t",i);{
int i =20;
printf("%d\t",i);
}
}

What is the output?


a) "Extern valueof i " 20
b) Externvalue of i"
c) 20
d) linker Error: unresolved external symbol i
Ans: d

18.int DIMension(int array[]){


return sizeof(array/sizeof(int);}
main(){

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


244
FAQ in C Language - Prepared by Ms.P.Edreena

int arr[10];
printf("Array dimension is %d",DIMension(arr));
}

What is output?
a) array dimension is 10
b) array dimension is 1
c) array dimension is 2
d) array dimension is 5
Ans: b

19. main(){
void swap();
int x = 45, y = 15;
swap(&x,&y);
printf("x = %d y=%d"x,y);
}
void swap(int *a, int *b){
*a^=*b, *b^=*a, *a^ = *b;

What is the output?


a) x = 15, y =45
b) x =15, y =15
c) x =45 ,y =15
d) x =45 y = 45
Ans: a

20.main(){
int i =257;
int *iptr =&i;
printf("%d%d",*((char*)iptr),*((char *)iptr+1));
}

What is output?
a)1, 257
b)257 1c)0 0d)1 1
Ans: d

21.main(){
int i =300;
char *ptr = &i;
*++ptr=2;
printf("%d",i);
}

What is output?
a) 556

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


245
FAQ in C Language - Prepared by Ms.P.Edreena

b) 300
c) 2
d) 302
Ans: a

22.#include
main(){
char *str ="yahoo";
char *ptr =str;
char least =127;
while(*ptr++)
least = (*ptr
printf("%d",least);
}

What is the output?


a) 0
b)127
c) yahoo
d) y
Ans: a

23.Declare an array of M pointers to functions returing pointers to


functions returing pointers to characters.
a) (*ptr[M]()(char*(*)());
b) (char*(*)())(*ptr[M])()
c) (char*(*)(*ptr[M]())(*ptr[M]()
d) (char*(*)(char*()))(*ptr[M])();

24.void main(){
int I =10, j=2;
int *ip = &I ,*jp =&j;
int k = *ip/*jp;
printf("%d",k);
}

What is the output?


a) 2
b) 5
c) 10
d) compile error:unexpected end of file in comment started in line 4
Ans: d

25.main(){
char a[4] ="GOOGLE";
printf("%s",a);
}

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


246
FAQ in C Language - Prepared by Ms.P.Edreena

What is the output?


a) 2
b) GOOGLE
c) compile error: yoo mant initializers
d) linkage error.
Ans: c

26.For 1MB memory, the number of address lines required


a) 12
b) 16
c) 20
d) 32
Ans: 16

27.There is a circuit using 3 nand gates with 2 inputes and 1 output,f


ind the output.
a) AND
b) OR
c) XOR
d) NAND
Ans: b

28. What is done for push operation


a) SP is incremented and then the value is stored.
b) PC is incremented and then the value is stored.
c) PC is decremented and then the value is stored.
d) SP is decremented and then the value is stored.
Ans: d

29.Memory allocation of variables declared in a program is:


a) Allocated in RAM
b) Allocated in ROM
c) Allocated in stack
d) Assigned in registers.
Ans: c

30.What action is taken when the processer under execution is interrupted by TRAP in
8085MPU?
a) Processor serves the interrupt request after completing the
execution of the current instruction.
b) processer serves the interrupt request after completing the current task.
c) processor serves the interrupt immediately.
d) processor serving the interrupt request depent deprnds upon the
priority of the current task under execution.
Ans: a

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


247
FAQ in C Language - Prepared by Ms.P.Edreena

31.Purpose of PC (program counter)in a microprocessor is:


a) To store address of TOS(top of stack)
b) To store address of next instructions to be executed
c) count the number of instructions
d) to store the base address of the stack.
Ans: b

32.Conditional results after execution of an instruction in a microprocess is stored in


a) register
b) accumulator
c) flag register
d) flag register part of PSW (program status word)
Ans: c

33.The OR gate can be converted to the NAND function by adding----gate(s)to the input of
the OR gate.
a) NOT
b) AND
c) NOR
d) XOR
Ans: a

34. In 8051 microcontroller , has a dual function.


a) port 3
b) port 2
c) port 1
d) port 0
Ans: b

35.An 8085 based microprocessor with 2MHz clock frequency,will execute the following
chunk of code with how much delay?
MVI B,38H
HAPPY: MVI C, FFH
SADDY: DCR C
JNZ SADDY
DCR B
JNC HAPPY

a) 102.3
b)114.5
c)100.5
d)120

36.In 8085 MPU what will be the status of the flag after the execution of the following chunk
of code.
MVI B,FFH
MOV A,B

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


248
FAQ in C Language - Prepared by Ms.P.Edreena

CMA
HLT
a) S = 1, Z = 0, CY = 1
b) S = 0, Z = 1, CY = 0
c) S = 1, Z = 0, CY = 0
d) S = 1, Z = 1 ,CY = 1

37.A positive going pulse which is always generated when 8085 MPU begins the machine
cycle.
a) RD
b) ALE address latch enable…
c) WR
d) HOLD
Ans: b

38.When a ----- instruction of 8085 MPU is fetched , its second and third bytes are placed in
the W and Z registers.
a) JMP
b) STA
c) CALL
d) XCHG
Ans: c

39.what is defined as one subdivision of the operation performed in one clock period.
a) T- State
b) Instruction Cycle
c) Machine Cycle
d) All of the above
Ans: a

40.At the end of the following code, what is the status of the flags.
LXI B, AEC4H
MOV A,C
ADD HLT
a) S = 1, CY = 0, P = 0 , AC = 1
b) S =0 , CY = 1, P = 0,AC = 1
c) S = 0, CY = 1, P = 0 , AC = 1
d) S = 0, CY = 1, P = 1 , AC = 1

41.In 8051 micro controller what is the HEX number in the accumulator after the execution
of the following code.
MOV A,#0A5H
CLR C
RRC A
RRC A
RL A
RL A

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


249
FAQ in C Language - Prepared by Ms.P.Edreena

SWAP A
a)A6
b)6A
c)95
d)A5.
Ans: a

42.The Pentium processor requires ------------ volts.


a)9 b)12 c)5 d)24
ans; c

43. The data bus on the Celeron processor is-------bits wide.


a)64 b)32 c)16 d)128
Ans: a

44.K6 processor
a) Hitachi b) toshiba c) zilog d) AMD.
Ans: d

45. What is the control word for 8255 PPI,in BSR mode to set bit PC3.
a)0EH b)0FH c)07H d)06H.
Ans:c

46.The repeated execution of a loop of code while waiting for an event to occur is called
---------.The cpu is not engaged in any real productive activity during this period,and the
process doesn't progress towards completion.
a) dead lock b) busy waiting c) trap door d) none.
Ans: b

47. Transparent DBMS is defined as


a) A DBMS in which there are no program or user access languages.
b) A DBMS which has no cross file capabilities but is user friendly and
provides user interface management
. c) A DBMS which keeps its physical structure hidden from user
d) None.
Ans: c

48. Either all actions are carried out or none are. users should not have to worry about the
effect of incomplete transctions.DBMS ensures this by undoing the actions of incomplete
transctions.this property is known as
a) Aggregation b) atomicity c) association d) data integrity.
ans : B…

49.------ algorithms determines where in available to load a program. common methods are
first fit,next fit,best fit.--------- algorithm are used when memory is full , and one process (or
part of a process) needs to be swaped out to accommodate a new program.The -------------

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


250
FAQ in C Language - Prepared by Ms.P.Edreena

algorithm determines which are the partions to be swaped out.


a) placement, placement, replacement
b) replacement, placement, placement
c) replacement, placement, replacement
d) placement, replacement, replacement
Ans: D

50.Trap door is a secret undocumented entry point into a program used to grant access
without normal methods of access authentication. A trap is a software interrupt,usually the
result of an error condition.
a)true b)false.
Ans: A

51. Given a binary search tree,print out the nodes of the tree
according t5o post order traversal.
4
/\
25
/\
13
a)3,2,1,5,4. b)1,2,3,4,5. c)1,3,2,5,4. d)5,3,1,2,4. Ans: C

52.which one of the following is the recursive travel technique.


a)depth first search b)preorder c)breadth first search d)none.

d) none

53. In recursive implementations which of the following is true for


saving the state of the steps
a) as full state on the stack
b) as reversible action on the stack
c) both a and b
d) none

54.Which of the following involves context switch


a)previliged instruction
b)floating point exception
c)system calls
d)all
e)none
ans : c

55. Piggy backing is a technique for


a) acknowledge
b) sequence
c) flow control

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


251
FAQ in C Language - Prepared by Ms.P.Edreena

d) retransmission
ans:A

56. A functional dependency XY is ___________dependency if removal of any attribute A


from X means that the dependency does not hold any more
a)full functional
b) multi valued
c)single valued
d)none
ans : a

57) A relation schema R is in BCNF if it is in ___________and satisfies an additional


constraints that for every functional dependency XY,X must be a candidate key
a)1 NF
b)2 NF
c)3 NF
d)5 NF

58) a _________sub query can be easily identified if it contains any references to the parent
sub query columns in the _________ clause
A) correlated ,WHERE
b) nested ,SELECT
c) correlated,SELECT
d) none

59) Hybrid device that combines the features of both bridge and router is known as
a) router b) bridge c) hub d) brouter

60) Which of the following is the most crucial phase of SDLC


a)testing b)code generation c) analysys and design d)implementation
Ans: c

61) To send a data packet using datagram ,connection will be established


a)no connection is required
b) connection is not established before data transmission
c)before data transmission
d)none
Ans: c

62)A software that allows a personal computer to pretend as as computer terminal is


a) terminal adapter
b)terminal emulation
c)modem
d)none
Ans: b

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


252
FAQ in C Language - Prepared by Ms.P.Edreena

63) super key is


a) same as primary key
b) primary key and attribute
c) same as foreign key
d) foreign key and attribute
Ans: b

64. In binary search tree which traversal is used for ascending order values
a) Inorder b)preorder c)post order d)none
Ans: a

65 .You are creating an index on ROLLNO colume in the STUDENT table.which statement
will you use?
a) CREATE INDEX roll_idx ON student, rollno;
b) CREATE INDEX roll_idx FOR student, rollno;
c) CREATE INDEX roll_idx ON student( rollno);
d) CREATE INDEX roll_idx INDEX ON student (rollno);
Ans: c

66.A________class is a class that represents a data structure that stores a number of data
objects
a. container b.component c.base d.derived
Ans: a

67.Which one of the following phases belongs to the compiler Back-end.


a. Lexical Analysis b.Syntax Analysis c. Optimization d.Intermediate
Representation.
Ans: c

68.Every context _sensitive language is context_free


a. true b.false
Ans: b

69. Input:A is non-empty list of numbers L


Xß-infinity
For each item in the list L,do
If the item>x,then
Xß the item
Return X
X represents:-
a)largest number
b)smallest number
c)smallest negative number
d) none

70.Let A and B be nodes of a heap,such that B is a child of A. the heap must then satisfy the
following conditions

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


253
FAQ in C Language - Prepared by Ms.P.Edreena

a)key(A)>=key(B)
b)key(A)
c)key(A)=key(B)
d)none

71.String ,List,Stack,queue are examples of___________


a)primitive data type
b)simple data type
c)Abstract data type
d)none
Ans: c

72.Which of the following is not true for LinkedLists?


a)The simplest kind of linked list is a single linked list ,which has one link per node .this link
points to the next node in the list,or to a null value or emptylist if it is the last node.
b)a more sophisticated kind of linked list is a double linkedlist or two way linkedlist .Each
node has two links ,one to the previous node and one to the next node.
c) in a circleLinkedList ,the first and last nodes are linked together.this can be done only for
double linked list.
d) to traverse a circular linkedlist ,u begin at any node and follow the list in either direction
until u return to the original node.
Ans: c

73.Sentinel node at the beginning and /or at the end of the linkedlist
is not used to store the data
a) true
b) false
Ans:a

74.Point out the error in the following program


main()
{
const char *fun();
*fun()='A';
}
const char *fun()
{
return "Hello";
}Ans. fun() returns to a "const char" pointer which cannot be modified

75. What would be the output of the following program?


main()
{
const int x=5;
int *ptrx;
ptrx=&x;
*ptrx=10;

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


254
FAQ in C Language - Prepared by Ms.P.Edreena

printf("%d",x);
}
a) 5 b) 10 c) Error d) Garbage value
Ans: c

76. A switch statement cannot include


a) constants as arguments b) constant expression as arguments
c) string as an argument d) None of the above
Ans:d

77. How long the following program will run?


main()
{
printf("\nSonata Software");
main();
}
a) infinite loop b) until the stack overflows
c) All of the above
d) None of the above
Ans: b

78. Point out the error in the following program


main()
{
int a=10;
void f();
a=f();
printf("\n%d",a);
}
void f()
{
printf("\nHi");
}
Ans: The program is trying to collect the value of a "void" function into an integer variable.

79. Would the following program compile?


main()
{
int a=10,*j;
void *k;
j=k=&a;
j++;
k++;
printf("\n%u%u",j,k);
}
a) Yes b) No, the format is incorrect
c) No, the arithmetic operation is not permitted on void pointers

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


255
FAQ in C Language - Prepared by Ms.P.Edreena

d) No, the arithmetic operation is not permitted on pointers

80. According to ANSI specifications which is the correct way of declaring main() when it
receives command line arguments?
a) main(int argc, char *argv[]) b) main(argc,argv) int argc; char *argv[];
c) main() {int argc; char *argv[]; } d) None of the above
Ans:a

PETMS, Chennai. Training, Placement & Overseas Education. 91-9840649653.


256

You might also like