CDS SET-1 - Merged

Download as pdf or txt
Download as pdf or txt
You are on page 1of 175

SRIDHAR

CONTENTS

Topic Page No

Features of C Language 1
C Tokens 2
Data Types 3
Operators 4 – 11
Control Statements 11 – 18
Functons, Data Passing Mechanisms 18 – 19
Variable Scope 20 – 21
Storage Classes 22 – 26
Recursion 26 – 31
Class Room Objectives 32 – 42
Previous Questions 43 – 65
Practice Questions 66 – 76
Key 77

C PROGRAMMING & DATA STRUCTURES 1


SRIDHAR

FEATURES OF C LANGUAGE
C is the most popular programming language, C has many features.
a. General Purpose Programming Language: C can be used to implement any
kind of applications such as math’s oriented, graphics, business oriented
applications. It is also called “system programming language” but equally
suited to writing a variety of applications.
b. Middle Level: As a middle level language it bridges elements of high level
language with the functionality of assembly language.
Ex:
#include<stdio.h>
void main()
{
int a=3,b=4,c;
asm
{
mov ax,a
mov bx,b
add ax,bx
mov c,ax
}
printf(" sum = %d",c);
}
output : sum=7
c. Structured Programming: Structured programming sometimes known as
modular programming). The programmers can easily divide a problem into a
number of modules or functions. Structured programs are composed of simple,
hierarchical program flow structures. These are sequence, selection, and
repetition
d. Portability: This refers to the ability of a program to run in different
environments.
e. Efficient Compilation and Execution: The process of compilation and
execution of programs is quite fast in C Language as compared to other
languages.
f. Modularity: C Language programs can be divided into small modules with
the help of functions which help in increasing understanding of the programs.
g. C is case sensitive language

C PROGRAMMING & DATA STRUCTURES 1


SRIDHAR

C TOKENS
 A token is the basic building block of a C program which can be recognized by
the compiler.

Identifier naming rules in C


 In c any name is called identifier. This name can be variable name, function name,
enum constant name, micro constant name or goto label name.

Rules for Identifier :


Rule 1: First character of any identifier must be either alphabets or underscore.
Rule 2: Name of identifier includes alphabets, digit and underscore.
Rule 3: Name of identifier cannot be any keyword of c program.
Rule 4: Name of identifier is case sensitive i.e. num and Num are two different
variables.

Keywords in C Language
auto double int struct
break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
default goto sizeof volatile
const float short unsigned
There are some additional keywords supported by Turbo C.

Asm far interrupt pascal near huge cdecl


Constants:
There are four basic types of constants in C. They are:
1. Integer constants : Full numbers are int constants Ex: 12, 78, -9, 19
2. Floating-point constants : Decimal values are floating point constants.
Ex: 0.1 2E-4 -0.1555e-4

C PROGRAMMING & DATA STRUCTURES 2


SRIDHAR

3. Character constants : A character constant is a single character, enclosed in


single quotation marks. Ex: ‘A’ ‘B’ ‘1’
4. String constants : A string constant consists of zero or more character enclosed in
double quotation marks(“”). Several string constants are given below.
Ex : “a”,”123”,”Rama”

Counting Tokens
Find the number of tokens in the following C statement.
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.

Data Types and its range in DOS Environment.


Data Type Range Bytes Format
Signed char -128 to +127 1 %c
Unsigned char 0 to 255 1 %c
Short signed int -32768 to +32767 2 %d
Short unsigned int 0 to 65535 2 %u
Signed int -32768 to +32767 2 %d
Unsigned int 0 to 65535 2 %u
Long signed int -2147483648 to +2147483647 4 %1d
Long unsigned int 0 to 4294967295 4 %1u
Float -3.4e38 to +3.4e38 4 %f
Double -1.7e308 to +1.7e308 8 %1f
Long double -1.7e4932 to +1.7e4932 10 %Lf
Note: The sizes and ranges of int, short and long are compiler dependent. Sizes in this
figure are for 16-bit compiler.

C PROGRAMMING & DATA STRUCTURES 3


SRIDHAR

Operators

i Arithmetic Operators (+, -, *, /, %):


e.g. Suppose a=5.0, b=2.0, c=5 and Suppose int a=9, b=4;
d=2 a + b=13 a - b=5
a/b=2.5 a/d=2.5 a * b=36 a / b=2
c/b=2.5 c/d=2 a % b=1
a % b is not possible
because % operator works with only
integers
ii Relational operators
== Equal to 5==3 returns false (0)
> Greater than 5>3 returns true (1)
< Less than 5<3 returns false (0)
!= Not equal to 5!=3 returns true(1)
>= Greater than or equal to 5>=3 returns true (1)
<= Less than or equal to 5<=3 return false (0)
iii Logical Operators
Assume c=5 and d=2
&& Logial AND a) ((c==5) && (d>5)) returns false.
b) ((c==5) && (d<5)) returns true.
|| Logical OR If c=5 and d=2 then, ((c==5) || (d>5)) returns true.
If c=5 then, !(c==5) returns false
! Logical NOT
iv Assignment Operators( =) Compound assignment
+=, -=, *= , /= , %=
e.g. a = c // value of c is assigned
&=, |=, ^=, >>= , <<=
to a Ex :
a += b means a = a+b
5=c //error 5 is a constant
associativity of
assignment operator is right to left.
v Increment and Decrement Operators (++, --)
Suppose a=5 and b=10 Suppose a= 5
a++; //a becomes 6 c = a++; // value of c=5 and a=6
a--; // a becomes 5 c = ++a; // value of c = 6 and a = 6
++a; //a becomes 6 c = a--; // value of c=5 and a=4
--a; // a becomes 5 c = --a; // value of c = 4 and a = 4

C PROGRAMMING & DATA STRUCTURES 4


SRIDHAR

vi Bitwise Operators
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
~ Bitwise complement( One’s complement)
<< Left Shift
>> Right Shift
vii Conditional operators : ?: (Ternary Operator)
conditional_expression ? expression1 : expression2;
expression1 is true part;
expression2 is false part;
viii Special Operators sizeof(char) = 1 sizeof(int) = 2
comma, sizeof , dot , arrow sizeof(float)=4 sizeof(double)=8
sizeof (long int) = 4

Bitwise AND (&) operator in C.


 The output of logical AND is 1 if both the corresponding bits of operand is
1. If either of bit is 0 or both bits are 0, the output will be 0.

Ex :
void main()
{
int a=12,b=25;
printf("Output=%d",a&b);
}
Ans : 8
Explanation :
 The bitwise AND operation of two integers 12 and 25.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bit Operation of 12 and 25


00001100
& 00011001 ________
00001000 = 8 (In decimal)

Bitwise OR( |) operator in C


 The output of bitwise OR is 1 if either of the bit is 1 or both the bits are 1.
 The output of bitwise OR is 0 if both the bits are 0.

C PROGRAMMING & DATA STRUCTURES 5


SRIDHAR

Ex :
void main()
{
int a=12,b=25;
printf("Output=%d",a&b);
}
Output : 29
Ans : 29
Explanation :
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise OR Operation of 12 and 25
00001100
| 00011001
00011101 = 29 (In decimal)

Bitwise XOR( ^) operator


 The output of bitwise XOR operator is 1 if the corresponding bits of two
operators are opposite otherwise 0.
Ex.
void main()
{
int a=12,b=25;
printf("Output=%d",a^b);
}
Output=21

Explanation :
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise XOR Operation of 12 and 25
00001100
| 00011001

00010101 = 21 (In decimal)

Bitwise compliment operator (~)


Bitwise compliment operator is an unary operator(works on one operand only).
It changes the corresponding bit of the operand to opposite bit,i.e., 0 to 1 and 1
to 0.
35=00100011 (In Binary)
Bitwise complement Operation of 35
~ 00100011
11011100 = 220 (In decimal)

C PROGRAMMING & DATA STRUCTURES 6


SRIDHAR

Twist in bitwise complement operator in C Programming


 Output of ~35 shown by compiler won't be 220, instead it shows -36. For
any integer n, bitwise complement of n will be -(n+1). To understand this,
you should understand the concept of 2's complement.
Decimal Binary 2's complement
0 00000000 -(11111111+1) = -00000000 = -0(decimal)
1 00000001 -(11111110+1) = -11111111 = -256(decimal)
12 00001100 -(11110011+1) = -11110100 = -244(decimal)
220 11011100 -(00100011+1) = -00100100 = -36(decimal)

 If we consider the bitwise complement of 35, 220(in decimal) is converted


into 2's complement which is -36. Thus, the output shown by computer will
be -36 instead of 220.
How is bitwise complement of any number N=-(N+1)?
 bitwise complement of N= ~N (represented in 2's complement form).
 2'complement of ~N= -(~(~N)+1) = -(N+1).

Ex :
int main()
{
printf("complement=%d\n",~35);
printf("complement=%d\n",~-12);
}
Output :
complement=-36
complement =11

Right Shift Operator(>>)


 Right shift operator moves the all bits towards the right by certain number
of bits which can be specified.
212 = 11010100 (In binary)
212>>2 = 00110101 (In binary) [Right shift by two bits]
212>>7 = 00000001 (In binary)
212>>8 = 00000000
212>>0 = 11010100 (No Shift)
Left Shift Operator( <<)
 Left shift operator moves the all bits towards the left by certain number of
bits which can be specified.
212 = 11010100 (In binary)
212<<1 = 110101000 (In binary) [Left shift by one bit]
212<<0 =11010100 (Shift by 0)
212<<4 = 110101000000 (In binary) =3392(In decimal)

C PROGRAMMING & DATA STRUCTURES 7


SRIDHAR

int main( )
{
int num=212,i;
for (i=0;i<=2;++i)
printf("Right shift by %d: %d\n",i,num>>i);
printf("\n");
for (i=0;i<=2;++i)
printf("Left shift by %d: %d\n",i,num<<i);
}
Right Shift by 0: 212
Right Shift by 1: 106
Right Shift by 2: 53
Left Shift by 0: 212
Left Shift by 1: 424
Left Shift by 2: 848

Interesting thing to note in Left and Right Shift


 For any positive number, right shift is equal to integer division of that
number by (shift bit plus one) and for any integer left shift is equal to the
multiplication of that number by (shift bit plus one).

For any positive number


X >> Y => X/ 2 Y What is the value of 48 >> 3 ?
Ans : 48 / 2 3 = 8
X << y => X * 2 Y What is the value of 8 << 3 ?
Ans : 8 * 2 3 = 64
Qualifiers for variables :
Qualifiers are used to control, how variables may be accessed or modified.
a. Const
b. Volatile
Const :
 If we want to restrict a variable for modifying then the variable need to be
declared as ‘const’.
Eg: const int a = 10; // constant integer with initial value 10
Volatile :
a) Volatile informs the compiler not to perform optimize techniques. Generally
‘volatile’ is used in conjunction to hardware.
b) Volatile variable can be changed at any time by same or external program.
c) If a variable to be maintained constant in current program and can be changed by
other external program then the declaration is volatile const.
volatile int d;
volatile const d = 10; // constant in current program and variable in external program

C PROGRAMMING & DATA STRUCTURES 8


SRIDHAR

Eg : void main ( )
{
volatile int num = 12;
num -- // volatile can be changed
printf (“%d”, num); // output 11
}
Questions on different types of Operators:
1. What is the output of this program?
void main( )
{
int a;
a=(5,10,15);
printf("%d",a);
}
Output:-15
Explanation:
 Here parenthesis is having more priority than assignment operator). (, ) Operator
is exist. Which follows left to right associating? So 15 is at right most. 15 will be
stored on a.
2. What is the output of this program?
main( )
{
int a,b,c;
c= (a=10,b=20,a+b);
printf("%d",c);
}
Output: 30
Explanation :
 Result of a+b is stored in c
3. What is the output of this program?
main( )
{
int a= 0;int b = 20;char x =1;char y =10;
if(a,b,x,y)
printf("hello");
}
Output: hello
Explanation:
 The comma operator has associativity from left to right. Only the rightmost value
is evaluated and the other values are evaluated and ignored. so, "hello" will be
printed.

C PROGRAMMING & DATA STRUCTURES 9


SRIDHAR

4. What is the output of this program?


main( )
{
int i;
i=200*200/200;
printf("%d",i);
}
Output: -127
Explanation :
 Because 200 * 200 is 40000 which is more than 32767 , finally 200 * 200 is -
25536. So -25536 /200 is -127.
5. What is the output of this program?
main( )
{
enum colors { BLACK,BLUE,GREEN};
printf("%d..%d..%d",BLACK,BLUE,GREEN);
}
Output: 0..1..2
Explanation:
 Enum assigns numbers starting from 0, if not explicitly defined.

6. What is the output of this program?


main( )
{
printf("%x",-1<<4);
}
Output: fff0
Explanation :
 1 is internally represented as all 1's. When left shifted four times the least
significant 4 bits are filled with 0's.The %x format specifier specifies that the
integer value be printed as a hexadecimal value.
7. What is the output of this program ?
main( )
{
int i=5;
printf(“%d”,i=++i ==6);
}
Output: 1
Explanation:
 The expression can be treated as i = (++i==6), because == is of higher precedence
than = operator. In the inner expression, ++i is equal to 6 yielding true(1). Hence
the result.

C PROGRAMMING & DATA STRUCTURES 10


SRIDHAR

8. What is the output of this program ?


main( )
{
int i=5;
printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);
}
Output: 45545
Explanation:
 The arguments in a function call are pushed into the stack from left to right. The
evaluation is by popping out from the stack. and the evaluation is from right to
left, hence the result.
9. What is the output of this program ?
main( )
{
int i=5,j=10;
i= i &= j && 10;
printf("%d %d",i,j);
}
Output: 1 10
Explanation:
 The expression can be written as i=(i&=(j&&10)); The inner expression (j&&10)
evaluates to 1 because j==10. i is 5. i = 5&1 is 1. Hence the result.
10. What is the output of this program ?
main( )
{
int i=4,j=7;
j = j || i++ && printf("YOU CAN");
printf("%d %d", i, j);
}
Output: 4 1
Explanation:
 The boolean expression needs to be evaluated only till the truth value of the
expression is not known. j is not equal to zero itself means that the expression’s
truth value is 1. Because it is followed by || and true || (anything) => true where
(anything) will not be evaluated. So the remaining expression is not evaluated and
so the value of i remains the same.

Control statements
A part of a program that can be executed. In ‘c’ we have different types of statements.
a) Selection :
- if
- else
- if – else – if
- ? [Ternary conditional operator]

C PROGRAMMING & DATA STRUCTURES 11


SRIDHAR

- switch case
b) Iteration or loop :
- for - while - do – while
c) Jump :
- break - continue - goto - return
d) Label :
- case
which comes under switch
- default
- label } used with goto
1. #include<stdio.h>
int main(void)
{
int x=1;
if(x)
printf("The Godfather");
x;
else
printf("%d",x);
return 0;
}
Output: error: Misplace else
Explanation:
 If you are not using { and } in if clause then you can write only one statement.
Otherwise it will cause of compilation error: Misplace else.
2. #include<stdio.h>
int main(void)
{
if('\0');
else if(NULL)
printf("codershunt");
else;
return 0;
}
Output: no output
Explanation:
 ‘\0’ is null character constant. Its ASCII value is zero. if(0) means false so
program control will check else if clause. NULL is macro constant which has been
defined in stdio.h which also returns zero.
3. #include<stdio.h>
int main(void)
{
if(!printf("Mukesh"))
if(printf(" Lakashmi"))
return 0;
}

C PROGRAMMING & DATA STRUCTURES 12


SRIDHAR

Output: Mukesh
Explanation:
 Return type of printf function is int. This function return a integral value which is
equal to number of characters a printf function will print on console.
 First of all printf function will print Mukesh. Since it is printing 6 character so it
will return 6. So, !printf("Mukesh") = !6 = 0 In c language zero represents false.
So if(0) is false so next statement which inside the body of first if statement will
not execute.

Ternary Operator

4. What is the output of this program ?


main( )
{
int i=10,j =20;
j = i, j?(i,j)?i:j:j;
printf("%d %d",i,j);
}
Output: 10 10
Explanation:
 The Ternary operator ( ? : ) is equivalent for if-then-else statement. So the
question can be written as:
if(i,j)
{
if(i,j)
j = i;
else
j = j;
}
else
j = j;
5. Choose the correct one.
Within a switch statement
(a) Continue can be used but Break cannot be used
(b) Continue cannot be used but Break can be used
(c) Both Continue and Break can be used
(d) Neither Continue nor Break can be used
Explanation:-
 The answer is b. Because switch is a case statement used to execute block of
statements for a particular case value. So only the particular case statements will
be executed for a passed value.
 So a break statement can be used in a switch statement in order to break the loop.
But continue statement cannot be used in a switch statement because the case
value is constant and cannot be changed in the middle.

C PROGRAMMING & DATA STRUCTURES 13


SRIDHAR

6. Choose the correct one The break statement causes an exit


(a) from the innermost loop only.
(b) only from the innermost switch.
(c) from all loops & switches.
(d) from the innermost loop or switch.
Explanation:-
 The answer is d. break statement is used to break the innermost loop or switch.
7.What is the output of below program
int main(void)
{
int i=3;
switch(i)
{
default: printf("two");
case 1: printf("three");
break;
case 2:printf("one");
break;
case 3: printf("zero");
break;
}
return 0;
}
(a) zero (b) one (c) two (d) three
Output: a
8. What is the output of below program
int main(void)
{
int i=1,j=2;
switch(i)
{
case 1: printf("GOOD");break;
case j: printf("BAD");break;
}
return 0;
}
(a) good (b) bad (c) error (d) no output
Explanation:

 The answer is c. Because the compiler will raise an error at case j: because case
statement value cannot be a variable. it should be a constant value.

9. // float is not allowed in switch


#include <stdio.h>
int main( )
{
float x = 1.1;

C PROGRAMMING & DATA STRUCTURES 14


SRIDHAR

switch (x)
{
case 1.1: printf("Choice is 1");
break;
default: printf("Choice other than 1, 2 and 3");
break;
}
return 0;
}
Output: Compiler Error: switch quantity not an integer

Examples on control statements:


Program 1: Program 2:
int main( ) int main( )
{ {
int i = 0; int i = 0;
for(i = 0; i < 3; i++) while(i < 3)
{ {
printf("loop "); printf("loop");
continue; continue;
} i++;
} }
}
Output : loop loop loop
Output :loop loop … loop ( infinite )
10. #include <stdio.h>
main( )
{
int i = 10;
do
{
printf("Hello %d\n", i );
i = i -1;
if( i == 6 )
break;
}while ( i > 0 );
}
Output:
Hello 10
Hello 9
Hello 8
Hello 7
Hello 6
11. What will be the output of the following program?
int main( )
{
int i=2,j=2;
while(i+1 ? --i: j++)

C PROGRAMMING & DATA STRUCTURES 15


SRIDHAR

printf("i=%d j=%d",i,j);
return 0;
}
Output: 1,2
Explanation:
 Consider the while condition: (i+1? --i:j++)
 It uses ternary operator. i=2, j=2 initially. i+1 = 3 which being a Non Zero Value
is TRUE. So --i is executed and i becomes 2-1 = 1. This is the actual value that
decides whether the while condition is TRUE or FALSE. since --i = 1 is a Non
Zero Value, i=1 j=2 is printed.
In the Second Iteration
i=1 and j=2.
In the condition (i+1? --i:j++)
i+1 = 2 is TRUE and the value of i is 1 , --i =0 which is FALSE and prints nothing
12. main( )
{
unsigned int i=65000;
while(i++!=0);
printf("%d",i);
}
Output: 1
Explanation:
 Note the semicolon after the while statement. When the value of i becomes 0 it
comes out of while loop. Due to post-increment on i the value of i while printing
is 1.
13. main( )
{
unsigned char i=0;
for(;i>=0;i++) ;
printf("%d\n",i);
}
Output: infinite loop.
Explanation:
 The difference between the previous question and this one is that the char is
declared to be unsigned. So the i++ can never yield negative value and i>=0 never
becomes false so that it can come out of the for loop.
14. main( )
{
int i=0;
for(;i++; printf("%d",i); ) ;
printf("%d",i);
}
Answer: 1

C PROGRAMMING & DATA STRUCTURES 16


SRIDHAR

Explanation:
 Before entering into the for loop the checking condition is "evaluated". Here it
evaluates to 0 (false) and comes out of the loop, and i is incremented (note the
semicolon after the for loop).
15. Consider the following C function.
float f(float x, int y)
{
float p, s; int i;
for (s=1, p=1, i=1; i < y; i ++)
{
p*= x/i;
s+=p;
}
return s;
}
For large values of y, the return value of the function f best approximates
(a) x^y
(b) e^x
(c) ln(1 + x)
(d) x^x
Output: (b)
Explanation:
 The function f( ) is implementation of Taylor’s Series to calculates e^x
e^x = 1 + x + x^2/2! + x^3/3! + ---
 More is the value of y more precise value of e^x will be returned by f( ) .
16. What does the following code does.?
int main( )
{
int x, y, m, n;
scant (“%d %d”, &x, &y);
m = x;
n = y;
while (m! = n)
{
if (m > n)
m = m – n;
else
n = n – m;
}
printf (“%d”, n);
}

Output: It produces the gcd of two numbers.

C PROGRAMMING & DATA STRUCTURES 17


SRIDHAR

Explanation :
 We can solve these type of questions by performing trial run.

Eg : set :
1) x = 10 y = 40 2) x = 29 y = 58 3) x = 80 y = 16
m = 10 n = 40 m = 29 n = 58 m = 80 n = 16
m = 10 n = 30 m = 29 n = 29 m = 64 n = 16
m = 10 n = 20 n = 29 m = 48 n = 16
m = 10 n = 10 m = 32 n = 16
return 10. 16.
a) x ÷ y using repeated subtraction. In all above sets
x 10
x÷y= 10 ÷ 40 =  0
y 40
x 29
29 ÷ 58 =  0
y 58
80
80 ÷ 16 =  5 // fat we got 16.
16
b) x mod y : 10) 40 ( 4
40
----- // fat we got 10
0
c) c.d of x & y: g.c.d (10, 40) = 10 g.c.d(29, 58) = 29
g.c.d (80, 16) = 16
All cases satisfied. It produces the gcd of two numbers.

Functions

 Function is collection of statements, which performs a specific task.


 It easy to re-use the code in different places and/or different programs.
 Function should be high cohesive and low coupling.
 Separating code out into functions also allows the programmer to concentrate
on different parts of the overall problem independently of the others.
o In "top-down" programming a programmer first works on the overall
algorithm of the problem, and just assumes that functions will be available
to handle individual details.
o Functions can then be concentrated on independently of the greater context
in which they will be used.
Return Type
 The "return type" indicates what kind of data this function will return.
 Some languages differentiate between "subroutines", which do not return a
value, and "functions", which do.
 In C there are no subroutines, only functions, but functions are not required to
return a value. The correct way to indicate that a function does not return a
value is to use the return type "void".

C PROGRAMMING & DATA STRUCTURES 18


SRIDHAR

 If no return type is given, the compiler will normally assume the function
returns an int. This can cause problems if the function does not in fact return
an int.

The Return Statement


 The return statement exits the called function and returns control back to the
calling function.
o Once a return statement is executed, no further instructions within the
function are executed.
 A single value ( of the appropriate type ) may be returned.
o Parentheses are allowed but not required around the return value.
o A function with a void return type will not have a return value after the
return statement.
 More than one return statement may appear in a function, but only one will
ever be executed by any given function call.
o (All returns other than the last need to be controlled by logic such as "if"
blocks.)
o The calling function may choose to ignore the value returned by the called
function.
Function Prototypes ( a.k.a. Function Declarations )
 This is a way of intimating to the compiler, what type of data is required by
the function, Examples:
 int add( int a, int b );
 int add( int, int );
 Type checking is only possible if the compiler already knows about the
function, including what kind of data the function is expecting to receive.
Data Passing Mechanisms
Pass By Value
o Ordinary data types (ints, floats, doubles, chars, etc) are passed by
value in C, which means that only the value is passed to the function
o Under the pass-by-value mechanism, the parameter variables within a
function receive a copy of the variables (data) passed to them.
 Any changes made to the variables within a function are local to that function
only, and do not affect the variables in main
Pass by Pointer / Address /References
 It passes the address of variable( L-Value ).
 Pass by pointer / address requires use of the address operator ( & ) and the
pointer dereference operator ( * ).

C PROGRAMMING & DATA STRUCTURES 19


SRIDHAR

Variable Scope
 Variable scope refers to the range ( the scope ) in which a variable is defined
and in which it exists.
 There are four variable scopes: ordinary local variables, function parameters,
global variables, and very local variables.
Local Variables
 Local variables are declared inside of a function, and outside of any braced
blocks such as while or for loops.
 The scope of these variables ( the range in which they exist and are valid ) is
from the point of their declaration to the end of the function.
 local variables are not initialized automatically. They must be initialized by
the programmer, or else they will start out with unknown random values.
Global Variables
 Global variables are declared outside of any function, ordinarily at the very
