You are on page 1of 94

Programming Languages:

Computer Fundamentals Questions and


Answers – Algorithms
This set of Computer Fundamentals Multiple Choice Questions & Answers (MCQs) focuses
on “Algorithms”.

1. The word ____________comes from the name of a Persian mathematician Abu Ja’far
Mohammed ibn-i Musa al Khowarizmi.
a) Flowchart
b) Flow
c) Algorithm
d) Syntax
View Answer

Answer: c
Explanation: The word algorithm comes from the name of a Persian mathematician Abu
Ja’far Mohammed ibn-i Musa al Khowarizmi.

2. In computer science, algorithm refers to a special method usable by a computer for the
solution to a problem.
a) True
b) False
View Answer

Answer: a
Explanation: The statement is true. This word algorithm refers to a special method usable by
a computer for the solution to a problem. The statement of the problem specifies in general
terms the desired input/output relationship.

3. This characteristic often draws the line between what is feasible and what is impossible.
a) Performance
b) System Evaluation
c) Modularity
d) Reliability
View Answer

Answer: a
Explanation: Algorithms help us to understand scalability. Performance often draws the line
between what is feasible and what is impossible.

4. The time that depends on the input: an already sorted sequence that is easier to sort.
a) Process
b) Evaluation
c) Running
d) Input
View Answer

Answer: c
Explanation: The running time depends on the input: an already sorted sequence is easier to
sort. The running time is given by the size of the input, since short sequences are easier to
sort than the longer ones. Generally, we seek upper bounds on the running time, because it is
reliable.

5. Which of the following is incorrect?


Algorithms can be represented:
a) as pseudo codes
b) as syntax
c) as programs
d) as flowcharts
View Answer

Answer: b
Explanation: Representation of algorithms:
-As programs
-As flowcharts
-As pseudo codes.

6. When an algorithm is written in the form of a programming language, it becomes a


_________
a) Flowchart
b) Program
c) Pseudo code
d) Syntax
View Answer

Answer: b
Explanation: An algorithm becomes a program when it is written in the form of a
programming language. Thus, any program is an algorithm.

7. Any algorithm is a program.


a) True
b) False
View Answer

Answer: b
Explanation: The statement is false. An algorithm is represented in the form of a
programming language is called a program. Any program is an algorithm but the reverse is
not true.

8. A system wherein items are added from one and removed from the other end.
a) Stack
b) Queue
c) Linked List
d) Array
View Answer

Answer: b
Explanation: In a queue, the items are inserted from the rear end and deleted from the front
end.

9. Another name for 1-D arrays.


a) Linear arrays
b) Lists
c) Horizontal array
d) Vertical array
View Answer

Answer: a
Explanation: Linear arrays are the 1-Dimensional arrays wherein only one row is present and
the items are inserted.

10. A data structure that follows the FIFO principle.


a) Queue
b) LL
c) Stack
d) Union
View Answer

Answer: a
Explanation: The answer is Queue. A Queue follows the FIFO principle. FIFO stands for
First In First Out.

Flowcharts
This set of Computer Fundamentals Multiple Choice Questions & Answers (MCQs) focuses
on “Flowcharts”.

1. The symbol denotes _______

a) I/O
b) Flow
c) Terminal
d) Decision
View Answer

Answer: c
Explanation: The symbol denotes a terminal. It is used for indication of start and stop nodes
of a program.
2. In computer science, algorithm refers to a pictorial representation of a flowchart.
a) True
b) False
View Answer

Answer: b
Explanation: The statement is false. The correct statement would be: In computer science,
flowchart refers to a pictorial representation of an algorithm.

3. The process of drawing a flowchart for an algorithm is called __________


a) Performance
b) Evaluation
c) Algorithmic Representation
d) Flowcharting
View Answer

Answer: d
Explanation: It is called as flowcharting. A flowchart is nothing but a pictorial representation
of an algorithm.

4. Actual instructions in flowcharting are represented in __________


a) Circles
b) Boxes
c) Arrows
d) Lines
View Answer

Answer: b
Explanation: The actual instructions are written in boxes. Boxes are connected by using
arrows to indicate the exact flow of a flowchart and the order in which they are to be
executed.

5. The following box denotes?

a) Decision
b) Initiation
c) Initialization
d) I/O
View Answer

Answer: a
Explanation: A diamond shape box denotes the decision making statements. It jumps to a
truth value or a false value.

6. A box that can represent two different conditions.


a) Rectangle
b) Diamond
c) Circle
d) Parallelogram
View Answer

Answer: b
Explanation: A diamond shape box denotes either a truth value or a false value. It jumps onto
two different statements following it via flow lines.

7. There should be certain set standards on the amount of details that should be provided in a
flowchart.
a) True
b) False
View Answer

Answer: b
Explanation: The statement is false. There should be no set standards on the amount of details
that should be provided in a flowchart.

8. A detailed flowchart is called ______


a) Stack
b) Macro
c) Micro
d) Union
View Answer

Answer: c
Explanation: A detailed flowchart or a flowchart with more details is called as micro
flowchart. It represents all the components of the algorithm that is followed.

9. Which of the following is not an advantage of a flowchart?


a) Better communication
b) Efficient coding
c) Systematic testing
d) Improper documentation
View Answer

Answer: d
Explanation: Flowcharts provide a proper documentation. It also provides systematic
debugging.

10. A flowchart that outlines the main segments of a program.


a) Queue
b) Macro
c) Micro
d) Union
View Answer

Answer: b
Explanation: The answer is Macro Flowchart. A macro flowchart outlines the important
components of a program. It therefore shows fewer details.
RAPTOR Tool – A Flowchart Interpreter
RAPTOR(Rapid Algorithmic Prototyping Tool for Ordered Reasoning) is a free graphical
authoring tool created by Martin C. Carlisle, Terry Wilson, Jeff Humphries and Jason Moore,
designed specifically to help students visualize their algorithms and avoid syntactic baggage.
Students can create flow-chart for a particular program and raptor tool will generate code for
it in various programming languages, such as C, C++, Java and so on.

Symbols in RAPTOR

Raptor has 6 types of symbols, each of which represents a unique kind of instruction. They
are – Assignment, Call, Input, Output, Selection and Loop symbols. The following image
shows these symbols-

RAPTOR Program Structure

A RAPTOR program consists of connected symbols that represent actions to be executed.

1. The arrows that connect the symbols determine the order in which the actions are
performed.
2. The execution of a RAPTOR program begins at the Start symbol and goes along the arrows to
execute the program.
3. The program stops executing when the End symbol is reached.
C Fundamentals–Tokens:

The number of tokens in the following C statement is (GATE 2000)

filter_none

edit

play_arrow

brightness_4

printf("i = %d, &i = %x", i, &i);

(A) 3
(B) 26
(C) 10
(D) 21

Answer: (C)
Explanation: In a C source program, the basic element recognized by the compiler is the
“token.” A token is source-program text that the compiler does not break down into
component elements.
There are 6 types of C tokens : identifiers, keywords, constants, operators, string literals and
other separators. There are total 10 tokens in the above printf statement.
Below are tokens in above program.

printf
(
"i = %d, &i = %x"
,
i
,
&
i
)
;

1. Which of the following operators is used to concatenate two strings without space?
a) #
b) < >
c) **
d) ##
View Answer

Answer: d
Explanation: The operator ## is used for token concatenation (to concatenate two strings
without space).

2. What will be the output of the following C code?

#include <stdio.h>
#define p( n ) printf( "t" #n " = %d", t##n )
int t3=10;
int main()
{
p(3);
}

a) t=10
b) t3=10
c) t10=3
d) t=3
View Answer

Answer: b
Explanation: The code shown above uses the ## operator to concatenate ‘t’ and 3. t3 has been
declared as 10 in the code, Hence the output of the code shown above is: t3=10

3. What will be the output of the following C code?


#include <stdio.h>
#define p( n,m ) printf( "%d", m##n )
int main()
{
p(3,4);
}

a) Error
b) Junk value
c) 34
d) 43
View Answer

Answer: d
Explanation: In the code shown above, we have concatenated the two tokens in the order: mn.
The value of m is equal to 4 and that of n is equal to 3. Hence the output of this code is 43.

4. What will be the output of the following C code?

#include <stdio.h>
#define p( n,m ) printf( "%d", m##n )
#define q(a,b) printf("%d",a##b)
main()
{
p(3,4);
q(5,5);
}

a) 4356
b) 3456
c) 4365
d) 3465
View Answer

Answer: a
Explanation: In the code shown above we have concatenated m and n in one statement and a
and b in another. Since we have not used a new line character, the output of this code will be
equal to 4356.

5. The following C code results in an error.

#include <stdio.h>
#define world( n ) printf( "t^^" #n" = %c", t##n )
int t3=1;
int main()
{
world(3);
}

a) True
b) False
View Answer
Answer: b
Explanation: The code shown above does not result in an error. The output of this code is
t^^3=junk value.

6. What will be the output of the following C code?

#include <stdio.h>
#define display( n ) printf( "a" #n " = %d", a##n )
int main()
{
display(3);
}

a) a3
b) 31
c) a 3
d) error
View Answer

Answer: d
Explanation: The code shown above results in an error because we have not explicitly
declared a3. Had we declared a3 in this code, it would not have thrown an error.

7. What will be the output of the following C code?

advertisement
#include <stdio.h>
#define hello( n ) a##n
int a3;
int main()
{
int x;
x=hello(3);
if(x!=0)
printf("hi");
else
printf("good");
}

a) error
b) a3
c) good
d) hi
View Answer

Answer: c
Explanation: The code shown will print ‘hi’ if x is not equal to zero and ‘good’ if x is equal to
zero. In the above code, we have declared x (equal to zero). Hence ‘good’ is printed as
output.

8. What will be the output of the following C code?

#include <stdio.h>
#define hello( n ) printf( "a" #n "= %d", a##n )
int a3=3;
int main()
{
#ifdef a3
hello(3);
#else
printf("sorry");
#endif
}

a) a3=3
b) error
c) a=3
d) sorry
View Answer

Answer: d
Explanation: The code shown above prints a3=3 if as is defined. Since a3 is not defines,
‘sorry’ is printed as output.

9. What will be the output of the following C code?

#include <stdio.h>
#define p( n ) printf( "t*" #n " = %s", t##n )
char tsan[]="tsan";
int main()
{
int x;
x=p(san);
}

a) error
b) tsan=tsan
c) t*san=t*san
d) t*san=tsan
View Answer

Answer: d
Explanation: The code shown above uses the ## operator to concatenate the tokens t* and
san. We have decalred tsan[]=tsan. Hence the output of the code shown will be: t*san=tsan.

10. What will be the output of the following C code?

#include <stdio.h>
#define p( n ) printf( "t%\n" #n " = %d", t##n )
int t3=10;
int main()
{
int x;
x=p(3);
}

a)
t
3=10

b) t3=10
c) t%3=10
d)

t
%3=10
View Answer
Answer: a
Explanation: In this code, operator ## is used to concatenate t and 3. However, a new line
character is a part of this statement. The variable t3 has been declared as 10. Hence the output
of this code will be: t
3=10

Variables:

Q 1 - What is the output of the below code snippet?

#include<stdio.h>

main()
{
int a = 1;
float b = 1.3;
double c;

c = a + b;
printf("%.2lf", c);
}

A - 2.30

B - 2.3

C - Compile error

D - 2.0

Answer : A
Explanation

2.30, addition is valid and after decimal with is specified for 2 places.

Q 2 - What is the output of the following program?

#include<stdio.h>
void f()
{
printf(“Hello\n”);
}
main()
{
;
}

A - No output

B - Error, as the function is not called.

C - Error, as the function is defined without its declaration

D -Error, as the main() function is left empty

Answer : A
Explanation

No output, apart from the option (a) rest of the comments against the options are invalid.

Q 3 - What is the output of the following program?

#include<stdio.h>

main()
{
int a[3] = {2,1};

printf("%d", a[a[1]]);
}

A-0

B-1

C-2

D-3

Answer : B
Explanation

1, The inner indirection evaluates to 1, and the value at index 1 for outer indirection is 1.

Q 4 - What is the output of the following program?

#include<stdio.h>

main()
{
char s[] = "Fine";
*s = 'N';

printf("%s", s);
}

A - Fine

B - Nine

C - Compile error

D - Runtime error

Answer : B
Explanation

