CDS SET-1 - Merged
CDS SET-1 - Merged
CDS SET-1 - Merged
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
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 TOKENS
A token is the basic building block of a C program which can be recognized by
the compiler.
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.
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.
Operators
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
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.
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)
Explanation :
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise XOR Operation of 12 and 25
00001100
| 00011001
Ex :
int main()
{
printf("complement=%d\n",~35);
printf("complement=%d\n",~-12);
}
Output :
complement=-36
complement =11
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
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.
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
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;
}
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
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.
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
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
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);
}
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
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.
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.
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.
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.
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
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);
}
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
Operators
Arithmetic Operators (+, -, *, /, %)
Relational operators (==, >, < , !=, >=, <=)
Logical Operators (&& , ||, ! )
Assignment Operator( =)
(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);
}
(c)main( )
{
int i=69;
if (++i, i++, ++i);
printf (“Hello %d”, i);
else
printf (“Bye %d”, i);
}
(b)main( )
{
int i=5;
switch (i);
{
default : printf (“A”);
case 4 : printf (“B”);
case 5 : printf (“C”);
}
}
(b)main( )
{
int i=3, j=4, k=5;
for (i; i= =j; k++);
{
printf (“Hello %d”, k);
}
}
(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);
}
(a) main( )
{
f( );
}
void f( );
{
printf (“Hello f”);
}
(b) f(int *x, int y);
{
*x=*x+y;
Y=*x+y;
}
main( )
{
int x=3, y=5;
f(&x, y);
printf (“%d”, x+y);
}
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)
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
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
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
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
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
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
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
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
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
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
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
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
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;
}
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.
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
}
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) ;
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
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
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
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
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;
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}
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
PRACTICE QUESTIONS
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
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
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
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
int g( )
{
int x = 1;
return f( );
}
int main( )
{
printf("%d", g( ));
}
(a) 1 (b) 0 (c) Compiler Error (d) 10
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
int main()
{
printf("%d", f(4));
}
(a) 5 (b) 7 (c) 11 (d) 18
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
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
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
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
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
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]
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. */
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]
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
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
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
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.
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
12 7 13 4 11 6
12 7 13 4 11 6
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 //.
(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) 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);
}
PREVIOUS QUESTIONS
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)
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)
{
PRACTICE
#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
#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;
}
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 …..
int x = 10
‘*’
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.
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
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
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 :
#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;
}
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 + 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.
(*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 :
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;
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++) :
x = cp++
mean ‘x’ contains ‘cp’ and then ‘cp’ will be incremented by1
L-value = memory location of ‘a’
R-value = ‘a’
*(++cp):
++*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
#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;
6. printf prints i = 0, j = 2.
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
int a[2][5] = {
{1, 2, 3, 4, 5},
{5, 4, 3, 2, 1}
};
a→ a[0] → a [0] →
&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<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
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
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 !
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".
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.
Explanation:
Apply the clock-wise rule to find the result.
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
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.
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)
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
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
main (void)
{
x=5;
p(&x);
print(x);
}
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
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
#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
#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 __________
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
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
#include<stdio.h>
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);
}
main( )
{
char * str = "hello";
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
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
Strings:
A string is a collection of characters and is terminated by a null character ’\0’.
Eg : “L E A D”
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.
Output : Chandra
int main( )
{
char str1[ ] = “lead”;
char str2[ ] = “lead”;
if (str1 = = str2) //------------(1)
printf (“equal”);
else
printf(“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 :
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
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.
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]);
}
Explanation:
Array names are constant pointer. So it cannot be modified
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.
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.
PREVIOUS
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)?
char p [20];
char *s=”string”;
int length = strlen(s);
for (i=0; i<length; i++)
p[i]=s[length-i]
printf (“%s”, p);
PRACTICE
#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()
#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
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
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
#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
#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
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.
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.
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);
}
(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);
}
(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;
}
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);
}
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);
PREVIOUS
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.
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.
#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.
#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.
PRACTICE
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
{
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
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.
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.
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.
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.
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 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);
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
Output: 100
Explanation:
Preprocessor executes as a seperate pass before the execution of the compiler. So
textual replacement of clrscr( ) to 100 occurs.
Explanation :
Because the data type of gate, which is taken as variable by the compiler, is unknown.
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.
(a) main ( )
{
#include <stdio.h>
#define A 15
printf (“%d”, A);
}
PRACTICE
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,
#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
{
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;
}
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)?
30. What will be the output of the program (myprog.c) given below if it is executed from
the command line?
#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
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 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