beginning of the file.
 The scope of global variables is from the point of declaration down to the end
of the file.
 Global variables are accessible to all functions within a file ( beyond the point
of declaration ), without having to be passed.
 global variables are initialized to zero .
Very Local Variables
 Variables declared within a { braced block }, such as a loop, if, or switch
construct are termed very local variables.
 The scope of very local variables is from the point of declaration to the end of
the block in which they are declared.
 This is usually done to avoid name conflict problems with other variables
having the same name declared in a more general scope.
Variable Eclipsing
 If the same variable name is used in multiple scopes (e.g. global, local, very
local), and the scopes overlap, then in the regions of overlap the more specific
variable will eclipse, or hide the more general variable(s).
 When the more specific variable goes out of scope, then the next more general
variable becomes visible again, unchanged by whatever may have occurred
while it was eclipsed.
 Example. In the code below the comments indicate which X will be printed at
which locations.

C PROGRAMMING & DATA STRUCTURES 20


SRIDHAR

1.What is the output of following code .


void pascal fun(int i,int j,int k)
{
printf(“%d %d %d”,i, j, k);
}
void cdecl gun(int i,int j,int k)
{
printf(“%d %d %d”,i, j, k);
}
main()
{
int i=10;
fun(i++,i++,i++);
printf(" %d\n",i);
i=10;
gun(i++,i++,i++);
printf(" %d",i);
}
Output:10 11 12 13
12 11 10 13
Explanation:
 Pascal argument passing mechanism forces the arguments to be called from left to
right. cdecl is the normal C argument passing mechanism where the arguments are
passed from right to left.
Call by Reference Example
1. What is the output of the following code?
int swap(int *a, int *b)
{
*a=*a+*b;*b=*a-*b;*a=*a-*b;
}
main( )
{
int x=10,y=20;
swap(&x,&y);
printf("x= %d y = %d\n",x,y);
}
Output: x = 20 y = 10

C PROGRAMMING & DATA STRUCTURES 21


SRIDHAR

Storage Classes
 Variables can be in one of four storage classes, depending on where in
computer memory they are stored.
Automatic Variables
 Automatic variables, ( a.k.a. auto variables ) are stored on a data structure
known as "the stack".
 The stack grows and shrinks as a program executes.
 In particular, when a new function is entered, space is allocated on the stack to
store all of the local variables for that function. ( Actually space is allocated
for each variable at the time when it first goes into scope, i.e. when it is
declared. )
 More importantly, when the function exits, the stack space allocated to that
function is freed up, and becomes available for other uses. ( The stack shrinks.
)
 Local variables, function parameters, and very local variables are ordinarily
auto variables stored on the stack.
 Any data stored in auto variables is lost when the variables go out of scope,
i.e. when a function exits. The next time the variable comes back into scope (
i.e. when the function gets called again ), the variable is allocated new space,
and re-initialized if an initialization is given.
Static Variables
 Static variables are stored in a separate storage area known as "the heap".
 Space for static variables is allocated one time only.
 Global variables are normally static. Other variables may be declared static.
 if function variables are declared as "static", then they are only initialized
once, and retain their values between function calls. The variables can still go
out of scope, but when they come back into scope they will still retain their
previous values.
 Example: The following code will generate the output shown below the code:
1. What is the output of this program ?
void staticExampleFunction( void );
void main( void )
{
for( int i = 0; i < 4; i++ )
staticExampleFunction( );
} // main
void staticExampleFunction( void )
{
int x = 0;
static int y = 0;
printf( "x = %d. y = %d.\n", ++x, ++y );
}

Output:
x = 1. y = 1.
x = 1. y = 2.
x = 1. y = 3.
x = 1. y = 4.

C PROGRAMMING & DATA STRUCTURES 22


SRIDHAR

 Static variables can be used to count how many times a function is called, or to
perform some special behavior the first time a function is called.
 Variation: The static keyword applied to a global variable makes it global to
this file only, and not visible from other files, ( in a multi-file development
project. )
Extern Variables
 The "extern" keyword applied to a variable indicates that it is declared and
allocated space in some other file.
 A declaration with the word "extern" is like a function prototype - It tells the
compiler of the existence of the variable, without actually creating it or
allocating any space for it.
 All such variables must be declared exactly once, ( i.e. in one file only of a
multi-file development project ) without the "extern", so that space can be
allocated for it.
 Extern variables are global in the file in which they are declared without
"extern", but may be either local or global in other files.
 Extern will be covered more fully under the topic of multi-file development.
Register Variables
 The keyword "register" suggests to the compiler that the given variable be
stored in one of the CPU registers, ( for faster access ), instead of in regular
memory.
 Register variables act as auto variables, except they do not have an "address",
and so cannot be referred to by pointer variables or by the address operator, &.
 Loop counters are the most common and obvious use of register variables.
Local static variable :
a) Compiler creates permanent storage for local static variable.
b) Static variable life is fixed to the block in which it is defined.
 In place of static variable, an extern variable can be used. The flip side of
usage of extern variable is that the extern variable can be modified in any of
the code block.
Global Static Variable:
Declaring a global variable as static, makes the global static variable available to the
file in which it is declared.
Static Local Static Global Extern
1. Available only in the 1. Available only in the 1. Available in multiple
block in which it is file in which it is files of program.
declared. declared.
Register variable:
All variables are stored in ROM which results in slower access ability. The most
frequently used variables and loop variable need to be stored in memory which takes
lesser time for CPU to access, the most nearest memory location is ‘Registers’.
Declaring a variable as ‘Register’ requests the compiler to store the variables in
processor registers.

C PROGRAMMING & DATA STRUCTURES 23


SRIDHAR

Points to remember :
i) The default value for global or extern variable is 0 for int, 0.00000 for float, 0
for char, null for string.
ii) If we will not specify ‘extern’ key word with global variables, then compiler
will automatically initialize with default value to a global variable.
iii) When an ‘extern’ keyword is used for a variable, it is only a declaration, i.e.
memory location will not be allocated at this point. To allocate memory, we
need to initialize the variable, then memory will be allocated, which is called
as definition.
iv) We can initialize the extern variable only globally. It is a compilation error to
initialize extern variable locally.
v) We can declare a extern variable and can initialize globally
vi) An extern variable can be declared multiple lines but initialized only once.
vii) Static variables have scope or visibility between function calls therefore static
variables are stored in fixed address.
viii) Static variables are initialized at compile time, because their address is
known and fixed.
ix) For local or auto variables, the visibility is only during the execution of
code, therefore :
a) each time when control comes, local variable is created & assigned address.
b) i.e. creation, assigning address, initialization for local variable happens
during run time.
2. What is the output of this program ?
void main( )
{
extern int i = 10; // not allowed
printf (“%d”, i);
}
Output : error : ‘i’ has both ‘extern’ and initialized.
3. What is the output of this program ?
void main ( )
{
extern int i;
printf (“%d”, i);
}
int i = 10; or extern int i = 10 // both will work
Output : 10.
4. What is the output of this program ?
extern int i;
int i = 25;
int i=9;
# include <stdio.h>
void main ( )
{
extern int i;
printf (“%d”, i);
}
Output : 25

C PROGRAMMING & DATA STRUCTURES 24


SRIDHAR

5. What is the output of this program ?


extern int i;
int i = 25;
extern int i;
# include <stdio.h>
int main( )
{
extern int i;
printf (“%d”, i);
return 0;
}
int i = 30;
Output : variable i is initialized more than once.
6. What is the output of this program ?
int a, b, c =0;
void fun1 (void);
main ( )
{
auto int a = 1;
fun1 ( );
a = a + 1;
fun1 ( );
prinft (“%d %d”, a,b);
}
fun1 (void)
{
register int a = 2;
int b = 1;
a + = ++b;
printf (“%d %d\n”, a,b);
}
Output :
4 2
4 2
2 0
Reason: ‘Register’ is similar to ‘auto’ no visibility of variable between the function
calls. Hence, every time control enters ‘register’ and ‘auto’ variables created fresh.

7. What is the outcome of the function trial () ?


int trial (int a, int b, int c)
{
if ((a >= b) && ((c<b))
return b; //--------------(1)
else if (a >= b)
return trial (a, c, b); //----------(2)
else
return trial (b, a, c); //------------(3)
}

C PROGRAMMING & DATA STRUCTURES 25


SRIDHAR

The function trial ( ):


a) finds the max of a, b, c
b) finds the min of a, b, c
c) finds the middle number of a, b, c
d) none of the above.
Explanation :
1. if ((a >= b) && (c < b) is true means the order is a b c returning ‘b’ means,
trial is used to find the middle #
2. else if (a >= b) means (c > b), trial (a, c, b) returns ‘c’ if a > = c
3. trial (b, a, c) means (a >= b) is false so the order is (b, a, c). need to check
further the order between a & c
8. What is the output of this program ?
int incr (int i) what is the value of ‘j’ at the end of code snippet
{
static int count = 0; //------------(4)
count = count + I; //---------------(5)
return (count); //--------------(6)
}
main ( )
{
int i, j; //------------(1)
for (i = 0; i <= 4; i ++) //---------- (2)
j = incr(i); //------------(3)
}
a) 10 b) 4 c) 6 d) 7
Explanation :
static count is initialized to ‘o’ and its scope is between the function calls.
1. i, j contains garbage values.
2. total loop is from i = 0, 1, 2, 3, 4
3. j = incr (i) = incr (0)
4. count = 0, count = count +I = count +0 = 0 + 0 = 0
5. 0 + 1
6. 1 + 2
7. 3 + 3
8. 6 + 4 = 10
Recursion:
A function that calls itself is known as recursive function and this technique is
known as recursion in C programming. Recursio n uses stack data structure to
perform its operations.
Advantages and Disadvantages of Recursion
Recursion is more elegant and requires few variables which make program clean.
Recursion can be used to replace complex nesting code by dividing the problem
into same problem of its sub-type.
It is also difficult to debug the code containing recursion.

C PROGRAMMING & DATA STRUCTURES 26


SRIDHAR

1. What is the output of this program ?


void foo (int n, int sum)
{
int k = 0, j = 0; // -----------(4)
if (n = = 0)
return;
k = n % 10;
j = n/10;
sum = sum + k; //--------------(5)
foo (j, sum); // ----------------(6)
printf (“%d”, k); //--------------(7)
}
int main( )
{
int a = 2045, sum = 0; //---------(1)
foo (a, sum); //----------(2)
printf (“%d”, sum); //---------(3)
}
Step by step of Execution Procedure of above program.
1. a sum are auto and contains 2048, 0
2. foo (2048, 0) will be called
4. k, y are auto andcontains 0 (n = 2048)
k = n%10 = 8
j = n/10 = 204
sum = 0 + 8 = 8
6. foo (204, 8)
k = 204 % 10 = 4
j = n / 10 = 20
sum = 8 + 4 = 12
6. foo(20, 12)
k = 20 % 10 = 0
j = 20 / 10 = 2
sum = 12 + 0
6. foo(2, 12)
k = 2 % 10 = 2
j=0
sum = 12 + 2
6. foo (0, 14)
if (n = = 0) return
Output : 2 0 4 8 0 because this ‘sum’ is from local main.
2. What is the output of this program ?
main( )
{
static int var = 5;
printf("%d ",var--);
if(var)
main( );
}
Output:5 4 3 2 1

C PROGRAMMING & DATA STRUCTURES 27


SRIDHAR

Explanation:
 When static storage class is given, it is initialized once. The change in the value of
a static variable is retained even between the function calls. Main is also treated
like any other ordinary function, which can be called recursively.
3. Reverse a Sentence Entered by user using recursion.
#include <stdio.h>
void Reverse( );
int main( )
{
printf("Enter a sentence: ");
reverse( );
return 0;
}
void reverse( )
{
char c;
scanf("%c",&c);
if( c != '\n')
{
reverse();
printf("%c",c);
}
}
Fibonacci Series
Following is another example, which generates Fibonacci series for a given number
using a recursive function:
4. Reverse a word using Recursive code.
void X(char *ptr)
{
ptr[0] ? X(ptr+1) :1;
printf(“%c”,ptr[0]);
}

main( )
{
X(“ABCDEF”);
}
Output: FEDCBA
5. What is the value printed by the following C program?
#include<stdio.h>
int f(int *a, int n)
{
if(n <= 0) return 0;
else if(*a % 2 == 0) return *a + f(a+1, n-1);
else return *a - f(a+1, n-1);
}

C PROGRAMMING & DATA STRUCTURES 28


SRIDHAR

int main( )
{
int a[] = {12, 7, 13, 4, 11, 6};
printf("%d", f(a, 6));
getchar( );
return 0;
}
(a) -9 (b) 5
(c) 15 (d) 19
Output: (c)
Explanation:
f( ) is a recursive function which adds f(a+1, n-1) to *a if *a is even. If *a is odd then
f( ) subtracts f(a+1, n-1) from *a. See below recursion tree for execution of f(a, 6).
f(add(12), 6) /*Since 12 is first element. a contains address of 12 */
|
12 + f(add(7), 5) /* Since 7 is the next element, a+1 contains address of 7 */
|
7 - f(add(13), 4)
|
13 - f(add(4), 3)
|
4 + f(add(11), 2)
|
11 - f(add(6), 1)
|
6+0

So, the final returned value is 12 + (7 – (13 – (4 + (11 – (6 + 0))))) = 15

C PROGRAMMING & DATA STRUCTURES 29


SRIDHAR

LAST MINUTE REVISION


fundamentals
(Features of C Language, C Tokens, Data Types,operators)
 C is the most popular programming language, C has many features.
 General Purpose Programming Language
 Structured programming sometimes known as modular programming
 Portability
 Efficient Compilation and Execution
 C is case sensitive language
C Tokens:
 A token is the basic building block of a C program which can be recognized
by the compiler
 In c any name is called identifier. This name can be variable name, function
name, enum constant name, micro constant name or goto label name.
 There are 32 standard keywords.
Constants :
 There are four basic types of constants in C. They are:
 1.Integer constants
 2.Floating-point constants
3.Character constants
 4.String constants
Data type:
Datatypes range
 signed char -128 to +127
 unsigned char 0 to 255
 short signed int -32768 to +32767
 short unsigned int 0 to 655535
 signed int -32768 to +32767
 unsigned int 0 to 655535
 long signed int -2147483648 to +2147483647
 long unsigned int 0 to 4294967295
 float -3.4e38 to +3.4e38
 double -1.7e308 to +1.7e308
 long double -1.7e4932 to +1.7e4932

Operators
 Arithmetic Operators (+, -, *, /, %)
 Relational operators (==, >, < , !=, >=, <=)
 Logical Operators (&& , ||, ! )
 Assignment Operator( =)

C PROGRAMMING & DATA STRUCTURES 30


SRIDHAR

 Compound assignment(+=, -=, *= , /= , %= ,&=, |=, ^=, >>= , <<=)


 Increment and Decrement Operators (++, --)
 Bitwise Operators (&,|,^,~,<<,>> )
 Conditional operators : ?:
 Special Operators :comma, sizeof , dot , arrow
Control statements
A part of a program that can be executed. In ‘c’ we have different types of statements.
a) Selection :
- if
- else
- if – else – if
- ? [Ternary conditional operator]
- switch case
b) Iteration or loop :
- for - while - do – while
c) Jump :
- break - continue - goto - return
d) Label :
- case
which comes under switch
- default
- label } used with goto

C PROGRAMMING & DATA STRUCTURES 31


SRIDHAR

CLASS ROOM OBJECTIVES


01. Structured programming language gives more importance to _________
(a) procedural abstraction (b) data abstraction
(c) procedural abstraction (d) none
02. Variable name in the program is to be checked when during.
03. Which keyword helps to define large numbers.
04. Which keyword used for not permitting to store values in secondary storage.
05. How many different types of operators available based upon operand dependency
factor.
(a) 1 (b) 2 (c) 3 (d) none
06. How many ternary and unary and binary operators exist in ‘c’ language.
07. How many arithematic operators are binary ternary and unary.
08. What is associativity of ‘+’ operator ?
09. What is associativity of assignment operator ?
10. What is associativity of relational operator ?
11. How many logical operators are unary, binary, ternary.
12. Find the output of the following programs
(a)main( )
{
int x=3, y=5, z=10;
int p;
p=x&&y&&z;
printf (“%d”, p);
}
(b)main( )
{
int x=5, y=7, z;
z=(x= =5) || (y=6);
printf (“%d %d %d”, x, y, z);
}
(c)main( )
{
int x=5, y=7, z;
z=(x= =6) || (y=6);
printf (“%d %d %d”, xyz);
}
(d)main( )
{
int x=5, y=7, z;
z=(x= =6) && (y=6);
printf (“%d %d %d”, x, y, z);
}

C PROGRAMMING & DATA STRUCTURES 32


SRIDHAR

13. Find the output of the following code segments


(a)main( )
{
int x=3, y=4, z=5;
p=x=y=z;
printf (“%d %d %d”, p, x, y, z);
}
(b)main( )
{
int x=x;
printf (“%d”, x);
}
14. Find the output of the following code segments
(a)main( )
{
int scanf=10, getch=20, clrscr;
clrscr=scanf+getch;
printf (“%d”, clrscr);
getch( );
}
(b)main( )
{
int scanf=10, getch=20, clrscr;
clrscr=scanf+getch;
printf (“%d”, clrscr);
}
(c)main( )
{
int scanf=10, getch=20, clrscr;
printf (“%d”, clrscr);
}
15. Find the output of the following programs
(a)main( )
{
int i=1, j=2;
{
int i=5;
printf (“%d”, i+j);
}
printf (“\n %d”, i-j);
}
(b)main( )
{
int i=15;
printf (“%d”, i);
printf (“%O”, i);
printf (“%x”, i);
}

C PROGRAMMING & DATA STRUCTURES 33


SRIDHAR

16. Find the output of the following code segments


(a)main( )
{
int i=015;
printf (“%d”, i);
printf (“%O”, i);
printf (“%x”, i);
}
(b)main( )
{
int i=10, 20, 30;
printf (“%d”, x);
}

17. Find the output of the following code segments


(a)main( )
{
int x=029;
printf (“%d”, x);
printf (“%O”, x);
printf (“%x”, x);
}
(b)main( )
{
printf (“Hello”, “World”)+3);
}

18. Find the output of the following code segments


(a)main( )
{
int x=5, y, z;
z=printf (“%d”, scanf(“%d %d”, &y, &z));
printf (“%d”, z);
}
(b)main( )
{
int var=65;
printf (&var);
}
19. Find the output of the following code segments
(a) int x;
x=sizeof (“Hello”) – sizeof (int)
printf (“%d”, x);
x=size of (int) – size of (int);
printf (“%d”, x);

C PROGRAMMING & DATA STRUCTURES 34


SRIDHAR

(b)main( )
{
int x, y, z;
x=printf (“one”);
y=size of (printf (“Two”));
z=size of (x+=y);
printf (“%d %d %d”, x, y, z);
}

20. Find the output of the following code segments


(a)main( )
{
int x=3, y=4, z;
x++;
y-1;
z=x+y;
printf (“%d %d %d”, x, y, z);
}
(b)main( )
{
printf (“\shyamala \ swagath \ chandu \ bollineni\”);
}

21. Find the output of the following code segments


(a)main( )
{
int x=5;
if (x=6);
printf (“Hello”);
else
printf (“Bye”);
}
(b)main( )
{
int i=5, j=6, k=7;
if (i<j; j>k; i= = k)
{
printf (“correct”);
}
else
{
printf (“wrong”);
}
}

C PROGRAMMING & DATA STRUCTURES 35


SRIDHAR

(c)main( )
{
int i=69;
if (++i, i++, ++i);
printf (“Hello %d”, i);
else
printf (“Bye %d”, i);
}

22. Find the output of the following programs


(a)main( )
{
int x=10, j=8, z=1;
if (++x || ++y);
{
printf (“%d %d %d”, x=y, y=z, z=5);
}
}
(b)main( )
{
int p=5;
if (p%2 = = 1);
{
printf (“Hello if”);
break;
}
printf (“Bye if”);
}

23. Find the output of the following code segments


(a)main( )
{
int p=3, q=4, r=5;
switch (p);
{
case q-1 : printf (“p = %d”, p);
case r+3 : printf (“R = %d”, r);
break;
default : printf (“Bye”);
}
}

C PROGRAMMING & DATA STRUCTURES 36


SRIDHAR

(b)main( )
{
int i=5;
switch (i);
{
default : printf (“A”);
case 4 : printf (“B”);
case 5 : printf (“C”);
}
}

24. Find the output of the following code segments


(a)main( )
{
int i=421;
switch (i);
{
case 420 : if (i = = 400)
{
case 421 : printf (“Hello switch”);
}
break;
case 422 : printf (“Bye switch”);
}
}
(b)main( )
{
float x=3.5;
switch (x);
{
case 3.1 : printf (“A”);
case 3.2 : printf (“B”);
case 3.5 : printf (“C”);
}
}

25. Find the output of the following code segments


(a)main( )
{
int i=1, sum=0;
for (i=0; i<5; i+1);
{
sum=sum+i
printf (“%d”, sum);
}
}

C PROGRAMMING & DATA STRUCTURES 37


SRIDHAR

(b)main( )
{
int i=3, j=4, k=5;
for (i; i= =j; k++);
{
printf (“Hello %d”, k);
}
}

26. Find the output of the following code segments


(a)main( )
{
int i=3, j=4, k=5, sum=0;
for (i; i<j; i++);
{
for (k; k--; k--);
{
sum=sum+i+k+1;
}
}
}
(b)main( )
{
int i j;
for (i=1; i<3; i++);
{
for (j=1; j<3; j++);
{
if (i= =j);
break;
printf (“%d %d\n”, I, j);
}
}
}

27. Find the output of the following code segments


(a) main( )
{
int i=0;
while (i++);
{
printf (“%d”, i);
}
}

C PROGRAMMING & DATA STRUCTURES 38


SRIDHAR

(b) main( )
{
int i=5;
while (i=5);
{
printf (“Hello %d’, i);
i++;
}
}
28. Find the output of the following code segments
(a) main( )
{
int n=10;
do;
{
printf (“%d”, n);
}
while (n--);
}
(b)main( )
{
int n=10;
do
{
printf (“%d”, n);
}
while (--n);
}

29. Find the output of the following program

(a) main( )
{
f( );
}
void f( );
{
printf (“Hello f”);
}
(b) f(int *x, int y);
{
*x=*x+y;
Y=*x+y;
}

C PROGRAMMING & DATA STRUCTURES 39


SRIDHAR

main( )
{
int x=3, y=5;
f(&x, y);
printf (“%d”, x+y);
}

30. Find the output of the following code segments


(a) int fun (int n, int*p);
{
int t, f;
if (n <= 1);
{
*f – p = 1;
return 1;
}
t=fun(n-1, f-p);
t=t+*f-p;
*f-p=t;
return f;
}
int main ( )
{
int x=15;
printf (“%d\n”);
fun (5, &x);
return 0;
}

(b)int f(int n, int k);


{
if (n = =0);
return 0;
else if (n%2);
return f(n/2, 2*k)+k;
else
return f(n/2, 2*k)-k;
}
main ( )
{
printf (“%d”, f(20, 1));
}

C PROGRAMMING & DATA STRUCTURES 40


SRIDHAR

31. Find the output of the following code segment


main ( );
{
static int i=5;
if (- -i);
{
main ( );
printf (“%d”, i);
}
}
32. Find the output of the following program
(a) main ( )
{
int fun ( );
{
static int num=16;
return num - -;
}
int main ( )
{
for (fun( ); fun( ); fun( ));
printf (“%d”, fun( ));
}
}
(b)f(int n)
{
if (n)
{
printf (“%d”, n);
f(- -n);
}
return n;
}
main ( )
{
int n = 5;
printf (“\n%d”, f(n));
}
33. Find the output of the following code segments
(a) fun ( )
{
auto int i=5;
static int j=5;
register int k=5;
i++, j++, k++;
printf(“%d %d %d\n”, i, j, k);
}

C PROGRAMMING & DATA STRUCTURES 41


SRIDHAR

main ( )
{
fun ( )
fun ( )
fun ( )
}
(b) fun ( )
{
auto int i=5;
static int j=5;
register int k=5;
extern int l=5;
printf(“%d %d %d %d\n”, I, j, k, l);
}
main ( )
{
fun ( )
fun ( )
}
34. Find the output of the following code segments
(a)f (static int i, int j);
{
i=i+j;
printf (“%d %d”, i, j);
}
main ( )
{
f(1, 2);
f(2, 3);
}
(b) f(int *p, int *q, int *r);
{
return *p: *q : *r;
}
main ( )
{
int i=10;
static int j=15;
auto int k=25;
printf (“%d”, f(&i, &j, &k));
}
(c) main ( )
{
int p=1, q=2, r=-3, m=4;
printf(“%d”, m?p?q:r:m+2);
}
35. The range of integer can be represented by n-bit system
(a) -2n-1 to 2n-1 – 1 (b) -(2n-1 – 1) to 2n-1 – 1
n-1
(c) -2 to 2 n-1
(d) -(2n-1 + 1) to (2n-1 – 1)