*s=’N’, changes the character at base address to ‘N’.

Q 5 - What is the output of the following statement?

#include<stdio.h>

main()
{
printf("%d", -1<<1 );
}

A-2

B - -2

C-1

D - -1

Answer : B
Explanation

A negative number stored in two’s compliment of positive number. After shifting we get
1110, which is equivalent to -2.

Q 6 - In the standard library of C programming language, which of the following header file
is designed for basic mathematical operations?

A - math.h

B - conio.h

C - dos.h
D - stdio.h

Answer : A
Explanation

math.h is a header file in the standard library designed for basic mathematical operations

Q 7 - In the given below code, if a short int value is 5 byte long, then how many times
the while loop will get executed?

#include<stdio.h>

int main ()
{
int j = 1;
while(j <= 300)
{
printf("%c %d\n", j, j);
j++;
}
return 0;
}

A - Unlimited times

B - 0 times

C - 300 times

D - 5 times

Answer : C
Explanation

If while(j <= 300),then whatever the size short int value, the while loop condition will
execute until j value becomes 300.

#include<stdio.h>

int main ()
{
int j = 1;

while(j <= 300)


{
printf("%c %d\n", j, j);
j++;
}
return 0;
}

Q 8 - fgets() function is safer than gets() because in fgets() function you can specify the size
of the buffer into which the supplied string will be stored.
A - True

D - False

Answer : A
Explanation

Both functions retrive and store a string from console or file, but fgets() functions are more
safer to use then gets() because gets() doesn't facilitate to detail the length of the buffer to
store the string in and fgets() facilitates to specify a maximum string length.

char *fgets(char *s, int size, FILE *stream);


char *gets(char *s);

Q 9 - What is the role of "r+" on the file "NOTES.TXT" in the given below code?

#include<stdio.h>

int main ()
{
FILE *fp;

fp = fopen("NOTES.TXT", "r+");
return 0;
}

A - "r+" open the file "NOTES.TXT" file for reading

B - "r+" open the file "NOTES.TXT" file for writing

C - "r+" open the file "NOTES.TXT" file for appending

D - "r+" open the file "NOTES.TXT" file for reading & writing both

Answer : D
Explanation

fopen() function is used to open a file and r++ enable the file for reading and writing.

#include<stdio.h>

int main ()
{
FILE *fp;

fp = fopen("NOTES.TXT", "r+");
return 0;
}

Q 10 - According to ANSI specification, how to declare main () function with command-line


arguments?

A - int main(int argc, char *argv[])


B - int char main(int argc, *argv)

C-

int main()
{
Int char (*argv argc);
)

D - None of the above

Answer : A
Explanation

Some time, it becomes necessary to deliver command line values to the C programming to
execute the particular code when the code of the program is controlled from outside. Those
command line values are called command line arguments. The command line arguments are
handled by the main() function.

Declaration of main () with command-line argument is,

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

Where, argc refers to the number of arguments passed, and argv[] is a pointer array which
points to each argument passed to the program.

Variable Names – 1
This section on C interview questions and answers focuses on “Variable Names”. One shall practice
these interview questions to improve their C programming skills needed for various interviews
(campus interviews, walk-in interviews, company interviews), placements, entrance exams and
other competitive exams. These questions can be attempted by anyone focusing on learning C
Programming language. They can be a beginner, fresher, engineering graduate or an experienced IT
professional. Our C Interview questions come with the detailed explanation of the answers which
helps in better understanding of C concepts.

Here is a listing of C interview questions on “Variable Names” along with answers,


explanations and/or solutions:

1. C99 standard guarantees uniqueness of __________ characters for internal names.


a) 31
b) 63
c) 12
d) 14
View Answer

Answer: b
Explanation: ISO C99 compiler may consider only first 63 characters for internal names.
2. C99 standard guarantees uniqueness of ___________ characters for external names.
a) 31
b) 6
c) 12
d) 14
View Answer

Answer: a
Explanation: ISO C99 compiler may consider only first 31 characters for external names.

3. Which of the following is not a valid variable name declaration?


a) int __a3;
b) int __3a;
c) int __A3;
d) None of the mentioned
View Answer

Answer: d
Explanation: None.

4. Which of the following is not a valid variable name declaration?


a) int _a3;
b) int a_3;
c) int 3_a;
d) int _3a
View Answer

Answer: c
Explanation: Variable name cannot start with a digit.

5. Why do variable names beginning with the underscore is not encouraged?


a) It is not standardized
b) To avoid conflicts since assemblers and loaders use such names
c) To avoid conflicts since library routines use such names
d) To avoid conflicts with environment variables of an operating system
View Answer

Answer: c
Explanation: None.

6. All keywords in C are in ____________


a) LowerCase letters
b) UpperCase letters
c) CamelCase letters
d) None of the mentioned
View Answer

Answer: a
Explanation: None.
7. Variable name resolution (number of significant characters for the uniqueness of variable)
depends on ___________
a) Compiler and linker implementations
b) Assemblers and loaders implementations
c) C language
d) None of the mentioned
View Answer

Answer: a
Explanation: It depends on the standard to which compiler and linkers are adhering.
advertisement

8. Which of the following is not a valid C variable name?


a) int number;
b) float rate;
c) int variable_count;
d) int $main;
View Answer

Answer: d
Explanation: Since only underscore and no other special character is allowed in a variable name, it
results in an error.

9. Which of the following is true for variable names in C?


a) They can contain alphanumeric characters as well as special characters
b) It is not an error to declare a variable to be one of the keywords(like goto, static)
c) Variable names cannot start with a digit
d) Variable can be of any length
View Answer

Answer: c
Explanation: According to the syntax for C variable name, it cannot start with a digit.

Variable Names – 2
Sanfoundry’s 1000+ Interview Questions & Answers on C help anyone preparing for Oracle
and other companies C interviews. One should practice these 1000+ interview questions and
answers continuously for 2-3 months to clear Oracle interviews on C Programming language.

Here is a listing of C interview questions on “Variable Names” along with answers,


explanations and/or solutions:

1. Which is valid C expression?


a) int my_num = 100,000;
b) int my_num = 100000;
c) int my num = 1000;
d) int $my_num = 10000;
View Answer
Answer: b
Explanation: Space, comma and $ cannot be used in a variable name.

2. What will be the output of the following C code?

1. #include <stdio.h>
2. int main()
3. {
4. printf("Hello World! %d \n", x);
5. return 0;
6. }

a) Hello World! x;
b) Hello World! followed by a junk value
c) Compile time error
d) Hello World!
View Answer

Answer: c
Explanation: It results in an error since x is used without declaring the variable x.
Output:
$ cc pgm1.c
pgm1.c: In function ‘main’:
pgm1.c:4: error: ‘x’ undeclared (first use in this function)
pgm1.c:4: error: (Each undeclared identifier is reported only once
pgm1.c:4: error: for each function it appears in.)

3. What will be the output of the following C code?

1. #include <stdio.h>
2. int main()
3. {
4. int y = 10000;
5. int y = 34;
6. printf("Hello World! %d\n", y);
7. return 0;
8. }

a) Compile time error


b) Hello World! 34
c) Hello World! 1000
d) Hello World! followed by a junk value
View Answer

Answer: a
Explanation: Since y is already defined, redefining it results in an error.
Output:
$ cc pgm2.c
pgm2.c: In function ‘main’:
pgm2.c:5: error: redefinition of ‘y’
pgm2.c:4: note: previous definition of ‘y’ was here
4. Which of the following is not a valid variable name declaration?
a) float PI = 3.14;
b) double PI = 3.14;
c) int PI = 3.14;
d) #define PI 3.14
View Answer

Answer: d
Explanation: #define PI 3.14 is a macro preprocessor, it is a textual substitution.

5. What will happen if the following C code is executed?

1. #include <stdio.h>
2. int main()
3. {
4. int main = 3;
5. printf("%d", main);
6. return 0;
7. }

a) It will cause a compile-time error


b) It will cause a run-time error
c) It will run without any error and prints 3
d) It will experience infinite looping
View Answer

Answer: c
Explanation: A C program can have same function name and same variable name.
$ cc pgm3.c
$ a.out
3

6. What is the problem in following variable declaration?

float 3Bedroom-Hall-Kitchen?;
advertisement

a) The variable name begins with an integer


b) The special character ‘-‘
c) The special character ‘?’
d) All of the mentioned
View Answer

Answer: d
Explanation: A variable name cannot start with an integer, along with that the C compiler
interprets the ‘-‘ and ‘?’ as a minus operator and a question mark operator respectively.

7. What will be the output of the following C code?

1. #include <stdio.h>
2. int main()
3. {
4. int ThisIsVariableName = 12;
5. int ThisIsVariablename = 14;
6. printf("%d", ThisIsVariablename);
7. return 0;
8. }

a) The program will print 12


b) The program will print 14
c) The program will have a runtime error
d) The program will cause a compile-time error due to redeclaration
View Answer

Answer: b
Explanation: Variable names ThisIsVariablename and ThisIsVariableName are both distinct
as C is case sensitive.
Output:
$ cc pgm4.c
$ a.out
14

8. Which of the following cannot be a variable name in C?


a) volatile
b) true
c) friend
d) export
View Answer

Answer: a
Explanation: volatile is C keyword.

Expressions:

1. What is the type of the following assignment expression if x is of type float and y is of type
int?

y = x + y;

a) int
b) float
c) there is no type for an assignment expression
d) double
View Answer

Answer: a
Explanation: None.

2. What will be the value of the following assignment expression?


(x = foo())!= 1 considering foo() returns 2

a) 2
b) True
c) 1
d) 0
View Answer

Answer: a
Explanation: None.

3. Operation “a = a * b + a” can also be written as ___________


a) a *= b + 1;
b) (c = a * b)!=(a = c + a);
c) a = (b + 1)* a;
d) All of the mentioned
View Answer

Answer: d
Explanation: None.

4. What will be the final value of c in the following C statement? (Initial value: c = 2)

1. c <<= 1;

a) c = 1;
b) c = 2;
c) c = 3;
d) c = 4;
View Answer

Answer: d
Explanation: None.

5. What will be the output of the following C code?

1. #include <stdio.h>
2. int main()
3. {
4. int a = 1, b = 2;
5. a += b -= a;
6. printf("%d %d", a, b);
7. }

a) 1 1
b) 1 2
c) 2 1
d) 2 2
View Answer
Answer: c
Explanation: None.

6. What will be the output of the following C code?

advertisement
1. #include <stdio.h>
2. int main()
3. {
4. int a = 4, n, i, result = 0;
5. scanf("%d", n);
6. for (i = 0;i < n; i++)
7. result += a;
8. }

a) Addition of a and n
b) Subtraction of a and n
c) Multiplication of a and n
d) Division of a and n
View Answer

Answer: c
Explanation: None.

7. Which of the following is an invalid assignment operator?


a) a %= 10;
b) a /= 10;
c) a |= 10;
d) None of the mentioned
View Answer

Answer: d
Explanation: None.

Conditional Expressions – 1

1. What will be the output of the following C code?

1. #include <stdio.h>
2. int main()
3. {
4. int x = 2, y = 0;
5. int z = (y++) ? y == 1 && x : 0;
6. printf("%d\n", z);
7. return 0;
8. }
a) 0
b) 1
c) Undefined behaviour
d) Compile time error
View Answer

Answer: a
Explanation: None.

2. What will be the output of the following C code?

1. #include <stdio.h>
2. int main()
3. {
4. int x = 1;
5. int y = x == 1 ? getchar(): 2;
6. printf("%d\n", y);
7. }

a) Compile time error


b) Whatever character getchar function returns
c) Ascii value of character getchar function returns
d) 2
View Answer

Answer: c
Explanation: None.

3. What will be the output of the following C code?

1. #include <stdio.h>
2. int main()
3. {
4. int x = 1;
5. short int i = 2;
6. float f = 3;
7. if (sizeof((x == 2) ? f : i) == sizeof(float))
8. printf("float\n");
9. else if (sizeof((x == 2) ? f : i) == sizeof(short int))
10. printf("short int\n");
11. }

a) float
b) short int
c) Undefined behaviour
d) Compile time error
View Answer

Answer: a
Explanation: None.

4. What will be the output of the following C code?


1. #include <stdio.h>
2. int main()
3. {
4. int a = 2;
5. int b = 0;
6. int y = (b == 0) ? a :(a > b) ? (b = 1): a;
7. printf("%d\n", y);
8. }