C PROGRAMMING & DATA STRUCTURES 42


SRIDHAR

PREVIOUS QUESTIONS:
Common Data for Questions 01 & 02 (GATE-1987)
Study the following program written in a block-structured language :
var x,y : integer;
procedure P (n : integer);
begin
x: = (n + 2)(n – 3);
End;
procedure Q
var x, y : integer;
begin
x: = 3;
y: = 4;
P(y);
Write (x) ------------------ ( 1 )
End;
begin
x ; = y;
y ; = 8;
Q;
Write (x) ------------------ ( 2 )
end;

01. What will be printed by the write statements marked (1) and (2) in the program if
variable are statically scoped ?
(a) 3, 6 (b) 6, 7 (c) 3, 7 (d) None
02. For the program given Q 01 in what will be printed by the write statements
marked (1) and (2) if the variables are dynamically scoped
(a) 3, 6 (b) 6, 7 (c) 3, 7 (d) None
03. An unrestricted use of the “go to” statement is harmful because of which of the
following reason(s) : (GATE-1989)
(a) It makes it more difficult to verify programs
(b) It makes programs more inefficient
(c) It makes it more difficult to modify existing programs
(d) It results in the compiler generating longer machine code.
04. In which of the following case(s) is it possible to obtain different results for call-
by reference and call-by-name parameter passing ? (GATE-1989)
(a) Passing an expression as a parameter
(b) Passing an array as a parameter
(c) Passing a pointer as a parameter
(d) Passing an array element as a parameter

C PROGRAMMING & DATA STRUCTURES 43


SRIDHAR

05. Indicate the result of the following program if the language uses (GATE-1989)
i) static scope rules and call by reference
ii) dynamic scope rules and call by reference
var x, y : integer;
procedure A (var z : integer);
var x : integer;
begin x : = 1; B; z :=x; end;
procedure B:
begin x:=x+1; end;
begin
x:=5; A(y); write(y);
…..end
06. Match the pairs in the following (GATE-1990)
List-I List-II
A. Pointer data type p. Type conversion
B. Activation record q. Dynamic data structure
C. Repeat-until r. Recursion
D. Coercion s. Nondeterminstic loop
(a) A-q, B-r, C-s, D-p (b) A-r, B-q, C-p, D-s.
(c) A-r, B-s, C-p, D-q (d) None
07. Match the pairs in the following (GATE-1990)
List-I List-II
A. Small talk p. Logic programming
B. LISP q. Data flow programming
C. Prolog r. Functional Programming
D. VAL s. Object-Oriented programming
08. Indicate all the true statements from the following : (GATE-1991)
(a) A programming language not supporting either recursion or type does not
need the support of dynamic memory
(b) Although C does not support call by name parameter passing, the effect can
be correctly simulated in C
09. Consider the following pseudo-code (GATE-1991)
(all data items are of type integer) :
Procedure P(a, b, c);
a: = 2;
c: = a+ b;
end {P}
begin
x := 1;
y := 5;
z := 100;
P(x, x*y,z);
Write (‘x=’, x, ‘z=’,z)
End:
Determine its output, if the parameters are passed to the procedure P by
(i) value (ii) reference and (iii) name

C PROGRAMMING & DATA STRUCTURES 44


SRIDHAR

10. For the following pseudo-code, indicate the output, if (GATE-1991)


(i) static scope rules and
(ii) dynamic scope rules are used
Var a, b : integer ;
Procedure P;
A : = 5; b : = 10;
end {P};
Procedure Q;
Var a, b : ineger;
P;
end {Q};
Begin
A : = 1; b : = 2;
Q;
Write (‘a=’, a, ‘b=’,b)
end

11. (a) What type of parameter passing mechanism (call-by-value, call-by-reference,


call-by-name, or call-by-result) is the following sequence of actions trying to
implement for a procedure call P(A[i]) where P (I: integer) is a procedure and A
is an integer array ?
1. Create a new local variable, say z
2. Asign to z the value of A[i]
3. Execute the body of P using z for A[i]
4. Set A[i] to z
Is the implementation correct ? Explain and correct it if necessary. You are
supposed to make only small changes.
(b) Show the activation records and the display structure just after the procedure
called at lines marked x and y have started their execution. Be sure to indicate
which of the two procedures named a you are fererring to (GATE-1992)
Program Test;
Procedure A;
Procedure B;
Procedure A;
……
end a;
begin
y:A;
end B;
begin
B;
end A;
begin
x:A;
end Test.

C PROGRAMMING & DATA STRUCTURES 45


SRIDHAR

Note : For sub-question 12 to 14, refer to the Pascal program shown in below
program PARAM (input, output)
var m, n : integer;
procedure P(var x, y : integer);
var m : integer;
begin
m : = 1;
x : = y + 1;
end;
procedure Q(x : ineger; vary; integer);
begin
x : = y + 1;
end;
begin
m : = 0 ; P(m, m); write(m);
n : = 0 ; Q(n*1, n); write(n);
end;
12. The value of m, output by the pgoram PARAM is : (GATE-1993)
(a) 1, because m is a local variable in P
(b) 0, because m is the actual parameter that corresponds to the formal
parameter in p
(c) 0, because both x and y are just reference to m and y has the value 0
(d) 1, because both x and y are just reference to m which gets modified in
procedure P
13. The value of n, output by the program PARAM is : (GATE-1993)
(a) 0, because n is the actual parameter corresponding to x in procedure Q
(b) 0, because n is the actual parameter to y in procedure Q
(c) 1, because n is the actual parameter corresponding to x in procedure Q
(d) 1, because n is the actual parameter corresponding to y in procedure Q
14. What is the scope of m declared in the main program ? (GATE-1993)
(a) PARAM, P, Q (b) PARAM, P (c) PARAM, Q (d) P, Q
15. For the program segment given below, which of the following are true ?
program main (output);
type link = ^data;
data = record
d : real;
n : link
end;
var ptr : link;
begin
new (ptr)
ptr = nil;
ptr^.d := 5.2;
write ln(ptr)
end
(a) The program leads to compile time error
(b) The program leads to run time error (c) The program outputs 5.2
(d) The program produces error relating to nil pointer dereferencing

C PROGRAMMING & DATA STRUCTURES 46


SRIDHAR

16. A stack is used to pass parameters to procedures in a procedure call


(GATE-1993)
(a) If a procedure P has two parameters as described in procedure definition
Procedure P (var x : integer; y: integer); and if P is called by ; P(a, b) State
precisely in a sentence what is pushed on stack for parameters a and b
(b) In the generated code for the body of procedure P, how will the addressing
of formal parameters x and y differ ?

17. What does the following code do ? (GATE-1993)


Var a, b : integer;
begin
a := a + b;
b := a – b;
a := a – b;
end;
(a) exchanges a and b (b) doubles a and stores in b
(c) doubles b and stores in a (d) leaves a and b unchanges

18. Consider the following recursing function : (GATE-1994)


Function fib (1:integer); integer;
begin
if (n=0) or (n=1) then fib:=1
else fib:=fib(n-1) + fib(n-2)
end;
The above function is run on a computer with a stack of 64 bytes. Assuming that
only return address and parameter and passed on the stack, and that an integer
value and an address takes 2 bytes each, estimate the maximum value of n for
which the stack will not overflow. Give reasons for your answer.

19. An unrestricted use of the “goto” statement is harmful because (GATE-1994)


(a) it makes it more difficult to verify programs
(b) it increases the running time of the programs
(c) it increases the memory required for the programs
(d) it results in the compiler generating longer machine codes

20. In which one of the following cases is it possible to obtain different results for
call-by reference and call-by-name parameter passing methods ? (GATE-1994)
(a) Passing a constant value as a parameter
(b) Passing the address of an array as a parameter
(c) Passing an array element as a parameter
(d) Passing an array following statements is true

C PROGRAMMING & DATA STRUCTURES 47


SRIDHAR

21. State whether the following statements are True and False with reasons for your
answer (GATE-1994)
(a) A subroutine cannot always be used to replace a macro in an assembly
language program
(b) A symbol declared as ‘external’ in assembly language is assigned an address
outside the program by the assembler itself

22. Consider the program below : (GATE-1994)


program main;
var r: integer;
procedure two;
begin write (r) end;
procedure one;
var r: integer;
begin r:=5 two; end;
begin r:=2;
two; one; two;
end;
What is printed by the above program if
(i) Static scoping is assumed for all variables;
(ii) Dynamic scoping is assumed for all variables;
Give reasons for your answer

23. What are x and y in the following macro definition ? (GATE-1995)


Load y
Mul x
Store y
End macro
(a) Variables (b) Identifiers
(c) Actual parameters (d) Fortnal parameters

24. What is the value of X printed by the following program ? (GATE-1995)


Program COMPUTE (input,
Output);
Var
X : integer;
Procedure FIND (X:real);
begin
X : = sqrt(X);
end;
begin
X := 2;
FIND(X);
writeln(X);
end
(a) 2 (b) 2
(c) Run time error (d) None of the above

C PROGRAMMING & DATA STRUCTURES 48


SRIDHAR

25. (a) Consider the following Pascal function where A and B are non-zero positive
integers. What is the value of GET(3, 2) ? (GATE-1995)
Function GET(A, B : integer); integer;
begin
if B = 0 then
GET := 1
else if A < B then
GET := 0
else
GET := GET(A-1, B) + GET(A-1, B-1)
end;
26. The correct matching for the following pairs is (GATE-1996)
List-I List-II
A. Activation record 1. Linking loader
B. Location counter 2. Garbage collection
C. Reference counts 3. Subroutine call
D. Address relocation 4. Assembler
(a) A – 3 B – 4 C – 1 D – 2 (b) A – 4 B – 3 C – 1 D – 2
(c) A – 4 B – 3 C – 2 D – 1 (d) A – 3 B – 4 C – 2 D – 1

27. Consider the following program in pseudo-Pascal syntax. What is printed by


theprogram if parameter a in procedure test 1 is passed as (GATE-1996)
(i) call-by-reference parameter ?
(ii) call-by-value
program Example (input, output)
var b: integer;
procedure test 2;
begin b: = 10 end
procedure test 1 (a : integer);
begin a : 5;
writeln (‘point 1: ‘a,b);
Test 2;
wrote, m(‘point:’a,b);
end;
begin (*Example*)
B:=3; test] (b);
writeln (‘point 3: ‘b)
end

C PROGRAMMING & DATA STRUCTURES 49


SRIDHAR

28. Heap allocation is required for languages (GATE-1997)


(a) that support recursion (b) that support dynamic data structures
(c) that use dynamic scope rules (d) None of the above

29. Given the following Pascal like program segment


procedure A;
x, y : integer;
procedure B;
x, z : real
S1
end B;
procedure C;
i:integer;
S2
end C;
end A;
The variables accessible in S1 and S2 are (GATE-1997)
(a) x or A, y, x of B and z in S1 and x of B, y and i in S2
(b) x or B, y and z in S1 and x of B, I and z in S2
(c) S1, x, z of B, y of A – S2 ; i of C, x, y of A
(d) None of the above

30. Consider the following program in Pseudo-Pascal syntax (GATE-1997)


program what;
var z : integer;
procedure recur (x);
begin fi x  40 then
begin x: x + z;
recur (x);
z=x+100;
end
end(*recur*);
being(*what*)
z=10;
recur(z);
writeln(z);
end
(a) Suppose the parameter to the procedure ‘recur’ is passed by value
(i) What value is printed by the program ?
(ii) How many time is ‘recur’ called?
(b)What value is printed by the program if the parameter is passed by reference?

C PROGRAMMING & DATA STRUCTURES 50


SRIDHAR

31. What value would the following function return for the input x = 95 ?
(GATE-1998)
function fun(x : integer); integer;
begin
if x > 100 then fun : x – 10
else fun : fun(fun(x + 11))
end;
(a) 89 (b) 90 (c) 91 (d) 92

32. What is the result of the following program ? (GATE-1998)


program side-effect (input, output);
var x, result : integer :
function f(var x:integer):integer;
begin
x:x+1; F:=x;
end
begin
x := 5;
result:=f(x)*f(x);
writeln(result);
end
(a) 5 (b) 25 (c) 36 (d) 42

33. Consider the following program in a language that has dynamic scooping :
(GATE-1999)
var x: real
procedure show:
begin print(x); end;
procedure small;
var x: real;
begin x:=0.125; show; end;
begin x:=0.25;
show; small
end.
Then the output of theprogram is:
(a) 0.125 0.125 (b) 0.25 0.25 (c) 0.25 0.125 (d) 0.125 0.25

34. Consider the following C function defition (GATE-1999)


int trial (int a, int b, int c)
{
if ((a > = b) && (c < b) return b;
else if (a > = b) return Trial (a, c, b);
else return trial (b, a, c);
}
The function trial;
(a) Finds the maximum of a, b, and c (b) Find the minimum of a, b and c
(c) Finds the middle number of a, b, c (d) None of the above

C PROGRAMMING & DATA STRUCTURES 51


SRIDHAR

35. Given the programming constructs (i) assignment (ii) for loops where the loop
parameter cannot be changed within the loop (iii) if-then-else (iv) forward go to
(v) arbitrary go to (vi) non-recursive procedure call (vii) recursive
procedure/function call (viii) repeat loop, which constructs will you not include
in a programming language such that it should be possible to program the
terminates (i.e., halting) function in the same programming language
(GATE-1999)
(a) (ii), (iii), (iv) (b) (v), (vii), (viii)
(c) (vi), (vii), (viii) (d) (iii), (vii), (viii)

36. What will be the output of the following program assuming that parameter
passing is (GATE-1999)
(i) call by value
(ii) call by reference
(iii) call by copy restore
procedure P(x,y, z);
begin y:=y+1; z:=x+x end;
begin
a:=2; b:=3;
P(a+b,a,a);
print (a);
end

37. The value of j at the end of the execution of the following C program
(GATE-2000)
int incr (int i)
{
static int count = 0;
count = count + I;
return (count);
}
main ( )
{
int i, j;
for (i = 0; i <=4; i++)
j = incr(i);
}
is :
(a) 10 (b) 4 (c) 6 (d) 7

38. Consider the following program is pseudo-Pascal syntax (GATE-2000)


program main
var x: integer;
procedure Q (z: integer);
begin
z:=z+x;
writeln(z)
end;
procedure P(y; integer);

C PROGRAMMING & DATA STRUCTURES 52


SRIDHAR

var x:integer;
begin
x:=y+2;
Q(x);
Writeln(x)
end;
begin
x:=5;
P(x);
Q(x);
writeln(x)
end
What is the output of the program, when
(a) The parameter passing mechanism is call-by-value and the scope rule is
static scoping ?
(b) The parameter passing mechanism is call-by-reference and the scope rule is
dynamic scoping ?

39. What is printed by the print statements in the program P1 assuming call by
reference parameter passing ? (GATE-2001)
program P1( )
{
x = 10;
y = 3;
func1(y,x,x);
print x;
print y;
}
func1 (x, y, z)
{
y=y+4;
z=x+y+z;
}
(a) 10, 3 (b) 31, 3 (c) 27, 7 (d) None of the above

40. Consider the following program


program P2
var n : int;
procedure W(var x: int)
begin
x=x+1;
print x;
end
procedure D
begin

C PROGRAMMING & DATA STRUCTURES 53


SRIDHAR

var n: int;
n = 3;
W(n);
end
begin\\begin P2
n = 10;
D;
end;
If the language has dynamic scoping and parameters are passed by reference,
what will be printed by the program ? (GATE-2001)
(a) 10 (b) 11 (c) 3 (d) None of the above

41. The results returned by function under value-result and reference parameter
passing conventions (GATE-2002)
(a) Do not differ (b) Differ in the present of loops
(c) Differ in all cases (d) May differ in the presence of exception

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


Char a[100][100];
Assuming that the main memory is byte-addressabel and that the array is stored
starting from memory address 0, the address of a [40][50] is (GATE-2002)
(a) 4040 (b) 4050 (c) 5040 (d) 5050

43. Which of the following statements is FALSE ? (GATE-2003)


(a) In statically typed languages, each variable in a program has a fixed type
(b) In un-typed languages, values do not have any types
(c) In dynamically typed languages, variables have no types
(d) In all statically typed languages, each variable in a program is associated
with values of aonly a single type during the execution of the program

Common Data for Questions 44 & 45 : (GATE-2003)


The following program fragment is written in a programming language that
allows global variables and does not allow nested declarations of functions
global int i = 100, j = 5;
void p(x)
{
int i = 10;
print (x + 10);
i= 200;
j = 20;
print (x);
}
main( )
{
p(i+ j);
}

C PROGRAMMING & DATA STRUCTURES 54


SRIDHAR

44. If the programming language uses static scoping and call by need parameter
pssing mechanism, the values printed by the above program are
(a) 115, 220 (b) 25, 220 (c) 25, 15 (d) 115, 105

45. If the programming languages uses dynamic scoping and call by name parameter
passing mechanism, the values printed by the above program are
(a) 115, 220 (b) 25, 220 (c) 25, 15 (d) 115, 105

46. Consider the following C function (GATE-2003)


float f,(float x, int y)
{
float p, s; int i;
for (s=1, p=1, j=1; i<y; i++)
{
p*=x/i;
s+=p;
}
return s;
}
For large values of y, the return value of the function f best approximates
(a) Xy (b) ex (c) ln(l+x) (d) Xx

47. Consider the following class definitions in a hypothetical Object Oriented


language that supports inheritance and uses dynamic binding. The language
should not be assumed to be either Java or C++, though the syntax is similar
Class P {
void f(int i)
print(i);
Class Q subclass of P
{
void f(int i)
{
print(2*i);
}
}
}
Now consider the following program fragment :
P x = new Q ( );
Q y = new Q ( );
P z = new Q ( );
x.f(1); ((P)y) . f(1); z.f(1);
Here ((p)y) denotes a typecast of y to P. The output produced by executing the
above program fragment will be (GATE-2003)
(a) 1 2 1 (b) 2 1 1 (c) 2 1 2 (d) 2 2 2

C PROGRAMMING & DATA STRUCTURES 55


SRIDHAR

48. Consider the following C function (GATE-2004)


void swap (int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
In order to exchange the values of two variables x and y
(a) call swap (x, y) (b) call swap (&x, &y)
(c) swap (x, y) cannot be used as it does not return any value
(d) swap (x, y) cannot be used as the parameters are passed by value

49. Consider the following C function (GATE-2004)


int f(int n)
{
static int i=1;
if (n>=5) return n;
n=n+i;
i ++;
return f(n);
}
The value returned by f(1) is
(a) 5 (b) 6 (c) 7 (d) 8

50. Consider the following C program (GATE-2004)


main ( )
{ int x, y, m, n;
scanf (“%d, %d”, &x, &y);
/*Assume x>0 and y>0*/
m=x; n=y;
while (m!=n)
{ if (m>n)
m = m-n;
else
n = n-m;
}
printf (“%d”, n);
}
The program computes
(a) x  y , using repeated subtraction
(b) x mod y using repeated subtraction
(c) the greatest common divisor of x and y
(d) the least common multiple of x and y

C PROGRAMMING & DATA STRUCTURES 56


SRIDHAR

51. The goal of structured programming is to (GATE-2004)


(a) have well indented programs
(b) be able to infer the flow of control from the compiler code
(c) be able to infer the flow of control form the program text
(d) avoid the use of GOTO statements

52. Choose the best matching between the programming styles in Group 1 and their
characteristics in Group 2 (GATE-2004)
Group 1 Group 2
P. Functional 1. Command-based, procedural
Q. Logic 2. Imperative, abstract data types
R. Object-oriented 3. Side-effect free, declarative,
expression Evaluation
S. Imperative 4. Declarative, clausal representation
theorem proving
(a) P – 2 Q – 3 R – 4 S – 1 (b) P – 4 Q – 3 R – 2 S – 1
(c) P – 3 Q – 3 R – 1 S – 2 (d) P – 3 Q – 4 R – 2 S – 1
53. Consider the following C-program (GATE-2005)
void foo (int n, int sum)
{
int k=0, j=0;
if (n= = 0) return;
k=n% 10; j=n/10;
sum=sum+k;
foo (j, sum);
printf (“%d”, k);
}
int main ( )
{
int a = 2048, sum = 0;
foo (a, sum);
printf (“%d/n”, sum);
}
What does the above program print?
(a) 8, 4, 0, 2, 14 (b) 8, 4, 0, 2, 0
(c) 2, 0, 4, 8, 14 (d) 2, 0, 4, 8, 0
54. Consider the following C-program (GATE-2005)
double foo(double);/*Line-1*/
int main( )
{
double da, db;
// input da
db=foo (da);
}
double foo (double a)
{
return a;
}

C PROGRAMMING & DATA STRUCTURES 57


SRIDHAR

The above code complied without any error or warning. If line 1 is deleted, the
above code will show
(a) no compile warning or error
(b) some complier-warning not leading to unintended results
(c) some complier warning due to type mismatch eventually leading to
unintended results
(d) complier errors.

55. A common property of logic programming languages and functional languages


is: (GATE-2005)
(a) both are procedural languages (b) both are based on 1-calculus
(c) both are declarative (d) both use Horn-clauses

56. Which one of the following are essential features of an object-oriented


programming language ?
i) Abstraction and encapsulation
ii) Strictly-typedness
iii) Type-safe property coupled with sub-type rule
iv) Polymorphism in the presence of inheritance (GATE-2005)
(a) (i) and (ii) only (b) (i) and (iv) only
(c) (i), (ii) and (iv) only (d) (i), (iii) and (iv) only

57. Consider the following C function: (GATE-2007)


int f(int n)
{
static int r=0;
if (n<=0) return 1;
if (n>3)
{
r=n;
return f(n-2)+2;
}
return f(n-1)+r;
}
What is the value of f(5)?
(a) 5 (b) 7 (c) 9 (d) 18

58. Choose the correct option to fill ?1 and ?2 so that the program below prints an
input string in reverse order. Assume that the input string is terminated by a
newline character. (GATE-2008)
void reverse (void)
{
int c;
if (?1) reverse ();
?2
}

C PROGRAMMING & DATA STRUCTURES 58


SRIDHAR

main ( )
{
printf (“Enter Text”); printf (“\n”)
reverse( ); printf(“\n”);
}
(a) ? is (getchar() !=’\n’) ? 2 is getchar (c) ;
(b) ? 1 is (c=getcher ( )) !=’\n’)? 2 is getchar (c) ;
(c) ? 1 is (c!=’\n’)? 2 is putchar (c) ;
(d) ? 1 is ((c=getchar ( ))!=’\n’)? 2 is putchar (c) ;

59. Which of the following are true ? (GATE-2008)


I. A programming language which does not permit global variables of any kind
and has no nesting of proceduces/functions, but permits recursion can be
implemented with static storage allocation
II. Multi-level access link (or display) arrangement is needed to arrange
activation records only if the programming language being implemented has
nesting of procedures/functions
III. Recursion in programming languages cannot be implemented with dynamic
storage allocation
IV. Nesting procedures/functions and recursion require a dynamic heap
allocation scheme and cannot be implemented with a stack-based allocation
scheme for activation records
V. Programming languages which permit a function to return a function as its
result cannot be implemented with a stack-based storage allocation scheme
for activation records
(a) II and V only (b) I, III and IV only
(c) I, II and V only (d) II, III and V only

60. Which languages necessarily need heap allocation in the runtime environment ?
(GATE-2010)
(a) Those that support recusion
(b) Those that use dynamic scoping
(c) Those that allow dynamic data structures
(d) Those that use global variables

Common data questions 61 and 62 (GATE-2011)


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;
}
61. What is the return value of the function foo when it is called as foo (345, 10)?
(a) 345 (b) 12 (c) 5 (d) 3

C PROGRAMMING & DATA STRUCTURES 59


SRIDHAR

62. What is the return value of the function foo when it is called as foo (513, 2)?
(a) 9 (b) 8 (c) 5 (d) 2

63. Consider the program given below, in a block structured pseudo-language with
lexical (GATE-2012)
scooping and nesting of procedures permitted.
program main;
var…
procedure A1;
var ….
call A2;
end A1
procedure A2;
var …
procedure A21;
var …
call A1,
end A21
call A21;
end A2;
call A1;
end main.
Consider the calling chain:
Main  A1  A 2  A 21  A1
The correct set of activation records along with their access links is given by

C PROGRAMMING & DATA STRUCTURES 60


SRIDHAR

Common Data for Questions 64 and 65:


Consider the following Coode segment.
int a, b, c = 0
void prtFun (void);
main ( )
{
static int a=1;/*Line 1*/
prtFun ( );
a+ = 1;
ptrFun ( );
printf (“\n %d%d”, a, b);
}
void prtFun (void)
{
static int a =2; /*line 2*/
int b=1;
a+=++b;
printf(“\n%d%d”, a, b);
}

64. What output will be generated by the given code segment? (GATE-2012)
(a) 3 1 (b) 4 2
4 1 6 1
4 2 6 1
(c) 4 2 (d) 3 1
6 2 5 2
2 0 5 2
65. What output will be generated by the given code segment if:
Line 1 is replaced by auto int a=1; Line 2 is replaced by register int a= 2;
(a) 3 1 (b) 4 2
4 1 6 1
4 2 6 1
(c) 4 2 (d) 4 2
6 2 4 2
2 0 2 0

66. What will be the output of the following C program segment ?


char inchar = ‘A’;
switch (inchar) {
case ‘A’ : printf(“choice A\n”);
case ‘B’ :
case ‘C’ : printf(“choice B”);
case ‘D’ :
case ‘E’ :
default : printf (“No choice”); } (GATE-2012)
(a) No choice (b) Choice A
(c) Choice A – Choice B No choice
(d) Program gives no output as it is erroneous

C PROGRAMMING & DATA STRUCTURES 61


SRIDHAR

67. What is the return value of f(p.p) if the value of p is initialized to 5 before the
call? Note that the first parameter is passed by reference, whereas the second
parameter is passed by value. (GATE-2013)
int f (int & x, int c)
{
c = c – 1;
if (c = = 0)
return 1;
x = x + 1;
return f(x, c) *x;
}
(a) 3024 (b) 6561 (c) 55440 (d) 161051

68. Consider the function func shown below (GATE-2014)


int func (int num)
{
int count = 0;
while (num)
{
count ++;
num>>= 1;
}
return (count) ;
}
The value returned by func (435) is ________

69. Suppose n and p are unsigned int variables in a C program. We wish to set p to
n
C3. If n is large, which one of the following statements is most likely to set p
correctly ? (GATE-2014)
(a) p = n * (n – 1) * (n – 2) / 6; (b) p = n * (n – 1) / 2 * (n – 2) / 3;
(c) p = n * (n – 1) / 3 * (n – 2) / 2; (d) p = n * (n – 1) * (n – 2) / 6.0;

70. Which of the following statements are CORRECT ? (GATE-2014)


1. Static allocation of all data areas by a compiler makes it impossible to
implement recursion
2. Automatic garbage collection is essential to implement recursion
3. Dynamic allocation of activation records is essential to implement recursion
4. Both Heap and stack are essential to implement recursion
(a) 1 and 2 only (b) 2 and 3 only (c) 3 and 4 only (d) 1 and 3 only

C PROGRAMMING & DATA STRUCTURES 62


SRIDHAR

71. Consider the following function (GATE-2014)


double f(double x)
{
if (abs(x*x-3)<0.01)
return x;
else
return f(x/2 + 1.5/x);
}
Give a value q(to 2 decimals) such that f(q) will return q: ______

72. Consider the C function given below. (GATE-2014)


int f(int f)
{
static int I = 50;
int k;
if (i = = j)
{
print f(“something”);
k = f(i);
return 0;
}
else return 0;
}
Which one of the following is TRUE ?
(a) The function returns 0 for all values of j
(b) The function prints the string something for all values of j
(c) The function returns 0 when j = 50
(d) The function will exhaust the runtime stack or run into an infinite loop when
j = 50

73. Consider the following pseudo code, where x and y are positive integers.
(GATE-2015)
begin
q := 0
r := x
while r  y do
begin
r := r – y
q := q+1
end
end

The post condition that needs to be satisfied after the program terminates is
(a) {r  qx  y  r  y} (b) {x  qy  r  r  y}
(c) { y  qx  r  0  r  y} (d) {q  1  r  y  y  0}

C PROGRAMMING & DATA STRUCTURES 63


SRIDHAR

74. Consider the following C function. (GATE-2015)


int fun (int n)
{
int x=1, k;
if (n==1) return x;
for (k=1; k<n; ++k)
x = x + fun (k) * fun (n-k);
return x;
}
The return value of fun (5) is _______.

75. Consider the following recursive C function. (GATE-2015)


void get (int n)
{
if (n<1) return;
get (n-1) ;
get (n-3) ;
printf (“%d”, n) ;
}

If get (6) function is being called in main () then how many times will the get ()
function be invoked before returning to the main () ?
(a) 15 (b) 25 (c) 35 (d) 45

76. Consider the following C program: (GATE-2015)


#include<stdio.h>
int main( )
{
int i, j, k = 0;
j = 2*3/4+2.0/5+8/5;
k - = -- j;
for (i = 0; i<5; i++)
{
switch ( i + k)
{
case 1:
case 2: printf(“\n%d”, i+k);
case 3: printf(“\n%d”, i+k);
default: printf(“\n%d”, i+k);
}
}
return 0;
}
The number of times printf statement is executed is _______.

C PROGRAMMING & DATA STRUCTURES 64


SRIDHAR

77. Consider the following C program. (GATE-2015)


#include<stdio.h>
int f1 (void) ;
int f2 (void) ;
int f3 (void) ;
int x = 10 ;
int main ( )
{
int x = 1 ;
x += f1 ( ) + f2 ( ) + f3 ( ) + f2 ( ) ;
printf (“ %d”, x) ;
return 0 ;
}

int f1( ) { int x = 25; x++; return x; }


int f2 ( ) { static int x = 50; x++; return x; }
int f3 ( ) { x * = 10; return x};
The output of the program is _______.

C PROGRAMMING & DATA STRUCTURES 65


SRIDHAR

PRACTICE QUESTIONS

1. Which of the following is not a valid declaration in C?


1. short int x;
2. signed short x;
3. short x;
4. unsigned short x;
(a) 3 & 4 (b) 3 (c) 1 (d) All are valid

2. Suppose n and p are unsigned int variables in a C program. We wish to set p to


n
C3. If n is large, which of the following statements is most likely to set p
correctly?
a) p = n * (n-1) * (n-2) / 6;
b) p = n * (n-1) / 2 * (n-2) / 3
c) p = n * (n-1) / 3 * (n-2) / 2;
d) p = n * (n-1) * (n-2) / 6.0

3. what is the output of following code ?


//x is a 2 byte integer
int main( )
{
unsigned int x = 35;
printf("Signed Result %d \n", ~x+1);
return 0;
}
a)35 b)-35 c)36 d)-36

4. The smallest integer that can be represented by an 8 bit number in 2’s complement
form is
a)-256 b)-128 c)-127 d)0

5. What is output of following code.


int main( )
{
printf(" %d", printf("%s", "HelloPrint"));
getchar( );
}
(a) HelloPrint 10 (b) HelloPrint (c) 10 HelloPrint (d) 10

6. What is the output of the following statement:


printf (“%-3d”,12345);
(a) 1 2 3 (b) -1 2 3 (c) 1 2 3 4 5 (d) 12

7. If an integer needs two bytes of storage, then the maximum value of a signed
integer is
(a) 216-1 (b) 215-1 (c) 216 d) 215

C PROGRAMMING & DATA STRUCTURES 66


SRIDHAR

8. What will be the output of the program ?


#include<stdio.h>
int main( )
{
printf(5+"Good Morning\n");
return 0;
}
(a) Good Morning (b) Good (c) M (d) Morning

9. Which of the following is the correct usage of conditional operators used in C?


(a) a>b ? c=30 : c=40;
(b) a>b ? c=30;
(c) max = a>b ? a>c?a:c:b>c?b:c
(d) return (a>b)?(a:b)

10. In which order do the following operators gets evaluated


1. Relational
2. Arithmetic
3. Logical
4. Assignment
(a) 2134 (b) 4321 (c) 1234 (d) 3214

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


main( )
{
int i = 5;
printf(“%d”, i=++i==6);
}
(a) 0 (b) 1 (c) 7 (d) 6

12. Assuming, integer is 2 byte, What will be the output of the program?
#include<stdio.h>
int main( )
{
printf("%x\n", -1>>1);
return 0;
}
(a) ffff (b) 0000 (c) 0fff (d) fff0

13. Assuming a integer 2-bytes, What will be the output of the program?
#include<stdio.h>
int main( )
{
printf("%x\n", -1<<3);
return 0;
}
(a) ffff (b) 0 (c) fff8 (d) -1

C PROGRAMMING & DATA STRUCTURES 67


SRIDHAR

14. If an unsigned int is 2 bytes wide then, What will be the output of the program ?
#include<stdio.h>
int main( )
{
unsigned int a=0xffff;
~a;
printf("%x\n", a);
return 0;
}
(a) ffff (b) 00ff (c) 0000 (d) ddfd

15. What will be the output of the program?


#include<stdio.h>
int main( )
{
int y=128;
const int x=y;
printf("%d\n", x);
return 0;
}
(a) 128 (b) Garbage value (c) Error (d) 0

16. What will be the output of the program?


int get( );
int main( )
{
const int x = get( );
printf("%d", x);
return 0;
}
int get( )
{
return 20;
}
(a) Garbage value (b) Error (c) 20 (d) 0

17. What will be the output of the program?


int main( )
{
const int c = -11;
const int d = 34;
printf("%d, %d\n", c, d);
return 0;
}
(a) Error (b) -11, 34 (c) 11, 34 (d) None of these

C PROGRAMMING & DATA STRUCTURES 68


SRIDHAR

18. What is the output of the following code:


#include<stdio.h>
int main( )
{
unsigned int x = -1;
int y = ~0;
if(x == y)
printf("same");
else
printf("not same");
return 0;
}
(a) Same (b) not same (c) Error (d) 0

19. what is the output of following code ?


#include <stdio.h>
int main( )
{
if (printf("rama")>printf("sai")>printf("sita"))
printf("TRUE");
else
printf("FALSE");
return 0;
}
(a) ramasaisitaFALSE (b) FALSE (c) TRUE (d) error

20. what is the output of following code ?


#include <stdio.h>
int main( )
{
if (printf("rama"+4)>printf("sai"+3)>printf("sita"+4))
printf("TRUE");
else
printf("FALSE");
return 0;
}
(a) ramasaisitaFALSE (b) FALSE (c) TRUE (d) error

21. What will be the output of the program?


#include<stdio.h>
int reverse(int);
void main( )
{
int no=5;
reverse(no);
}

C PROGRAMMING & DATA STRUCTURES 69


SRIDHAR

int reverse(int no)


{
if(no == 0)
return 0;
else
printf("%d,", no);
reverse (no--);
}
(a) Print 5, 4, 3, 2, 1 (b) Print 1, 2, 3, 4, 5
(c) Print 5, 4, 3, 2, 1, 0 (d) Infinite loop

22. The output of the following code segment will be


char x = ‘B’;
switch (x)
{
case ‘A’: printf(“a”);
case ‘B’: printf(“b”);
case ‘C’: printf(“c”);
}
(a) B (b) b (c) BC (d) bc
23. What is the following function computing? Assume a and b are positive integers.
int fn( int a, int b)
{
if (b == 0)
return b;
else
return (a * fn(a, b - 1));
}
(a) Output will be 0 always (b) Output will always be b
(c) Computing ab (d) Computing a * b

24. What is the purpose of the function ?


void f(int i)
{
int j;
for (j=0;j<16;j++)
{
if (i & (0x8000>>j))
printf("1");
else
printf("0");
}
}
(a) prints hex representation of i (b) prints decimal representation of i
(c) prints binary representation of I (d)none.

C PROGRAMMING & DATA STRUCTURES 70


SRIDHAR

25. What is the output of following code ?


int x = 0;
int f( )
{
return x;
}

int g( )
{
int x = 1;
return f( );
}
int main( )
{
printf("%d", g( ));
}
(a) 1 (b) 0 (c) Compiler Error (d) 10

26. What is the output from prg_1.c and prg_2.c


// Prg_1.c
void fun( ) { printf(“p1”); }
int main(void)
{
fun(10, "GfG", "GQ");
return 0;
}
//prg_2.c
void fun(void) { printf(“P2”); }
int main(void)
{
fun(10, "GfG", "GQ");
return 0;
}
(a) Prg_1.c prints p1 and Prg_2.c prints p2
(b) Prg_1.c prints p1 but prg_2.c gives compile time error
(c) Prg_2.c prints p2 but prg_1.c gives compile time error
(d) Prg_1.c and prg_2.c gives compile time error

C PROGRAMMING & DATA STRUCTURES 71


SRIDHAR

27. what is the output of following code


#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
(c) 14 11 8 5 2 (d) 15 12 8 5 2

28. Consider the following C function


int f(int n)
{
static int i = 1;
if (n >= 5)
return n;
n = n+i;
i++;
return f(n);
}
The value returned by f(1) is ------ ?
(a) 5 (b) 6 (c) 7 (d) 8
29. Consider the following C function, what is the output?
int f(int n)
{
static int r = 0;
if (n <= 0) return 1;
if (n > 3)
{
r = n;
return f(n-2)+2;
}
return f(n-1)+r;
}

int main()
{
printf("%d", f(4));
}
(a) 5 (b) 7 (c) 11 (d) 18

C PROGRAMMING & DATA STRUCTURES 72


SRIDHAR

30. What is the Output of following program


#include <stdio.h>
int fun(int n)
{
static int s = 0;
s = s + n;
return (s);
}
int main()
{
int i = 5, x;
while (i > 0)
{
x = fun(i);
i--;
}
printf ("%d ", x);
}
(a) 15 (b) 100 (c) 55 (d) 0
31. What is the output of following code ?
int x = 0;
int f1( )
{
x = 5;
return x;
}
int f2( )
{
x = 10;
return x;
}
int main( )
{
int p = f1( )+f2( );
printf("%d ", x);
return 0;
}
(a) 5 (b) 10 (c) 15 (d) 0
32. There is a error in the below program. Which statement will you add to remove it?
#include<stdio.h>
int main( )
{
int a;
a = f(10, 3.14);
printf("%d\n", a);
return 0;
}

C PROGRAMMING & DATA STRUCTURES 73


SRIDHAR

float f(int aa, float bb)


{
return ((float)aa + bb);
}
(a) Add prototype: float f(aa, bb)
(b) Add prototype: float f(int, float)
(c) Add prototype: float f(float, int)
(d) Add prototype: float f(bb, aa)

33. Which of the following statements are correct about the function?
ong fun(int num)
{
int i;
long f=1;
for(i=1; i<=num; i++)
f = f * i;
return f;
}
(a) The function calculates the value of 1 raised to power num
(b) The function calculates the square root of an integer
(c) The function calculates the factorial value of an integer
(d) None of above

34. What will be the output of the program If characters 'a', 'b' and 'c' enter are
supplied as input?
int main( )
{
void fun( );
fun( );
printf("\n");
return 0;
}
void fun( )
{
char c;
if((c = getchar( ))!= '\n')
fun( );
printf("%c", c);
}
(a) abc abc (b) bca (c) Infinite loop (d) Cba

35. Which of the following is the correct order if calling functions in the below code?
a = f1(23, 14) * f2(12/4) + f3();
(a) f1, f2, f3 (b) f3, f2, f1
(c) Order may vary from compiler to compiler (d) None of above

C PROGRAMMING & DATA STRUCTURES 74


SRIDHAR

36. Which of the following statements are correct about the program?
#include<stdio.h>
int main( )
{
printf("%p\n", main( ));
return 0;
}
(a) It prints garbage values infinitely
(b) Runs untill stack overflow. without printing anything
(c) Error: main( ) cannot be called inside printf( )
(d) No Error and print nothing
37. Point out the error in the program
#include<stdio.h>
int f(int a)
{
a > 20? return(10): return(20);
}
int main( )
{
int f(int);
int b;
b = a > 20? return(10): return(20);
printf("%d\n", b);
}
(a) Error: Prototype declaration (b) No error
(c) Error: return statement cannot be used with conditional operators
(d) None of above
38. What is the output of this program?
#include <stdio.h>
int counter(int i)
{
static int count = 0;
count = count + i;
return count;
}
int main(void)
{
int i, j;
for (i = 0; i <= 5; i++)
j = counter(i);
printf("%d\n", j);
return 0;
}
(a) 10 (b) 15 (c) 6 (d) 7

C PROGRAMMING & DATA STRUCTURES 75


SRIDHAR

39. Which statement in the following program produces compile time error
main( )
{ int i=15;
auto int j=i; // statement-1
static int k=i; // statement-2
register int m=i; // statement-3
}
(a) statemet-1 (b) statemet-2
(c) statemet-3 (d) none

40. In C, static storage class cannot be used with


(a) Global variable (b) Function parameter
(c) Function name (d) Local variable

41. Choose the correct one


(a) Address operator can not be applied to register variables
(b) Address operator can not be applied to static variables
(c) Use of register declaration will not increase the execution time
(d) None of the above

C PROGRAMMING & DATA STRUCTURES 76


SRIDHAR

Key

PREVIOUS

1. A 2. B 3. A 4. D 5. ___ 6. A
7. ___ 8. ___ 9. ___ 10. ___ 11. ____ 12. D
13. B 14. C 15. D 16.___ 17. A 18. ___
19. A 20. C 21. ___ 22. ___ 23. B 24. A
25. ___ 26. D 27. ___ 28. B 29. C 30. ___
31. C 32. D 33. C 34. C 35. B 36. ____
37. A 38. ____ 39. B 40. D 41. D 42. B
43. B 44. D 45. B 46. B 47. C 48. D
49. A 50. C 51. D 52. D 53. D 54. D
55. C 56. B 57. D 58. D 59. B 60. C
61. B 62. D 63. D 64. C 65. D 66. C
67. B 68. 9 69. B 70. D 71. 1.72 to 1.74
72. D 73. B 74. 51 75. B 76. 10 77. 230

PRACTICE

1. D 2. B 3. B 4. B 5. A 6. C
7. B 8. D 9. C 10. A 11. B 12. A
13. C 14. A 15. A 16. C 17. B 18. A
19. A 20. B 21. D 22. D 23. A 24. C
25. B 26. B 27. C 28. C 29. C 30. A
31. B 32. B 33. C 34. D 35. C 36. B
37. C 38. B 39. B 40. B 41. D

C PROGRAMMING & DATA STRUCTURES 77


SRIDHAR

CONTENTS

Topic Page No

Arrays 1 – 20
Pointers 21 – 51
Strings 52 – 61
Structure 62 – 68
Union 69 – 71
Bitfield 72 – 77
C Preprocessor Directives 78 – 93
Last Minute Revision 94 – 95

C PROGRAMMING & DATA STRUCTURES 1


SRIDHAR

ARRAYS
 An array is a storage area which can store similar type of values in adjacent memory
locations and can able to refer it by array name with index.
 int emp[5]; [int memory = 2 bytes]
100 102 104 106 108
98 90 31 28 21
emp  [0] [1] [2] [3] [4]

 Array index starts from 0


 Maximum index value is array size – 1
 Size of an array =  size of its individual elements.
 Eg : int a[10]
Size of an array = sizeof (sizeof datatype of int) * total no of elements
= 2 x10 = 20 bytes
 Array initialization:
i) int a[3] = {1, 2, 3}; ii) int a[] = {1,2,3};
 The compiler allocates memory for that array during compilation based on array size .
a) int a[ ]; /* it is compile time error. Because size is not specified*/
b) int a[ ] = {1, 2, 4, 6}; /* is a valid one, because compiler gets an idea on the number of
elements in array. */
c) It is suggestive to declare the size in the first place, to optimize the program execution.
int a[3] = {1, 2, 4};
 Once an array is declared, the address of array cannot be changed.
For ex:
int arr[7]={6, 19, 10, 13, 11, 8, 10};
 arr
100 102 104 106 108 110 112  Address
6 19 10 13 11 8 10
[0] [1] [2] [3] [4] [5] [6]  index

arr

200
 arr = Array name, which acts as a pointer to an array.
= address of first element of an array
= array name = & of its first element.
= arr = & arr [0]
 arr + 1 = & arr[0] + 1 = &arr [ 1]
= 100 + 1 = 102
 On declaring an array, compiler allocates memory, and it is fixed.
Eg : int a[10];
int b[10];
a = b; /* Trying to assign address of an array b (its first element) to an
array a. It is compile time error to assign a new address. */

C PROGRAMMING & DATA STRUCTURES 1


SRIDHAR

 Compiler doesn’t check the bounds of an array in C language.


int a[3] = {1, 12, 13};

1 12 13
a 0 1 2

1 12 13
&a
printf (“%d”, a[3]); // it prints garbage.
a[3] = a[2] + 1; // are valid and doesn’t throw any compilation error.
 int a[3] = {0}; is valid and initializes all values to ‘0’ at a stretch
 int a[6] = {1, 2, 3}; will work like this

1 2 3 0 0 0
a
compiler fill the remaining element to ‘0’
 int a[3] = {1, 2, 3, 4, 5};
if number of elements are more than sizeof array then compiler throws an error.
 int a[3] = {1, ‘A’, 3.8};
printf (“%d %d %d”, a[0], a[1], a[2]);
output : 1, 65, 3
Compiler always tries to convert the array values into the array type.
 Loc (element): location is a function which gives the starting address of array element.
Eg: loc (a[2]) = 100 102 104 106 108
11 12 13 14 15
[0] [1] [2] [3] [4]

Base Address (B.A)= 100


int a[5] = {11, 12, 13, 14, 15};
int size = 2 bytes
loc (a[2]) = B.A + [datatype_size * index] = B.A + [2 x 2] = 100 + 4 = 104
a[4] = B.A + [size * index]
= 100 + [2 x 4] = 108
Two Dimensional Arrays:
 Two-dimensional array is an array which is a collection of one dimensional arrays which are
of same size and contains same type of data.
 int a[2][3] = { {1, 2, 3}, {4, 5, 6} };
1 2 3
4 5 6
Similar to one dimensional array the index for 2-d array also starts from 0.
 Eg: 2nd rowy 3rd column is represented or accessed as a[1] [2]  6.
1 2 3
4 5 6

C PROGRAMMING & DATA STRUCTURES 2


SRIDHAR

 int a[ ] [3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; 7 8 9

 int arr[ ] = {2, 3, 4, 5};

2 3 4 5
100 102 104 106
100
arr
 array name (arr) = &(arr) = &arr[0] i.e.
arr, &arr, &arr[0] points to first element of an array.
i.e. contains the address of first element.
 arr, &arr[0] if incremental by ‘1’ points to next array element i.e. arr[1].
 (&arr + 1) points to next row.
Passing an array to a Function:
 To pass an array to a function can be done in three ways :
a) a formal parameter as a pointer.
b) formal parameter as a ‘sized array’.
c) as an unsized array.
a) A formal parameter as a pointer:
void print (int *aptr, int asize)
{
for (int i = 0; i < asize; i++)
{
printf(“%d”, *(aptr + i)); //------------- (i)
}
for (int i = 0; i < asize; i++)
{
printf(“%d”, aptr[i]); //------------- (ii)
}
}
void main ( )
{
int a[5] = {5, 4, 3, 2, 1};
print (a, 5);
}

i. Output: 5 4 3 2 1
ii. Output = 5 4 3 2 1

C PROGRAMMING & DATA STRUCTURES 3


SRIDHAR

b) passing a sized array


void print (int a[5], int b)
{
int i=0;
for (i; i<b; i++)
{
printf (“%d”, a[i]);
}
}
Output: 5 4 3 2 1
c) passing an unsized array.
void print (int a[ ], int n)
{
int i = 0;
for (i; i < n; i++)
{
printf (“%d”, a[i]);
}
}
Output: 5 4 3 2 1
1. What is the output of following code.
# include <stdio.h>
# define print(x) printf(“%d”, x)
int x;
void Q (int z) … (6)
{
z += x; … (7)
print(z); … (8)
}
void P (int *y) … (3)
{
int x = *y + 2; … (4)
Q(x); … (5)
*y = x – 1: … (9)
print(x); … (10)
}

C PROGRAMMING & DATA STRUCTURES 4


SRIDHAR

main (void)
{
x = 5; … (1)
P(&x); … (2)
printf(x); … (11)
}
Explanation:
1. ‘x’ is an external variable and is assigned ‘5’
2. function ‘p’ is called with an address of x.
3. y = &x. now ‘y’ points to x.

x 5 global

4. A new variable ‘x’ which is a local variable is created.


x=*y+2=5+2=7

x 7 local

5. A function ‘Q’ is called with ‘x’. The ‘x’ available for the function call is
local ‘x’. Therefore Q(7) will be called.
6. int z received Q(7) and assigns z = 7
7. In z + = x, ‘x’ is a global variable. Therefore z+ = x => (z = z + x)
= z = 7 + 5 = 12
Global ‘x’ value. Therefore z = 12
8. printf(z) prints 12
9. *y = x – 1; therefore *y = 7 – 1 = 4
Therefore now
6 global

10. printf(x) prints 7 x: 7 local

11. print(x) prints global ‘x’ = 6


global x
12 7 6

C PROGRAMMING & DATA STRUCTURES 5


SRIDHAR

2. What is the outcome of following code.


Consider these two functions( work1() and works2() ) and two statements s1, s2
about them.
1.int work1 (int *a, int i, int j)
{
int x = a[i+ 2];
a[j] = x + 1;
return a[i + 2] – 3;
}

2.int work2 (int *a, int i, int j)


{
int t1 = i + 2;
int t2 = a[t1];
a[j] = t2 + 1;
return t2 – 3;
}
Explanation:
a) checking the equality of (1) & (2)
let array a[4] = {1, 2, 3, 4}