a) Compile time error


b) 1
c) 2
d) Undefined behaviour
View Answer

Answer: c
Explanation: None.
advertisement

5. What will be the output of the following C code?

1. #include <stdio.h>
2. int main()
3. {
4. int y = 1, x = 0;
5. int l = (y++, x++) ? y : x;
6. printf("%d\n", l);
7. }

a) 1
b) 2
c) Compile time error
d) Undefined behaviour
View Answer

Answer: a
Explanation: None.

6. What will be the output of the following C code?

1. #include <stdio.h>
2. void main()
3. {
4. int k = 8;
5. int m = 7;
6. int z = k < m ? k++ : m++;
7. printf("%d", z);
8. }

a) 7
b) 8
c) Run time error
d) 15
View Answer
Answer: a
Explanation: None.

7. What will be the output of the following C code?

1. #include <stdio.h>
2. void main()
3. {
4. int k = 8;
5. int m = 7;
6. int z = k < m ? k = m : m++;
7. printf("%d", z);
8. }

a) Run time error


b) 7
c) 8
d) Depends on compiler
View Answer

Answer: b
Explanation: None.

8. What will be the output of the following C code?

1. #include <stdio.h>
2. void main()
3. {
4. 1 < 2 ? return 1 : return 2;
5. }

a) returns 1
b) returns 2
c) Varies
d) Compile time error
View Answer

Answer: d
Explanation: None.

Conditional Expressions – 2
1. What will be the output of the following C code?

1. #include <stdio.h>
2. void main()
3. {
4. int k = 8;
5. int m = 7;
6. k < m ? k++ : m = k;
7. printf("%d", k);
8. }
a) 7
b) 8
c) Compile time error
d) Run time error
View Answer

Answer: c
Explanation: None.

2. What will be the output of the following C code?

1. #include <stdio.h>
2. void main()
3. {
4. int k = 8;
5. int m = 7;
6. k < m ? k = k + 1 : m = m + 1;
7. printf("%d", k);
8. }

a) Compile time error


b) 9
c) 8
d) Run time error
View Answer

Answer: a
Explanation: None.

3. What will be the final values of a and c in the following C statement? (Initial values: a = 2,
c = 1)

c = (c) ? a = 0 : 2;

a) a = 0, c = 0;
b) a = 2, c = 2;
c) a = 2, c = 2;
d) a = 1, c = 2;
View Answer

Answer: a
Explanation: None.

4. What will be the data type of the following expression? (Initial data type: a = int, var1 =
double, var2 = float)

expression (a < 50)? var1 : var2;

a) int
b) float
c) double
d) Cannot be determined
View Answer

Answer: c
Explanation: None.

5. Which expression has to be present in the following?

exp1 ? exp2 : exp3;

a) exp1
b) exp2
c) exp3
d) all of the mentioned
View Answer

Answer: d
Explanation: None.

6. What will be the final value of c in the following C code snippet? (Initial values: a = 1, b =
2, c = 1)

c += (-c) ? a : b;

a) Syntax Error
b) c = 1
c) c = 2
d) c = 3
View Answer

Answer: c
Explanation: None.
advertisement

7. The following C code can be rewritten as _______

c = (n) ? a : b;

a)

if (!n)c = b;
else c = a;

b)

if (n <;= 0)c = b;
else c = a;

c)

if (n > 0)c = a;
else c = b;
d) All of the mentioned
View Answer

Answer: a
Explanation: None.

C Operators
1234
Question 1
Wrong
#include "stdio.h"
int main()
{
int x, y = 5, z = 5;
x = y == z;
printf("%d", x);

getchar();
return 0;
}
A0
1
C5
D Compiler Error
C Operators    
Discuss it

Question 1 Explanation: 
The crux of the question lies in the statement x = y==z. The operator == is executed before =
because precedence of comparison operators (<=, >= and ==) is higher than assignment
operator =. The result of a comparison operator is either 0 or 1 based on the comparison
result. Since y is equal to z, value of the expression y == z becomes 1 and the value is
assigned to x via the assignment operator.
Question 2
Wrong

#include <stdio.h>

int main()
{
    int i = 1, 2, 3;
    
    printf("%d", i);
    
    return 0;
}
A1
B3
C Garbage value
Compile time error
C Operators    
Discuss it

Question 2 Explanation: 
Comma acts as a separator here. The compiler creates an integer variable and initializes it
with 1. The compiler fails to create integer variable 2 because 2 is not a valid identifier.
Question 3
Wrong
#include <stdio.h>

int main()
{
    int i = (1, 2, 3);
    
    printf("%d", i);
    
    return 0;
}

A1
3
C Garbage value
D Compile time error
C Operators    
Discuss it

Question 3 Explanation: 
The bracket operator has higher precedence than assignment operator. The expression within
bracket operator is evaluated from left to right but it is always the result of the last expression
which gets assigned.
Question 4
Correct

#include <stdio.h>

int main()
{
    int i;
  
    i = 1, 2, 3;
    printf("%d", i);
    
    return 0;
}
1
B3
C Garbage value
D Compile time error
C Operators    
Discuss it

Question 4 Explanation: 
Comma acts as an operator. The assignment operator has higher precedence than comma
operator. So, the expression is considered as (i = 1), 2, 3 and 1 gets assigned to variable i.
Question 5
Wrong
#include <stdio.h>
int main()
{
    int i = 3;
    printf("%d", (++i)++);
    return 0;
}
What is the output of the above program?
A3
B4
C5
Compile-time error
C Operators    
Discuss it

Question 5 Explanation: 
In C, prefix and postfix operators need l-value to perform operation and return r-value. The
expression (++i)++ when executed increments the value of variable i(i is a l-value) and
returns r-value. The compiler generates the error(l-value required) when it tries to post-
incremeny the value of a r-value.
Question 6
Correct
What is the output of below program?
#include <stdio.h>
int foo(int* a, int* b)
{
    int sum = *a + *b;
    *b = *a;
    return *a = sum - *b;
}
int main()
{
    int i = 0, j = 1, k = 2, l;
    l = i++ || foo(&j, &k);
    printf("%d %d %d %d", i, j, k, l);
    return 0;
}
1211
B 1121
C 1221
D 1222
C Operators    
Discuss it

Question 6 Explanation: 
The control in the logical OR goes to the second expression only if the first expression results
in FALSE. The function foo() is called because i++ returns 0(post-increment) after
incrementing the value of i to 1. The foo() function actually swaps the values of two variables
and returns the value of second parameter. So, values of variables j and k gets exchanged and
OR expression evaluates to be TRUE.
Question 7
Wrong
#include <stdio.h>
int main()
{
    int i = 5, j = 10, k = 15;
    printf("%d ", sizeof(k /= i + j));
    printf("%d", k);
    return 0;
}
Assume size of an integer as 4 bytes. What is the output of above program?
41
B 4 15
C 21
D Compile-time error
C Operators    
Discuss it

Question 7 Explanation: 
The main theme of the program lies here: sizeof(k /= i + j). An expression doesn't get
evaluated inside sizeof operator. sizeof operator returns sizeof(int) because the result of
expression will be an integer. As the expression is not evaluated, value of k will not be
changed.
Question 8
Correct
#include <stdio.h>
int main()
{
    //Assume sizeof character is 1 byte and sizeof integer is 4 bytes
    printf("%d", sizeof(printf("GeeksQuiz")));
    return 0;
}
A GeeksQuiz4
B 4GeeksQuiz
C GeeksQuiz9
4
E Compile-time error
C Operators    
Discuss it

Question 8 Explanation: 
An expression doesn't get evaluated inside sizeof operator. GeeksQuiz will not be printed.
printf returns the number of characters to be printed i.e. 9 which is an integer value. sizeof
operator returns sizeof(int).
Question 9
Correct
Output of following program?
#include <stdio.h>
int f1() { printf ("Geeks"); return 1;}
int f2() { printf ("Quiz"); return 1;}
 
int main()
{
  int p = f1() + f2();
  return 0;
}
A GeeksQuiz
B QuizGeeks
Compiler Dependent
D Compiler Error
C Operators    
Discuss it

Question 9 Explanation: 
The operator ‘+’ doesn't have a standard defined order of evaluation for its operands. Either
f1() or f2() may be executed first. So a compiler may choose to output either “GeeksQuiz” or
“QuizGeeks”.
Question 10
Wrong
What is the output of following program?
#include <stdio.h>
 
int main()
{
   int a = 1;
   int b = 1;
   int c = a || --b;
   int d = a-- && --b;
   printf("a = %d, b = %d, c = %d, d = %d", a, b, c, d);
   return 0;
}
A a = 0, b = 1, c = 1, d = 0
a = 0, b = 0, c = 1, d = 0
C a = 1, b = 1, c = 1, d = 1
D a = 0, b = 0, c = 0, d = 0
C Operators    
Discuss it

Question 10 Explanation: 
Let us understand the execution line by line. Initial values of a and b are 1.
// Since a is 1, the expression --b is not executed because
// of the short-circuit property of logical or operator
// So c becomes 1, a and b remain 1
int c = a || --b;

// The post decrement operator -- returns the old value in current


expression
// and then updates the value. So the value of expression --a is 1.
Since the
// first operand of logical and is 1, shortcircuiting doesn't happen
here. So
// the expression --b is executed and --b returns 0 because it is pre-
increment.
// The values of a and b become 0, and the value of d also becomes 0.
int d = a-- && --b;

Flow Control Statements:

Control Statements – 1
This section of our 1000+ Java MCQs focuses on control statements of Java Programming
Language.

1. Which of these selection statements test only for equality?


a) if
b) switch
c) if & switch
d) none of the mentioned
View Answer

Answer: b
Explanation: Switch statements checks for equality between the controlling variable and its constant
cases.

2. Which of these are selection statements in Java?


a) if()
b) for()
c) continue
d) break
View Answer

Answer: a
Explanation: Continue and break are jump statements, and for is a looping statement.

3. Which of the following loops will execute the body of loop even when condition
controlling the loop is initially false?
a) do-while
b) while
c) for
d) none of the mentioned
View Answer
Answer: a
Explanation: None.

4. Which of these jump statements can skip processing the remainder of the code in its body
for a particular iteration?
a) break
b) return
c) exit
d) continue
View Answer

Answer: d
Explanation: None.

5. Which of this statement is incorrect?


a) switch statement is more efficient than a set of nested ifs
b) two case constants in the same switch can have identical values
c) switch statement can only test for equality, whereas if statement can evaluate any type of
boolean expression
d) it is possible to create a nested switch statements
View Answer

Answer: b
Explanation: No two case constants in the same switch can have identical values.

6. What will be the output of the following Java program?

1. class selection_statements
2. {
3. public static void main(String args[])
4. {
5. int var1 = 5;
6. int var2 = 6;
7. if ((var2 = 1) == var1)
8. System.out.print(var2);
9. else
10. System.out.print(++var2);
11. }
12. }

a) 1
b) 2
c) 3
d) 4
View Answer

Answer: b
Explanation: var2 is initialised to 1. The conditional statement returns false and the else part gets
executed.
output:
$ javac selection_statements.java
$ java selection_statements
2

7. What will be the output of the following Java program?

1. class comma_operator
2. {
3. public static void main(String args[])
4. {
5. int sum = 0;
6. for (int i = 0, j = 0; i < 5 & j < 5; ++i, j = i + 1)
7. sum += i;
8. System.out.println(sum);
9. }
10. }

a) 5
b) 6
c) 14
d) compilation error
View Answer

Answer: b
Explanation: Using comma operator, we can include more than one statement in the initialization
and iteration portion of the for loop. Therefore both ++i and j = i + 1 is executed i gets the value –
0,1,2,3,4 & j gets the values -0,1,2,3,4,5.
output:
advertisement
$ javac comma_operator.java
$ java comma_operator
6

8. What will be the output of the following Java program?

1. class jump_statments
2. {
3. public static void main(String args[])
4. {
5. int x = 2;
6. int y = 0;
7. for ( ; y < 10; ++y)
8. {
9. if (y % x == 0)
10. continue;
11. else if (y == 8)
12. break;
13. else
14. System.out.print(y + " ");
15. }
16. }
17. }

a) 1 3 5 7
b) 2 4 6 8
c) 1 3 5 7 9
d) 1 2 3 4 5 6 7 8 9
View Answer

Answer: c
Explanation: Whenever y is divisible by x remainder body of loop is skipped by continue statement,
therefore if condition y == 8 is never true as when y is 8, remainder body of loop is skipped by
continue statements of first if. Control comes to print statement only in cases when y is odd.
output:
$ javac jump_statments.java
$ java jump_statments
1 3 5 7 9

9. What will be the output of the following Java program?

1. class Output
2. {
3. public static void main(String args[])
4. {
5. final int a=10,b=20;
6. while(a<b)
7. {
8.  
9. System.out.println("Hello");
10. }
11. System.out.println("World");
12.  
13. }
14. }

a) Hello
b) run time error
c) Hello world
d) compile time error
View Answer

Answer: d
Explanation: Every final variable is compile time constant.

10. What will be the output of the following Java program?

1. class Output
2. {
3. public static void main(String args[])
4. {
5. int a = 5;
6. int b = 10;
7. first:
8. {
9. second:
10. {
11. third:
12. {
13. if (a == b >> 1)
14. break second;
15. }
16. System.out.println(a);
17. }
18. System.out.println(b);
19. }
20. }
21. }

a) 5 10
b) 10 5
c) 5
d) 10
View Answer

Answer: d
Explanation: b >> 1 in if returns 5 which is equal to a i:e 5, therefore body of if is executed and block
second is exited. Control goes to end of the block second executing the last print statement, printing
10.
output:
$ javac Output.java
$ java Output
10

Control Statements – 2
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Control
Statements”.

1. What would be the output of the following code snippet if variable a=10?

1. if(a<=0)
2. {
3. if(a==0)
4. {
5. System.out.println("1 ");
6. }
7. else
8. {
9. System.out.println("2 ");
10. }
11. }
12. System.out.println("3 ");

a) 1 2
b) 2 3
c) 1 3
d) 3
View Answer
Answer: d
Explanation: Since the first if condition is not met, control would not go inside if statement and
hence only statement after the entire if block will be executed.

2. The while loop repeats a set of code while the condition is not met?
a) True
b) False
View Answer

Answer: b
Explanation: While loop repeats a set of code only until the condition is met.

3. What is true about a break?


a) Break stops the execution of entire program
b) Break halts the execution and forces the control out of the loop
c) Break forces the control out of the loop and starts the execution of next iteration
d) Break halts the execution of the loop for certain time frame
View Answer

Answer: b
Explanation: Break halts the execution and forces the control out of the loop.

4. What is true about do statement?


a) do statement executes the code of a loop at least once
b) do statement does not get execute if condition is not matched in the first iteration
c) do statement checks the condition at the beginning of the loop
d) do statement executes the code more than once always
View Answer

Answer: a
Explanation: Do statement checks the condition at the end of the loop. Hence, code gets executed at
least once.

5. Which of the following is used with the switch statement?


a) Continue
b) Exit
c) break
d) do
View Answer

Answer: c
Explanation: Break is used with a switch statement to shift control out of switch.

6. What is the valid data type for variable “a” to print “Hello World”?

1. switch(a)
2. {
3. System.out.println("Hello World");
4. }
a) int and float
b) byte and short
c) char and long
d) byte and char
View Answer

Answer: d
Explanation: The switch condition would only meet if variable “a” is of type byte or char.
advertisement

7. Which of the following is not a decision making statement?


a) if
b) if-else
c) switch
d) do-while
View Answer

Answer: d
Explanation: do-while is an iteration statement. Others are decision making statements.

8. Which of the following is not a valid jump statement?


a) break
b) goto
c) continue
d) return
View Answer

Answer: b
Explanation: break, continue and return transfer control to another part of the program and returns
back to caller after execution. However, goto is marked as not used in Java.

9. From where break statement causes an exit?


a) Only from innermost loop
b) Terminates a program
c) Only from innermost switch
d) From innermost loops or switches
View Answer

Answer: d
Explanation: The break statement causes an exit from innermost loop or switch.

10. Which of the following is not a valid flow control statement?


a) exit()
b) break
c) continue
d) return
View Answer
Answer: a
Explanation: exit() is not a flow control statement in Java. exit() terminates the currently running
JVM.

Break and continue:


1. Which keyword can be used for coming out of recursion?
a) break
b) return
c) exit
d) both break and return
View Answer

Answer: b
Explanation: None.

2. What will be the output of the following C code?

1. #include <stdio.h>
2. int main()
3. {
4. int a = 0, i = 0, b;
5. for (i = 0;i < 5; i++)
6. {
7. a++;
8. continue;
9. }
10. }

a) 2
b) 3
c) 4
d) 5
View Answer

Answer: d
Explanation: None.

3. What will be the output of the following C code?

1. #include <stdio.h>
2. int main()
3. {
4. int a = 0, i = 0, b;
5. for (i = 0;i < 5; i++)
6. {
7. a++;
8. if (i == 3)
9. break;
10. }
11. }
a) 1
b) 2
c) 3
d) 4
View Answer

Answer: d
Explanation: None.

4. The keyword ‘break’ cannot be simply used within _________


a) do-while
b) if-else
c) for
d) while
View Answer

Answer: b
Explanation: None.

5. Which keyword is used to come out of a loop only for that iteration?
a) break
b) continue
c) return
d) none of the mentioned
View Answer

Answer: b
Explanation: None.

6. What will be the output of the following C code?

1. #include <stdio.h>
2. void main()
3. {
4. int i = 0, j = 0;
5. for (i = 0;i < 5; i++)
6. {
7. for (j = 0;j < 4; j++)
8. {
9. if (i > 1)
10. break;
11. }
12. printf("Hi \n");
13. }
14. }

a) Hi is printed 5 times
b) Hi is printed 9 times
c) Hi is printed 7 times
d) Hi is printed 4 times
View Answer
Answer: a
Explanation: None.
advertisement

7. What will be the output of the following C code?

1. #include <stdio.h>
2. void main()
3. {
4. int i = 0;
5. int j = 0;
6. for (i = 0;i < 5; i++)
7. {
8. for (j = 0;j < 4; j++)
9. {
10. if (i > 1)
11. continue;
12. printf("Hi \n");
13. }
14. }
15. }

a) Hi is printed 9 times
b) Hi is printed 8 times
c) Hi is printed 7 times
d) Hi is printed 6 times
View Answer

Answer: b
Explanation: None.

8. What will be the output of the following C code?

1. #include <stdio.h>
2. void main()
3. {
4. int i = 0;
5. for (i = 0;i < 5; i++)
6. if (i < 4)
7. {
8. printf("Hello");
9. break;
10. }
11. }

a) Hello is printed 5 times


b) Hello is printed 4 times
c) Hello
d) Hello is printed 3 times
View Answer

Answer: c
Explanation: None.
Break and Continue – 2
1. What will be the output of the following C code?

1. #include <stdio.h>
2. void main()
3. {
4. int i = 0;
5. if (i == 0)
6. {
7. printf("Hello");
8. continue;
9. }
10. }

a) Hello is printed infinite times


b) Hello
c) Varies
d) Compile time error
View Answer

Answer: d
Explanation: None.

2. What will be the output of the following C code?

1. #include <stdio.h>
2. void main()
3. {
4. int i = 0;
5. if (i == 0)
6. {
7. printf("Hello");
8. break;
9. }
10. }

a) Hello is printed infinite times


b) Hello
c) Varies
d) Compile time error
View Answer

Answer: d
Explanation: None.

3. What will be the output of the following C code?

1. #include <stdio.h>
2. int main()
3. {
4. int i = 0;
5. do
6. {
7. i++;
8. if (i == 2)
9. continue;
10. printf("In while loop ");
11. } while (i < 2);
12. printf("%d\n", i);
13. }

a) In while loop 2
b) In while loop in while loop 3
c) In while loop 3
d) Infinite loop
View Answer

Answer: a
Explanation: None.

4. What will be the output of the following C code?

1. #include <stdio.h>
2. int main()
3. {
4. int i = 0, j = 0;
5. for (i; i < 2; i++){
6. for (j = 0; j < 3; j++)
7. {
8. printf("1\n");
9. break;
10. }
11. printf("2\n");
12. }
13. printf("after loop\n");
14. }

a)

1
2
after loop

b)

1
after loop

c)

1
2
1
2
after loop

d)

advertisement
1
1
2
after loop
View Answer
Answer: c
Explanation: None.
 
 

5. What will be the output of the following C code?

1. #include <stdio.h>
2. int main()
3. {
4. int i = 0;
5. while (i < 2)
6. {
7. if (i == 1)
8. break;
9. i++;
10. if (i == 1)
11. continue;
12. printf("In while loop\n");
13. }
14. printf("After loop\n");
15. }

a)

In while loop
After loop

b) After loop
c)

In while loop
In while loop
After loop

d) In while loop
View Answer

Answer: b
Explanation: None.

6. What will be the output of the following C code?

1. #include <stdio.h>
2. int main()
3. {
4. int i = 0;
5. char c = 'a';
6. while (i < 2)
7. {
8. i++;
9. switch (c)
10. {
11. case 'a':
12. printf("%c ", c);
13. break;
14. break;
15. }
16. }
17. printf("after loop\n");
18. }

a) a after loop
b) a a after loop
c) after loop
d) error
View Answer

Answer: b
Explanation: None.

7. What will be the output of the following C code?

1. #include <stdio.h>
2. int main()
3. {
4. printf("before continue ");
5. continue;
6. printf("after continue\n");
7. }

a) Before continue after continue


b) Before continue
c) After continue
d) Compile time error
View Answer

Answer: d
Explanation: None.

goto statements:

Question 1
Wrong
Choose the best statement with respect to following three program snippets.
/*Program Snippet 1 with for loop*/
for (i = 0; i < 10; i++)
{
   /*statement1*/
   continue;
   /*statement2*/
}
 
/*Program Snippet 2 with while loop*/
i = 0;
while (i < 10)
{
   /*statement1*/
   continue;
   /*statement2*/
   i++;
}
 
/*Program Snippet 3 with do-while loop*/
i = 0;
do
{
   /*statement1*/
   continue;
   /*statement2*/
   i++;
}while (i < 10);
All the loops are equivalent i.e. any of the three can be chosen
A
and they all will perform exactly same.
B continue can't be used with all the three loops in C.
After hitting the continue; statement in all the loops, the next
C expression to be executed would be controlling expression
(i.e. i < 10) in all the 3 loops.
None of the above is correct.
C Loops & Control Structure    C Quiz - 105    
Discuss it

Question 1 Explanation: 

First and foremost, continue can be used in any of the 3 loops in C. In case of “for” loop,
when continue is hit, the next expression to be executed would be i++ followed by
controlling expression (i.e. i < 10). In case of “while” loop, when continue is hit, the next
expression to be executed would be controlling expression (i.e. i < 10). In case of “do-while”
loop, when continue is hit, the next expression to be executed would be controlling
expression (i.e. i < 10). That’s why “while” and “do-while” loops would behave exactly same
but not the “for” loop. Just to re-iterate, i++ would be executed in “for” loop when continue is
hit.

Question 2
Wrong
In the context of "break" and "continue" statements in C, pick the best statement.
A “break” can be used in “for”, “while” and “do-while” loop body.
B “continue” can be used in “for”, “while” and “do-while” loop body.
“break” and “continue” can be used in “for”, “while”, “do-while” loop body and “switch”
C
body.
“break” and “continue” can be used in “for”, “while” and “do-while” loop body. But only
“break” can be used in “switch” body.
“break” and “continue” can be used in “for”, “while” and “do-while” loop body. Besides,
E
“continue” and “break” can be used in “switch” and “if-else” body.
C Loops & Control Structure    C Quiz - 105    
Discuss it

Question 2 Explanation: 
As per C standard, “continue” can be used in loop body only. “break” can be used in loop
body and switch body only. That’s why correct answer is D.
Question 3
Wrong
What would happen when we compile and run this program?
#include "stdio.h"
int main()
{
  int i;
  goto LOOP;
  for (i = 0 ; i < 10 ; i++)
  {
     printf("GeeksQuizn");
     LOOP:
      break;
  }
  return 0;
}
No compile error and it will print GeeksQuiz 10 times
A
because goto label LOOP wouldn’t come in effect.
No compile error and it’ll print GeeksQuiz only once
B because goto label LOOP would come in picture only after
entering for loop.
Compile Error because any goto label isn’t allowed in for
C
loop in C.
No compile error but behaviour of the program would
D depend on C compiler due to nondeterministic behaviour of
goto statement.
No compile error and it will not print anything.
C Loops & Control Structure    C Quiz - 105    
Discuss it