1. i = 1, j = 2
x = a[1 + 2] = 4
= a[2] = 4 + 1 = 5
return a[1 + 2] – 3
= a[3] – 3
=4–3=1
Return 1;
2. int t1 = 1 + 2 3;
int t2 = a[3] = 4
a[2] = 4 + 1 = 5
return 4 – 3;

S1: Both code snippets returning same value, hence the functions are computing
same output.
S2: For better optimization, compiler must refer less number of memory locations.

Lets see the memory access in both functions.


int x = a[i + 2] … (1)
a[j] = x + 1 … (2)

C PROGRAMMING & DATA STRUCTURES 6


SRIDHAR

return a[i + 2] … (3)


Total ‘3’ memory reference are needed in work1.
int t1 = i + 2;
int t2 = a[t1]; … (1)
a[j] = t2 + 1 … (2)
return t2 – 3;
Only ‘2’ memory references in case work 2.
Therefore, S1 is true, S2 is true.
3. What is the output of following code.
# include <stdio.h>
int f(int *a, int n)
{
if (n <= 0)
return 0; … (A)
else if (*a % 2 == 0)
return *a + f(a + 1, n – 1); … (B)
else
return *a – f (a + 1, n – 1); … (C)
}
void main ( )
{
int a[ ] = {12, 7, 13, 4, 11, 6};
printf (“ ans : %d”, f(a, 6));
}

Output : 15
Explantation :
1. f(a, 6) = will assign the first element address to ‘a’ in function call.
for 12 : (B) is satisfied, therefore *a means value at address contained by ‘a’
Therefore *a = 12
12 + f(a + 1, 5), therefore a + 1 increments to next location i.e.
= 12 + f(a + 1, 5)

a → a[1]

12 7 13 4 11 6
2. for 7 : (C) is satisfied
Therefore 12 + 7 – f (a + 1, 4)
Therefore 19 – f(a – 11, 4)
a+1

12 7 13 4 11 6

C PROGRAMMING & DATA STRUCTURES 7


SRIDHAR

3. for 13 : (C) is satisfied


Therefore 19 [13 – f(a + 1, 3)]
= 19 – 3 + f (a + 1, 3)
= 6 + f (a + 1, 3)
a+1

12 7 13 4 11 6

4. for 4 : (B) is satisfied


Therefore 6 + 4 + f (a + 1, 2)
= 10 + f(a + 1, 2)

12 7 13 4 11 6

5. for 11 : (C) is satisfied


Therefore 10 +11 – f(a + 1, 1)
= 21 – f(a + 1, 1)
Now

12 7 13 4 11 6
6. for 6 : (B) is satisfied
therefore 21 – f (a + 1, 1)
21 – [6 + f(a + 1, 0)]
Therefore 21 – 6 + f(a + 1, 0)
= 15 + f(a + 1, 0)
Now

12 7 13 4 11 6

7. for current value of ‘a’ which is beyond the index, (a) will be satisfied.
Therefore 15 + 0 = 15 //.

C PROGRAMMING & DATA STRUCTURES 8


SRIDHAR

CLASS ROOM OBJECTIVES

1. Find the output of the following programs


(a) main( )
{
int B[3][2]={10,20,30,40,50,60};
printf (“%d”, B[0][1]);
printf (“%d”, B[2][1]);
printf (“%d”, B[0][2]);
printf (“%d”, B[2][5]);
}
(b) main( )
{
int a[3]={5,6,7};
int b[3][2]={5,6,7,1,2,3};
int c[3][2][3]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18};
printf (“%d”, c[0][0][0]);
printf (“%d”, c[0][1][2]);
printf (“%d”, c[1][1][1]);
}
2. Find the output of the following code segments
(a) main( )
{
int A[4][5][6]={1,2,…120};//numbers from 1 to 120//
printf (“%d”, A[1][1][1]);
}

(b) main( )
{
int A[3][4][5][3]={0,1,….179}; // numbers from 0 to 179//
printf (“%d”, A[1][2][3][2]);
}
3. Which declaration is valid in c
(a) int x[3][2]={1,2,3,4,5,6}; (b) int x[ ][2]={1,2,3,4,5,6};
(c) int x[2][ ]={1,2,3,4,5,6}; (d) int x[ ][ ]={1,2,3,4,5,6};
4. Find the output of the program
main( )
{
int x[3][3]={1,2,3,4,5,6,7,8,9};
int y[3][3]={9,8,7,6,5,4,3,2,1};
int i,j,t;

C PROGRAMMING & DATA STRUCTURES 9


SRIDHAR

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


{
for (j=0; j<3; j++)
{
t=x[i][j];
x[i][j]=y[i][j];
y[i][j]=t;
}
}
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
printf (“%d, x[i][j]);
}
}
}
5. Consider the following ‘c’ program which is suppose to compute the transpose of
given 4 x 4 matrix M. (note that there is an x in the program which indicates some
missing statement choose the correct one.)
#include <stdio.h>
#define Row 4
#define Col 4
int M{Row][Col]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
main( )
{
int i, j, t;
for (i=0; i<4; i++)
{
x
}
for (i=0; i<4; i++)
{
for (j=0; j<4; j++)
{
printf (“%d”, M[i][j]);
}
}
}
(a) for (j=0; j<4; j++) (b) for (j=0; j<4; j++)
{ {
t=M[i][j]; M[i][j]=t;
M[i][j]=M[j][i]; t=M[j][i];
M[j][i]=t; }
}

C PROGRAMMING & DATA STRUCTURES 10


SRIDHAR

(c) for (j=1; j<4; j++) (d) for (j=i; j<4; j++)
{ {
t=M[i][j]; M[i][j]=t;
M[i][j]=M[j][i]; t=M[i][j];
M[j][i]=t; M[i][j]=M[i][j];
} }
6. The goal of structured program is to
(a) have well defined indented program
(b) be able to infer the flow of control from the compiled code
(c) be able to infer the flow of control from the program text
(d) avoid use of goto statement
7. Find the output of the following program
(a) main( )
{
char s[7]=”Hello”;
s[2]=65;
}

(b) main( )
{
char s[10]=”Morning”;
int i;
for (i=0; s[i]; i++)
{
puts [s+i];
}
}
8. Find the output of the following code segments
(a) main( )
{
char s[5]=”GATE”;
char t[5]=”2015”;
char x[5];
x=s;
s=t;
t=x;
puts (s);
puts (t);
}

C PROGRAMMING & DATA STRUCTURES 11


SRIDHAR

9. Find the output of the following code segments


(a) main( )
{
char x[5]=”GATE”;
char t;
t=x[0];
x[0]=x[1];
x[1]=t;
puts (x);
}
(b) main( )
{
char x[5]=”ABCD”;
char t;
t=x[0];
x[0]=x[4];
x[4]=t;
puts (x);
}
10. Find the output of the following code segment
main( )
{
int x[5]={5,6,7,8,9};
printf (“%d”, x[4]);
printf (“%d”, 4[x]);
printf (“%d”, *(x+4));
printf (“%d”, *&x[4]);
}

PREVIOUS QUESTIONS

01. Assume the following C variable declaration (GATE-2003)


int * A[10], B[10] [10];
of the following expressions
I. A[2] II. A[2][3] III. B[1] IV. B[2][3]
Which will not give compile-time errors if used as left hand sides of assignment
statements in a C program ?
(a) I, II and IV only (b) II, III and IV only
(c) II and IV only (d) IV only

C PROGRAMMING & DATA STRUCTURES 12


SRIDHAR

02. What does the following fragment of C-program print ? (GATE-2011)


char c[ ] = “GATE2011’;
char *p = c;
printf (“%s”, p + p[3] – p[1]);
(a) GATE2011 (b) E2011 (c) 2011 (d) 01

03. Let A be a square matrix of size n  n. Consider the following pseudo-code. What is
the expected output ? (GATE-2014)
C = 100;
for i = 1 to n do
for j = 1 to n do
{
temp = A[i][j] + C;
A[i][j] = A[j][i];
A[j][i] = temp – C;
}
for i = 1 to n do
for j = 1 to n do
output (a[i][j]);
(a) The matrix A itself (b) Transpose of matrix A
(c) Adding 100 to the upper diagonal elements and subtracting 100 from lower
diagonal elements of A
(d) None of the above

04. What is the output of the following C code ? Assume that the address of x is 2000 (in
decimal) and an integer requires four bytes of memory. (GATE-2015)
int main ( )
{
unsigned int x[4][3] = {(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12)};
printf (“%u, %u, %u”, x+3, *(x+3), *(x+2)+3);
}
(a) 2036, 2036, 2036 (b) 2012, 4, 2204
(c) 2036, 10, 10 (d) 2012, 4, 6

05. Consider the following two C code segments. Y and X are one and two dimensional
arrays of size n and n  n respectively, where 2  n  10 . Assume that in both code
segments, elements of Y are initialized to 0 and each element X[i][j] of array X is
initialized to i+j. Further assume that when stored in main memory all elements of X
are in same main memory page frame. (GATE-2015)

C PROGRAMMING & DATA STRUCTURES 13


SRIDHAR

Code Segment 1 :
// initialize elements of Y to 0
// initialize elements X[i][j] of X to i+j
for (i = 0; i < n; i++)
Y[i] += X[0][i];
Code Segment 2 :
// initialize elements of Y to 0
// initialize elements X[i][j] of X to i+j
for (i = 0; i < n; i++)
Y[i] += X[i][0];
Which of the following statements is/are correct ?
S1 : Final contents of array Y will be same in both code segments
S2 : Elements of array X accessed inside the for loop shown in code segment 1
are contiguous in main memory
S3 : Elements of array X accessed inside the for loop shown in code segment 2
are contiguous in main memory
. (a) Only S2 is correct (b) Only S3 is correct
(c) Only S1 and S2 are correct (d) Only S1 and S3 are correct

06. Suppose you are provided with the following function declaration in the C
programming language. (GATE-2015)
int partition (int a[ ], int n);
The function treats the first element of a[ ] as a pivot, and rearranges the array so
that all elements less than or equal to the pivot is in the left part of the array, and all
elements greater than the pivot is in the right part. In addition, it moves the pivot so
that the pivot is the last element of the left part. The return value is the number of
elements in the left part.
The following partially given function in the C programming language is used to
find the kth smallest element in an array a[ ] of size n using the partition function.
We assume k  n.
int kth_smallest (int a[ ], int n, int k)
{
int left_end = partition (a, n);
if (left_end+1 == k)
{
return a[left_end];
}
if (left_end+1 > k)
{

C PROGRAMMING & DATA STRUCTURES 14


SRIDHAR

return kth_smallest ( _________________ );


}
else
{
return kth_smallest ( _________________ );
}
}
The missing argument lists are respectively
(a) (a, left_end, k) and (a + left_end+1, n-left_end-1, k-left_end-1)
(b) (a, left_end, k) and (a, n-left_end-1, k-left_end-1)
(c) (a+left_end+1, n-left_end-1, k-left_end-1) and (a, left_end, k)
(d) (a, n-left_end-1, k-left_end-1) and (a, left_end, k)

PRACTICE

1. What is the value of x printed by statement_2


int main(void)
{
int x=0;
char s[ ] = "hello";
printf("%s%n",s,&x); // statement_1
printf("\nx=: %d",x); // statement_2
return 0;
}
a) 5 b) Hello c) 1 d) Address of s
2. What is the output of following code ?

int f(int arr[ ] , int n)


{
int res = 0, i;
for (i = 0; i < n; i++)
res ^= arr[i];
return res;
}
int main(void)
{
int arr[ ] = {12, 12, 90, 90, 14, 14, 14};
int n = sizeof(arr)/sizeof(arr[0]);
printf ("\n %d ", f(arr,n));
return 0;
}
a) it prints odd occurrence of number
b) it prints highest element of the array
c) it prints lowest element of the array
d) compile error

C PROGRAMMING & DATA STRUCTURES 15


SRIDHAR

3. Predict the output of following program?

#include <stdio.h>
int main( )
{
char arr[100];
printf("%d", scanf("%s", arr));
/* Suppose that input value given for above scanf is "cQuiz" */
return 1;
}
a) 5 b) 1 c) 0 d) Garbage

4. What will be the output of the program?

#include<stdio.h>
int main( )
{
void fun(char*);
char a[100];
a[0] = 'A'; a[1] = 'B';
a[2] = 'C'; a[3] = 'D';
fun(&a[0]);
return 0;
}

void fun(char *a)


{
a++;
printf("%c", *a);
a++;
printf("%c", *a);
}
a) AB b) BC c) CD d) No output
5. What will happen if in a C program you assign a value to an array element whose
subscript exceeds the size of array?
a) The element will be set to 0.
b) The compiler would report an error.
c) The program may crash if some important data gets overwritten.
d) The array size would appropriately grow.
6. In C, if you pass an array as an argument to a function, what actually gets passed?
a) Value of elements in array
b) First element of the array
c) Base address of the array
d) Address of the last element of array.

C PROGRAMMING & DATA STRUCTURES 16


SRIDHAR

7. What will be the output of the program ?


#include<stdio.h>
int main()
{
static int a[2][2] = {1, 2, 3, 4};
int i, j;
static int *p[] = {(int*)a, (int*)a+1, (int*)a+2};
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
printf("%d,%d,%d,%d\n",*(*(p+i)+j),*(*(j+p)+i),*(*(i+p)+j), *(*(p+j)+i));
}
}
return 0;
}
a) 1, 1, 1, 1 b) 1, 1, 1, 1 (c) 1, 2, 1, 2 (d) 1, 2, 3, 4
2, 3, 2, 3 2, 2, 2, 2 2, 3, 2, 3 2, 3, 4, 1
3, 2, 3, 2 2, 2, 2, 2 3, 4, 3, 4 3, 4, 1, 2
4, 4, 4, 4 3, 3, 3, 3 4, 2, 4, 2 4, 1, 2, 3

8. What will be the output of the program ?


#include<stdio.h>
int main( )
{
void fun (int, int[ ]);
int arr[ ] = {1, 2, 3, 4};
int i;
fun(4, arr);
for(i=0; i<4; i++)
printf("%d,", arr[ i]);
return 0;
}
void fun (int n, int arr[ ])
{
int *p=0;
int i=0;
while(i++ < n)
p = &arr[i];
*p=0;
}
a) 2, 3, 4, 5 b) 1, 2, 3, 4 c) 0, 1, 2, 3 d) 3, 2, 1, 0

C PROGRAMMING & DATA STRUCTURES 17


SRIDHAR

9. What will be the output of the program ?


#include<stdio.h>
int main( )
{
int arr[1]={10};
printf("%d\n", 0[arr]);
return 0;
}
a) 1 b) 10 c) 0 d) 6
10. What will be the output of the program if the array begins 1200 in memory?
#include<stdio.h>
int main( )
{
int arr[ ]={2, 3, 4, 1, 6};
printf("%u, %u, %u\n", arr, &arr[0], &arr);
return 0;
}
a) 1200, 1202, 1204 b) 1200, 1200, 1200
c) 1200, 1204, 1208 d) 1200, 1202, 1200
11. What will be the output of the program ?
#include<stdio.h>
int main( )
{
char p[ ] = "%d\n";
p[1] = 'c';
printf(p, 65);
return 0;
}
a) A b) a c) c d) 65
12. What will be the output of the program ?
#include<stdio.h>
int main( )
{
int i;
char a[ ] = "\0";
if(printf("%s", a))
printf("The string is empty\n");
else
printf("The string is not empty\n");
return 0;
}
a) The string is empty b) The string is not empty
c) No output d) 0

C PROGRAMMING & DATA STRUCTURES 18


SRIDHAR

13. What is the output of this program?


#include <stdio.h>
int main(void)
{
char p;
char buf[10] = {1, 2, 3, 4, 5, 6, 9, 8};
p = (buf + 1)[5];
printf("%d\n", p);
return 0;
}
a) 5 b) 6 c) 9 d) Garbage
14. The output of the following statements is
char ch[6]={‘e’, ‘n’, ‘d’, ‘\0’, ‘p’};
printf(“%s”, ch);

a) endp (b) end0p (c) end (d) error


15. A two dimensional integer array TABLE [6] [8] is stored in row major order with
base address 351. What is the address of TABLE [3] [4]?
a) 407 (b) 408 (c) 405 d) 399
16. Explain the method to calculate the address of an element in an array. A [25, 4]
matrix array DATA is stored in memory in ‘row-major order’. If base address is 200
and ω= 4 words per memory cell. Calculate the address of DATA [12, 3] .
(a) 407 (b) 408 (c) 405 (d) 404

C PROGRAMMING & DATA STRUCTURES 19


SRIDHAR

Pointers
 Pointer is a variable which stores address of another variable.
 As we know computer memory consist of collection of bits. Which can able to store 1 or 0.
Bits are generally grouped to form bytes etc.
100 102 104 106 108 110 …..

 Each location in memory is assigned with unique address.


 Each location contains some value (either garbage or valid)
 Each location can be assigned a name called variable.

 int x = 10

 In the above diagram 110 is L-value of variable x and 10 is R-value of x


 Compiler associates the name of a variable to its address. At machine or hardware level
memory locations are accessed based on address.
 ‘& operator returns the address of a variable.
 Eg :
int a = 112, b = -1
float c = 3.14;
int *d = &a;
float *e = &c;

 ‘*’
int temp = *d; // get the value of a variable to which
// ‘d’ points. In this case, ‘d’ points to ‘a’.
Therefore *d = 112.
 A pointer must point to similar type of variables address.
 A ‘NULL’ pointer is a pointer which doesn’t point to any location.
Eg : int *ptr = 0;
 int i = 10;
int *ptr = &i;
ptr  is a pointer which Contains an address.
*ptr  represents the value stored in the memory location to which the pointer points.

C PROGRAMMING & DATA STRUCTURES 20


SRIDHAR

Types of Pointers
1. int *p;
// p is a pointer to an integer quantity.
2. int *p[10];
// p is a 10-element array of pointers to integer quantities
3. int (*p)[10];
// p is a pointer to a 10-element integer array
4. int *p(void);
// p is a function that returns a pointer to an integer quantity
5. int p(char *a);
// p is a function that accepts an argument which is a pointer to a character returns
an integer quantity
6. int *p(char *a);
// p is a function that accepts an argument which is a pointer to a character returns a
pointer to an integer quantity
7. int (*p)(char *a);
// p is pointer to a function that accepts an argument which is a pointer to a character
returns an integer quantity
8. int (*p(char *a))[10];
// p is a function that accepts an argument which is a pointer to a character returns a
pointer to a 10-element integer array
9. int p(char (*a)[]);
// p is a function that accepts an argument which is a pointer to a character array returns
an integer quantity
10. int p(char *a[]);
// p is a function that accepts an argument which is a array of pointers to characters
returns an integer quantity
11. int *p(char a[]);
// p is a function that accepts an argument which is a character array returns a pointer to
an integer quantity
12. int *p(char (*a)[]);
// p is a function that accepts an argument which is a pointer to a character array returns
a pointer to an integer quantity
13. int *p(char *a[]);
// p is a function that accepts an argument which is an array of pointers to characters
// returns a pointer to an integer quantity
14. int (*p)(char (*a)[]);
// p is pointer to a function that accepts an argument which is a pointer to a character
array returns an integer quantity
15. int *(*p)(char (*a)[]);
// p is pointer to a function that accepts an argument which is a pointer to a character
array returns a pointer to an integer quantity
16. int *(*p)(char *a[]);
// p is pointer to a function that accepts an argument which is a array of pointers to
// characters returns a pointer to an integer quantity

C PROGRAMMING & DATA STRUCTURES 21


SRIDHAR

17. int (*p[10])(void);


// p is 10-element array of pointers to functions; each function returns an integer
quantity
18. int (*p[10])(char a);
// p is 10-element array of pointers to functions; each function accepts an argument
which is a character and returns an integer quantity.
19. int *(*p[10])(char a);
// p is 10-element array of pointers to functions; each function accepts an argument
which is a character and returns a pointer to an integer quantity
20. int *(*p[10])(char *a);
// p is 10-element array of pointers to functions; each function accepts an argument
which is a pointer to a character and returns a pointer to an integer quantity

Null pointer A pointer which doesn’t point to any location.


Ex : int *ptr = 0;
Wild pointer A pointer which is not initialized with any address.
Ex : int *ptr
Dangling pointer A pointer pointing to a location where the location no more exist.
Ex : int *ptr

Constant pointer A pointer that cannot change the address its holding.
Ex: char *const ptr = &ch;
Function pointer. A pointer which stores the memory location of a function.
Ex: int (*fptr) (int ,int)
Array pointer An array, which can store pointers to an data type available.
Ex: int *p[10];
Pointer array A pointer which stores the address of an array.
Ex: int (*p)[10];
Single pointer A pointer stores the address of the Variable.
Ex: int *ptr;
Double pointer A pointer stores the address of the Pointer Variable.
Ex: int **ptr;

Example
1. main( )
{
char s[ ]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}
Output: 77

C PROGRAMMING & DATA STRUCTURES 22


SRIDHAR

Explanation: p is pointing to character '\n'. str1 is pointing to character 'a' ++*p. "p is
pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10, which is
then incremented to 11. The value of ++*p is 11. ++*str1, str1 is pointing to 'a' that is
incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98.
Now performing (11 + 98 – 32), we get 77 (77 is the ASCII value for "M");
So we get the output 77.
2. fun(char *ptr)
{
ptr=(char *) malloc(6);
ptr="Hello";
}
main( )
{
char *ptr=”bye";
fun(ptr);
printf("%s",ptr);
}
Output: bye
3. main( )
{
char string[ ]="Hello World";
display(string);
}
void display(char *string)
{
printf("%s",string);
}
Output: Compiler Error : Type mismatch in redeclaration of function display
Explanation :
 In third line, when the function display is encountered, the compiler doesn't know
anything about the function display. It assumes the arguments and return types to be
integers, (which is the default type).
 When it sees the actual function display, the arguments and type contradicts with
what it has assumed previously. Hence a compile time error occurs.

Constant Pointers
C PROGRAMMING & DATA STRUCTURES 23
SRIDHAR

 A constant pointer is a pointer that cannot change the address its holding. In other words, we
can say that once a constant pointer points to a variable then it cannot point to any other
variable.
 A constant pointer is declared as follows :

int * const ptr;


code to illustrate constant pointer:
#include<stdio.h>
int main(void)
{
int var1 = 10, var2 = 20;
int *const ptr = &var1;
ptr = &var2;
printf("%d\n", *ptr);
return 0;
}
Output : Error

In the above example:


 We declared two variables var1 and var2
 A constant pointer ‘ptr’ was declared and made to point var1
 Next, ptr is made to point var2.
 Finally, we try to print the value ptr is pointing to.
 So we see that while compiling the compiler complains about ‘ptr’ being a read only
variable. This means that we cannot change the value ptr holds.
Hence we conclude that a constant pointer which points to a variable cannot be made to point to
any other variable.
Pointer to Constant
 A pointer to constant data is known as pointer to constant.:
 These type of pointers can change the address they point to but cannot change the value kept
at those address.
An example of definition could be : const int* ptr;
Lets take a small code to illustrate a pointer to a constant :
#include<stdio.h>
int main(void)
{
int var1 = 0;
const int* ptr = &var1;
*ptr = 1;
printf("%d\n", *ptr);
return 0;
}

In the above code

C PROGRAMMING & DATA STRUCTURES 24


SRIDHAR

 We defined a variable var1 with value 0


 we defined a pointer to a constant which points to variable var1
 Now, through this pointer we tried to change the value of var1
 Used printf to print the new value.
 Now, when the above program is compiled we see that the compiler complains about
‘*ptr’ being read-only.
 This means that we cannot change the value using pointer ‘ptr’ since it is defined a
pointer to a constant.
Constant Pointer to a Constant
 If you have understood the above two types then this one is very easy to understand as its
a mixture of the above two types of pointers.
 A constant pointer to constant is a pointer that can neither change the address its pointing
to and nor it can change the value kept at that address.
for example :
const int* const ptr;
Lets look at a piece of code to understand this :

#include<stdio.h>
int main(void)
{
int var1 = 0,var2 = 0;
const int* const ptr = &var1;
*ptr = 1;
ptr = &var2;
printf("%d\n", *ptr);
return 0;
}

In the code above :


 We declared two variables var1 and var2.
 We declared a constant pointer to a constant and made it to point to var1
 Now in the next two lines we tried to change the address and value pointed by the
pointer.
 When the code was compiled we see that the compiler complained about both the value
and address being changed.
 Hence we conclude that a constant pointer to a constant cannot change the address and
value pointed by it.

Pointer to pointer( **) :

C PROGRAMMING & DATA STRUCTURES 25


SRIDHAR

 A pointer to a pointer his a kind of a pointer which holds address of another pointer
int x = 10;
int *ptr = &x;
int **dptr = & ptr;

Expression Value
x 10
ptr &x = 100
*ptr value at &x = 10
dptr 200 = &ptr
*dptr value at &ptr = 100
**dptr va;ie at &ptr = 10
 Example expressions :
char ch = ‘a’
char *cptr = &ch;

Expression:
 ‘ch ‘ : ch is a memory location, so it an be used as both L-value and R-value
 &ch : address of any variable cannot be used as L-value. It is a valid R-value.
cp :
 L-value means memory: ‘cp’ is a memory loc.
 R-value means the value : ‘cp’ contains value.
 Hence ‘cp’ is valid for both L-value and R-value.
*cp + 1:

 *cp: means value at address i.e. ‘a’


 a + 1 = b. ‘b’ is a value, hence it is valid as R-value and illegal as L-value.
*(cp + 1):

 cp contains address of ch.


 cp + 1 points to next memory location.

C PROGRAMMING & DATA STRUCTURES 26


SRIDHAR

 *(cp + 1) = value at memory location as shown above for L-value ‘ch2’ memory location
is considered for R-value, the value is the field ‘ch1’ is considered.
++cp:
 ++cp means incrementing cp by 1 if we increment ‘cp’ by 1, it becomes 101 and points to
ch2. address cannot be used as an L-value.
 R-value = 101.

cp++ :
Eg: x = cp++
 First ‘cp’ is assigned to x. after that it increments.

 Hence it cannot be used as L-value and can be used as R-value.

(*cp)++ :
*cp = a
a++ = b

 ‘b’ is a numeric value. Hence (*cp++) cannot be used as a L-value. It can be used as an
R-value.

++ *++cp :

++cp : cp + 1 = 100 + 1 = 101


*++cp : value at ++cp = b
++b = ‘c’

 Therefore ++*++cp results in numeral. It can be used as a R-value, but not as a L-value.

Pointer Arithmetic :
 There are two types of arithmetic operations on pointer
i.e ( Addition and Subtraction).
 In pointer arithmetic the type of variable a pointer points is taken as an unit.
Eg : int a = 10;
int *ptr = &a;

C PROGRAMMING & DATA STRUCTURES 27


SRIDHAR

 ptr + 1 : increments the pointer one time equal to size of the data type it points.
Therefore ptr + 1 results in
Eg : float f1 = 10.9;
float *ptr = &f;
ptr + 1;

*++cp:

cp: *++cp

 ++cp : value at ++cp = value at 101 = b.


 Therefore L-value = memory location 101
 R-value = b

*(cp++) :

 x = cp++
 mean ‘x’ contains ‘cp’ and then ‘cp’ will be incremented by1
 L-value = memory location of ‘a’
 R-value = ‘a’

*(++cp):

 *(++cp) : L-value = memory loc 101


R – value = b

C PROGRAMMING & DATA STRUCTURES 28


SRIDHAR

++*cp :
 *cp = a
 ++*cp = a + 1 = b
 Therefore L-value is illegal because it returns a numeral.
 R-value = b.
# include <stdio.h>
int fun(int n, int *fp) ... (3)
{
int t, f;
if (n <= 1) ... (4)
{
*fp = 1;
return 1;
}
t = fun (n – 1, fp); ... (5)
f = t + *fp;
*fp = t;
return f;
}
int main ( )
{
int x = 15; … (1)
printf (“%d\n”, fun(s, &x)); … (2)
return 0;
}
Output : 8
Explanation :
1. A local variable ‘x’ is created with assigned value 15.
2. A function call is made with &x. i.e.100. fun (5, 100).
3. In the function the address is assigned to *f – p
4. n = 5, so (5) will get executed.
T = fun (5, 100) t = fun(4, 100) t = fun(3, 100) t = fun(2, 100)
T=5 t=3 t=2 t = 1 t=fun(4100)
F=5+3 f=3+2 *f – p = 2 f = 1 + 1;
*f – p = 5 *f–p=3 *f – p = 2 *f – p = 1
Return 8; return 5 return 3 return 2

C PROGRAMMING & DATA STRUCTURES 29


SRIDHAR

What is the output of following program.

#include <stdio.h>
void f(int *p ,int *q) … (3)
{
p = q; … (4)
*p = 2; … (5)
}

int i = 0, j = 1; … (1)
int main( )
{
f(&i, &j); … (2)
printf (“%d %d”, i, j); ... (6)
return 0;
}

Explanation :
1. Global variables I,j are declared and assigned with 0, 1
2. A function call is made f(&i, &j) = f (100, 200)
3. The addresses are assigned to pointer p,q

4. p = q;

5. *p = 2; The location to which the pointer ‘p’ points is assigned 2.

6. printf prints i = 0, j = 2.

C PROGRAMMING & DATA STRUCTURES 30


SRIDHAR

Function pointer :
 Similar to a variable, function code also stored in memory location
 A pointer which stores the memory location of a function is called as a function pointer.
1. float addone(float source)
{
return source + 1.0;
}
int main( )
{
float res;
// similar to pointer to a variable, we need to declare apointer to hold
function address
float (*fp) (float);
// float is the function return type. Add one returns float.
// (float) is the function addone receives float parameter.
fp = &addone ; // similar to variable, we are assigning
// address of function to a variable
res = (*fp) (9.8); //function calling with value 9.8
printf(“\n Result= %0.2f”, res);
}
Output : Result=10.80

2. What does the following c-statements declare :


int (*f) (int *)
Output : a pointer to a function, which returns an integer and receives the address as a
parameter.
3. int addone (int *ptr)
{
return *ptr + 1;
}
main ( )
{
int y = 10, x;
int (*fptr) (int *); // declaring a function pointer
fptr = addone // fptr = add one also works. //assigning the function
x = fptr(&y); //address to a pointer.
printf (“%d”, x); // calling of the function through address
// of a variable.
}
Output : 11

Two-dimensional array and pointers :

C PROGRAMMING & DATA STRUCTURES 31


SRIDHAR

 A two dimensional array is a collection of one dimensional array.


Eg : int a[2][5]
a[2]  number of 1D arrays
a[5]  each array is a collection of 5 elements.

int a[2][5] = {
{1, 2, 3, 4, 5},
{5, 4, 3, 2, 1}
};

a : The array name always points to first element i.e.

a→ a[0] → a [0] →

 Therefore (%u, a) = 0 (%u, a + 1) = 20 E


 ‘a’ is of type pointer to an array. On incrementing it will point to next array i.e. a[1].
&a : ‘&a’ is a pointer to array.

 &a : points to complete 2-D array. Therefore (%u, &a) = 0. (%u, &a + 1) = 36
 A[0] : points to first element of a[0].
 Therefore (%u, &a[0]) = 0 (%u, &a[0] + 1) = 4
 Therefore a  1-D array pointer  array by array
&a  2-D array pointer
&a[0]  element by element in array by array.
&a[0]  similar to ‘a’
 To access element by element of all the array elements, the only option is a[0].
 Therefore to access all elements of a[2][5] :

for (i = 0; i < 2; i++) # for each row.


{

C PROGRAMMING & DATA STRUCTURES 32


SRIDHAR

for (j = 0; y < 5; y++)


{
printf (“%d”, *(*(a + i) + j);
}
}

Difference between “pointer to int” and “pointer to array of ints”


int main( )
{
int i,j;
int (*x)[5]; //pointer to an array of integers
int y[5] = {1,2,3,4,5}; //array of integers
int a[3][5];
int *z; //pointer to integer
for(i=0; i <3; i++)
{

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


{
a[i][j]=10*(i+1)+j;
}
}
printf(“\n From one Dimensional array( Using int pointer ) \n”);
z=y;
for( i=0;i<5;i++)
printf("%d\t ",z[i]);
x = y;
printf(“\n From one Dimensional array( Using pointer to array of int) \n”);
printf("\n\t");
for(i=0;i<5;i++)
printf("%d\t ",(*x)[i]);
printf("\n\t");
x=a;
j=0;
printf(“\n From 2 D array ( Using pointer to an array of int) :\n”);
while(j < 3)

C PROGRAMMING & DATA STRUCTURES 33


SRIDHAR

{
for(i=0;i<5;i++)
printf("%d\t ",(*x)[i]);
printf("\n\t");
x++;
j++;
}
}
Output :
From one Dimensional array( Using int pointer )
1 2 3 4 5
From one Dimensional array( Using pointer to an array of int)
1 2 3 4 5
From 2 D array ( Using pointer to an array of int ) :
10 11 12 13 14 15
20 21 22 23 24 25
30 31 32 33 34 35

Various Types of Questions on Pointers :


1. main ( )
{
static char *s[ ] = {“black”, “white”, “yellow”, “violet”};
char **ptr[ ] = {s+3, s+2, s+1, s}, ***p;
p = ptr;
**++p;
printf(“%s”,*--*++p + 3);
}
Output : ck
Explanation:
 p holds the initial value of ptr, i.e. p = s+3. The next statement increment value in p
by 1 , thus now value of p = s+2.
 In the printf statement the expression is evaluated *++p causes gets value s+1 then
the pre decrement is executed and we get s+1 – 1 = s.
 The indirection operator now gets the value from the array of s and adds 3 to the
starting address.
 The string is printed starting from this position. Thus, the output is ‘ck’.

C PROGRAMMING & DATA STRUCTURES 34


SRIDHAR

2. main( )
{
char *cptr,c;
void *vptr,v;
c=10; v=0;
cptr=&c; vptr=&v;
printf("%c %v",c,v);
}
Output: Compiler error (at line number 4): size of v is Unknown.
Explanation:
 You can create a variable of type void * but not of type void, since void is an empty
type. In the second line you are creating variable vptr of type void * and v of type
void hence an error.

3. main( )
{
char *str1="abcd";
char str2[ ]="abcd";
printf("%d %d %d",sizeof(str1),sizeof(str2),sizeof("abcd"));
}

Output: 2 5 5
Explanation:
 In first sizeof, str1 is a character pointer so it gives you the size of the pointer
variable.
 In second sizeof the name str2 indicates the name of the array whose size is 5
(including the '\0' termination character). The third sizeof is similar to the second one.

4. main( )
{
char *p;
p="%d\n";
p++;
p++;
printf(p-2,300);
}
Output: 300
Explanation:
 The pointer points to % since it is incremented twice and again decremented by 2, it
points to '%d\n' and 300 is printed.
 4

C PROGRAMMING & DATA STRUCTURES 35


SRIDHAR

5. void main( )
{
int i;
char a[ ]="\0";
if(printf("%s\n",a) )
printf("Ok here \n");
else
printf("Forget it\n");
}
Output: Ok here
Explanation:
 Printf will return how many characters does it print. Hence printing a null character
returns 1 which makes the if statement true, thus "Ok here" is printed.

6. void main( )
{
void *v;
int integer=2;
int *i=&integer;
v=i;
printf("%d",(int*)*v);
}
Output: Compiler Error. We cannot apply indirection on type void*.

Explanation:
 Void pointer is a generic pointer type. No pointer arithmetic can be done on it. Void
pointers are normally used for,
 Passing generic pointers to functions and returning such pointers.
 As a intermediate pointer type.
 Used when the exact pointer type will be known at a later point of time.

7. main( )
{
int a[10];
printf("%d",*a+1-*a+3);
}
Output: 4

Explanation:
 *a and -*a cancels out. The result is as simple as 1 + 3 = 4 !

C PROGRAMMING & DATA STRUCTURES 36


SRIDHAR

8.main( )
{
char *p = “ayqm”;
char c;
c = ++*p++;
printf(“%c”,c);
}
Output: b
Explanation:
 There is no difference between the expression ++*(p++) and ++*p++. Parenthesis
just works as a visual clue for the reader to see which expression is first evaluated.

9. int aaa( )
{
printf(“Hi”);
}
int bbb( )
{
printf(“hello”);
}
int ccc( )
{
printf(“bye”);
}
main( )
{
int ( * ptr[3]) ( );
ptr[0] = aaa;
ptr[1] = bbb;
ptr[2] =ccc;
ptr[2]();
}

Output: bye

Explanation:
 Since ptr[2] contains the address of the function ccc, the call to the function ptr[2]( )
is same as calling ccc( ). So it results in printing "bye".

10. void ( * abc( int, void ( *def) () ) ) ( );

Output: abc is a ptr to a function which takes 2 parameters .(. an integer variable.(b).
a ptrto a funtion which returns void. the return type of the function is void.

C PROGRAMMING & DATA STRUCTURES 37


SRIDHAR

Explanation:
 Apply the clock-wise rule to find the result.

11. void main( )


{
int *mptr, *cptr;
mptr = (int*)malloc(sizeof(int));
printf(“%d”,*mptr);
int *cptr = (int*)calloc(sizeof(int),1);
printf(“%d”,*cptr);
}
Output: garbage-value 0
Explanation:
 The memory space allocated by malloc is uninitialized, whereas calloc returns the
allocated memory space initialized to zeros

12. Differentiate the given declarations.


i. const char *a;
ii. char* const a;
iii. char const *a;

Output:
i. 'const' applies to char * rather than 'a' ( pointer to a constant char )
*a='F' : illegal
a="Hi" : legal
ii. 'const' applies to 'a' rather than to the value of a (constant pointer to char )
*a='F' : legal
a="Hi" : illegal
iii. Same as i.

13. main( )
{
int a=2,*f1,*f2;
f1=f2=&a;
*f2+=*f2+=a+=2.5;
printf("\n%d %d %d",a,*f1,*f2);
}

Output: 16 16 16

C PROGRAMMING & DATA STRUCTURES 38


SRIDHAR

Explanation:
 f1 and f2 both refer to the same memory location a. So changes through f1 and f2
ultimately affects only the value of a.

14. main( )
{
int i = 257;
int *iptr = &i;
printf("%d %d", *((char*)iptr), *((char*)iptr+1) );
}
Output: 11
Explanation:
 The integer value 257 is stored in the memory as, 00000001 00000001, so the
individual bytes are taken by casting it to char * and get printed.
15. main( )
{
int i=300;
char *ptr = &i;
*++ptr=2;
printf("%d",i);
}

Output: 556
Explanation:
 The integer value 300 in binary notation is: 00000001 00101100. It is stored in
memory (small-endian) as: 00101100 00000001.
 Result of the expression *++ptr = 2 makes the memory representation as: 00101100
00000010. So the integer corresponding to it is 00000010 00101100 => 556.

16. void main( )


{
printf(“sizeof (void *) = %d \n”, sizeof( void *));
printf(“sizeof (int *) = %d \n”, sizeof(int *));
printf(“sizeof (double *) = %d \n”, sizeof(double *));
printf(“sizeof(struct unknown *) = %d \n”, sizeof(struct unknown *));
}
Output:
sizeof (void *) = 2
sizeof (int *) = 2
sizeof (double *) = 2
sizeof(struct unknown *) = 2

C PROGRAMMING & DATA STRUCTURES 39


SRIDHAR

Explanation:
 The pointer to any type is of same size.
17. What is an lvalue and also an rvalue.
lvalue denotes a place in the computer's memory. An rvalue denotes a value, so it can
only be used on the right hand side of an assignment.
18. Choose the the correct one Which define s to be
struct node
{
int i;
float j;
};
struct node *s[10] ;
(a) An array, each element of which is a pointer to a structure of type node
(b) A structure of 2 fields, each field being a pointer to an array of 10 elements
(c) A structure of 3 fields: an integer, a float, and an array of 10 elements
(d) An array, each element of which is a structure of type node.
Output: (a)

Class Room Objectives


1. Find the output of the following code segments
(a) void add (int i, int j);
{
printf (“sum=%d”, i+j);
}
void sub (int i, int j);
{
printf (“sub=%d”, i-j);
}
main ( )
{
int x=5, y=3;
void (*p) (int, int);
p=add;
(*p) (x,y);
}
(b)main( )
{
int i=5;
int *ip;
&p=&i;
printf(“%d”, *ip);
}

C PROGRAMMING & DATA STRUCTURES 40


SRIDHAR

2. Find the output of the following code segments


(a) main( )
{
char j=’A’;
int i=5;
void *vp;
vp = &i;
printf (“%d”, *(int*)vp);
vp=&j;
printf (“%d”, *cchar*)vp);
}
(b) main( )
{
int i=5;
int *p;
p=&i;
printf (“%d”, *p);
*p=7;
printf (“%d”, i);
}
3. Find the output of the following code segments
(a) main( )
{
int i=5;
int *p;
int **q;
q=&p;
printf (“%d”, **q);
}
(b) main( )
{
int x[ ] = {1,2,3,4,5};
int *p=x+2;
*P=*p-2;
P=p+1;
*p=*p-3;
for (i=0; i<4; i++);
printf (“%d”, x[i]);
}

C PROGRAMMING & DATA STRUCTURES 41


SRIDHAR

4. Find the output of the following program


(a) main( )
{
static int a[ ] = {0,1,2,3,4};
static int *p[ ] = {a, a+1, a+2, a+3, a+4};
int **ptr;
ptr=p;
**ptr++;
printf (“%d %d %d”, ptr-p, *ptr-a, **ptr);
*++*ptr;
printf (“\n%d %d %d”, ptr p, *ptr-a, **ptr);
++**ptr;
printf (“\n%d %d %d”, ptr-p, *ptr-a, **ptr);
}
(b) main( )
{
static char *s[ ] = {“ice”, “green”, “cone”, “please”};
static char **ptr[ ] = {s+3, s+2, s+1, s};
char ***p = ptr;
printf (“%s”, **++p);
printf (“\n%s”, *--*++p+3);
printf (\n%s”, *p[-2]+3);
printf (“\n%s”, p[-1][-1]+1);
}

PREVIOUS

1. A certain processor supports only the immediate and the direct addressing modes.
Which of the following programming language features cannot be implemented on
this processor ? (GATE-1999)
(a) Pointers (b) Arrays
(c) Records (d) Recursive procedures with local variable

2. The most appropriate matching for the following pairs (GATE-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 (d) X – 3 Y – 1 Z – 2

C PROGRAMMING & DATA STRUCTURES 42


SRIDHAR

3. Assume that objects of the type short, float and long occupy 2 bytes, 4 bytes and 8
bytes, respectively. The memory requirement for variabhle t, ignoring alignment
considerations, is (GATE-2000)
(a) 22 bytes (b) 14 bytes (c) 18 bytes (d) 10 bytes

4. Consider the following three C functions : (GATE-2001)

[P1] int *g(void)


{
intx = 10;
return(&x);
}
[P2] int *g(void)
{
int*px;
*px=10;
return px;
}
[P3] int *g(void)
{
px = (int*) malloc (size of (int));
*px=10;
return px;
}
Which of the above three functions are likely to cause problems with pointers?
(a) Only P3 (b) Only P1 and P3
(c) Only P1 and P2 (d) P1, P2 and P3

5. Consider the C program shown below (GATE-2003)


# include<stdio.h>
#define print (x) printf(“%d”,x)
int x;
void Q (int z)
{
z+=x;
print(z);
}
void p (int*y)
{
int x=*y+2;
Q(x);
*y=x-1;
print (x);.
}

C PROGRAMMING & DATA STRUCTURES 43


SRIDHAR

main (void)
{
x=5;
p(&x);
print(x);
}

The output of this program is


(a) 1 2 7 6 (b) 22 12 11 (c) 14 6 6 (d) 7 6 6

6. What does the following C-statement declare? (GATE-2005)


int(*f)(int*);
(a) A function that takes as integer pointer as argument and returns as integer
(b) A function that takes an integer pointer as argument and returns an integer
pointer
(c) A pointer to a function that takes an integer pointer as argument and returns as
integer
(d) A function that takes an integer pointer as argument returns a function pointer

7. Consider this C code to swap two integers and these five statements: the code
(GATE-2006)
Void swap (int *px, int *py)
{
*px = *px - *py;
*py = *px + *py;
* px = *py- *px;
}
S1: will generate a complication error
S2: may generate a segmentation fault at runtime depending on the arguments
passed
S3: Correctly implements the swap procedure for all input pointers referring to
integers stored in memory location accessible to the process.
S4: implements the swap procedure correctly for some but not all valid input
pointers.
S5: may add or subtract integers and pointers
(a) S1 (b) S 2 and S3 (c) S 2 and S 4 (d) S 2 and S5

C PROGRAMMING & DATA STRUCTURES 44


SRIDHAR

8. What is printed by the following C program? (GATE-2008)

int f (int x, int*py, int**ppz)


{
int y, z;
**ppz+=1; z=*ppz;
*py+=2; y=*py;
x+=3;
return x+y+z;
}
void main()
{
int c, *b, **a;
c=4; b=&c; a=&b;
printf (“%d”, f(c, b, a));
}
(a) 18 (b) 19 (c) 21 (d) 22

9. What does the following program print? (GATE-2010)


#include<studio.h>
void f(int*p, int*q)
{
p=q;
*p=2;
}
int i = 0, j=1;
int main ( )
{
f(&i, &j);
printf(“%d%d\n”, i, j);
return 0;
}
(a) 2 2 (b) 2 1 (c) 0 1 (d) 0 2

10. Consider the following program in C language (GATE-2014)


# include <stdio.h>
main ( )
{
int i;
int *pi = &i;
scanf(“%d”, pi);

C PROGRAMMING & DATA STRUCTURES 45


SRIDHAR

printf(“%d\n”, i + 5)
}
Which one of the following statements is TRUE ?
(a) Compilation fails (b) Execution results in a run time error
(c) On execution, the value printed in 5 more than the address of variable i
(d) On execution, the value printed is 5 more than the integer value entered

11. Consider the following C program segment (GATE-2015)

#include <stdio.h>
int main ( )
{
char sl[7] = “1234”, *p;
p = s1 + 2;
*p = ‘0’;
printf (“%s”, s1);
}
What will be printed by the program ?
(a) 12 (b) 1201400 (c) 1204 (d) 1034

12. Consider the following C program segment (GATE-2015)

#include <stdio.h>
int main ( )
{
static int a[ ] = {10, 20, 30, 40, 50};
static int *p[ ] = {a, a+3, a+4, a+1, a+2};
int **ptr = p;
ptr ++ ;
printf (“%d%d”, ptr-p, **ptr);
}
The output of the program is __________

13. Consider the following function written in the C programming language.


(GATE-2015)
void foo (char *a)
{
if (*a && *a !a= ` `)

C PROGRAMMING & DATA STRUCTURES 46


SRIDHAR

foo (a + 1);
putchar (*a);
}
The output of the above function on input “ABCD EFGH” is
(a) ABCD EFGH (b) ABCD
(c) HGFE DCBA (d) DCBA

PRACTICE
1. What is output of p1.c and p2.c
// P1.c
int main()
{
register int i = 10;
int *a = &i;
printf("%d", *a);
getchar();
return 0;
}
//p2.c
int main()
{
int i = 10;
register int *a = &i;
printf("%d", *a);
getchar();
return 0;
}
(a) p1.c prints 10 & p2.c prints 10
(b) p1.c prints error & p2.c prints 10
(c) p1.c prints 10 & p2.c prints error

C PROGRAMMING & DATA STRUCTURES 47


SRIDHAR

(d) p1.c prints error & p2.c prints error


2. int main(void)
{
const volatile int local = 10;
int *ptr = (int*) &local;
printf("local : %d \n", local);
*ptr = 100;
printf("local: %d \n", local);
}
(a) Local 10 Local 100 (b) Local 10 Local 10
(c) Local 100 Local 10 (d) Local 100 Local 100

2. What is (void*)0?
(a) Representation of NULL pointer (b) Representation of generic pointer
(c) Error (d) Wild pointer
3. Can you combine the following two statements into one?
char *p;
p = (char*) malloc(100);
(a) char p = *malloc(100); (b) char *p = (char) malloc(100);
(c) char *p = (char*)malloc(100); (d) char *p = (char *)(malloc*)(100);
4. What would be the equivalent pointer expression for referring the array
elementa[i][j][k][l]
(a) ((((a+i)+j)+k)+l) (b) *(*(*(*(a+i)+j)+k)+l)
(c) (((a+i)+j)+k+l) (d) ((a+i)+j+k+l)

5. If the binary eauivalent of 5.375 in normalised form is 0100 0000 1010 1100 0000
0000 0000 0000, what will be the output of the program (on intel machine)?
int main( )
{
float a=5.375;
char *p;
int i;
p = (char*)&a;
for(i=0; i<=3; i++)
printf("%02x\n", (unsigned char)p[i]);
}
(a) 40 AC 00 00 (b) 04 CA 00 00
(c) 00 00 AC 40 (d) 00 00 CA 04

6. What will be the output of the program?

#include<stdio.h>

C PROGRAMMING & DATA STRUCTURES 48


SRIDHAR

int check(int, int);


int main( )
{
int c;
c = check(10, 20);
printf("c=%d\n", c);
return 0;
}
int check(int i, int j)
{
int *p, *q;
p=&i;
q=&j;
i>=45 ? return(*p): return(*q);
}
(a) Print 10 (b) Print 20 (c) Print 1 (d) Compile erro
7. What will be the output of the program ?
#include<stdio.h>
int main( )
{
static int arr[ ] = {0, 1, 2, 3, 4};
int *p[ ] = {arr, arr+1, arr+2, arr+3, arr+4};
int **ptr=p;
ptr++;
printf("%d, %d, %d\n", ptr-p, *ptr-arr, **ptr);
*ptr++;
printf("%d, %d, %d\n", ptr-p, *ptr-arr, **ptr);
*++ptr;
printf("%d, %d, %d\n", ptr-p, *ptr-arr, **ptr);
++*ptr;
printf("%d, %d, %d\n", ptr-p, *ptr-arr, **ptr);
return 0;
}
(a) 0, 0, 0 (b) 1, 1, 2 (c) 1, 1, 1 (d) 0, 1, 2
1, 1, 1 2, 2, 3 2, 2, 2 1, 2, 3
2, 2, 2 3, 3, 4 3, 3, 3 2, 3, 4
3, 3, 3 4, 4, 1 3, 4, 4 3, 4, 5
8. What do the following declaration signify?
int (*pf)();

C PROGRAMMING & DATA STRUCTURES 49


SRIDHAR

(a) pf is a pointer to function (b) pf is a function pointer


(c) pf is a pointer to a function which return int
(d) pf is a function of pointer variable

9. main( )
{
int i = 258;
int *iptr = &i;
printf("%d %d", *((char*)iptr), *((char*)iptr+1) );
}
a) 2 1 b) 2 5 c) 5 8 d) 1 8
10. What is the output of this program?
#include <stdio.h>
int main(void)
{
int a[5] = { 1, 2, 3, 4, 5 };
int *ptr = (int*)(&a + 1);
printf("%d %d\n", *(a + 1), *(ptr - 1));
return 0;
}
(a) 2 2 (b) 2 1 (c) 2 5 (d) None
9. What is the output of this program on an implementation where int and all pointer
types occupy 2 bytes?
#include <stdio.h>
void f(char**);
int main(void)
{
char *argv[] = { "ab", "cd", "ef", "gh", "ij", "kl" };
f(argv);
return 0;
}
void f(char **p)
{
char *t;
t = (p += sizeof(int))[-1];
printf("%s\n", t);
}