Question 3 Explanation: 
goto statement can be used inside a function and its label can point to anywhere in the same
function. Here, for loop expressions i.e. i = 0 and i < 10 and i++ wouldn’t be executed at all.
Because goto would make the program jump directly inside the for loop. And from there, it’ll
execute break statement which would exit the loop. So effectively nothing would be printed.
Question 4
Correct
A typical “switch” body looks as follows:
switch (controlling_expression)
{
  case label1:
    /*label1 statements*/
    break;
  case label2:
    /*label1 statements*/
    break;
  default:
    /*Default statements*/
}
Which of the following statement is not correct statement?
A “switch” body may not have any “case” label at all and it would still compile.
B “switch” body may not have the “default” label and it would still compile.
“switch” body may contain more than one “case” labels where the label value of these
“case” is same and it would still compile. If “switch” controlling expression results in this
“case” label value, the “case” which is placed first would be executed.
D “switch” body may not have any “break” statement and it would still compile.
“switch” body can have the “default” label at first i.e. before all the other “case” labels. It
E
would still compile.
C Loops & Control Structure    C Quiz - 105    
Discuss it

Question 4 Explanation: 
In "switch" body, two "case" can't result in same value. Though having only "case" or only
"default" is okay. In fact, "switch" body can be empty also.
Question 5
Wrong
Which of the following is correct with respect to “Jump Statements” in C?
A goto
B continue
C break
D return
All of the above.
C Loops & Control Structure    C Quiz - 105    
Discuss it

Question 5 Explanation: 
As per C standard, “A jump statement causes an unconditional jump to another place”. So if
we see carefully, all “goto”, “continue”, “break” and “return” makes the program control
jump unconditionally from one place to another. That’s why correct answer is E.

C Loops & Control Structure


12345
Question 1
Wrong
#include <stdio.h>
 
int main()
{
    int i = 1024;
    for (; i; i >>= 1)
        printf("GeeksQuiz");
    return 0;
}
How many times will GeeksQuiz be printed in the above program?
A 10
11
C Infinite
D The program will show compile-time error
C Loops & Control Structure    
Discuss it

Question 1 Explanation: 
In for loop, mentioning expression is optional. >>= is a composite operator. It shifts the
binary representation of the value by 1 to the right and assigns the resulting value to the same
variable. The for loop is executed until value of variable i doesn't drop to 0.
Question 2
Correct
#include <stdio.h>
#define PRINT(i, limit) do
                        {
                            if (i++ < limit)
                            {
                                printf("GeeksQuizn");
                                continue;
                            }
                        }while(0)
 
int main()
{
    int i = 0;
    PRINT(i, 3);
    return 0;
}
How many times GeeksQuiz is printed in the above program ?
1
B3
C4
D Compile-time error
C Loops & Control Structure    
Discuss it

Question 2 Explanation: 
If a macro needs to be expanded in multiple lines, it is the best practice to write those lines
within do{ }while(0) to avoid macro side effects. After GeeksQuiz is printed once, the
control reaches the while statement to check for the condition. Since, the condition is false,
the loop gets terminated.
Question 3
Wrong
What is the output of the below program?
#include <stdio.h>
int main()
{
    int i = 0;
    switch (i)
    {
        case '0': printf("Geeks");
                break;
        case '1': printf("Quiz");
                break;
        default: printf("GeeksQuiz");
    }
    return 0;
}
A Geeks
B Quiz
GeeksQuiz
D Compile-time error
C Loops & Control Structure    
Discuss it

Question 3 Explanation: 
At first look, the output of the program seems to be Geeks. But, the cases are labeled with
characters which gets converted to their ascii values 48(for 0) and 49(for 1). None of the
cases is labeled with value 0. So, the control goes to the default block and GeeksQuiz is
printed.
Question 4
Wrong
#include <stdio.h>
int main()
{
    int i = 3;
    switch (i)
    {
        case 0+1: printf("Geeks");
                break;
        case 1+2: printf("Quiz");
                break;
        default: printf("GeeksQuiz");
    }
    return 0;
}
What is the output of the above program?
A Geeks
Quiz
C GeeksQuiz
D Compile-time error
C Loops & Control Structure    
Discuss it

Question 4 Explanation: 
Expression gets evaluated in cases. The control goes to the second case block after evaluating
1+2 = 3 and Quiz is printed.
Question 5
Wrong
Predict the output of the below program:
#include <stdio.h>
#define EVEN 0
#define ODD 1
int main()
{
    int i = 3;
    switch (i & 1)
    {
        case EVEN: printf("Even");
                break;
        case ODD: printf("Odd");
                break;
        default: printf("Default");
    }
    return 0;
}
A Even
Odd
C Default
D Compile-time error
C Loops & Control Structure    
Discuss it

Question 5 Explanation: 
The expression i & 1 returns 1 if the rightmost bit is set and returns 0 if the rightmost bit is
not set. As all odd integers have their rightmost bit set, the control goes to the block labeled
ODD.
Question 6
Correct
#include <stdio.h>
int main()
{
    int i;
    if (printf("0"))
        i = 3;
    else
        i = 5;
    printf("%d", i);
    return 0;
}
Predict the output of above program?
A3
B5
03
D 05
C Loops & Control Structure    
Discuss it

Question 6 Explanation: 
The control first goes to the if statement where 0 is printed. The printf("0") returns the
number of characters being printed i.e. 1. The block under if statement gets executed and i is
initialized with 3.
Question 7
Correct
#include <stdio.h>
int i;
int main()
{
    if (i);
    else
        printf("Ëlse");
    return 0;
}
What is correct about the above program?
A if block is executed.
else block is executed.
C It is unpredictable as i is not initialized.
D Error: misplaced else
C Loops & Control Structure    
Discuss it

Question 7 Explanation: 
Since i is defined globally, it is initialized with default value 0. The Else block is executed as
the expression within if evaluates to FALSE. Please note that the empty block is equivalent to
a semi-colon(;). So the statements if (i); and if (i) {} are equivalent.
Question 8
Correct
#include<stdio.h>
int main()
{
   int n;
   for (n = 9; n!=0; n--)
     printf("n = %d", n--);
   return 0;
}
What is the output?
A97531
B 987654321
Infinite Loop
D9753
C Loops & Control Structure    
Discuss it

Question 8 Explanation: 
The program goes in an infinite loop because n is never zero when loop condition (n != 0) is
checked. n changes like 7 5 3 1 -1 -3 -5 -7 -9 ...
Question 9
Wrong
Output?
#include <stdio.h>
int main()
{
    int c = 5, no = 10;
    do {
        no /= c;
    } while(c--);
  
    printf ("%dn", no);
    return 0;
}
A 1
B Runtime Error
C 0
Compiler Error
C Loops & Control Structure    
Discuss it

Question 9 Explanation: 
There is a bug in the above program. It goes inside the do-while loop for c = 0 also. So it fails
during runtime.
Question 10
Wrong
# include <stdio.h>
int main()
{
   int i = 0;
   for (i=0; i<20; i++)
   {
     switch(i)
     {
       case 0:
         i += 5;
       case 1:
         i += 2;
       case 5:
         i += 5;
       default:
         i += 4;
         break;
     }
     printf("%d  ", i);
   }
   return 0;
}
A 5 10 15 20
B 7 12 17 22
16 21
D Compiler Error
C Loops & Control Structure    
Discuss it

Question 10 Explanation: 
Initially i = 0. Since case 0 is true i becomes 5, and since there is no break statement till last
statement of switch block, i becomes 16. Now in next iteration no case is true, so execution
goes to default and i becomes 21. In C, if one case is true switch block is executed until it
finds break statement. If no break statement is present all cases are executed after the true
case. If you want to know why switch is implemented like this, well this implementation is
useful for situations like below.
switch (c)
{
case 'a':
case 'e':
case 'i' :
case 'o':
case 'u':
printf(" Vowel character");
break;
default :
printf("Not a Vowel character");; break;
}

C Functions
12345
Question 1
Wrong
Output of following program?
#include <stdio.h>
int main()
{
    int i = 5;
    printf("%d %d %d", i++, i++, i++);
    return 0;
}
A 765
B 567
C 777
Compiler Dependent
C Functions    
Discuss it

Question 1 Explanation: 
When parameters are passed to a function, the value of every parameter is evaluated before
being passed to the function. What is the order of evaluation of parameters - left-to-right or
right-to-left? If evaluation order is left-to-right, then output should be 5 6 7 and if the
evaluation order is right-to-left, then output should be 7 6 5. Unfortunately, there is no fixed
order defined by C standard. A compiler may choose to evaluate either from left-to-right. So
the output is compiler dependent.
Question 2
Correct
In C, parameters are always
Passed by value
B Passed by reference
C Non-pointer variables are passed by value and pointers are passed by reference
D Passed by value result
C Functions    
Discuss it

Question 2 Explanation: 
In C, function parameters are always passed by value. Pass-by-reference is simulated in C by
explicitly passing pointer values.
Question 3
Correct
Which of the following is true about return type of functions in C?
A Functions can return any type
Functions can return any type except array and functions
C Functions can return any type except array, functions and union
D Functions can return any type except array, functions, function pointer and union
C Functions    
Discuss it

Question 3 Explanation: 
In C, functions can return any type except arrays and functions. We can get around this
limitation by returning pointer to array or pointer to function.
Question 4
Wrong
#include <stdio.h>
int main()
{
  printf("%d", main); 
  return 0;
}
Address of main function
B Compiler Error
C Runtime Error
D Some random value
C Functions    
Discuss it

Question 4 Explanation: 
Explanation: Name of the function is actually a pointer variable to the function and prints the
address of the function. Symbol table is implemented like this.
struct
{
char *name;
int (*funcptr)();
}
symtab[] = {
"func", func,
"anotherfunc", anotherfunc,
};
Question 5
Wrong
Output?
#include <stdio.h>
 
int main()
{
    int (*ptr)(int ) = fun;
    (*ptr)(3);
    return 0;
}
 
int fun(int n)
{
  for(;n > 0; n--)
    printf("GeeksQuiz ");
  return 0;
}
A GeeksQuiz GeeksQuiz GeeksQuiz
B GeeksQuiz GeeksQuiz
Compiler Error
D Runtime Error
C Functions    
Discuss it

Question 5 Explanation: 
The only problem with program is fun is not declared/defined before it is assigned to ptr. The
following program works fine and prints "GeeksQuiz GeeksQuiz GeeksQuiz "
int fun(int n);

int main()
{
// ptr is a pointer to function fun()
int (*ptr)(int ) = fun;

// fun() called using pointer


(*ptr)(3);
return 0;
}

int fun(int n)
{
for(;n > 0; n--)
printf("GeeksQuiz ");
}
Question 6
Wrong
Output of following program?
#include<stdio.h>
 
void dynamic(int s, ...)
{
    printf("%d ", s);
}
 
int main()
{
    dynamic(2, 4, 6, 8);
    dynamic(3, 6, 9);
    return 0;
}
23
B Compiler Error
C 43
D 32
C Functions    
Discuss it

Question 6 Explanation: 
In c three continuous dots is known as ellipsis which is variable number of arguments of
function. The values to parameters are assigned one by one. Now the question is how to
access other arguments. See this for details.
Question 7
Correct
Predict the output?
#include <stdio.h>
int main()
{
    void demo();
    void (*fun)();
    fun = demo;
    (*fun)();
    fun();
    return 0;
}
 
void demo()
{
    printf("GeeksQuiz ");
}
A GeeksQuiz
GeeksQuiz GeeksQuiz
C Compiler Error
D Blank Screen
C Functions    
Discuss it

Question 7 Explanation: 
This is a simple program with function pointers. fun is assigned to point to demo. So the two
statements "(*fun)();" and "fun();" mean the same thing.
Question 8
Correct
What is the meaning of using extern before function declaration? For example following
function sum is made extern
extern int sum(int x, int y, int z)
{
return (x + y + z);
}
A Function is made globally available
extern means nothing, sum() is same without extern keyword.
C Function need not to be declared before its use
D Function is made local to the file.
C Functions    
Discuss it