(a) ab (b) cd (c) ef (d) gh


10. What is the output of following code ?

main( )
{
char * str = "hello";

C PROGRAMMING & DATA STRUCTURES 50


SRIDHAR

char * ptr = str;


char least = 127;
while (*ptr++)
least = ((*ptr)<(least))?(*ptr):(least);
printf("%d", least);
}
(a) 0 (b) 127 (c) 1 (d) Garbage
11. What will be output when you will execute following c code?
#include<stdio.h>
void main( )
{
char *ptr="cquestionbank";
printf("%d",-3[ptr]);
}

(a) Address of 3rd location (b) -103


(c) -100 (d) Garbage

12. What does the following declaration mean?

int (*ptr)[10];
(a) ptr is array of pointers to 10 integers
(b) ptr is a pointer to an array of 10 integers
(c) ptr is an array of 10 integers
(d) ptr is an pointer to array

13. Declare the following statement?


"An array of three pointers to chars".
(a) char *ptr[3](); (b) char *ptr[3];
(c) char (*ptr[3])(); (d) char **ptr[3];

C PROGRAMMING & DATA STRUCTURES 51


SRIDHAR

14. Point out the correct statement which correctly allocates memory dynamically for 2D
array following program?
int main( )
{
int *p, i, j;
/* Add statement here */
for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
{
p[i*4+j] = i;
printf("%d", p[i*4+j]);
}
}
return 0;
}
(a) p = (int*) malloc(3, 4); (b) p = (int*) malloc(3*sizeof(int));
(c) p = malloc(3*4*sizeof(int)); (d) p = (int*) malloc(3*4*sizeof(int));
15. Point out the error in the following program
#include<stdio.h>
#include<stdlib.h>
int main( )
{
int *a[3];
a = (int*) malloc(sizeof(int)*3);
free(a);
return 0;
}
(a) Error: unable to allocate memory
(b) Error: We cannot store address of allocated memory in a
(c) Error: unable to free memory (d) No error

C PROGRAMMING & DATA STRUCTURES 52


SRIDHAR

16. Point out the error in the following program


#include<stdio.h>
#include<stdlib.h>
int main( )
{
char *ptr;
*ptr = (char)malloc(30);
strcpy(ptr, "RAM");
printf("%s", ptr);
free(ptr);
return 0;
}

(a) Error: in strcpy() statement. (b) Error: in *ptr = (char)malloc(30);


(c) Error: in free(ptr); (d) No error
17. What is the meaning of following declaration ?
void (*f[10]) (int, int)
(a) f is an array of 10 of pointer to function(which takes 2 arguments of type int)
returning void
(b) f is a function(which takes 2 arguments of type int) returning void
(c) f is a generic pointer, which points to a function that takes 2 int arguments
(d) f is a function which takes 10 generic pointer as argument

Strings:
 A string is a collection of characters and is terminated by a null character ’\0’.
Eg : “L E A D”

Append with null character

String declaration & definition :


1. char name[ ] = {‘L’, ‘E’, ‘A’, ‘D’,’\0’};
Initializing the string as a char array.

2. char name[5] = “LEAD”;


// name is a constant pointer. It is compile time error to assign a new address to name.

C PROGRAMMING & DATA STRUCTURES 53


SRIDHAR

1: int main( )
{
int i = 0;
char name[ ] = {‘L’, ‘E’, ‘A’, ‘D’, ‘\0’}; //same for “LEAD”;
for (i = 0; name[i] != ‘\0’; i++)
{
printf (“%c ”, name[i]);
}
return 0;
}
Output : L E A D
2. Accessing array elements through pointer.

for (i = 0; *(name + i)!= ‘\0’; i++)


{
printf (“%c”, *(name + i));
}
3. char name[ ] ={‘C’, ‘h’, ‘a’, ‘n’, ‘d’, ‘r’, ‘a’, ‘\0’};
printf(“%s”, name);

Output : Chandra

To check equality of strings :

int main( )
{
char str1[ ] = “lead”;
char str2[ ] = “lead”;
if (str1 = = str2) //------------(1)
printf (“equal”);
else
printf(“not equal”);
}

Output: not equal

Explanation :
 If (str1 = = str2) => if (100 = = 200) never be equal. The reason is array names are
pointers which holds address rather value.

String Literals :

C PROGRAMMING & DATA STRUCTURES 54


SRIDHAR

 When characters are enclosed in “ “ it is called as a string literal.


char name1[ ] = “lead”;  created in normal RAM can be changed
char *name2 = “lead”;  created is a segment and it is constant. It is compilation
error to modify the content.
Eg:
*(name1 + 1) = ‘B’; //void and results in lBad.
*(name2 + 1) = ‘B’; // error.
char name1 [ ] = “Chandra”;
char name2 [ ] = “sekhar”;
name1 = name2; // is error, because we are trying to assign a new address to array name which is
constant address pointer.
char *name1 = “chandra”
char *name2 = “sekhar”
name1 = name2; // it is valid because name,1 name2 are not constant pointers.
 ‘%s’ prints from starting address to end of string.

1. int main( )
{
char *ptr = “Chandra”;
printf (“%s”, ptr);
return 0;
}
Output : Chandra
2. Print a string from specified position
int main( )
{
char *ptr = “sekhar”;
printf (“%s”, &ptr[1]);
// &ptr[1] means starts from ‘e'//
}
Output : ekhar
3. Print a string char by char
int main( )
{
char *ptr = “Chandra”;
int i = 0;
for (i = 0; *(ptr + i) != ‘\0’; i ++)
{
printf (“%c”, *(ptr + i));
}
}
Output : Chandra

C PROGRAMMING & DATA STRUCTURES 55


SRIDHAR

4. What happens when a string is not null terminated and we are trying to print.

int main( )
{
char str[ ] = {‘C’, ‘h’, ‘a’, ‘n’, ‘d’, ‘r’, ‘a’};
printf(“%s”, str);
return 0;
}
Output :
 Chandra || = || = L – due to not appending the null characters.
 String prints the characters up to end, later junk characters are displayed.

String Manipulation Functions


String Functions
1 char *strcpy (char *dest,char *src) --Copy one string into another.
2 int strcmp(char *str1, char *str2) Compare string1 and string2 to determine
alphabetic order.
If str1 and str2 are equal then it return 0.
If str1 is greater than str2 then it return +ve value
If str1 is smaller than str2 then it return -ve value
3 char *strcpy(char *str1, char *str2) . -- Copy string2 to stringl.
4 size_t strlen(const char *string) -- Determine the length of a string.
5 char *strncat(char *str1, char *str2, int n) -- Append n characters from string2 to
stringl.
6 int strncmp(char *str1, char *str2, int n) -- Compare first n characters of two strings.
7 char *strncpy(char *str1,const char *str2, int n)-- Copy first n characters of string2
to stringl .
8 int strcasecmp(const char *s1, const char *s2)-- case insensitive version of strcmp().
9 int strncasecmp(const char *s1, const char *s2, int n) -- case insensitive version
of strncmp().
10 char *strchr(const char *string, int c) -- Find first occurrence of character c in string.
11 char *strrchr(const char *string, int c) -- Find last occurrence of character c in
string.
12 char *strstr(const char *s1, const char *s2)
-- locates the first occurrence of the string s2 in string s1.
13 char *strpbrk(const char *s1, const char *s2)
-- returns a pointer to the first occurrence in string s1 of any character from string s2,
or a null pointer if no character from s2 exists in s1
16 char *strtok(char *s1, const char *s2) -- break the string pointed to by s1 into a
sequence of tokens, each of which is delimited by one or more characters from the
string pointed to by s2.

C PROGRAMMING & DATA STRUCTURES 56


SRIDHAR

Two dimensional strings:


 In many real time applications we use collection of names. In these scenarios 2-D strings will
become handy. Let analyse 2-D strings through array & pointers both.
1.#include <string.h> // the library which is a collection of
#include <stdio.h> // std string functions & definitions.
void main( )
{
char namelist[3][10] = {“Chandra”, “sekhar”, “vorugunti”};
char searchname[10];
int a,i;
scanf (“%s”, searchname); //assume user enters “sekhar”
for (i = 0; i < 3; i++)
{
a = strcmp (namelist [i], searchname);
if (a = = 0)
{
printf (“user found”); return 0;}
}
printf (“user not found”);
}
//assume user enters “sekhar”
}
Output : user found

2.main( )
{
static char names[5][20]={"pascal","ada","cobol","fortran","perl"};
int i;
char *t;
t=names[3];
names[3]=names[4]; // cannot be assigned
names[4]=t;
for (i=0;i<=4;i++)
printf("%s",names[i]);
}

Output: Compiler error: Lvalue required in function main

Explanation:
 Array names are constant pointer. So it cannot be modified

C PROGRAMMING & DATA STRUCTURES 57


SRIDHAR

3. What is the output of following ‘C’ program segment:

char p[20];
char *s = “string”;
int length = strlen(s);
for (i = 0; i < length; i++);
p[i] = s[length – i];
printf (“%s”, p);

Output : No output

Explanation :
 strlen(s) return ‘6’ excluding the null character.
p[0] = s[6 – 0] = null
p[1] = s[6 – 1] = g
p[2] = s[6 – 2] = n
p[3] = s[6 – 3] = i
p[4] = s[6 – 4] = r
p[5] = s[6 – 5] = t
Therefore p = ‘-gnirt’
 The starting is ‘null’ for ‘p’. Hence no output is displayed. The compiler treats the
‘\0’ null character as an end point of string. ‘p’ contains ‘\0’ at starting index itself,
hence no output. The strlen (p) returns 0.

4. What does the following fragment of ‘c’ program print ?


char c[ ] = “GATE 2011”;
char *p = c;
printf (“%s”, p + p[3] – p[1]);

Ans: 2011
Explanation :
In printf (“%s”, p + p[3] – p[1]);
 The index of result of an expression will be an index, from that index of ‘p’ the string
will be printed till the null character.
p[3] = E
p[1] = A
p[3] – P[1] = ASCII value of ‘E’ – ASCII value of ‘A’
=ABCDE
= 4.
 Therefore p + 4 ‘p’ is starting address adding ‘4’ to ‘p’ means ‘p’ points to ‘2’.
Therefore it prints from 2 to \0, Therefore 2011.

C PROGRAMMING & DATA STRUCTURES 58


SRIDHAR

CLASS ROOM OBJECTIVES


1.main( )
{
char s[5]=”GATE”;
char t[5]=”2015”;
char x[5];
strcpy (x, s);
strcpy (s,t);
strcpy (t,x);
puts (s);
puts (t);
}
2. Find the output of the following code segments
(a) main( )
{
int i,j;
char s[3][4]={“abcd”, “ef”, “gh”};
puts (s[0]);
puts (s[1]);
puts (s[2]);
}
(b) main( )
{
int i,j;
char x[5]=”ABC”;
i=size of (x);
j=strlen (x);
printf (“%d”, i+j);
}
3. Find the output of the following code segments
(a) main( )
{
char x[ ]={‘H’, ‘E’, ‘l’, ‘l’, ‘o’, ‘\0’};
char y[ ] = “HELLO”;
printf (“%d %d”, strlen (x), strlen (y));
}
(b) main( )
{
char t[10]=”HARI”;
char s[10];
strrev (*t);
strcxpy (s, t);
puts (s);
puts (t);
}

C PROGRAMMING & DATA STRUCTURES 59


SRIDHAR

PREVIOUS

1. Consider the following C program: (GATE-2001)

void abc(char*s)
{
if (s[0]= =’\0’) return;
abc(s+1);
abc(s+1);
printf(“%c”,s[0]);
}
main ( )
{
abc(“123”)
}
(a) What will be the output of the program?
(b) If abc(s) is called with a null-terminated stgring s of length n characters (not
counting the null (‘\0’) character), how many characters will be printed by
abc(s)?

2. Consider the following C program segment: (GATE-2004)

char p [20];
char *s=”string”;
int length = strlen(s);
for (i=0; i<length; i++)
p[i]=s[length-i]
printf (“%s”, p);

The output of the program is


(a) gnirts (b) string (c) gnirt (d) No output is printed

C PROGRAMMING & DATA STRUCTURES 60


SRIDHAR

PRACTICE

1. What is the output of following code ?

#include <stdio.h>
char *fun( )
{
static char arr[1024];
return arr;
}
int main( )
{
char *str = "cworld";
strcpy(fun( ), str);
str = fun( );
strcpy(str, "csmart");
printf("%s", fun( ));
return 0;
}
a) cworld b) csmart c) cworldscsmart d)none

2. Which of the following function is used to find the first occurrence of a given string in
another string?
(a) strchr() (b) strrchr() (c) strstr() (d) strnset()

3. What will be the output of the program ?

#include<stdio.h>
int main()
{
static char mess[6][30] = {"Don't walk in front of me...",
"I may not follow;",
"Don't walk behind me...",
"Just walk beside me...",
"And be my friend." };
printf("%c, %c\n", *(mess[2]+9), *(*(mess+2)+9));
return 0;
}
(a) t, t (b) k, k (c) n, k (d) m, f

C PROGRAMMING & DATA STRUCTURES 61


SRIDHAR

4. What will be the output of the program ?


#include<stdio.h>
int main( )
{
char str[ ] = "Nagpur";
str[0]='K';
printf("%s, ", str);
str = "Kanpur";
printf("%s", str+1);
return 0;
}
(a) Karagpur, Kanpur (b) Nagpur, Kanpur (c) Karagpur, Kanpur (d) Error
5. What will be the output of the program ?
#include<stdio.h>
#include<string.h>
int main( )
{
char sentence[80];
int i;
printf("Enter a line of text\n");
gets(sentence);
for(i=strlen(sentence)-1; i >=0; i--)
putchar(sentence[i]);
return 0;
}
(a) The sentence will get printed in same order as it entered
(b) The sentence will get printed in reverse order
(c) Half of the sentence will get printed (d) None of above

6. What will be the output of the program (in 16 bit platform DOS) ?
#include<stdio.h>
#include<string.h>
int main( )
{
char *str1 = "India";
char *str2 = "BIG";
char *str3;
str3 = strcat(str1, str2);
printf("%s %s\n", str3, str1);
return 0;
}
(a) IndiaBIGIndia (b) IndiaBIG IndiaBIG
(c) India India (d) Error

C PROGRAMMING & DATA STRUCTURES 62


SRIDHAR

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

main( )
{
char s[10];
strcpy(s, “abc”);
printf(“%d %d”, strlen(s), sizeof(s));
}
(a) 3 10 (b) 3 3 (c) 10 3 (d) 10 10

8. What will be the output of the program ?

#include<stdio.h>
int main( )
{
char *names[ ] = { "Suresh", "Siva", "Sona", "Baiju", "Ritu"};
int i;
char *t;
t = names[3];
names[3] = names[4];
names[4] = t;
for(i=0; i<=4; i++)
printf("%s,", names[i]);
return 0;
}
(a) Suresh, Siva, Sona, Baiju, Ritu (b) Suresh, Siva, Sona, Ritu, Baiju
(c) Suresh, Siva, Baiju, Sona, Ritu (d) Suresh, Siva, Ritu, Sona, Baiju

9. What will be the output of the program ?

#include<stdio.h>
int main( )
{
char str1[ ] = "Hello";
char str2[10];
char *t, *s;
s = str1;
t = str2;
while(*t=*s)
*t++ = *s++;
printf("%s\n", str2);
return 0;
}
(a) Hello (b) HelloHello (c) No output (d) ello

C PROGRAMMING & DATA STRUCTURES 63


SRIDHAR

Structures:
 A structure is a is a collection of logically related heterogeneous elements.
 Every elements of a structure will have its own memory location.
 Every element of a structure can be accessed by accessing operator (Dot or arrow).
Example :
struct student
{
char name[10];
int age;
}
struct student soly = {“chandra”, 13}; Collectively grouped as student
printf (“%s”, sobj.name);
printf (“%d”, sobj.age);
Output : chandra 13.
 Each structure element is accessed through (structure object) (variable name)
 Size of structure object = sum of size of its logical elements. In student structure size of name
= 10 and age = 2. Total size of structure = 12
 Accessing structures through pointers.
int main( )
{
struct book …(1)
{
char name[25];
char author[25];
int age;
};
struct book b1={“FWC#”, “sekhar”, 30}; …(2)
struct book *ptr; …(3)
ptr = &b1; …(4)
printf (“%s %s %d”, b1.name, b1.author, b1.age); …(5)
printf (“%s %s %d”, ptr name, ptr author, ptr age); …(6)
}
Explanation :
1. A structure is declared with three fields name, author, age
2. declaring a struct variable
3. declaring a pointer to a struct variable.
4. Assuming the book structure object to the pointer
5. Displaying the ‘book’ structure objects through structure object.

C PROGRAMMING & DATA STRUCTURES 64


SRIDHAR

(.) dot operator is used in this scenario.


6. displaying the ‘book’ structure objects through structure pointer. (  ) arrow operator
is used in this scenario.

Nesting of structure:
 Nesting of structure is possible i.e. we can declare a structure within another structure but it
is necessary inner structure must declares structure variable otherwise we cannot access the
data member of inner structure.
For example:
1. What will be output of c code?
#include<stdio.h>
int main()
{
struct world
{
int a;
char b;
struct india
{
char c;
float d;
}p;
};
struct world st ={1,'A','J',1.8};
printf("%d \t %c\t %c\t %f",st.a,st.b,st.p.c,st.p.d);
return 0;
}
Output: 1 A J 1.800000
Array, union, structure can be member of a structure.

C PROGRAMMING & DATA STRUCTURES 65


SRIDHAR

Class Room Objectives


1. Find the output of the following code segments

struct A
{
int i;
Char j;
}
A, *b;
main ( )
{
a.i=5;
a.j=A;
b=&a;
printf(“%d %c”, (*b).i, (*b).j);
printf (“\n%d %c”, b .i, b .j);
}

2. Find the output of the following programs

(a) struct A
{
int rollno;
char name[20];
}
s;
main( )
{
s.rollno=101;
strcpy(s.name, ‘RAMA’);
printf(“%d”, size of s);
}

(b) struct A
{
int i;
Char j;
}
A,*b;
main( )
{
printf(“%d %d”, size of a, size of b);
}

C PROGRAMMING & DATA STRUCTURES 66


SRIDHAR

3. Find the output of the following code segments

(a) struct demo


{
int i;
char j;
struct TAG
{
int k;
}
L;
}
d={2, ‘A’, 4};
printf(“%d”, size of d.l);
}

(b) main ( )
{
struct A
{
int i;
char j;
}
s={100, ‘A’}, u;
f(&s, u);
printf (“%d %d”, s.i, s.j);
printf(“%d %d”, u.i, u.j);
}
f(struct A*p, struct Aq)
{
q.i=p I;
q.j=p j;
p i=q.i+3;
p j=q.j+2;
}

C PROGRAMMING & DATA STRUCTURES 67


SRIDHAR

4. Find the output of the following code segment

typedef struct
{
char *a;
char *b;
}
t;
void f1, (ts);
void f2 (t*p);
main ( )
{
static ts={“A”, “B”};
printf (“%s %s\n”, s.a., s.b);
f1(s);
printf (“%s %s”. s.a, s.b);
f2(&s);
}
void f1(t s);
{
s.a=”u”;
s.b=”v”;
printf (“\n %s %s”, s.a., s.b);
}
void f2 (t *p);
{
p.a=”v”;
p.b=”w”;
printf(“\n %s %s”, p.a, p.b);
}

C PROGRAMMING & DATA STRUCTURES 68


SRIDHAR

PRACTICE

1. Point out the correct statement which correctly free the memory pointed to by 's' and
'p' in the following program?

int main( )
{
struct ex
{
int i;
float j;
char *s
};
struct ex *p;
p = (struct ex *)malloc(sizeof(struct ex));
p->s = (char*)malloc(20);
return 0;
}
(a) free(p); , free(p->s); (b) free(p->s); , free(p);
(c) free(p->s); (d) free(p);

2. What will be output of following c code?


void main( )
{
struct employee
{
unsigned id: 8;
unsigned sex:1;
unsigned age:7;
};
struct employee emp1={203,1,23};
clrscr();
printf("%d\t%d\t%d",emp1.id,emp1.sex,emp1.age);
getch();
}
(a) 203 1 23 (b) 8 1 7 (c) 23 1 203 (d) 7

C PROGRAMMING & DATA STRUCTURES 69


SRIDHAR

PREVIOUS

1. The following C declarations (GATE-2000)

struct node
{
int i;
float j;
};
struct node *s[10];

Define s to be
(a) An array, each element of which is a pointer to a structure of type node
(b) A structure of 2 fields, each field being a pointer to an array of 10 elements
(c) A structure of 3 fields; an integer, a float, and an array of 10 elements
(d) An array, each element of which is a structure of type node.

2. Consider the following C declaration (GATE-2000)


struct
{
short s[5];
union
{
float y;
long z;
}
u;
}
t;

C PROGRAMMING & DATA STRUCTURES 70


SRIDHAR

UNIONS :
 Union is a special data type which allows storing of different data types in the same memory
location.
 The element which occupies more memory that will be shared by all elements of union.
 Only one element of union can be initialized at a time.

1. What will be the output of the program ?

#include<stdio.h>
int main( )
{
union a
{
int i;
char ch[2];
};
union a u;
u.ch[0]=3;
u.ch[1]=2;
printf("%d, %d, %d\n", u.ch[0], u.ch[1], u.i);
return 0;
}
(A) 3, 2, 515 (B) 515, 2, 3 (C) 3, 2, 5 (D) 515, 515, 4
Output: Option A
Explanation:
 The system will allocate 2 bytes for the union.
 The statements u.ch[0]=3; u.ch[1]=2; store data in memory as given below.

2. What will be the output of the program ?

C PROGRAMMING & DATA STRUCTURES 71


SRIDHAR

#include<stdio.h>
int main( )
{
union var
{
int a, b;
};
union var v;
v.a=10;
v.b=20;
printf("%d\n", v.a);
return 0;
}
Choose correct one ?
(A) 10 (B) 20 (C) 30 (D) 0

Output : B.
Explanation:
Same memory is used by both a and b. The latest value 20 will be available in memory.

3. Find the output of the following programs


(a) union B
{
int i;
char j;
}
u={295};
main( )
{
printf(“%d %d”, u.i, u.j);
}
(b) main ( )
{
union student
{
int rollno;
char name[5];
}
s={“BABA”};
printf(“%s”, s.name);
printf (“%d”, s.rollno);
}

PRACTICE

C PROGRAMMING & DATA STRUCTURES 72


SRIDHAR

1. What will be the output of the program?


union employee
{
char name[15];
int age;
float salary;
};
const union employee e1;
int main( )
{
strcpy(e1.name, "K");
printf("%s %d %f", e1.name, e1.age, e1.salary);
return 0;
}
a) Error: RValue required
b) Error: cannot convert from 'const int *' to 'int *const'
c) Error: LValue required in strcpy
d) No error

BitField
 A structure declarator can also have a specified number of bits, called a "bit field." Its length
is set off from the declarator for the field name by a colon. A bit field is interpreted as an
integral type.
Syntax :
struct TagName
{
type-specifier field_name : size;
};
 The size specifies the width of the field in bits. The type-specifier for the field_name must
be unsigned int, or signed int, or int, and the size must be a nonnegative integer value.
 Arrays of bit fields, pointers to bit fields, and functions returning bit fields are not allowed.
 Bit fields can be declared as part of a structure.
 The address-of operator (&) cannot be applied to bit-field components. Unnamed bit
fields cannot be referenced, and their contents at run time are unpredictable. They can be
used as "dummy" fields, for alignment purposes.
 An unnamed bit field whose width is specified as 0 guarantees that storage for the member
following it in the struct-declaration-list begins on an int boundary.
 Bit fields are allocated within an integer from least-significant to most-significant bit. In the
following code
struct mybitfields
{

C PROGRAMMING & DATA STRUCTURES 73


SRIDHAR

unsigned short a : 4;
unsigned short b : 5;
unsigned short c : 7;
}
test;
int main( void );
{
test.a = 2;
test.b = 31;
test.c = 0;
}
the bits would be arranged as follows:
0000000 11111 0010
ccccccc bbbbb aaaa

 Bit fields must also be long enough to contain the bit pattern. For example, these two
statements are not legal:
short a:17; /* Illegal! */ b’cos max num of bits for short is 16 bits
int long y:33; /* Illegal! */ b’cos max num of bits for long is 32 bits

1. What will be output of c code?


#include<stdio.h>
void main()
{
struct employee
{
unsigned id: 8;
unsigned sex:1;
unsigned age:7;
};
struct employee emp1={203,1,23};
printf("%d\t%d\t%d",emp1.id,emp1.sex,emp1.age);
}
Output: 203 1 23
Explanation:
 We can access the data member of bit field's structure in same way as normal
structure.

How bit data or fields in a structure are stored in the memory:

C PROGRAMMING & DATA STRUCTURES 74


SRIDHAR

 Minimum size of structure which has at least one bit type member is two byte i.e. 16 bit. This
is called word size of microprocessor.
 Word size depends on microprocessor. Turbo c is based on 8086 microprocessor which word
size is two byte.

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

AGE SEX ID

Bits are filled from right to left direction. In the above question 8 bit is used for id, 1 bit for sex
and 7 bit for age.

2. What will be output of c code?


#include <stdio.h>
void main( )
{
struct bitfield
{
unsigned a:5;
unsigned c:5;
unsigned b:6;
}
bit;
char *p;
struct bitfield *ptr,bit1={1,3,3};
p=&bit1;
p++;
printf("%d",*p);
}
Output: 12
Explanation:
Binary value of 1 is 00001 (in 5 bit)
Binary value of 3 is 00011 (in 5 bit)
Binary value of 3 is 000011 (in 6 bit)

In memory it can be represented as:

C PROGRAMMING & DATA STRUCTURES 75


SRIDHAR

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

AGE SEX ID

Let's assume memory address of bit1 is 500 which have assigned to char pointer p. Since
char is one byte data type so p++ will be 501. *p means content of memory address 501
which is (00001100) and its binary equivalent value is 12. Hence output is 12.

3. What is the output of following code.

int main( )
{
struct value
{
int bit1:1;
int bit3:4;
int bit4:4;
}
bit={1, 2, 13};
printf("%d, %d, %d\n", bit.bit1, bit.bit3, bit.bit4);
return 0;
}
Choose correct one .
A. 1, 2, 13 B. 1, 4, 4 C. -1, 2, -3 D. -1, -2, -13

Output: Option C

Explanation:
 Note the below statement inside the struct: int bit1:1; --> 'int' indicates that it is a
SIGNED integer.
 For signed integers the leftmost bit will be taken for +/- sign. If you store 1 in 1-bit
field: The left most bit is 1, so the system will treat the value as negative number.
 The 2's complement method is used by the system to handle the negative values.
Therefore, the data stored is 1.
 The 2's complement of 1 is also 1 (negative). Therefore -1 is printed. If you store 2 in
4-bits field: Binary 2: 0010 (left most bit is 0, so system will treat it as positive value)
0010 is 2 Therefore 2 is printed.
If you store 13 in 4-bits field: Binary 13: 1101 (left most bit is 1, so system will treat it
as negative value) Find 2's complement of 1101: 1's complement of 1101 : 0010 2's
complement of 1101 : 0011 (Add 1 to the result of 1's complement) 0011 is 3 (but
negative value) Therefore -3 is printed.

C PROGRAMMING & DATA STRUCTURES 76


SRIDHAR

4. What will be the output of the program in 16 bit platform (TurboC under DOS) ?
#include<stdio.h>
int main( )
{
struct value
{
int bit1:1;
int bit3:4;
int bit4:4;
}bit;
printf("%d\n", sizeof(bit));
return 0;
}
A. 1 B.2 C.4 D.9

Output: Option B

Explanation:
 Since C is a compiler dependent language, in Turbo C (DOS) the output will be 2, but
in GCC (Linux) the output will be 4.

Class Room Objectives

1. Find the output of the following code segments


(a) struct bit field
{
unsigned int i : 3;
unsigned int j : 2;
}
b;
main( )
{
printf(“%d”, size of b);
}

C PROGRAMMING & DATA STRUCTURES 77


SRIDHAR

2. Find the output of the following code segments


(a) struct bitfiled
{
unsigned int i;
unsigned int j;
}
b;
main( )
{
printf(“%d”, size of b);
}
(b) struct x
{
unsigned int i=17;
unsigned int j=3;
}
y;
main( )
{
printf(“%d”, size of y);
}

PRACTICE
1. What will be output of following c code?
void main( )
{
struct bitfield
{
unsigned a:5;
unsigned c:5;
unsigned b:6;
}bit;
char *p;
struct bitfield *ptr,bit1={1,3,3};
p=&bit1;
p++;
clrscr();
printf("%d",*p);
getch();
}
(a) 12 b) 1 c )3 d)13

C PROGRAMMING & DATA STRUCTURES 78


SRIDHAR

C Preprocessor Directives
 The C Preprocessor is not part of the compiler, but is a separate step in the compilation
process.
 C Preprocessor is just a text substitution tool and they instruct compiler to do required pre-
processing before actual compilation.
 Following section lists down all important preprocessor directives:

Directive Description
#define Substitutes a preprocessor macro
#include Inserts a particular header from another file
#undef Undefines a preprocessor macro
#ifdef Returns true if this macro is defined
#ifndef Returns true if this macro is not defined
#if Tests if a compile time condition is true
#else The alternative for #if
#elif #else an #if in one statement
#endif Ends preprocessor conditional
#error Prints error message on stderr
#pragma Issues special commands to the compiler, using a standardized method
 Use of the preprocessor is advantageous since it makes:
 programs easier to develop,
 easier to read,
 easier to modify
#define
 Use this to define constants or any macro substitution. Use as follows:
#define <macro> <replacement name>
For Example
#define FALSE 0
#define TRUE !FALSE
 We can also define small "parameterized macro " using #define.
 For example max. of two variables:
#define max(A,B) ( (A) > (B) ? (A):(B))
 So if in our C code we typed something like:
x = max(q+r,s+t);

C PROGRAMMING & DATA STRUCTURES 79


SRIDHAR

 after preprocessing, it would appear like this to the compiler:


x = ( (q+r) > (r+s) ? (q+r) : (s+t));
 Another example :
#define LEFT_SHIFT_8 <<8
x = y LEFT_SHIFT_8;
 after preprocessing, it would appear like this to the compiler:
x = y <<8;
#undef
 This commands undefined a macro. A macro must be undefined before being redefined to a
different value.
#include
 This directive includes a file into code.
 It has two possible forms:
#include <file> or #include "file"
 <file> tells the compiler to look where system include files are held.
 "file" looks for a file in the current directory (where program was run from)
#if -- Conditional inclusion
 #if evaluates a constant integer expression. You always need a #endif to delimit end of
statement.
 We can have else etc. as well by using #else and #elif -- else if.
 Another common use of #if is with:
#ifdef
-- if defined and
#ifndef
-- if not defined
 These are useful for checking if macros are set -- perhaps from different program modules
and header files.
 For example, to set integer size for a portable C program between TurboC (on MSDOS) and
Unix (or other) Operating systems. Recall that TurboC uses 16 bits/integer and UNIX 32
bits/integer.
 Assume that if TurboC is running a macro TURBOC will be defined. So we just need to
check for this:
#ifdef TURBOC
#define INT_SIZE 16
#else
#define INT_SIZE 32
#endif

C PROGRAMMING & DATA STRUCTURES 80


SRIDHAR

Preprocessor Directives (Macros)


01. What is the output of this program ?

#define square(x) x*x


main( )
{
int i;
i = 64/square(4);
printf("%d",i);
}

Output: 64

Explanation:
 The macro call square(4) will substituted by 4*4 so the expression becomes
i = 64/4*4 . Since / and * has equal priority the expression will be evaluated as
(64/4)*4 i.e. 16*4 = 64

02. What is the output of this program ?

#define clrscr( ) 100


main( )
{
clrscr( );
printf("%d\n",clrscr( ));
}

Output: 100

Explanation:
 Preprocessor executes as a seperate pass before the execution of the compiler. So
textual replacement of clrscr( ) to 100 occurs.

07. What is the output of this program?

#define PRINT(gate) (gate)


int main( )
{
printf("%s",PRINT(gate));
return 0;
}

Output : compile error

Explanation :
 Because the data type of gate, which is taken as variable by the compiler, is unknown.

C PROGRAMMING & DATA STRUCTURES 81


SRIDHAR

08. What is the output of this program?

#define PRINT(gate) (#gate)


int main( )
{
printf("%s",PRINT(gate));
return 0;
}

Output : gate

Explanation:
 In C, there’s a # directive, also called ‘Stringizing Operator’, which does this magic.
Basically # directive converts its argument in a string.

Class Room Objectives

1. Find the output of the following programs


(a) #define A 10
main ( )
{
int j;
j=A++;
printf(“%d ”, j);
}
(b) #define A 10
main ( )
{
printf (“%d”, A);
#define A 20
printf (“%d”, A);
}
#define A 30

2. Find the output of the following code segments


(a) #define MUL(A, B); A*B
main ( )
{
int i=2; j=3; k;
k=MUL(i,j);
printf (“%d”, k);
k=MUL (i+j, i-j);
printf(“%d”, k);
}

C PROGRAMMING & DATA STRUCTURES 82


SRIDHAR

(b) #define MUL(A, B) (A)*(B)


main ( )
{
int i=2; j=3; k;
k=MUL(i,j);
printf (“%d”, k);
k=MUL (i+j, i-j);
printf(“%d”, k);
}
3. Find the output of the following code segments
(a) #define Square (x)
main ( )
{
int x;
x=36/square(6);
printf(“%d”, x);
}
(b) #define scan “%s Hello world”
main ( )
{
printf (scanf, scanf);
}
4. Find the output of the following code segment
(a) main ( )
{
printf (“Rama %sai”, “Hari”);
}
5. Find the output of the following program
(a) #define macro (n, a, I, m) m##a##; ##n
#define main macro (n, a, I, m)
int main ( )
{
printf (“Hello c”);
}
(b) #define A 5
main ( )
{
#if def A
#define B 10
#end if
printf (“%d %d”, A, B);
}

C PROGRAMMING & DATA STRUCTURES 83


SRIDHAR

6. Find the output of the following code segments

(a) #if n def A


main ( )
{
#define B 10
#end if
printf (“%d %d”, A, B);
}

(b) #define f(g, g), g##g


int main ( )
{
int var12 = 100;
printf (“%d”, f(var,12));
}
7. Find the output of the following code segments

(a) main ( )
{
#include <stdio.h>
#define A 15
printf (“%d”, A);
}

(b) main (int arg C, char *argv [ ])


{
int i;
for (i=0; i<argc; i++);
{
printf (“%s”, argv[i]);
}
}

C PROGRAMMING & DATA STRUCTURES 84


SRIDHAR

PRACTICE

1. Point out the error in the following code?


typedef struct
{
int data;
NODEPTR link;
}*NODEPTR;
(a) : in *NODEPTR (b) Error: typedef cannot be used until it is defined
(c) No error (d) None of above
2. What is x in the following program?
#include<stdio.h>
int main( )
{
typedef char (*(*arrfptr[3])())[10];
arrfptr x;
return 0;
}
(a) x is a pointer (b) x is an array of three pointer
(c) x is an array of three function pointers (d) Error in x declaration
3. Consider the following code segment:
typedef int (*test)(float*, float*);
test tmp;
What is the type of tmp?
(a) function taking two pointer-to-float arguments and returning pointer to int
(b) pointer to int
(c) pointer to function taking two pointer-to-float arguments and returning int
(d) none of the above
4. What will be the output of the program?
#include<stdio.h>
void fun(int);
typedef int (*pf) (int, int);
int proc(pf, int, int);
int main()
{
int a=3;
fun(a);
return 0;
}

C PROGRAMMING & DATA STRUCTURES 85


SRIDHAR

void fun(int n)
{
if(n > 0)
{
fun(--n);
printf("%d,", n);
fun(--n);
}
}
(a) 0, 2, 1, 0, (b) 1, 1, 2, 0, (c) 0, 1, 0, 2, (d) 0, 1, 2, 0,

5. What will be the output of the program?


#include<stdio.h>
int fun(int, int);
typedef int (*pf) (int, int);
int proc(pf, int, int);
int main( )
{
printf("%d\n", proc(fun, 6, 6));
return 0;
}
int fun(int a, int b)
{
return (a==b);
}
int proc(pf p, int a, int b)
{
return ((*p)(a, b));
}
(a) 6 (b) 1 (c) 0 (d) -1

6. What will the SWAP macro in the following program be expanded to on


preprocessing? will the code compile?

#include<stdio.h>
#define SWAP(a, b, c)(c t; t=a, a=b, b=t)
int main( )
{
int x=10, y=20;
SWAP(x, y, int);
printf("%d %d\n", x, y);
return 0;
}
(a) It compiles (b) Compiles with an warning
(c) Not compile (d) Compiles and print nothing

C PROGRAMMING & DATA STRUCTURES 86


SRIDHAR

7. In which stage the following code


#include<stdio.h>
gets replaced by the contents of the file stdio.h
(a) During editing (b) During linking
(c) During execution (d) During preprocessing
8. What will be the output of the program?
#include<stdio.h>
#define MAN(x, y) ((x)>(y)) ? (x):(y);
int main()
{
int i=10, j=5, k=0;
k = MAN(++i, j++);
printf("%d, %d, %d\n", i, j, k);
return 0;
}
(a) 12, 6, 12 (b) 11, 5, 11 (c) 11, 5, Garbage (d) 12, 6, Garbage
9. What will be the output of the program?
#include<stdio.h>
#define SQUARE(x) x*x
int main( )
{
float s=10, u=30, t=2, a;
a = 2*(s-u*t)/SQUARE(t);
printf("Result = %f", a);
return 0;
}
(a) Result = -100.000000 (b) Result = -25.000000
(c) Result = 0.000000 (d) Result = 100.000000

10. What will be the output of the program?


#include<stdio.h>
#define JOIN(s1, s2) printf("%s=%s %s=%s \n", #s1, s1, #s2, s2);
int main( )
{
char *str1="India";
char *str2="BIG";
JOIN(str1, str2);
return 0;
}
(a) str1=IndiaBIX str2=BIG (b) str1=India str2=BIG
(c) str1=India str2=IndiaBIG (d) Error: in macro substitution

C PROGRAMMING & DATA STRUCTURES 87


SRIDHAR

11. What will be the output of the program?


#include<stdio.h>
#define PRINT(int) printf("int=%d, ", int);
int main( )
{
int x=2, y=3, z=4;
PRINT(x);
PRINT(y);
PRINT(z);
return 0;
}
(a) int=2, int=3, int=4 (b) int=2, int=2, int=2
(c) int=3, int=3, int=3 (d) int=4, int=4, int=4
12. What will be the output of the program?
#include<stdio.h>
#define SWAP(a, b) int t; t=a, a=b, b=t;
int main( )
{
int a=10, b=12;
SWAP(a, b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
(a) a = 10, b = 12
(b) a = 12, b = 10
(c) Error: Declaration not allowed in macro
(d) Error: Undefined symbol 't'
13. What will be the output of the program?
#include<stdio.h>
#define FUN(i, j) i##j
int main( )
{
int va1=10;
int va12=20;
printf("%d\n", FUN(va1, 2));
return 0;
}
(a) 10 (b) 20 (c) 1020 (d) 12
14. What will be the output of the program?
#include<stdio.h>
#define MAX(a, b) (a > b ? a : b)
int main( )

C PROGRAMMING & DATA STRUCTURES 88


SRIDHAR

{
int x;
x = MAX(3+2, 2+7);
printf("%d\n", x);
return 0;
}
(a) 8 (b) 9 (c) 6 (d) 5
15. What will be the output of the program?
#include<stdio.h>
#define MIN(x, y) (x<y)? x : y;
int main( )
{
int x=3, y=4, z;
z = MIN(x+y/2, y-1);
if(z > 0)
printf("%d\n", z);
return 0;
}
(a) 3 (b) 4 (c) 0 (d) No output
16. What will be the output of the program?
#include<stdio.h>
#define MESS junk
int main( )
{
printf("MESS\n");
return 0;
}
(a) junk (b) MESS (c) Error (d) Nothing will print
17. Point out the error in the program
#include<stdio.h>
#define SI(p, n, r) float si; si=p*n*r/100;
int main()
{
float p=2500, r=3.5;
int n=3;
SI(p, n, r);
SI(1500, 2, 2.5);
return 0;
}

(a) 26250.00 7500.00 (b) Nothing will print


(c) Error: Multiple declaration of si (d) Garbage values

C PROGRAMMING & DATA STRUCTURES 89


SRIDHAR

18. Point out the error in the program


#include<stdio.h>
int main( )
{
int i;
#if A
printf("Enter any number:");
scanf("%d", &i);
#elif B
printf("The number is odd");
return 0;
}
(a) Error: unexpected end of file because there is no matching #endif
(b) The number is odd
(c) Garbage values (d) None of above
19. Which of the following are correct preprocessor directives in C?
1: #ifdef 2: #if 3. #elif 4. #undef
(a) 1, 2 (b) 4 (c) 1, 2, 4 (d) 1, 2, 3, 4
20. What will be the output
#define f(a,b) a+b
#define g(a,b) a*b
main()
{
int m;
m=2*f(3,g(4,5));
printf("\n m is %d",m);
}
(a) 46 (b) 70 (c) 26 (d) None of the above
21. The maximum combined length of the command-line arguments including the spaces
between adjacent arguments is
(a) 128 characters (b) 256 characters
(c) 67 characters (d) It may vary from one operating system to another
22. What will be the output of the program (myprog.c) given below if it is executed
from the command line?
cmd> myprog one two three
/* myprog.c */
#include<stdio.h>
int main(int argc, char **argv)
{
printf("%c\n", **++argv);
return 0;
}

C PROGRAMMING & DATA STRUCTURES 90


SRIDHAR

(a) myprog one two three (b) myprog one


(c) o (d) two
23. What will be the output of the program (myprog.c) given below if it is executed from
the command line?

cmd> myprog one two three


/* myprog.c */
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char **argv)
{
printf("%s\n", *++argv);
return 0;
}
(a) myprog (b) one (c) two (d) three
24. What will be the output of the program (sample.c) given below if it is executed
from the command line (Turbo C in DOS)?

cmd> sample 1 2 3
/* sample.c */
#include<stdio.h>
int main(int argc, char *argv[ ])
{
int j;
j = argv[1] + argv[2] + argv[3];
printf("%d", j);
return 0;
}
(a) 6 (b) sample 6 (c) Error (d) Garbage value
25. What will be the output of the program (sample.c) given below if it is executed
from the command line (turbo c under DOS)?

cmd> sample Good Morning


/* sample.c */
#include<stdio.h>
int main(int argc, char *argv[ ])
{
printf("%d %s", argc, argv[1]);
return 0;
}

(a) 3 Good (b) 2 Good (c) Good Morning (d) 3 Morning

C PROGRAMMING & DATA STRUCTURES 91


SRIDHAR

26. What will be the output of the program


#include<stdio.h>
void fun(int);
int main(int argc)
{
printf("%d ", argc);
fun(argc);
return 0;
}
void fun(int i)
{
if(i!=4)
main(++i);
}
(a) 1 2 3 (b) 1 2 3 4 (c) 2 3 4 (d) 1
27. What will be the output of the program (sample.c) given below if it is executed
from the command line?
cmd> sample "*.c"
int main(int argc, int *argv)
{
int i;
for(i=1; i<argc; i++)
printf("%s\n", argv[i]);
}
(a) *.c (b) "*.c" (c) sample *.c
(d) List of all files and folders in the current directory
28. What will be the output of the program if it is executed like below?
cmd> sample
int main(int argc, char **argv)
{
printf("%s\n", argv[argc-1]);
return 0;
}
(a) 0 (b) sample (c) samp (d) No output
29. What will be the output of the program (sample.c) given below if it is executed from
the command line?
cmd> sample friday tuesday Sunday
int main(int argc, char *argv[ ])
{
printf("%c", **++argv);
return 0;
}
(a) S (b) f (c) sample (d) Friday

C PROGRAMMING & DATA STRUCTURES 92


SRIDHAR

30. What will be the output of the program (myprog.c) given below if it is executed from
the command line?

cmd> myprog friday tuesday Sunday


/* myprog.c */
#include<stdio.h>
int main(int argc, char *argv[ ])
{
printf("%c", *++argv[1]);
return 0;
}
(a) r (b) f (c) m (d) y
31. What will be the output of the program (sample.c) given below if it is executed from
the command line?

cmd> sample one two three


/* sample.c */
#include<stdio.h>
int main(int argc, char *argv[ ])
{
int i=0;
i+=strlen(argv[1]);
while(i>0)
{
printf("%c", argv[1][--i]);
}
return 0;
}
(a) three two one (b) owt
(c) eno (d) eerht
32. Which of the following is TRUE about argv?
(a) It is an array of character pointers
(b) It is a pointer to an array of character pointers
(c) It is an array of strings (d) None of above
33. Which of the following statements are FALSE about the below code?

int main(int ac, char *av[ ])


{
}
(a) ac contains count of arguments supplied at command-line
(b) av[ ] contains addresses of arguments supplied at a command line
(c) In place of ac and av, argc and argv should be used.
(d) The variables ac and av are always local to main( )

C PROGRAMMING & DATA STRUCTURES 93


SRIDHAR

34. If int is 2 bytes wide.What will be the output of the program?

#include <stdio.h>
void fun(char**);
int main( )
{
char *argv[ ] = {"ab", "cd", "ef", "gh"};
fun(argv);
return 0;
}
void fun(char **p)
{
char *t;
t = (p+= sizeof(int))[-1];
printf("%s\n", t);
}
(a) ab (b) cd (c) ef (d) gh

C PROGRAMMING & DATA STRUCTURES 94


SRIDHAR

LAST MINUTE REVISION

Structure :

 A structure is a is a collection of logically related heterogeneous elements.


 Every elements of a structure will have its own memory location.
 Every element of a structure can be accessed by accessing operator.
 Each structure element is accessed through (structure object) (variable name)
 Size of structure object = sum of size of its logical elements. In student structure size of
name = 10 and age = 2. Total size of structure = 12
 Nesting of structure is possible i.e. we can declare a structure within another structure but
it is necessary inner structure must declares structure variable otherwise we cannot access
the data member of inner structure
 Array, union, structure can be member of a structure.

Union:

 Union is a special data type which allows storing of different data types in the same
memory location.
 The element which occupies more memory that will be shared by all elements of union.
 Only one element of union can be initialized at a time.

BitField

 A structure declarator can also have a specified number of bits, called a "bit field." Its
length is set off from the declarator for the field name by a colon. A bit field is
interpreted as an integral type
 Arrays of bit fields, pointers to bit fields, and functions returning bit fields are not
allowed.
 Bit fields can be declared as part of a structure.
 The address-of operator (&) cannot be applied to bit-field components. Unnamed bit
fields cannot be referenced, and their contents at run time are unpredictable.
 Bit fields are allocated within an integer from least-significant to most-significant bit.

The C Preprocessor

C PROGRAMMING & DATA STRUCTURES 95


SRIDHAR

 C Preprocessor is just a text substitution tool and they instruct compiler to do required
pre-processing before actual compilation.
 Use of the preprocessor is advantageous since it makes:
 programs easier to develop,
 easier to read,
 easier to modify
 #define:Use this to define constants or any macro substitution
 #undef:This commands undefined a macro. A macro must be undefined before being
redefined to a different value.
 #include:This directive includes a file into code.
 #if -- Conditional inclusion:#if evaluates a constant integer expression. You always need
a #endif to delimit end of statement.
 Another common use of #if is with:
 #ifdef: if defined and Returns true if macro is defined
 #ifndef: if not defined and Returns true if this macro is not defined
 #else :The alternative for #if
 #elif :#else an #if in one statement
 #endif: Ends preprocessor conditional
 #error : Prints error message on stderr
 #pragma: Issues special commands to the compiler, using a standardized method

C PROGRAMMING & DATA STRUCTURES 96

You might also like