Question 8 Explanation: 
extern keyword is used for global variables. Functions are global anyways, so adding extern
doesn't add anything.
Question 9
Correct
What is the meaning of using static before function declaration? For example following
function sum is made static
static int sum(int x, int y, int z)
{
return (x + y + z);
}
A Static means nothing, sum() is same without static keyword.
B Function need not to be declared before its use
Access to static functions is restricted to the file where they are declared
D Static functions are made inline
C Functions    
Discuss it

Question 9 Explanation: 
In C, functions are global by default. Unlike global functions, access to static functions is
restricted to the file where they are declared. We can have file level encapsulation using static
variables/functions in C because when we make a global variable static, access to the variable
becomes limited to the file in which it is declared.
Question 10
Wrong
In C, what is the meaning of following function prototype with empty parameter list
void fun()
{
   /* .... */
}
A Function can only be called without any parameter
Function can be called with any number of parameters of any types
C Function can be called with any number of integer parameters.
D Function can be called with one integer parameter.
C Functions    
Discuss it

Question 10 Explanation: 
Empty list in C mean that the parameter list is not specified and function can be called with
any parameters. In C, to declare a function that can only be called without any parameter, we
should use "void fun(void)" As a side note, in C++, empty list means function can only be
called without any parameter. In C++, both void fun() and void fun(void) are same.

Recursion
Recursion : The process in which a function calls itself directly or indirectly is called
recursion and the corresponding function is called as recursive function…. Read More

 
123
Question 1
Wrong
Predict output of following program
#include <stdio.h>
 
int fun(int n)
{
    if (n == 4)
       return n;
    else return 2*fun(n+1);
}
 
 
int main()
{
   printf("%d ", fun(2));
   return 0;
}
A 4
B 8
16
D Runtime Error
Recursion    
Discuss it

Question 1 Explanation: 
Fun(2) = 2 * Fun(3) and Fun(3) = 2 * Fun(4) ....(i)
Fun(4) = 4 ......(ii)
From equation (i) and (ii),
Fun(2) = 2 * 2 * Fun(4)
Fun(2) = 2 * 2 * 4
Fun(2) = 16.

So, C is the correct answer


Question 2
Wrong
Consider the following recursive function fun(x, y). What is the value of fun(4, 3)
int fun(int x, int y)
{
  if (x == 0)
    return y;
  return fun(x - 1,  x + y);
}
13
B 12
C 9
D 10
Recursion    
Discuss it

Question 2 Explanation: 
The function fun() calculates and returns ((1 + 2 … + x-1 + x) +y) which is x(x+1)/2 + y.
Question 3
Correct
What does the following function print for n = 25?
void fun(int n)
{
  if (n == 0)
    return;
 
  printf("%d", n%2);
  fun(n/2);

A 11001
10011
C 11111
D 00000
Recursion    
Discuss it

Question 3 Explanation: 
The function mainly prints binary representation in reverse order.
Question 4
Wrong
What does the following function do?
int fun(int x, int y)
{
    if (y == 0)   return 0;
    return (x + fun(x, y-1));
}
A x+y
B x + x*y
x*y
D xy
Recursion    
Discuss it

Question 4 Explanation: 
The function adds x to itself y times which is x*y.
Question 5
Wrong
What does fun2() do in general?
int fun(int x, int y)
{
    if (y == 0)   return 0;
    return (x + fun(x, y-1));
}
 
int fun2(int a, int b)
{
    if (b == 0) return 1;
    return fun(a, fun2(a, b-1));
}
A x*y
B x+x*y
C xy
yx
Recursion    
Discuss it

Question 5 Explanation: 
The function multiplies x to itself y times which is xy.
Question 6
Wrong
Output of following program?
#include<stdio.h>
void print(int n)
{
    if (n > 4000)
        return;
    printf("%d ", n);
    print(2*n);
    printf("%d ", n);
}
 
int main()
{
    print(1000);
    getchar();
    return 0;
}
A 1000 2000 4000
1000 2000 4000 4000 2000 1000
C 1000 2000 4000 2000 1000
D 1000 2000 2000 1000
Recursion    
Discuss it

Question 7
Wrong
What does the following function do?
int fun(unsigned int n)
{
    if (n == 0 || n == 1)
        return n;
 
    if (n%3 != 0)
        return 0;
 
    return fun(n/3);
}
A It returns 1 when n is a multiple of 3, otherwise returns 0
It returns 1 when n is a power of 3, otherwise returns 0
C It returns 0 when n is a multiple of 3, otherwise returns 1
D It returns 0 when n is a power of 3, otherwise returns 1
Recursion    
Discuss it

Question 8
Wrong
Predict the output of following program
#include <stdio.h>
int f(int n)
{
    if(n <= 1)
        return 1;
    if(n%2 == 0)
        return f(n/2);
    return f(n/2) + f(n/2+1);
}
 
 
int main()
{
    printf("%d", f(11));
    return 0;
}
A Stack Overflow
B 3
C 4
5
Recursion    
Discuss it

Question 8 Explanation: 
On successive recursion F(11) will be decomposed into F(5) + F(6) -> F(2) + F(3) + F(3) ->
F(1) + 2 * [F(1) + F(2)] -> 1 + 2 * [1 + F(1)] -> 1 + 2 * (1 + 1) -> 5. Hence , option D is the
correct answer i.e, 5.
Question 9
Correct
Consider the following recursive C function that takes two arguments
unsigned int foo(unsigned int n, unsigned int r) {
  if (n  > 0) return (n%r +  foo (n/r, r ));
  else return 0;
}
What is the return value of the function foo when it is called as foo(345, 10) ?
A 345
12
C5
D3
Recursion    GATE CS 2011    
Discuss it

Question 9 Explanation: 
The call foo(345, 10) returns sum of decimal digits (because r is 10) in the number n. Sum of
digits for 345 is 3 + 4 + 5 = 12.

This solution is
contributed by Pranjul Ahuja
Question 10
Correct
Consider the same recursive C function that takes two arguments
unsigned int foo(unsigned int n, unsigned int r) {
  if (n  > 0) return (n%r +  foo (n/r, r ));
  else return 0;
}
What is the return value of the function foo when it is called as foo(513, 2)?
A9
B8
C5
2
Recursion    GATE CS 2011    
Discuss it

Question 10 Explanation: 
foo(513, 2) will return 1 + foo(256, 2). All subsequent recursive calls (including foo(256, 2))
will return 0 + foo(n/2, 2) except the last call foo(1, 2) . The last call foo(1, 2) returns 1. So,
the value returned by foo(513, 2) is 1 + 0 + 0…. + 0 + 1. The function foo(n, 2) basically
returns sum of bits (or count of set bits) in the number n.

C Storage Classes and Type Qualifiers


1234
Question 1
Wrong
Which of the following is not a storage class specifier in C?
A auto
B register
C static
D extern
volatile
F typedef
C Storage Classes and Type Qualifiers    
Discuss it

Question 1 Explanation: 
volatile is not a storage class specifier. volatile and const are type qualifiers.
Question 2
Correct
Output of following program?
#include <stdio.h>
int main()
{
    static int i=5;
    if(--i){
        main();
        printf("%d ",i);
    }
}
A 4321
B 1234
0000
D Compiler Error
C Storage Classes and Type Qualifiers    
Discuss it

Question 2 Explanation: 
A static variable is shared among all calls of a function. All calls to main() in the given
program share the same i. i becomes 0 before the printf() statement in all calls to main().
Question 3
Wrong
#include <stdio.h>
int main()
{
    static int i=5;
    if (--i){
        printf("%d ",i);
        main();
    }
}
A 4321
B 1234
4444
D 0000
C Storage Classes and Type Qualifiers    
Discuss it

Question 3 Explanation: 
Since i is static variable, it is shared among all calls to main(). So is reduced by 1 by every
function call.
Question 4
Correct
#include <stdio.h>
int main()
{
    int x = 5;
    int * const ptr = &x;
    ++(*ptr);
    printf("%d", x);
   
    return 0;
}
A Compiler Error
B Runtime Error
6
D 5
C Storage Classes and Type Qualifiers    
Discuss it

Question 4 Explanation: 
See following declarations to know the difference between constant pointer and a pointer to a
constant. int * const ptr —> ptr is constant pointer. You can change the value at the location
pointed by pointer p, but you can not change p to point to other location. int const * ptr —>
ptr is a pointer to a constant. You can change ptr to point other variable. But you cannot
change the value pointed by ptr. Therefore above program works well because we have a
constant pointer and we are not changing ptr to point to any other location. We are only
icrementing value pointed by ptr.
Question 5
Wrong
#include <stdio.h>
int main()
{
    int x = 5;
    int const * ptr = &x;
    ++(*ptr);
    printf("%d", x);
   
    return 0;
}
Compiler Error
B Runtime Error
C 6
D 5
C Storage Classes and Type Qualifiers    
Discuss it

Question 5 Explanation: 
See following declarations to know the difference between constant pointer and a pointer to a
constant. int * const ptr —> ptr is constant pointer. You can change the value at the location
pointed by pointer p, but you can not change p to point to other location. int const * ptr —>
ptr is a pointer to a constant. You can change ptr to point other variable. But you cannot
change the value pointed by ptr. In the above program, ptr is a pointer to a constant. So the
value pointed cannot be changed.
Question 6
Wrong
#include<stdio.h>
int main()
{
  typedef static int *i;
  int j;
  i a = &j;
  printf("%d", *a);
  return 0;
}
A Runtime Error
B 0
C Garbage Value
Compiler Error
C Storage Classes and Type Qualifiers    
Discuss it

Question 6 Explanation: 
Compiler Error -> Multiple Storage classes for a. In C, typedef is considered as a storage
class. The Error message may be different on different compilers.
Question 7
Wrong
Output?
#include<stdio.h>
int main()
{
   typedef int i;
   i a = 0;
   printf("%d", a);
   return 0;
}
A Compiler Error
B Runtime Error
C 0
1
C Storage Classes and Type Qualifiers    
Discuss it

Question 7 Explanation: 
There is no problem with the program. It simply creates a user defined type i and creates a
variable a of type i.
Question 8
Wrong
#include<stdio.h>
int main()
{
  typedef int *i;
  int j = 10;
  i *a = &j;
  printf("%d", **a);
  return 0;
}
A Compiler Error
B Garbage Value
C 10
0
C Storage Classes and Type Qualifiers    
Discuss it

Question 8 Explanation: 
Compiler Error -> Initialization with incompatible pointer type. The line typedef int *i makes
i as type int *. So, the declaration of a means a is pointer to a pointer. The Error message may
be different on different compilers.
Question 9
Correct
Output?
#include <stdio.h>
int fun()
{
  static int num = 16;
  return num--;
}
 
int main()
{
  for(fun(); fun(); fun())
    printf("%d ", fun());
  return 0;
}
A Infinite loop
B 13 10 7 4 1
14 11 8 5 2
D 15 12 8 5 2
C Storage Classes and Type Qualifiers    
Discuss it

Question 9 Explanation: 
Since num is static in fun(), the old value of num is preserved for subsequent functions calls.
Also, since the statement return num– is postfix, it returns the old value of num, and updates
the value for next function call.
fun() called first time: num = 16 // for loop initialization done;

In test condition, compiler checks for non zero value

fun() called again : num = 15

printf("%d \n", fun());:num=14 ->printed

Increment/decrement condition check

fun(); called again : num = 13

----------------

fun() called second time: num: 13

In test condition,compiler checks for non zero value

fun() called again : num = 12

printf("%d \n", fun());:num=11 ->printed

fun(); called again : num = 10

--------

fun() called second time : num = 10

In test condition,compiler checks for non zero value

fun() called again : num = 9

printf("%d \n", fun());:num=8 ->printed

fun(); called again   : num = 7

--------------------------------

fun() called second time: num = 7

In test condition,compiler checks for non zero value

fun() called again : num = 6

printf("%d \n", fun());:num=5 ->printed


fun(); called again   : num = 4

-----------

fun() called second time: num: 4

In test condition,compiler checks for non zero value

fun() called again : num = 3

printf("%d \n", fun());:num=2 ->printed

fun(); called again   : num = 1

----------

fun() called second time: num: 1

In test condition,compiler checks for non zero value

fun() called again : num = 0 => STOP


Question 10
Correct
#include <stdio.h>
int main()
{
  int x = 10;
  static int y = x;
   
  if(x == y)
     printf("Equal");
  else if(x > y)
     printf("Greater");
  else
     printf("Less");
  return 0;
}
Compiler Error
B Equal
C Greater
D Less
C Storage Classes and Type Qualifiers    
Discuss it

Question 10 Explanation: 
In C, static variables can only be initialized using constant literals. This is allowed in C++
though.  See this GFact for details.

C Structure & Union


123
Question 1
Wrong
#include‹stdio.h›
int main()
{
    struct site
    {
        char name[] = "GeeksQuiz";
        int no_of_pages = 200;
    };
    struct site *ptr;
    printf("%d ", ptr->no_of_pages);
    printf("%s", ptr->name);
    getchar();
    return 0;
}
A 200 GeeksQuiz
B 200
Runtime Error
D Compiler Error
C Structure & Union    
Discuss it

Question 1 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.
Question 2
Wrong
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
Runtime Error
C Structure & Union    
Discuss it

Question 2 Explanation: 
In C, struct and union types cannot have static members. In C++, struct types are allowed to
have static members, but union cannot have static members in C++ also.
Question 3
Wrong
struct node
{
   int i;
   float j;
};
struct node *s[10];
The above C declaration define 's' to be (GATE CS 2000)
A An array, each element of which is a pointer to a structure of type node
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.
C Structure & Union    
Discuss it

Question 3 Explanation: 
Refer Structures in C.
Question 4
Wrong
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
(GATE CS 2000)
22 bytes
B 14 bytes
C 18 bytes
D 10 bytes
C Structure & Union    
Discuss it

Question 4 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).
Question 5
Wrong
#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
Garbage Value
C Structure & Union    
Discuss it

Question 5 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 can be a member because pointers of all types are of same size and compiler can
calculate size of struct
Question 6
Which of the following operators can be applied on structure variables?
A Equality comparison ( == )
B Assignment ( = )
C Both of the above
D None of the above
C Structure & Union    
Discuss it

Question 7
Wrong
union test
{
    int x;
    char arr[8];
    int y;
};
 
int main()
{
    printf("%d", sizeof(union test));
    return 0;
}
Predict the output of above 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.
A 12
16
C8
D Compiler Error
C Structure & Union    
Discuss it
Question 7 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.
Question 8
Wrong
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;
}
Predict the output of above 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.
A Nothing is printed
G
C Garbage character followed by 'G'
D Garbage character followed by 'G', followed by more garbage characters
E Compiler Error
C Structure & Union    
Discuss it

Question 8 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 character and keeps printing
till it finds a \0. Since the first character itself is \0, nothing is printed.
Question 9
Correct
# include <iostream>
# include <string.h>
using namespace std;
 
struct Test
{
  char str[20];
};
 
int main()
{
  struct Test st1, st2;
  strcpy(st1.str, "GeeksQuiz");
  st2 = st1;
  st1.str[0] = 'S';
  cout << st2.str;
  return 0;
}
A Segmentation Fault
B SeeksQuiz
GeeksQuiz
D Compiler Error
C Structure & Union    
Discuss it

Question 9 Explanation: 
Array members are deeply copied when a struct variable is assigned to another one. See Are
array members deeply copied? for more details.
Question 10
Correct
Predict the output of 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
201
C 012
D 210
C Structure & Union    
Discuss it

Question 10 Explanation: 
Refer designated Initialization discussed here.

Pointers:

C Pointer Basics
12345
Question 1
Wrong
What is the output of following program?
# include <stdio.h>
void fun(int x)
{
    x = 30;
}
 
int main()
{
  int y = 20;
  fun(y);
  printf("%d", y);
  return 0;
}
A 30
20
C Compiler Error
D Runtime Error
C Pointer Basics    
Discuss it

Question 1 Explanation: 
Parameters are always passed by value in C. Therefore, in the above code, value of y is not
modified using the function fun(). So how do we modify the value of a local variable of a
function inside another function. Pointer is the solution to such problems. Using pointers, we
can modify a local variable of a function inside another function. See the next question. Note
that everything is passed by value in C. We only get the effect of pass by reference using
pointers.
Question 2
Correct
Output of following program?
# include <stdio.h>
void fun(int *ptr)
{
    *ptr = 30;
}
 
int main()
{
  int y = 20;
  fun(&y);
  printf("%d", y);
 
  return 0;
}
A 20
30
C Compiler Error
D Runtime Error
C Pointer Basics    
Discuss it

Question 2 Explanation: 
The function fun() expects a pointer ptr to an integer (or an address of an integer). It modifies
the value at the address ptr. The dereference operator * is used to access the value at an
address. In the statement ‘*ptr = 30’, value at address ptr is changed to 30. The address
operator & is used to get the address of a variable of any data type. In the function call
statement ‘fun(&y)’, address of y is passed so that y can be modified using its address.
Question 3
Wrong
Output of following program?
#include <stdio.h>
 
int main()
{
    int *ptr;
    int x;
 
    ptr = &x;
    *ptr = 0;
 
    printf(" x = %dn", x);
    printf(" *ptr = %dn", *ptr);
 
    *ptr += 5;
    printf(" x  = %dn", x);
    printf(" *ptr = %dn", *ptr);
 
    (*ptr)++;
    printf(" x = %dn", x);
    printf(" *ptr = %dn", *ptr);
 
    return 0;
}
x=0
*ptr = 0
x=5
*ptr = 5
x=6
*ptr = 6
x = garbage value
*ptr = 0
x = garbage value
B
*ptr = 5
x = garbage value
*ptr = 6
x=0
*ptr = 0
x=5
C
*ptr = 5
x = garbage value
*ptr = garbage value
x=0
*ptr = 0
x=0
D
*ptr = 0
x=0
*ptr = 0
C Pointer Basics    
Discuss it

Question 3 Explanation: 
See the comments below for explanation.
int *ptr; /* Note: the use of * here is not for dereferencing,
it is for data type int */
int x;

ptr = &x; /* ptr now points to x (or ptr is equal to address of x) */


*ptr = 0; /* set value ate ptr to 0 or set x to zero */

printf(" x = %d\n", x); /* prints x = 0 */


printf(" *ptr = %d\n", *ptr); /* prints *ptr = 0 */

*ptr += 5; /* increment the value at ptr by 5 */


printf(" x = %d\n", x); /* prints x = 5 */
printf(" *ptr = %d\n", *ptr); /* prints *ptr = 5 */

(*ptr)++; /* increment the value at ptr by 1 */


printf(" x = %d\n", x); /* prints x = 6 */
printf(" *ptr = %d\n", *ptr); /* prints *ptr = 6 */
Question 4
Correct
Consider a compiler where int takes 4 bytes, char takes 1 byte and pointer takes 4 bytes.
#include <stdio.h>
 
int main()
{
    int arri[] = {1, 2 ,3};
    int *ptri = arri;
 
    char arrc[] = {1, 2 ,3};
    char *ptrc = arrc;
 
    printf("sizeof arri[] = %d ", sizeof(arri));
    printf("sizeof ptri = %d ", sizeof(ptri));
 
    printf("sizeof arrc[] = %d ", sizeof(arrc));
    printf("sizeof ptrc = %d ", sizeof(ptrc));
 
    return 0;
}
sizeof arri[] = 3 sizeof ptri = 4 sizeof arrc[] =
A
3 sizeof ptrc = 4
sizeof arri[] = 12 sizeof ptri = 4 sizeof arrc[]
B
= 3 sizeof ptrc = 1
sizeof arri[] = 3 sizeof ptri = 4 sizeof arrc[] =
C
3 sizeof ptrc = 1
sizeof arri[] = 12 sizeof ptri = 4 sizeof arrc[]
= 3 sizeof ptrc = 4
C Pointer Basics    
Discuss it

Question 4 Explanation: 
Size of an array is number of elements multiplied by the type of element, that is why we get
sizeof arri as 12 and sizeof arrc as 3. Size of a pointer is fixed for a compiler. All pointer
types take same number of bytes for a compiler. That is why we get 4 for both ptri and ptrc.
Question 5
Wrong
Assume that float takes 4 bytes, predict the output of following program.
#include <stdio.h>
 
int main()
{
    float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5};
    float *ptr1 = &arr[0];
    float *ptr2 = ptr1 + 3;
 
    printf("%f ", *ptr2);
    printf("%d", ptr2 - ptr1);
 
   return 0;
}
90.500000 3
B 90.500000 12
C 10.000000 12
D 0.500000 3
C Pointer Basics    
Discuss it

Question 5 Explanation: 
When we add a value x to a pointer p, the value of the resultant expression is p + x*sizeof(*p)
where sizeof(*p) means size of data type pointed by p. That is why ptr2 is incremented to
point to arr[3] in the above code. Same rule applies for subtraction. Note that only integral
values can be added or subtracted from a pointer. We can also subtract or compare two
pointers of same type.
Question 6
Wrong
#include<stdio.h>
int main()
{
    int arr[] = {10, 20, 30, 40, 50, 60};
    int *ptr1 = arr;
    int *ptr2 = arr + 5;
    printf("Number of elements between two pointer are: %d.",
                                (ptr2 - ptr1));
    printf("Number of bytes between two pointers are: %d", 
                              (char*)ptr2 - (char*) ptr1);
    return 0;
}
Assume that an int variable takes 4 bytes and a char variable takes 1 byte
Number of elements between two pointer are: 5. Number of bytes between two pointers
are: 20
Number of elements between two pointer are: 20. Number of bytes between two pointers
B
are: 20
Number of elements between two pointer are: 5. Number of bytes between two pointers
C
are: 5
D Compiler Error
E Runtime Error
C Pointer Basics    
Discuss it

Question 6 Explanation: 
Array name gives the address of first element in array. So when we do '*ptr1 = arr;', ptr1
starts holding the address of element 10. 'arr + 5' gives the address of 6th element as
arithmetic is done using pointers. So 'ptr2-ptr1' gives 5. When we do '(char *)ptr2', ptr2 is
type-casted to char pointer and size of character is one byte, pointer arithmetic happens
considering character pointers. So we get 5*sizeof(int)/sizeof(char) as a difference of two
pointers.
Question 7
Wrong
#include<stdio.h>
int main()
{
   int a;
   char *x;
   x = (char *) &a;
   a = 512;
   x[0] = 1;
   x[1] = 2;
   printf("%dn",a);  
   return 0;
}
What is the output of above program?
Machine dependent
B 513
C 258
D Compiler Error
C Pointer Basics    
Discuss it

Question 7 Explanation: 
Output is 513 in a little endian machine. To understand this output, let integers be stored
using 16 bits. In a little endian machine, when we do x[0] = 1 and x[1] = 2, the number a is
changed to 00000001 00000010 which is representation of 513 in a little endian machine.
Question 8
Wrong
int main()
{
 char *ptr = "GeeksQuiz";
 printf("%cn", *&*&*ptr);
 return 0;
}
A Compiler Error
B Garbage Value
C Runtime Error
G
C Pointer Basics    
Discuss it

Question 8 Explanation: 
The operator * is used for dereferencing and the operator & is used to get the address. These
operators cancel out effect of each other when used one after another. We can apply them
alternatively any no. of times. In the above code, ptr is a pointer to first character of string g.
*ptr gives us g, &*ptr gives address of g, *&*ptr again g, &*&*ptr address of g, and finally
*&*&*ptr gives ‘g’ Now try below
int main()
{
char *ptr = "GeeksQuiz";
printf("%s\n", *&*&ptr);
return 0;
}
Question 9
Wrong
#include<stdio.h>
void fun(int arr[])
{
  int i;
  int arr_size = sizeof(arr)/sizeof(arr[0]);
  for (i = 0; i < arr_size; i++)
      printf("%d ", arr[i]);
}
 
int main()
{
  int i;
  int arr[4] = {10, 20 ,30, 40};
  fun(arr);
  return 0;
}
A 10 20 30 40
Machine Dependent
C 10 20
D Northing
C Pointer Basics    
Discuss it

Question 9 Explanation: 
In C, array parameters are always treated as pointers. So following two statements have the
same meaning.
void fun(int arr[])
void fun(int *arr)
[] is used to make it clear that the function expects an array, it doesn’t change anything
though. People use it only for readability so that the reader is clear about the intended
parameter type. The bottom line is, sizeof should never be used for array parameters, a
separate parameter for array size (or length) should be passed to fun(). So, in the given
program, arr_size contains ration of pointer size and integer size, this ration= is
compiler dependent. #include void fun(int arr[], size_t arr_size) { int i; for (i = 0; i <
arr_size; i++) printf("%d ", arr[i]); } int main() { int i; int arr[] = {10, 20 ,30, 40}; // Use of
sizeof is fine here size_t n = sizeof(arr)/sizeof(arr[0]); fun(arr, n); return 0; } [/sourcecode]
Output: 10 20 30 40
Question 10
Wrong
The reason for using pointers in a Cprogram is
A Pointers allow different functions to share and modify their local variables.
B To pass large structures so that complete copy of the structure can be avoided.
C Pointers enable complex “linked" data structures like linked lists and binary trees.
All of the above
C Pointer Basics    
Discuss it

Question 10 Explanation: 
See below explanation (A) With pointers, address of variables can be passed different
functions can use this address to access the variables. (B) When large structure variables
passed or returned, they are copied as everything is passed and returned by value in C. This
can be costly with structure containing large data. To avoid this copying of large variables,
we generally use poitner for large structures so that only address is copied. (C) With pointers,
we can implement “linked” data structures. Java uses reference variables to implement these
data structures. Note that C doesn't support reference variables.

C Arrays
1234
Question 1
Wrong
Predict the output of below 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
lvalue required
C Arrays    
Discuss it

Question 1 Explanation: 
Array name in C is implemented by a constant pointer. It is not possible to apply increment
and decrement on constant types.
Question 2
Wrong
Predict the output of below 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;
}
2004 2020
B 2004 2004
C 2004 Garbage value
The program fails to compile because
D Address-of operator cannot be used with
array name
C Arrays    
Discuss it

Question 2 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.
Question 3
Wrong
What is output?
# include <stdio.h>
 
void print(int arr[])
{
   int n = sizeof(arr)/sizeof(arr[0]);
   int i;
   for (i = 0; i < n; i++)
      printf("%d ", arr[i]);
}
 
int main()
{
   int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
   print(arr);
   return 0;
}
A 1, 2, 3, 4, 5, 6, 7, 8
B Compiler Error
12
D Run Time Error
C Arrays    
Discuss it

Question 3 Explanation: 
See http://www.geeksforgeeks.org/using-sizof-operator-with-array-paratmeters/ for
explanation.
Question 4
Output of following 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
6
D Runtime Error
C Arrays    
Discuss it

Question 5
Wrong
Consider the following C-function in which a[n] and b[m] are two sorted integer arrays and
c[n + m] be another integer array.
void xyz(int a[], int b [], int c[])
{
  int i, j, k;
  i = j = k = O;
  while ((i<n) && (j<m))
     if (a[i] < b[j]) c[k++] = a[i++];
     else c[k++] = b[j++];
}
Which of the following condition(s) hold(s) after the termination of the while loop? (GATE
CS 2006) (i) j < m, k = n+j-1, and a[n-1] < b[j] if i = n (ii) i < n, k = m+i-1, and b[m-1] <=
a[i] if j = m
A only (i)
B only (ii)
either (i) or (ii) but not both
D neither (i) nor (ii)
C Arrays    
Discuss it
Question 5 Explanation: 
The function xyz() is similar to merge() of mergeSort(). The condition (i) is true if the last
inserted element in c[] is from a[] and condition (ii) is true if the last inserted element is from
b[].
Question 6
Wrong
Assume the following C variable declaration
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
(GATE CS 2003)?
I, II, and IV only
B II, III, and IV only
C II and IV only
D IV only
C Arrays    
Discuss it

Question 6 Explanation: 
See following for explanation.
int main()
{
int *A[10], B[10][10];
int C[] = {12, 11, 13, 14};

/* No problem with below statement as A[2] is a pointer


and we are assigning a value to pointer */
A[2] = C;

/* No problem with below statement also as array style indexing


can be done with pointers*/
A[2][3] = 15;

/* Simple assignment to an element of a 2D array*/


B[2][3] = 15;

printf("%d %d", A[2][0], A[2][3]);


return 0;
}
Question 7
Correct
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 (GATE CS 2002)
A 4040
4050
C 5040
D 5050
C Arrays    
Discuss it

Question 7 Explanation: 
Address of a[40][50] = Base address + 40*100*element_size + 50*element_size
= 0 + 4000*1 + 50*1
= 4050
Based on row major or column major
if row major then the result will be 4050
if column major then
Address of a[40][50] = Base address + 50*100*element_size +
40*element_size
= 0 + 5000*1 + 40*1
= 5040
Question 8
Wrong
Which of the following is true about arrays in C.
A For every type T, there can be an array of T.
For every type T except void and function type, there can be an array of T.
C When an array is passed to a function, C compiler creates a copy of array.
D 2D arrays are stored in column major form
C Arrays    
Discuss it

Question 8 Explanation: 
In C, we cannot have an array of void type and function types. For example, below program
throws compiler error
int main()
{
void arr[100];
}
But we can have array of void pointers and function pointers. The below program works fine.
int main()
{
void *arr[100];
}
See examples of function pointers for details of array function pointers.
Question 9
Correct
Predict the output of the below program:
#include <stdio.h>
#define SIZE(arr) sizeof(arr) / sizeof(*arr);
void fun(int* arr, int n)
{
    int i;
    *arr += *(arr + n - 1) += 10;
}
 
void printArr(int* arr, int n)
{
    int i;
    for(i = 0; i < n; ++i)
        printf("%d ", arr[i]);
}
 
int main()
{
    int arr[] = {10, 20, 30};
    int size = SIZE(arr);
    fun(arr, size);
    printArr(arr, size);
    return 0;
}
A 20 30 40
B 20 20 40
50 20 40
D Compile-time error
C Arrays    
Discuss it

Question 9 Explanation: 
The crux of the question lies in the expression: *arr += *(arr + n - 1) += 10; The composite
operator (here +=) has right to left associativity. First 10 is added to the last element of the
array. The result is then added to the first element of the array.
Question 10
Wrong
Predict output of following program
int main()
{
    int i;
    int arr[5] = {1};
    for (i = 0; i < 5; i++)
        printf("%d ", arr[i]);
    return 0;
}
A 1 followed by four garbage values
10000
C 11111
D 00000
C Arrays    
Discuss it

Question 10 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};

C Dynamic Memory Allocation


1
Question 1
Wrong
The most appropriate matching for the following pairs (GATE CS 2000)
X: m=malloc(5); m= NULL;        1: using dangling pointers
Y: free(n); n->value=5;         2: using uninitialized pointers
Z: char *p; *p = ’a’;           3. lost memory is:
A X—1 Y—3 Z-2
B (X—2 Y—1 Z-3
C X—3 Y—2 Z-1
X—3 Y—1 Z-2
C Dynamic Memory Allocation    
Discuss it

Question 1 Explanation: 
X -> A pointer is assigned to NULL without freeing memory so a clear example of memory
leak Y -> Trying to retrieve value after freeing it so dangling pointer. Z -> Using uninitialized
pointers
Question 2
Wrong
Consider the following three C functions :
[PI] int * g (void)
{
  int x= 10;
  return (&x);

   
[P2] int * g (void)
{
  int * px;
  *px= 10;
  return px;
}
   
[P3] int *g (void)
{
  int *px;
  px = (int *) malloc (sizeof(int));
  *px= 10;
  return px;
}
Which of the above three functions are likely to cause problems with pointers? (GATE 2001)
A Only P3
B Only P1 and P3
Only P1 and P2
D P1, P2 and P3
C Dynamic Memory Allocation    
Discuss it

Question 2 Explanation: 
In P1, pointer variable x is a local variable to g(), and g() returns pointer to this variable. x
may vanish after g() has returned as x exists on stack. So, &x may become invalid. In P2,
pointer variable px is being assigned a value without allocating memory to it. P3 works
perfectly fine. Memory is allocated to pointer variable px using malloc(). So, px exists on
heap, it’s existence will remain in memory even after return of g() as it is on heap.
Question 3
Wrong
Output?
# include<stdio.h>
# include<stdlib.h>
  
void fun(int *a)
{
    a = (int*)malloc(sizeof(int));
}
  
int main()
{
    int *p;
    fun(p);
    *p = 6;
    printf("%dn",*p);
    return(0);
}
May not work
B Works and prints 6
C Dynamic Memory Allocation    
Discuss it

Question 3 Explanation: 
The program is not valid. Try replacing “int *p;” with “int *p = NULL;” and it will try to
dereference a null pointer. This is because fun() makes a copy of the pointer, so when
malloc() is called, it is setting the copied pointer to the memory location, not p. p is pointing
to random memory before and after the call to fun(), and when you dereference it, it will
crash. If you want to add memory to a pointer from a function, you need to pass the address
of the pointer (ie. double pointer).
Question 4
Wrong
Which of the following is/are true
calloc() allocates the memory and also initializes the allocates memory to zero, while
A
memory allocated using malloc() has random data.
B malloc() and memset() can be used to get the same effect as calloc().
C calloc() takes two arguments, but malloc takes only 1 argument.
D Both malloc() and calloc() return 'void *' pointer.
All of the above
C Dynamic Memory Allocation    
Discuss it

Question 4 Explanation: 
All of the given options are true. See http://www.geeksforgeeks.org/calloc-versus-malloc/ for
details.
Question 5
Correct
What is the return type of malloc() or calloc()
void *
B Pointer of allocated memory type
C void **
D int *
C Dynamic Memory Allocation    
Discuss it

Question 5 Explanation: 
malloc() and calloc() return void *. We may get warning in C if we don't type cast the return
type to appropriate pointer.
Question 6
Wrong
Which of the following is true?
"ptr = calloc(m, n)" is equivalent to following
A
ptr = malloc(m * n);
"ptr = calloc(m, n)" is equivalent to following

ptr = malloc(m * n); memset(ptr, 0, m * n);


"ptr = calloc(m, n)" is equivalent to following
C
ptr = malloc(m); memset(ptr, 0, m);
"ptr = calloc(m, n)" is equivalent to following
D
ptr = malloc(n); memset(ptr, 0, n);
C Dynamic Memory Allocation    
Discuss it

Question 6 Explanation: 
See calloc() versus malloc() for details.
Question 7
Wrong
What is the problem with following code?
#include<stdio.h>
int main()
{
    int *p = (int *)malloc(sizeof(int));
 
    p = NULL;
 
    free(p);
}
Compiler Error: free can't be applied on NULL
A
pointer
Memory Leak
C Dangling Pointer
The program may crash as free() is called for
D
NULL pointer.
C Dynamic Memory Allocation    
Discuss it

Question 7 Explanation: 
free() can be called for NULL pointer, so no problem with free function call. The problem is
memory leak, p is allocated some memory which is not freed, but the pointer is assigned as
NULL. The correct sequence should be following:
free(p);
p = NULL;
Question 8
Wrong
Consider the following program, where are i, j and k are stored in memory?
int i;
int main()
{
    int j;
    int *k = (int *) malloc (sizeof(int));
}
A i, j and *k are stored in stack segment
B i and j are stored in stack segment. *k is stored on heap.
i is stored in BSS part of data segment, j is stored in
stack segment. *k is stored on heap.
j is stored in BSS part of data segment, i is stored in
D
stack segment. *k is stored on heap.
C Dynamic Memory Allocation    
Discuss it

Question 8 Explanation: 
i is global variable and it is uninitialized so it is stored on BSS part of Data Segment
(http://en.wikipedia.org/wiki/.bss) j is local in main() so it is stored in stack frame
(http://en.wikipedia.org/wiki/Call_stack) *k is dynamically allocated so it is stored on Heap
Segment. See following article for more details. Memory Layout of C Programs
Question 9
Wrong
Which languages necessarily need heap allocation in the run time environment?
A Those that support recursion
B Those that use dynamic scoping
C Those that use global variables
Those that allow dynamic data structures
C Dynamic Memory Allocation    Heap    ISRO CS 2017    
Discuss it

Question 10
Wrong
We use malloc and calloc for
Dynamic memory allocation
B Static memory allocation
C Both dynamic and static memory allocation
D None of the above
C Dynamic Memory Allocation    ISRO CS 2017 - May    
Discuss it

Question 10 Explanation: 
Both Calloc() and Malloc() are used for dynamic memory allocation. Refer: calloc() versus
malloc()

You might also like