Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: C Programing
Description: Some Basic Programs Og C Programing

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


C Programs with Solutions

C
Programs with Solutions

By

S
...
E
...
D)
...
, MACEEE
...
Ltd
...
Ltd
...
laxmipublications
...
com
Copyright © 2011 by Laxmi Publications Pvt
...
All rights reserved
...


Price: < 180
...


First Edition: 2011
OFFICES








Bangalore
Cochin
Hyderabad
Kolkata
Mumbai

080-26 75 69 30
0484-237 70 04, 405 13 03
040-24 65 23 33
033-22 27 43 84
022-24 91 54 15, 24 92 78 69

Ranchi







0651-221 47 64

UCP–9612–180–C PROGRAM WITH SOLUTION–ANA
Typeset at : Monu Printographics, Delhi

Chennai
Guwahati
Jalandhar
Lucknow
Patna

044-24 34 47 26
0361-251 36 69, 251 38 81
0181-222 12 72
0522-220 99 16
0612-230 00 97

C—
Printed at : Ajit Printers, Delhi

Dedicated to
My Son
Master A
...
C Concepts
2
...
Fundamentals—C Programs
4
...
Sample Questions
6
...
Questions

Pages
1–11
12–51
52–112
113–248
249–261
262–279
280–286

Preface
This book gives a rich collection of C programs
...
This
book will be useful for students of BE, MCA, BCA, MSc, and BSc, which have C programming language as a part of the course
...
The second chapter
focuses on introduction C programming
...
Fourth chapter focuses on C debugging
...
Sixth chapter deals with the short questions
and answers
...
Suggestions for improvement will be appreciated and incorporated
...
0 OVERVIEW OF C PROGRAMMING
C language is one of the most popular computer languages today because it is a structured,
high level, machine independent language
...
C is called a high level,
compiler language
...

C is one of a large number of high level languages which can be used for general purpose
programming, i
...
, anything from writing small programs for personal amusement to writing complex
applications
...
Before C, high level languages were criticized by machine
code programmers because they shielded the user from the working details of the computer
...
This is vitally important for writing lengthy programs because complex problems are
only manageable with a clear organization and program structure
...
These provide an excellent basis for controlling
the flow of programs
...
The richness of
a language shapes what it can talk about
...

C tries to make the best of a computer by linking as closely as possible to the local environment
...
It is a robust
language whose rich set of built-in functions and operators can be used to write any complex program
...

Programs written in C are efficient and fast
...
C is highly portable
...
Another feature of C is its ability to extend itself
...
1 INTRODUCTION
C is a remarkable language
...
C is a structured language
...
It is easy for debugging, testing, and maintenance if a language is a structured
one
...
2 STRUCTURE OF A C PROGRAM
Include header file section
Global declaration section
main()
{
Declaration part
Executable part
}
User-defined functions
{
Statements
}

Include Header File Section
C program depends upon some header files for function definition that are used in program
...
h
...


Global Declaration
This section declares some variables that are used in more than one function
...
This section must be declared outside of all the functions
...
The function main() is
a starting point of every C program
...


Declaration Part
The declaration part declares the entire variables that are used in executable part
...
Initialisation means providing initial value
to the variables
...
This part conatins
a set of statements or a single statement
...


User Defined Function
The functions defined by the user are called user-defined functions
...


1
...
Creation of program
Programs should be written in C editor
...
The default extension is C
...
Compilation of a program
The source program statements should be translated into object programs which is suitable
for execution by the computer
...
If
there is no error, compilation proceeds and translated program are stored in another file
with the same file name with extension “
...

3
...


1
...


dot

^

Caret

;

Semicolon

*

Asterisk

:

Colon

-

Minus

'

Apostrophe

+

Plus

4

C PROGRAMS

WITH

SOLUTIONS

"

Quotation mark

<

Less than

!

Exclamation mark

>

Greater than

|

Vertical bar

()

Parenthesis left/right

/

Slash

[]

Bracket left/right

\

Back slash

{}

Braces left/right

~

Tilde

%

Percent

_

Underscore

#

Number sign or Hash

$

Dollar

=

Equal to

?

Question mark

@

At the rate

1
...
6 C KEYWORDS
Auto

Double

Int

Struct

Break

Else

Long

Switch

Case

Enum

Register

Typedef

Char

Extern

Return

Union

Const

Float

Short

Unsigned

Continue

For

Signed

Void

Default

Goto

Sizeof

Volatile

Do

If

Static

while

C CONCEPTS

5

1
...
They are user-defined names,
consisting sequence of letters and digits, with the letter as the first character
...
8 CONSTANTS
Values do not change during the execution of the program
Types:
1
...
It requires minimum two bytes and maximum four bytes
...

Eg: 2
...
342
2
...
Characters are also represented with a
single digit or a single special symbol or white space enclosed within a pair of single
quote marks
Eg: ‘a’, ‘8’, “ ”
...

Eg: “Hello”, “india”, “444”

1
...
Its value may be changed during the program
execution
...


1
...
4e – 38 to +3
...
7e – 308 to 1
...
4e – 4932 to 1
...
11 OPERATORS
It indicates an operation to be performed on data that yields value
...
12 INPUT AND OUTPUT
Reading data from input devices and displaying the results on the screen are the two main
tasks of any program
...
13

DECISION STATEMENTS

It checks the given condition and then executes its sub-block
...

Types:
1
...
If-else statement
3
...
Break statement
5
...
Goto statement
7
...
Nested switch ()case
9
...
14 LOOP CONTROL STATEMENTS
Loop is a block of statements which are repeatedly executed for certain number of times
...
For loop
2
...
While loop
4
...
do-while statement with while loop

C CONCEPTS
Statement

9

Syntax

For loop

For(initialize counter; test condition; re-evaluation parameter)
{
Statement;
Statement;
}

Nested for loop

for(initialize counter; test condition; re-evaluation parameter)
{
Statement;
Statement;
for(initialize counter; test condition; re-evaluation parameter)
Statement;
Statement;
}
}

While loop

While (test condition)
{
Body of the loop
}

Do while loop

do
{
Statement;
}
While(condition);

Do-while with while loop

Do while(condition)
{
Statement;
}
While (condition);

1
...

Types
1
...
Two dimensional arrays
3
...
Insertion
2
...
Searching
4
...
Merging

1
...
Group of characters, digits, symbols enclosed within
quotation marks are called as strings
...
17

11

FUNCTIONS

It is a self-contained block or a sub program of one or more statements that performs a
special task
...
Any change made in the formal argument does not effect the actual
arguments because formal arguments are photo copies of actual arguments
...
Function operates on address
rather than values
...


1
...


Chapter

2

INTRODUCTION—C PROGRAMS

1] Program to find sum of two numbers
...
h>
#include ...

#include ...
h>
void main()
{
int r;
float pi=3
...
000
circumference=31
...

#include ...
h>
void main()
{
int p,r,t,si;
clrscr();
printf(“enter principle, Rate of interest & time to find simple interest: ”);
scanf(“%d%d%d”,&p,&r,&t);
si=(p*r*t)/100;
printf(“simple intrest= %d”,si);
getch();
}
Output:
enter principle, rate of interest & time to find simple interest: 500
5
2
simple interest=50
4] Program to convert temperature from degree centigrade to Fahrenheit
...
h>
#include ...
8*c)+32;
printf(“temp in Fahrenheit=%f ”,f);
getch();
}
Output:
enter temp in centigrade: 32
temp in Fahrenheit=89
...

#include ...
h>
void main()
{
int s1,s2,s3,s4,s5,sum,total=500;
float per;
clrscr();
printf(“enter marks of 5 subjects: ”);
scanf(“%d%d%d%d%d”,&s1,&s2,&s3,&s4,&s5);
sum=s1+s2+s3+s4+s5;
printf(“sum=%d”,sum);
per=(sum*100)/total;
printf(“percentage=%f”,per);
getch();
}
Output:
enter marks of 5 subjects: 60
65
50
60
60
sum=300
percentage=60
...

#include ...
h>

I NTRODUCTION—C P ROGRAMS
void main()
{
int a,b;
clrscr();
printf(“enter value for a & b: ”);
scanf(“%d%d”,&a,&b);
a=a+b;
b=a-b;
a=a-b;
printf(“after swapping the value of a & b: %d %d”,a,b);
getch();
}
Output:
enter value for a & b: 4 5
after swapping the value of a & b: 5 4
7] Program to reverse a given number
...
h>
#include ...

#include ...
h>
void main()
{
int gs,bs,da,ta;
clrscr();
printf(“enter basic salary: ”);
scanf(“%d”,&bs);
da=(10*bs)/100;
ta=(12*bs)/100;
gs=bs+da+ta;
printf(“gross salary=%d”,gs);
getch();
}
Output:
enter basic salary: 100
gross salary=122
9] Program to print a table of any number
...
h>
#include ...

#include ...
h>
void main()
{
int a,b,c;
clrscr();
printf(“enter value of a, b & c: ”);
scanf(“%d%d%d”,&a,&b,&c);
if((a>b)&&(a>c))
printf(“a is greatest”);
if((b>c)&&(b>a))
printf(“b is greatest”);
if((c>a)&&(c>b))
printf(“c is greatest”);
getch();
}
Output:
enter value for a, b& c: 5
7
4
b is greatest
11] Program to show the use of conditional operator
...
h>
#include ...

#include ...
h>
void main()
{
int n;
clrscr();
printf(“enter any year: ”);
scanf(“%d”,&n);
if(n%4==0)
printf(“year is a leap year”);
else
printf(“year is not a leap year”);
getch();
}
Output:
enter any year: 1947
year is not a leap year
13] Program to find whether given no
...

#include ...
h>
void main()
{
int n;
clrscr();
printf(“enter any no: ”);
scanf(“%d”,&n);
if(n%2==0)
printf(“no is even”);
else

I NTRODUCTION—C P ROGRAMS
printf(“no is odd”);
getch();
}
Output:
enter any no: 5
no is odd
14] Program to shift inputed data by two bits to the left
...
h>
#include ...
Display Monday to Sunday
...
h>
#include ...

#include ...
h>
void main()
{
int a,b,n,s,m,su,d;
clrscr();
printf(“enter two no’s : ”);
scanf(“%d%d”,&a,&b);
printf(“enter 1 for sum\n2 for multiply\n3for subtraction\n4 for division: ”);
scanf(“%d”,&n);
switch(n)
{
case 1:
s=a+b;
printf(“sum=%d”,s);
break;
case 2:
m=a*b;
printf(“multiply=%d”,m);
break;
case 3:
su=a-b;
printf(“subtraction=%d”,su);
break;
case 4:
d=a/b;
printf(“divission=%d”,d);
break;

21

22

C PROGRAMS

WITH

SOLUTIONS

default:
printf(“wrong input”);
break;
}
getch();
}
Output:
enter two no’s: 8
4
enter 1 for sum
2 for multiply
3 for subtraction
4 for division: 1
sum=12
17] Program to display first 10 natural no
...

#include ...
h>
void main()
{
int i,sum=0;
clrscr();
for(i=1;i<=10;i++)
{
printf(“%d no is= %d\n”,i,I);
sum=sum+i;
}
printf(“sum =%d”,sum);
getch();
}
Output:
1 no is=1
2 no is=2
3 no is=3
4 no is=4
5 no is=5

I NTRODUCTION—C P ROGRAMS
6 no is=6
7 no is=7
8 no is=8
9 no is=9
10 no is=10
sum=55
18] Program to print stars Sequence1:
#include ...
h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
printf(“*”);
printf(“\n”);
}
getch();
}
Output:
*
**
***
****
*****
19]

Program to print stars Sequence2
...
h>
#include ...


#include ...
h>
void main()
{
int i,j,k;
clrscr();
for(i=1;i<=3;i++)
{
for(j=3;j>=i;j--)
printf(“ ”);
{
for(k=1;k<=i*2-1;k++)
printf(“*”);
}
printf(“\n”);
}
getch();
}

I NTRODUCTION—C P ROGRAMS
Output:
*
***
*****
21] Program to print Fibonacci series up to 100
...
h>
#include ...

#include ...
h>
void main()
{
int n,i,fact=1;
clrscr();
printf(“Enter any no: ”);
scanf(“%d”,&n);

25

26

C PROGRAMS

WITH

SOLUTIONS

for(i=n;i>=1;i--)
{
fact=fact*i;
}
printf(“Factorial=%d”,fact);
getch();
}
Output:
Enter a no: 5
Factorial=120
23] Program to find whether given no
...
or not
...
h>
#include ...
+1/n
...
h>
#include ...
+n
...
h>
#include ...

#include ...
h>
void main()
{
int a,b,c;
clrscr();
printf(“Read the integers from keyboard:- ”);
scanf(“%d %d”,&a,&b);
c=a&b;
printf(“\nThe Answer after ANDing is: %d ”,c);
getch();
}
Output:
Read the integers from keyboard:- 8 4
The Answer after ANDing is: 0
27] Program to add two number using pointers
...
h>
#include ...

#include ...
h>
void main()
{
int *p1,*p2,sum;
clrscr();
printf(“enter two no’s: ”);
scanf(“%d%d”,&*p1,&*p2);
sum=*p1+*p2;
printf(“sum=%d”,sum);
getch();
}
Output:
enter two no’s: 10
20
sum=30
29] Program to show sum of 10 elements of array & show the average
...
h>
#include ...
2f”,av);
getch();
}
Output:
enter elements of an array: 4
5
6
1
2
3
5
5
4
7
sum=42
average=4
...
in an array
...
h>
#include ...

#include ...
h>
void main()
{
int a[3][2],b[3][2],i,j;
clrscr();
printf(“enter value for a matrix: ”);
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
scanf(“%d”,&a[i][j]);
}
printf(“enter value for b matrix: ”);
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
scanf(“%d”,&b[i][j]);
}
printf(“\na matrix is\n\n”);
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)

31

32

C PROGRAMS

WITH

SOLUTIONS

{
printf(“ %d ”,a[i][j]);
}
printf(“\n”);
}
printf(“\nb matrix is\n\n”);
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf(“ %d ”,b[i][j]);
}
printf(“\n”);
}
getch();
}
Output:
enter value for a matrix: 7
8
9
4
5
6
enter value for b matrix: 3
2
1
4
5
6
a matrix is
7 8
9 4
5 6

I NTRODUCTION—C P ROGRAMS
b matrix is
3 2
1 4
5 6
32] Program to find sum of two matrices
...
h>
#include ...

#include ...
h>
void main()
{
int a[5],b[5],c[5],i;
clrscr();
printf(“enter value for array a ”);
for(i=0;i<5;i++)
scanf(“%d”,&a[i]);
printf(“enter value for array b ”);
for(i=0;i<5;i++)
scanf(“%d”,&b[i]);
for(i=0;i<5;i++)

I NTRODUCTION—C P ROGRAMS
c[i]=a[i]-b[i];
printf(“subtraction”);
for(i=0;i<5;i++)
printf(“ %d ”,c[i]);
getch();
}
Output:
enter value for array a: 7
8
9
4
5
enter value for array b: 4
5
6
1
2
subtraction 3 3 3 3 3
34] Program to find multiplication of two matrices
...
h>
#include ...

#include ...
h>
void main()
{
int a[3][2],b[2][3],i,j;
clrscr();
printf(“Enter value for matrix: ”);
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
scanf(‘%d”,&a[i][j]);
}
printf(“Matrix:\n”);
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
printf(“ %d ”,a[i][j]);
printf(“\n”);
}
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
b[j][i]=a[i][j];
}
printf(“Transpose matrix:\n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
printf(“ %d ”,b[i][j]);
printf(“\n”);
}
getch();
}

37

38

C PROGRAMS

WITH

SOLUTIONS

Output:
Enter value for matrix: 4
5
6
1
2
3
Matrix:
45
61
23
Transpose matrix:
462
513
36] Program to find the maximum number in array using pointer
...
h>
#include ...

#include ...
h>
void main()
{
char a[50];
clrscr();
printf(“enter any string: ”);
gets(a);
puts(a);
getch();
}
Output:
enter any string: hi everyone
hi everyone
38] Program to find square of a number using functions
...
h>
#include ...

#include ...
h>
void main()
{
void swap(int,int);
int a,b,r;
clrscr();
printf(“enter value for a&b: ”);
scanf(“%d%d”,&a,&b);
swap(a,b);
getch();
}
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
printf(“after swapping the value for a & b is : %d %d”,a,b);
}
Output:
enter value for a&b: 4
5
after swapping the value for a & b : 5 4

I NTRODUCTION—C P ROGRAMS
40] Program to find factorial of a number using functions
...
h>
#include ...

#include ...
h>
void main()
{
void table();
clrscr();
table();
getch();
}

41

42

C PROGRAMS

WITH

SOLUTIONS

void table()
{
int n,i,r;
printf(“enter a no to know table: ”);
scanf(“%d”,&n);
for(i=1;i<=10;i++)
{
r=n*i;
printf(“%d*%d=%d\n”,n,i,r);
}
}
Output:
enter a no to know table: 2
2*1=2
2*2=4
2*3=6
2*4=8
2*5=10
2*6=12
2*7=14
2*8=16
2*9=18
2*10=20
42] Program to show call by value
...
h>
#include ...

#include ...
h>
void main()
{
int a,b,*aa,*bb,swap();
clrscr();
a=5;
b=10;
aa=&a;
bb=&b;
printf(“value of a= %d & value of b=%d before swap”,a,b);
swap(aa,bb);
printf(“\nvalue of a=%d & b=%d after swap”,a,b);
getch();
}
int swap(int *x,int *y)
{
int temp;
temp=*x;

43

44

C PROGRAMS

WITH

SOLUTIONS

*x=*y;
*y=temp;
}
Output:
value of a= 5 & value of b=10 before swap
value of a=10 & b=5 after swap
44] Program to find largest of two numbers using functions
...
h>
#include ...

#include ...
h>
void main()
{
int n;
clrscr();
printf(“enter number: ”);
scanf(“%d”,&n);
if(n<0)
printf(“invalid number”);
else
printf(“%d!=%d”,n,fact(n));
getch();
}
int fact(int x)
{
if(x==0)
return 1;
else
return(x*fact(x-1));
}
Output:
enter number: 5
5!=120
46] Program to find whether a string is palindrome or not
...
h>
#include ...
File Operations:
#include ...
h>
void main()
{
file *fp,*fp1;
char c;
clrscr();
fp=fopen(“test
...
end)\n”);
c=getchar();
while(c!=’#’)
{
fputc(c,fp);
c=getchar();
}
rewind(fp);
fp=fopen(“test
...
c”,”w”);
c=fgetc(fp);
while(c!=eof)
{
fputc(c,fp);
c=fgetc(fp);
}
fclose(fp);
fclose(fp1);
fp1=fopen(“tes
...
Merging One Dimensional Array – Excluding The Repeating Element
#include ...
h>
void main()
{
int a[50],b[50],n1,n2,i,x;
clrscr();
printf(“enter the number of elements in the first array”);
scanf(“%d”,&n1);
printf(“enter the elements\n”);

47

48

C PROGRAMS

WITH

SOLUTIONS

for(i=0;i{
printf(“enter a[%d]”,i+1);
scanf(“%d”,&a[i]);
}
printf(“enter the number of elements in the second array”);
scanf(“%d”,&n2);
printf(“enter the elements\n”);
for(i=0;i{
printf(“enter b[%d]”,i+1);
scanf(“%d”,&b[i]);
}
for(x=0;x{
for(i=0;i{
if(b[i]==a[x])
{
b[i]=’ ‘;
}
}
}
for(i=o;i{
printf(“%d”,a[i]);
}
for(i=0;i{
if(b[i]==’ ‘;)
continue;
else
printf(“%d”,b[i]);
}
getch();
}

I NTRODUCTION—C P ROGRAMS
Output:
Enter the number of elements in the first array
3
Enter the elements
3
5
7
Enter the number of elements in the first array
3
Enter the elements
2
5
9
3 5 7 2 9
49
...

#include ...
h>
#include ...
h>
#include ...
of words=%d”,spc+1);
printf(“\nno
...
of consonants=%d”,cons);
printf(“\nno
...
on special characters=%d”,punc);
getch();
}

Output:
Enter the statement
*Nothing is impossible in the world
...
of words=6
No
...
of consonants=19
No
...
of special characters=1

I NTRODUCTION—C P ROGRAMS
50
...
Display
their values in integer constants
...
h>
#include ...
A program to evaluate the equation y=xn when n is a non-negative integer
...
h>
#include ...
0;
count=1;
while(count<=n)
{
y=y*x;
count++;
}
printf(“x=%f; n=%d; x to power n=%f”, x, n,y);
}
Output:
Enter the values of x and n: 2
...
500000; n=4; x to power n= 39
...
A program to print the multiplication table from 1*1 to 12*10
...
h>
#include ...
Program uses a for loop to print the powers of 2 table for the power 0 to 20, both positive and
negative
...
h>
#include ...
0/(double)p;
printf(“10ld 10%d %20
...
000000000000

2

1

0
...
250000000000

8

3

0
...
062500000000

32

5

0
...
015625000000

128

7

0
...
003906250000

512

9

0
...
000976562500

2048

11

0
...
000244140625

8192

13

0
...
000061035156

32768

15

0
...
000015258789

131072

17

0
...
000003814697

524288

19

0
...
000000953674

4
...
A program to read the marks
obtained by each student in various subjects and to compute and print the total marks obtained
by each of them
...
h>
#include ...
The program illustrates the use of the break statement in a C program
...
h>
#include ...
000000
Average=23
...
A program to evaluate the series 1/1-x= 1+x+x2 +x3 +
...

#include ...
h>
#define LOOP 100
#define ACCURACY 0
...
of terms=%d”, sum,n);
end:
;
}
Output:
Input value of x:
...
265800; No
...
75
EXIT FROM LOOP
Sum=3
...
of terms=34
Input value of x:
...
Program illustrates the use of continue statement
...
h>
#include ...
h>
void main()

FUNDAMENTALS— C PROGRAMS
{
int count, negative;
double number, sqroot;
printf(“enter 9999 to STOP”);
count=0;
negative=0;
while(count<=100)
{
printf(“enter a number:”);
scanf(“%lf”, &number);
if(number==9999)
break;
if(number<0)
{
printf(“Number is negative ”);
negative++;
continue;
}
sqroot=sqrt(number);
printf(“Number=%lf square root=%lf ”, number, sqroot);
count++;
}
printf(“Number of items done =%d”, count);
printf(“Negative items=%d”, negative);
printf(“END OF DATA”);
}
Output:
Enter 9999 to STOP
Enter a number: 25
...
000000
Square root =5
...
5
Number =40
...
363961
Enter a number:-9

59

60

C P ROGRAMS

WITH

SOLUTIONS

Number is negative
Enter a number: 16
Number= 16
...
000000
Enter a number: -14
...
000000
Square root=8
...
Program to print binomial coefficient table
...
h>
#include ...
Program to draw a histogram
...
h>
#include ...
Program of minimum cost problem
...
h>
#include ...
1)
{
cost=40-8*p+p*p;
if(p= =0)

63

64

C P ROGRAMS

WITH

SOLUTIONS

{
cost1=cost;
continue;
}
if(cost>=cost1)
break;
cost1=cost;
p1=p;
}
p=(p+p1)/2
...
2f AT p=%
...
00 AT p=4
...
Program for plotting of two functions (y1=exp(-ax); y2=exp(-ax2 /2))
...
h>
#include ...
h>
void main()
{
int i;
float a, x, y1, y2;
a=0
...
25)
y1=(int) (50*exp(-a*x)+0
...
5);
if(y1= =2)
{
if(x= = 2
...
5)
printf(“X |”);
else
printf(“ |”);
for(i=1; i<=y2-1; ++i)
printf(“ ”);
printf(“*”);
for(i=1; i<=(y1-y2-1); ++i)
printf(“_”);
printf(“0”);
continue;
}
if(x==2
...
Write a program using a single –subscribed variable to evaluate the following expressions:
10

Total =

∑ X2
2

the values of x1, x2,
...


i =1

#include ...
h>
void main()
{
int i;
float x[10], value, total;
printf(“ENTER 10 REAL NUMBERS”);
for(i=0; i<10; i++)
{
scanf(“%f”, &value);
x[i]=value;
}
total=0
...
2f”, i+1, x[i]);
printf(“total=%
...
1 2
...
3 4
...
5 6
...
7 8
...
9 10
...
10
X[2]=2
...
30
X[4]=4
...
50
X[6]=6
...
70
X[8]=8
...
90
X[10]=10
...
86
13
...

43 65 51 27 79 11 56 61 82 09 25 36 07 49 55 63 74 81 49 37 40 49 16 75 87 91 33 24 58 78 65
56 76 67 45 54 36 63 12 21 73 49 51 19 39 49 68 93 85 59
Write a program to count the number of students belonging to each of the following groups of
marks: 0-9,10-19,20 -29,----,100
...
h>
#include ...
Write a program for sorting the elements of an array in descending order
...
h>
#include ...
Write a program for finding the largest number in an array
#include ...
h>
void main()
{
int *arr, i, j, n, LARGE;
clrscr();
printf(“Enter the number of elements in the array”);
scanf(“%d”, &n);
arr=(int*) malloc(sizeof(int)*n);
for(i=0; i{
printf(“Enter a number”);
scanf(“%d”, &arr[i]);
}
LARGE=arr[0];
for(i=1; i{
if(arr[i]>LARGE)
LARGE=arr[i];
}
printf(“The largest number in the array is : %d”, LARGE);
getch();
}

FUNDAMENTALS— C PROGRAMS
Output:
Enter the number of elements in the array:5
Enter a number: 32
Enter a number: 43
Enter a number: 23
Enter a number: 57
Enter a number: 47
The largest number in the array is : 57
16
...

#include ...
h>
#include ...
Write a program for finding the desired kth smallest element in an array
...
h>
#include ...
Program to sort a list of numbers and to determine median
...
h>
#include ...
0;
else
median=a[n/2+1];
for(i=1; mi<=n; i++)
printf(“%f”, a[i]);
printf(“median is %f”, median);
}
Output:
Enter the number of items
5
Input 5 values
1
...
222 3
...
444 5
...
555000 4
...
333000 2
...
111000
Median is 3
...
000000 8
...
000000 5
...
000000 3
...
500000
19
...

#include ...
h>
#include ...
625000
Standard deviation: 23
...
Program to evaluate responses to a multiple-choice test
...
h>
#include ...
Program for production and sales analysis
...
h>
#include ...
Value matrices of production & sales”);
printf(“2
...
Product-wise monthly value of production& sales”);
printf(“4
...
Exit”);
number=0;
while(1)
{
printf(“ENTER YOUR CHOICE:”);
scanf(“%d”, &number);
printf(“\n”);
if(number= =5)
{
printf(“GOOD BYE”);
break;
}
switch(number)
{
case 1:
printf(“VALUE MATRIX OF PRODUCTION”);
for(i=1; i<=4; i++)
{
printf(“Week (%d), i”);

81

82

C P ROGRAMS

WITH

SOLUTIONS

for(j=1; j<=5; j++)
printf(“%7d”, Mvalue);
printf(“\n”);
}
printf(“VALUE MATRIX OF SALES”);
for(i=1; i<=4; i++)
{
printf(“Week(%d)”, i);
for(j=1; j<=5; j++)
printf(“%7d”, Svalue[i][j]);
printf(“\n”);
}
break;
case 2:
printf(“TOTAL WEEKLY PRODUCTION & SALES”);
printf(“

PRODUCTION SALES”);

printf(“

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

----

”);

for(i=1; i<=4; i++)
{
printf(“week(%d”, i);
printf(“%7d%7d”, Mweek[i], Sweek[i]);
}
break;
case 3:
printf(“PRODUCT WISE TOTAL PRODUCTION & SALES”);
printf(“
printf(“

PRODUCTION SALES”);
--------------

----

”);

for(j=1; j<=5; j++)
{
printf(“Product(%d”,ji);
printf(“%7d%7d”, Mproduct[j], Sproduct[j]);
}
break;
case 4:
printf(“GRAND TOTAL OF PRODUCTION SALES”);

FUNDAMENTALS— C PROGRAMS

83

printf(“Total production=%d”, Mtotal);
break;
default:
printf(“Wrong choice, select gain”);
break;
}
}
Printf(“Exit from the program”);
}
Output:
Enter products manufactured week wise
M11, M12, ----, M21, M22,------etc
11

15

12

14

13

13

13

14

15

12

12

16

10

15

14

14

11

15

13

12

Enter products sold week wise
S11, S12, ----, S21, S22,-----etc
10

13

9

12

11

12

10

12

14

10

11

14

10

14

12

12

10

13

11

10

Enter cost of each product
10 20 30 15 25
Following is the list of things you can request for enter appropriate item number and press
RETURN key
...
Value matrices of production & sales
2
...
Product-wise monthly value of production & sales
4
...
Exit

84

C P ROGRAMS

WITH

SOLUTIONS

Enter your choice: 1
VALUE MATRIX OF PRODUCTION
Week (1)

110

300

360

210

325

Week (2)

130

260

420

225

300

Week (3)

120

320

300

225

350

Week (4)

140

220

450

210

300

VALUE MATRIX OF SALES
Week (1)

100

260

270

180

275

Week (2)

120

200

360

210

250

Week (3)

110

280

300

210

300

Week (4)

120

200

390

165

250

Enter your choice: 2
TOTAL WEEKLY PRODUCTION & SALES
PRODUCTION
--------------------

SALES
----------

Week(1)

1305

1085

Week(2)

1335

1140

Week(3)

1305

1200

Week(4)

1315

1125

Enter your choice: 3
PRODUCT WISE TOTAL PRODUCTION & SALES
PRODUCTION

SALES

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

---------

Product(1)

500

450

Product(2)

1100

450

Product(3)

1530

450

Product(4)

855

450

Product(5)

1275

1075

Enter your choice: 4
GRAND TOTAL OF PRODUCTION SALES
Total production=5260

FUNDAMENTALS— C PROGRAMS
Total sales=4550
ENTER YOUR CHOICE:5
GOOD BYE
Exit from the program
22
...

#include ...
h>
void main()
{
char word1[40], word2[40], word3[40], word4[40];
printf(“enter text:”);
scanf(“%s%s”, word1, word2);
scanf(“%s”, word3);
scanf(“%s”, word4);
printf(“\n”);
printf(“word1=%s\nword2=%s\n”, word1, word2);
printf(“word3=%s\nword4=%s\n”, word3, word4”);
}
Output:
Enter text:
Seventh Street, sakthinagar, erode
Word1=seventh
Word2=street
Word3=sakthinagar
Word4=erode
23
...

#include ...
h>
void main()
{
char line[81], character;

85

86

C P ROGRAMS

WITH

SOLUTIONS

int c;
c=0;
printf(“Enter text
...
press at end
Programming in c is interesting
Programming in c is interesting
Enter text
...
Write a program to copy one string into another and count the number of characters copied
...
h>
#include ...
Program for printing of the alphabet set in decimal and character form
...
h>
#include ...
Program to concatenation of strings
...
h>
#include ...
Program to illustration of string handling functions
...
h>
#include ...
h>
void main()
{
char s1[20], s2[20], s3[20];
int x, l1,l2,l3;
printf(“enter two string constants”);
printf(“?”);
scanf(“%s %s”, s1,s2);
x=strcmp(s1,s2);
if(x!=0)
{
printf(“strings are not equal”);
strcat(s1, s2);
}
else
printf(“strings are equal”);
strcpy(s3,s1);
l1=strlen(s1);
l2=strlen(s2);
l3=strlen(s3);
printf(“s1=%s length =%d characters”, s1,l1);
printf(“s2=%s length =%d characters”, s2,l2);
printf(“s3=%s length =%d characters”, s3,l3);
}
Output:
Enter two string constants
? ananda murugan
Strings are not equal
S1=ananda murugan length=13 characters

89

90

C P ROGRAMS

WITH

S2=murugan

SOLUTIONS

length=7 characters

S3=ananda murugan length=13 characters
Enter two string constants
? anand anand
Strings are equal
S1=anand length=5 characters
S2=anand length=5 characters
S3=anand length=5 characters
28
...

#include ...
h>
#define ITEMS 5
#define MAXCHAR 20
void main()
{
char string[ITEMS][MAXCHAR], dummy[MAXCHAR];
int i=0, j=0;
printf(“enter names of %d items”, ITEMS);
while(iscanf(“%s”, string[i++]);
for(i=1; i{
for(j=1; j<=ITEMS-i; j++)
{
if(strcmp(string[j-1), string[j]>0)
{
strcpy(dummy, string[j-1]);
strcpy(string[j-1], string[j]);
strcpy(string[j], dummy);
}
}
}

FUNDAMENTALS— C PROGRAMS

91

printf(“alphabetical list”);
for(i=0; iprintf(“%s”, string[i]);
}
Output:
enter names of 5 times
Ananda
murugan renuka devi shri
alphabetical list
Ananda
devi
murugan
renuka
shri
29
...

#include ...
h>
void main()
{
char line[81], ctr;
int i, c, end=0, characters =0, words=0
...

Admiration involves a glorious obliquity of vision
...

Fools admire, but men of sense approve
Number of lines=4
Number of words=36
Number of characters=205
30
...

#include ...
h>

FUNDAMENTALS— C PROGRAMS

93

#define CUSTOMERS 10
void main()
{
char first_name[20] [10], second_name[20][10], surname[20][10], name[20][20],
telephone[20][10], dummy[20];
int i,j;
printf(“input names and telephone numbers”);
printf(“?”);
for(i=0; i{
scanf(“%s %s %s %s”, first_name[i], second_name[i], surname[i], telephone[i]);
strcpy(name[i], surname[i]);
strcat(name[i], “ ,”);
dummy[0]=first_name[i][0];
dummy[1]=’\0’;
strcat(name[i], dummy);
strcat(name[i], “
...
Program for functions with no arguments and no return values
#include ...
h>
void printline(void);
void value (void);
void main()
{
printline();
value();
printline();
}
void printline(void)
{
int i;
for(i=1; i<=35; i++)
printf(“%c”, ‘-‘);
printf(“\n”);
}
void value(void)
{
int year, period;

FUNDAMENTALS— C PROGRAMS

95

float inrate, sum, principal;
printf(“principal amount?”);
scanf(“%f”, &principal);
printf(“interest rate?”);
scanf(“%f”, &inrate);
printf(“period?”);
scanf(“%d”, &period);
sum=principal;
year=1;
while(year<=period)
{
sum=sum*(1+inrate);
year=year+1;
}
printf(“\n%8
...
2f %5d %12
...
12

Period?
5000
...
12

5

8811
...
Program for functions with arguments but no return values
...
h>
#include ...
12 5
ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
5000
...
120000

5

8811
...
Program for functions with arguments and return values
...
h>
#include ...
12

5

****************************************************************************
5000
...
1200000

5

8811
...
Write a function power that computes x raised to the power y for integers x and y and
returns double-type value
...
h>
#include ...
0;
if(y>=0)
while(y--)
p*=x;
else
while(y++)
p/=x;
return(p);
}

FUNDAMENTALS— C PROGRAMS
Output:
Enter x,y: 16

2

16 to power 2 is 256
...
003906
35
...

#include ...
h>
void main()
{
int x=1, y=2, z;
z=add(x,y);
printf(“z=%d”, z);
}
add(a,b);
{
return(a+b);
}
Output:
z=3
36
...
Call them at different places
...
h>
#include ...
Write a program to show how similar variable names can be used in different functions
...
h>
#include ...
Write a program to show the effect of global variables on different functions
...
h>
#include ...
Write a program to display message using user-defined function
...
h>
#include ...
Write a program to return more than one value from user defined function
...
h>
#include ...
Write a program to pass arguments to user-defined function by value and by reference
...
h>
#include ...
Write a program to return only absolute value like abs() function
...
h>
#include ...
Write a program to calculate square and cube of an entered number
...

#include ...
h>
void main()
{

F UNDAMENTALS—C P ROGRAMS
int m;
clrscr();
printf(“Cube: %d”, cube(sqr(input())));
}
input()
{
int k;
printf(“Number:”);
scanf(“%d”, &k);
return k;
}
sqr(m)
{
printf(“Square:%d”, m*m);
return m;
}
cube(m)
{
return m*m*m;
}
Output:
Number:2
Square: 4
Cube:8
44
...

#include ...
h>
void main()
{
int input(int);
int x;
clrscr();
x=input(x);

105

106

C P ROGRAMS

WITH

SOLUTIONS

printf(“x=%d”, x);
}
input(int k)
{
printf(“Enter value of x=”);
scanf(“%d”, &k);
return(k);
}
Output:
Enter value of x=5
x=5
45
...

#include ...
h>
#include ...
Write a program to perform multiplication and division of numbers with return value of
function
...
h>
#include ...
h>
void main()
{
int input(int);
int sqr(int);
int x;
clrscr();
x=sqr(5*input(x)/2);
printf(“Square=%d, x”);
}
input(int k)
{
printf(“Enter value of x=”);
scanf(“%d, &k”);
return(k);
{
sqr(int m)
{
return (pow(m,2));
}
Output:
Enter value of x=5
Square=144

108

C P ROGRAMS

WITH

SOLUTIONS

47
...

#include ...
h>
#include ...
Write a program to use mod(%) with function
...
h>
#include ...
Write a program to evaluate the equation s=sqr(a()+b()) using function
...
h>
#include ...
Write a program to call user-defined function through if statement
...
h>
#include ...
Write a program to call user-defined function through switch() statement
...
h>
#include ...
h>
#include ...
Write a program to call function through the for loop
...
h>
#include ...
h>
void main()
{
int plus(int), m=1;
clrscr();
for(; plus(m); m++)
{
printf(“%3d”, m);
}
}
plus (int k)
{
if(k= =10)
{
exit(1);
return NULL;
}
else
return(k);
}
Output:
123456789

Chapter

4

C DEBUGGING

Find the output or error(s) for the following Programs:
1
...

Explanation:
p is a pointer to a “constant integer”
...

2
...
Generally array
name is the base address for that array
...
i is the index number/displacement
113

114

C P ROGRAMS

WITH

SOLUTIONS

from the base address
...
i[s] may be surprising
...

3
...
1;
double you = 1
...

Depending on the number of bytes, the precession with of the value represented varies
...
So float stores 0
...

Rule of Thumb:
Never compare or at-least be cautious when using floating point numbers with relational
operators (== , >, <, <=, >=,!= )
...
main()
{
static int var = 5;
printf(“%d ”,var--);
if(var)
main();
}
Answer:
54321
Explanation:
When static storage class is given, it is initialized once
...
Main is also treated like any other ordinary
function, which can be called recursively
...
main()
{
int c[ ]={2
...
4,4,6
...
In the first loop, since only q is incremented and
not c , the value 2 will be printed 5 times
...
So the values 2 3 4
6 5 will be printed
...
main()
{
extern int i;
i=20;
printf(“%d”,i);
}
Answer:
Linker Error : Undefined symbol ‘_i’
Explanation:
extern storage class in the following declaration,
extern int i;
specifies to the compiler that the memory for i is allocated in some other program and that
address will be given to the current program at the time of linking
...
Hence a linker error has occurred
...
main()
{
int i=-1,j=-1,k=0,l=2,m;
m=i++&&j++&&k++||l++;
printf(“%d %d %d %d %d”,i,j,k,l,m);

116

C P ROGRAMS

WITH

SOLUTIONS

}
Answer:
00131
Explanation:
Logical operations always give a result of 1 or 0
...
So the expression ‘i++ && j++ &&
k++’ is executed first
...
Now the
expression is 0 || 2 which evaluates to 1 (because OR operator always gives 1 except for ‘0
|| 0’ combination- for which it gives 0)
...
The values of other variables
are also incremented by 1
...
main()
{
char *p;
printf(“%d %d ”,sizeof(*p),sizeof(p));
}
Answer:
12
Explanation:
The sizeof() operator gives the number of bytes taken by its operand
...
Hence sizeof(*p) gives a value of 1
...

9
...
It is executed only when all other
cases doesn’t match
...
main()
{
printf(“%x”,-1<<4);
}
Answer:
fff0
Explanation :
-1 is internally represented as all 1’s
...
The %x format specifier specifies that the integer value be printed as a hexadecimal
value
...
main()
{
char string[]=“Hello World”;
display(string);
}
void display(char *string)
{
printf(“%s”,string);
}
Answer:
Compiler Error : Type mismatch in redeclaration of function display
Explanation:
In third line, when the function display is encountered, the compiler doesn’t know anything
about the function display
...
When it sees the actual function display, the arguments and type contradicts with
what it has assumed previously
...

12
...
Same maths rules applies, ie
...

Note:
However you cannot give like --2
...
, i--)
...

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

15
...
h>
main()
{

C DEBUGGING

119

char s[]={‘a’,‘b’,‘c’,‘\n’,‘c’,'\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf(“%d”,++*p + ++*str1-32);
}
Answer:
77
Explanation:
p is pointing to character ‘\n’
...
“p is pointing to ‘\n’ and
that is incremented by one
...
The value
of ++*p is 11
...
ASCII value
of ‘b’ is 98
...

16
...
h>
main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf(“%d----%d”,*p,*q);
}
Answer:
SomeGarbageValue---1
Explanation:
p=&a[2][2][2] you declare only two 2D arrays, but you are trying to access the third
2D(which you are not declared) it will print garbage values
...
Now q is pointing to starting address of a
...

17
...
h>
main()
{

120

C P ROGRAMS

WITH

SOLUTIONS

struct xx
{
int x=3;
char name[]=“hello”;
};
struct xx *s;
printf(“%d”,s->x);
printf(“%s”,s->name);
}
Answer:
Compiler Error
Explanation:
You should not initialize variables in declaration
...
#include ...
Hence, the elements are of yy are to be
accessed through the instance of structure xx, which needs an instance of yy to be known
...
Hence for nested structure yy you have to declare member
...
main()
{
printf(“\nab”);
printf(“\bsi”);
printf(“\rha”);
}
Answer:
hai
Explanation:
\n - newline
\b - backspace
\r - linefeed
20
...
The evaluation
is by popping out from the stack and the evaluation is from right to left, hence the result
...
#define square(x) x*x
main()
{
int i;
i = 64/square(4);
printf(“%d”,i);
}
Answer:
64
Explanation:
The macro call square(4) will substituted by 4*4 so the expression becomes i = 64/4*4
...
e
...


122

C P ROGRAMS

WITH

SOLUTIONS

22
...
Similarly blank
space is converted to ‘!’
...

23
...
h>
#define a 10
main()
{
#define a 50
printf(“%d”,a);
}
Answer:
50
Explanation:
The preprocessor directives can be redefined anywhere in the program
...

24
...
So textual
replacement of clrscr() to 100 occurs
...
So it doesn’t give any problem
...
main()
{
printf(“%p”,main);
}
Answer:
Some address will be printed
...

main() is also a function
...
%p in printf
specifies that the argument is an address
...

26
...
So it becomes a function call
...

27
...
%d
...
1
...

28
...
%d”,sizeof(farther),sizeof(farthest));
}
Answer:
4
...

29
...
%d”);
}
Answer:
400
...
Any number of printf’s
may be given
...
If more number of assignments
given in the program, then printf will take garbage values
...
main()
{
char *p;
p=“Hello”;
printf(“%c\n”,*&*p);
}
Answer:
H
Explanation:
* is a dereference operator & is a reference operator
...
Here p points to the first character in the string “Hello”
...
Again & references it to an address and * dereferences
it to the value H
...
main()
{
int i=1;
while (i<=5)
{
printf(“%d”,i);
if (i>2)
goto here;
i++;
}
}
fun()
{
here:
printf(“PP”);
}
Answer:
Compiler error: Undefined label ‘here’ in function main
...

The label ‘here’ is available in function fun() hence it is not visible in function main
...
main()
{
static char names[5][20]={“pascal”,“ada”,“cobol”,“fortran”,“perl”};
int i;
char *t;
t=names[3];
names[3]=names[4];
names[4]=t;
for (i=0;i<=4;i++)
printf(“%s”,names[i]);
}
Answer:
Compiler error: Lvalue required in function main
Explanation:
Array names are pointer constants
...

33
...

Explanation:
Side effects are involved in the evaluation of i
...
void main()
{
int i=5;
printf(“%d”,i+++++i);
}
Answer:
Compiler Error
Explanation:
The expression i+++++i is parsed as i ++ ++ + i which is an illegal combination of operators
...
#include ...

Explanation:
The case statement can have only constant expressions (this implies that we cannot
use variable names directly so an error)
...

36
...
Here 10 is given as input
which should have been scanned successfully
...

37
...
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”
...

39
...
h>
main()
{
char s[]={‘a’,‘b’,‘c’,‘\n’,‘c’,‘\0’};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf(“%d”,++*p + ++*str1-32);
}
Answer:
M
Explanation:
p is pointing to character ‘\n’
...
” the ASCII value of ‘\n’ is 10
...
The value of ++*p is 11
...
ASCII value of ‘b’ is 98
...

i
...
, (11+98-32)=77(“M”);

C DEBUGGING

129

40
...
h>
main()
{
struct xx
{
int x=3;
char name[]=“hello”;
}
struct xx *s=malloc(sizeof(struct xx));
printf(“%d”,s->x);
printf(“%s”,s->name);
}
Answer:
Compiler Error
Explanation:
Initialization should not be done for structure members inside the structure declaration
41
...
h>
main()
{
struct xx
{
int x;
struct yy
{
char s;
struct xx *p;
}
struct yy *q;
}
}
Answer:
Compiler Error
Explanation:
In the end of nested structure yy a member have to be declared
...
main()
{
extern int i;
i=20;
printf(“%d”,sizeof(i));
}
Answer:
Linker error: undefined symbol ‘_i’
...
The compiler
passes the external variable to be resolved by the linker
...
During linking the linker searches for the definition of i
...

43
...

Explanation:
The rule is that a variable is available for use from the point of declaration
...
Hence an error
...
main()
{
extern out;
printf(“%d”, out);
}
int out=100;
Answer:
100
Explanation:
This is the correct way of writing the previous program
...
main()
{
show();
}
void show()
{
printf(“I’m the greatest”);
}
Answer:
Compier error: Type mismatch in redeclaration of show
...
So the
default return type (ie, int) is assumed
...
Hence the error
...
declare void show() in main()
...
define show() before main()
...
declare extern void show() before the use of show()
...
main( )
{
int a[2][3][2] = {{{2,4},{7,8},{3,4}},{{2,2},{2,3},{3,4}}};
printf(“%u %u %u %d \n”,a,*a,**a,***a);
printf(“%u %u %u %d \n”,a+1,*a+1,**a+1,***a+1);
}
Answer:
100, 100, 100, 2
114, 104, 102, 3
Explanation:
The given array is a 3-D one
...

2

4

7

8

3

4

2

2

2

3

3

4

100

102

104

106

108

110

112

114

116

118

120

122

thus, for the first printf statement a, *a, **a give address of first element since the
indirection ***a gives the value
...


132

C P ROGRAMS

WITH

SOLUTIONS

for the second printf a+1 increases in the third dimension thus points to value at 114,
*a+1 increments in second dimension thus points to 104, **a +1 increments the first
dimension thus points to 102 and ***a+1 first gets the value at first location and then
increments it by 1
...

47
...

Explanation:
Error is in line with statement a++
...

Simply array name is a non-modifiable lvalue
...
main( )
{
static int a[ ] = {0,1,2,3,4};
int *p[ ] = {a,a+1,a+2,a+3,a+4};
int **ptr = p;
ptr++;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
*ptr++;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);

C DEBUGGING

133

*++ptr;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
++*ptr;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
}
Answer:
111
222
333
444
Explanation:
Let us consider the array and the two pointers with some address
a
0

1

2

3

4

100

102

104

106

108
p

100

102

104

106

108

1000

1002 1004 1006

1008

ptr
1000
2000
After execution of the instruction ptr++ value in ptr becomes 1002, if scaling factor for
integer is 2 bytes
...
Hence the
output of the firs printf is 1, 1, 1
...
Hence, the outputs for the second printf are ptr – p = 2, *ptr – a = 2, **ptr = 2
...
Hence, the outputs for the third printf are ptr – p = 3, *ptr – a = 3, **ptr = 3
...
So the value in array p at location 1006 changes from 106 10 108
...


134

C P ROGRAMS

WITH

SOLUTIONS

49
...
Suppose the
inputs are MOUSE, TRACK and VIRTUAL
...

M

T

R

A

C

K

\0

The third input starts filling from the location 102
M

T

V

I

R

T

U

A

L

\0

This is the final value stored
...
e
...

50
...
vp = &ch stores
address of char ch and the next statement prints the value stored in vp after type casting it to the
proper data type pointer
...
Similarly the output from second printf is ‘20’
...

51
...
Then we have
ptr which is a pointer to a pointer of type char and a variable p which is a pointer to a pointer of type
char p hold the initial value of ptr, i
...
, p = s+3
...
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
...
Thus, the output is ‘ck’
...
main()
{
int i, n;
char *x = “girl”;
n = strlen(x);
*x = x[n];
for(i=0; i
136

C P ROGRAMS

WITH

SOLUTIONS

{
printf(“%s\n”,x);
x++;
}
}
Answer:
(blank space)
irl
rl
l
Explanation:
Here a string (a pointer to char) is initialized with a value “girl”
...
The next statement assigns value at the nth location
(‘\0’) to the first location
...
Now the printf statement prints the string
after each iteration it increments it starting position
...
The first time x[0] = ‘\0’
hence it prints nothing and pointer value is incremented
...
e
...

53
...

assert failed (i<5), ,
Explanation:
Asserts are used during debugging to make sure that certain conditions are satisfied
...
After debugging use, #undef NDEBUG
and this will disable all the assertions from the source code
...

54
...
Where-ever it comes you can just ignore it
just because it has no effect in the expressions (hence the name dummy operator)
...
What are the files which are automatically opened when a C file is executed?
Answer:
stdin, stdout, stderr (standard input,standard output,standard error)
...
What will be the position of the file marker?
a: fseek(ptr,0,SEEK_SET);
b: fseek(ptr,0,SEEK_CUR);
Answer:
a: The SEEK_SET sets the file position marker to the starting of the file
...

57
...
Then it matches with a
quotation mark and then it reads all character upto another quotation mark
...
What is the problem with the following code segment?
while ((fgets(receiving array,50,file_ptr)) != EOF);
Answer & Explanation:
fgets returns a pointer
...


138

C P ROGRAMS

WITH

SOLUTIONS

59
...

Explanation:
main function calls itself again and again
...
Since there is no condition to terminate the function
call, the call stack overflows at runtime
...

60
...

Explanation:
You can create a variable of type void * but not of type void, since void is an empty
type
...

61
...

In second sizeof the name str2 indicates the name of the array whose size is 5 (including
the ‘\0’ termination character)
...

62
...
In C the value 0 is considered to be the boolean value FALSE
and any non-zero value is considered to be the boolean value TRUE
...
!TRUE is FALSE (0) so it prints 0
...
#define FALSE -1
#define TRUE 1
#define NULL 0
main() {
if(NULL)
puts(“NULL”);
else if(FALSE)
puts(“TRUE”);
else
puts(“FALSE”);
}
Answer:
TRUE
Explanation:
The input program to the compiler after processing by the preprocessor is,
main(){
if(0)
puts(“NULL”);

140

C P ROGRAMS

WITH

SOLUTIONS

else if(-1)
puts(“TRUE”);
else
puts(“FALSE”);
}
Preprocessor doesn’t replace the values given inside the double quotes
...
In second if -1 is boolean value true
hence “TRUE” is printed
...
main()
{
int k=1;
printf(“%d==1 is “”%s”,k,k==1?“TRUE“:”FALSE”);
}
Answer:
1==1 is TRUE
Explanation:
When two strings are placed together (or separated by white-space) they are
concatenated (this is called as “stringization” operation)
...
The conditional operator( ?: ) evaluates to “TRUE”
...
main()
{
int y;
scanf(“%d”,&y); // input given is 2000
if( (y%4==0 && y%100 != 0) || y%100 == 0)
printf(“%d is a leap year”);
else
printf(“%d is not a leap year”);
}
Answer:
2000 is a leap year
...


C DEBUGGING

141

66
...
So it can be used to declare the
variable name of the type arr2
...
Hence an error
...

67
...
In the innermost block i is declared as,
const volatile unsigned
...
i is assumed of type int
...
In the next
block, i has value 20 and so printf prints 20
...
After compilation is over the linker
resolves it to global variable i (since it is the only variable visible there)
...

68
...
But the
lifetime of i is lifetime of the function so it lives upto the exit of main function
...

69
...
In printf first you just
print the value of i
...

70
...
h>
main()

C DEBUGGING

143

{
const int i=4;
float j;
j = ++i;
printf(“%d %f”, i,++j);
}
Answer:
Compiler error
Explanation:
i is a constant
...

71
...
h>
main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf(“%d
...
1
Explanation:
p=&a[2][2][2] you declare only two 2D arrays but you are trying to access the third
2D(which you are not declared) it will print garbage values
...
if you print *q
meAnswer:it will print first element of 3D array
...
#include ...
i value may be stored either in register or in memory
...
main()
{
int i=5,j=6,z;
printf(“%d”,i+++j);
}
Answer:
11
Explanation:
The expression i+++j is treated as (i++ + j)
...
struct aaa{
struct aaa *prev;
int i;
struct aaa *next;
};
main()
{
struct aaa abc,def,ghi,jkl;
int x=100;
abc
...
prev=&jkl;
abc
...
i=1;def
...
next=&ghi;
ghi
...
prev=&def;
ghi
...
i=3;jkl
...
next=&abc;
x=abc
...
next->next->prev->next->i
this one points to “ghi” node the value of at particular node is 2
...
struct point
{
int x;
int y;
};
struct point origin,*pp;
main()
{
pp=&origin;
printf(“origin is(%d%d)\n”,(*pp)
...
y);
printf(“origin is (%d%d)\n”,pp->x,pp->y);
}
Answer:
origin is(0,0)
origin is(0,0)
Explanation:
pp is a pointer to structure
...

Note:
Since structure point is globally declared x & y are initialized as zeroes
...
main()
{
int i=_l_abc(10);
printf(“%d\n”,--i);
}
int _l_abc(int i)
{

146

C P ROGRAMS

WITH

SOLUTIONS

return(i++);
}
Answer:
9
Explanation:
return(i++) it will first return i and then increments
...
e
...

77
...
%p
...
0002
...

78
...

Explanation:
Declaration of convert and format of getc() are wrong
...
main(int argc, char **argv)
{
printf(“enter the character”);
getchar();
sum(argv[1],argv[2]);
}
sum(num1,num2)
int num1,num2;
{
return num1+num2;
}
Answer:
Compiler error
...
They are passed to the function sum without converting
it to integer values
...
# include ...

81
...
h>
aaa() {
printf(“hi”);
}
bbb(){
printf(“hello”);
}
ccc(){
printf(“bye”);
}
main()
{
int (*ptr[3])();
ptr[0]=aaa;
ptr[1]=bbb;
ptr[2]=ccc;
ptr[2]();
}
Answer:
bye
Explanation:
ptr is array of pointers to functions of return type int
...
Similarly ptr[1] and ptr[2] for bbb and ccc respectively
...

82
...
h>
main()
{
FILE *ptr;
char i;
ptr=fopen(“zzz
...
c followed by an infinite loop
...

83
...
%d”,i++,j);
printf(“%d
...
0
Explanation:
The value of i is 0
...
So the statement following the if statement is not executed
...

84
...
Here _AH is the pseudo global variable denoting the accumulator
...

85
...
main(){
int a= 0;int b = 20;char x =1;char y =10;
if(a,b,x,y)
printf(“hello”);
}
Answer:
hello
Explanation:
The comma operator has associativity from left to right
...
Thus the value of last variable
y is returned to check in if
...


C DEBUGGING

151

87
...
It is compared with a signed value
...
The unsigned equivalent of -2 is
a huge value so condition becomes false and control comes out of the loop
...
In the following pgm add a stmt in the function fun such that the address of ‘a’ gets stored
in ‘j’
...

89
...
int abc(int a,float b)
{
/* some code */
}
ii
...
ANSI C notation
ii
...

90
...

91
...

92
...
When this function is invoked from main, the following substitutions for formal
parameters take place: func for pf, 3 for val1 and 6 for val2
...
The function func has two
integer parameters
...
since
3 is not equal to 6, a==b returns 0
...

93
...
The function main() will be called recursively
unless I becomes equal to 0, and since main() is recursively called, so the value of
static I ie
...

94
...
5;
return(ret);
}
Answer:
Here value is 7
Explanation:
The int ret(int ret), ie
...

Firstly, the function ret() is called in which the sizeof(float) i
...
, 4 is passed, after the
first expression the value in ret will be 6, as ret is integer hence the value stored in ret
will have implicit type conversion from float to int
...

95
...
Hence the ‘I’ will hold the value equal to 5, after the pre-increment
in the printf statement, the 6 will be printed
...
void main()
{
unsigned giveit=-1;
int gotit;
printf(“%u ”,++giveit);
printf(“%u \n”,gotit=--giveit);
}
Answer:
0 65535
Explanation:
give it value is incremented
...

97
...
Hence printing a null character
returns 1 which makes the if statement true, thus “Ok here” is printed
...
void main()
{
void *v;
int integer=2;
int *i=&integer;
v=i;
printf(“%d”,(int*)*v);
}
Answer:
Compiler Error
...


156

C P ROGRAMS

WITH

SOLUTIONS

Explanation:
Void pointer is a generic pointer type
...
Void
pointers are normally used for:
1
...

2
...

3
...

99
...

Explanation:
An identifier is available to use in program code from the point of its declaration
...
The i, j and k are automatic
variables and so they contain some garbage value
...

100
...

101
...
The printf returns No
...
Still the outer printf prints
something and so returns a non-zero value
...

102
...

Explanation:
Since i is an unsigned integer it can never become negative
...

103
...
h>
main()
{
int x,y=2,z,a;
if(x=y%2) z=2;
a=2;
printf(“%d %d”,z,x);
}
Answer:
Garbage-value 0
Explanation:
The value of y%2 is 0
...
The condition reduces to if (x) or in
other words if(0) and so z goes uninitialized
...


158

C P ROGRAMS

WITH

SOLUTIONS

104
...
The result is as simple as 1 + 3 = 4 !
105
...
main()
{
unsigned int i=65000;
while(i++!=0);
printf("%d",i);
}
Answer:
1
Explanation:
Note the semicolon after the while statement
...
Due to post-increment on i the value of i while printing is 1
...
main()
{

C DEBUGGING

159

int i=0;
while(+(+i--)!=0)
i-=i++;
printf(“%d”,i);
}
Answer:
-1
Explanation:
Unary + is the only dummy operator in C
...
The
value –1 is printed due to the post-decrement operator
...
main()
{
float f=5,g=10;
enum{i=10,j=20,k=50};
printf(“%d\n”,++k);
printf(“%f\n”,f<<2);
printf(“%lf\n”,f%g);
printf(“%lf\n”,fmod(f,g));
}
Answer:
Line no 5: Error: Lvalue required
Line no 6: Cannot apply leftshift to float
Line no 7: Cannot apply mod to float
Explanation:
Enumeration constants cannot be modified, so you cannot apply ++
...

fmod() is to find the modulus values for floats as % operator is for ints
...
main()
{
int i=10;
void pascal f(int,int,int);
f(i++,i++,i++);
printf(“ %d”,i);

160

C P ROGRAMS

WITH

SOLUTIONS

}
void pascal f(integer :i,integer:j,integer :k)
{
write(i,j,k);
}
Answer:
Compiler error: unknown type integer
Compiler error: undeclared function write
Explanation:
Pascal keyword doesn’t mean that pascal code can be used
...

110
...
cdecl is the normal C argument passing mechanism where the arguments are
passed from right to left
...
What is the output of the program given below?
main()
{
signed char i=0;
for(;i>=0;i++) ;
printf(“%d\n”,i);
}
Answer:
-128
Explanation:
Notice the semicolon at the end of the for loop
...
The
inner loop executes to increment the value from 0 to 127 (the positive range of char)
and then it rotates to the negative value of -128
...
It prints the current value of i that is -128
...
main()
{
unsigned char i=0;
for(;i>=0;i++) ;
printf(“%d\n”,i);
}
Answer:
infinite loop
Explanation:
The difference between the previous question and this one is that the char is declared
to be unsigned
...

113
...

Explanation:
The detail if the char is signed/unsigned by default is implementation dependent
...
On the other hand if it considers char to be unsigned by default, it goes to
infinite loop
...
But don’t write
programs that depend on such behavior
...
Is the following statement a declaration/definition
...

x is a pointer to array of(size 10) integers
...

115
...

Explanation:
The name error is used in the two meanings
...
The another use is that it is a type name (due to typedef) for enum
errorType
...

Note: The extra comma in the declaration, enum errorType{warning, error, exception,}
is not an error
...

116
...
error =1;
printf(“%d”,g1
...

Typedef struct error{int warning, error, exception;}error;
This error can be used only by preceding the error by struct kayword as in:
struct error someError;
typedef struct error{int warning, error, exception;}error;
This can be used only after
...
error =1;
printf(“%d”,g1
...

Note:
This code is given here to just explain the concept behind
...
It reduces the readability of the code
...
#ifdef something
int some=0;
#endif
main()
{
int thing = 0;
printf(“%d %d\n”, some ,thing);
}
Answer:
Compiler error : undefined symbol some
Explanation:
This is a very simple example for conditional compilation
...

118
...
If a name is not known the preprocessor treats it to be equal to zero
...
What is the output for the following program?
main()
{
int arr2D[3][3];

C DEBUGGING

165

printf(“%d\n”, ((arr2D==* arr2D)&&(* arr2D == arr2D[0])) );
}
Answer:
1
Explanation:
This is due to the close relation between the arrays and pointers
...
arr2D is made up of a 3 single arrays that
contains 3 integers each
...
*arr2D refers to the start of
the first 1D array (of 3 integers) that is the same address as arr2D
...

Similarly, *arr2D is nothing but *(arr2D + 0), adding a zero doesn’t change the value/
meaning
...
So the expression
(*(arr2D + 0) == arr2D[0]) is true (1)
...

120
...

Explanation:
~ (tilde operator or bit-wise negation operator) operates on 0 to produce all ones to fill
the space for an integer
...


166

C P ROGRAMS

WITH

SOLUTIONS

121
...
Simple checking will help understand this
...
main()
{
char *p = “ayqm”;
printf(“%c”,++*(p++));
}
Answer:
b
Explanation:
Address of p is incremented and the value of p is incremented after that
...
main()
{
int i=5;
printf(“%d”,++i++);
}
Answer:
Compiler error: Lvalue required in function main
Explanation:
++i yields an rvalue
...

124
...
Parenthesis just
works as a visual clue for the reader to see which expression is first evaluated
...
int aaa() {printf(“Hi”);}
int bbb(){printf(“hello”);}
iny ccc(){printf(“bye”);}
main()
{
int ( * ptr[3]) ();
ptr[0] = aaa;
ptr[1] = bbb;
ptr[2] =ccc;
ptr[2]();
}
Answer:
bye
Explanation:
int (* ptr[3])() says that ptr is an array of pointers to functions that takes no arguments
and returns the type int
...
Similarly, the other
two array elements also get initialized with the addresses of the functions bbb and ccc
...
So it results in printing “bye”
...
main()
{

168

C P ROGRAMS

WITH

SOLUTIONS

int i=5;
printf(“%d”,i=++i ==6);
}
Answer:
1
Explanation:
The expression can be treated as i = (++i==6), because == is of higher precedence
than = operator
...
Hence the
result
...
main()
{
char p[ ]=“%d\n”;
p[1] = ‘c’;
printf(p,65);
}
Answer:
A
Explanation:
Due to the assignment p[1] = ‘c’ the string becomes, “%c\n”
...

128
...
(a)
...
(b)
...
the return type of the function is void
...

129
...
So “some” and
“some\0” are equivalent
...

130
...

Explanation:
If a string constant is initialized explicitly with characters, ‘\0’ is not appended
automatically to the string
...
So str1 and str2 are not the same, hence the result
...
main()
{
int i = 3;
for (;i++=0;) printf(“%d”,i);
}
Answer:
Compiler Error: Lvalue required
...


170

C P ROGRAMS

WITH

SOLUTIONS

132
...

133
...
Inside the while loop the conditional operator evaluates
to false, executing i--
...
The while condition becomes false and hence, comes out of the while loop,
printing the i value
...
main()
{
int i=10,j=20;
j = i, j?(i,j)?i:j:j;
printf(“%d %d”,i,j);
}

C DEBUGGING

171

Answer:
10 10
Explanation:
The Ternary operator ( ? : ) is equivalent for if-then-else statement
...
1
...
char* const a;
3
...

Answer:
1
...
‘const’ applies to ‘a’ rather than to the value of a (constant pointer to char )
*a=‘F’

: legal

a=“Hi”

: illegal

3
...

136
...
i is 5
...
Hence the result
...
main()
{
int i=4,j=7;
j = j || i++ && printf(“YOU CAN”);
printf(“%d %d”, i, j);
}
Answer:
41
Explanation:
The boolean expression needs to be evaluated only till the truth value of the
expression is not known
...
Because it is followed by || and true || (anything) => true where (anything)
will not be evaluated
...

Similarly when && operator is involved in an expression, when any of the operands
become false, the whole expression’s truth value becomes false and hence the remaining
expression will not be evaluated
...

138
...


C DEBUGGING

173

139
...
5;
switch(i)
{
case 1: printf(“1”);
case 2: printf(“2”);
default : printf(“0”);
}
}
Answer:
Compiler Error: switch expression not integral
Explanation:
Switch statements can be applied only to integral types
...
main()
{
extern i;
printf(“%d\n”,i);
{
int i=20;
printf(“%d\n”,i);
}
}
Answer:
Linker Error : Unresolved external symbol i
Explanation:
The identifier i is available in the inner block and so using extern has no use in resolving
it
...
main()
{
int a=2,*f1,*f2;
f1=f2=&a;
*f2+=*f2+=a+=2
...
So changes through f1 and f2
ultimately affects only the value of a
...
main()
{
char *p=“GOOD”;
char a[ ]=“GOOD”;
printf(“\n sizeof(p) = %d, sizeof(*p) = %d, strlen(p) = %d”, sizeof(p),
sizeof(*p), strlen(p));
printf(“\n sizeof(a) = %d, strlen(a) = %d”, sizeof(a), strlen(a));
}
Answer:
sizeof(p) = 2, sizeof(*p) = 1, strlen(p) = 4
sizeof(a) = 5, strlen(a) = 4
Explanation:
sizeof(p) => sizeof(char*) => 2
sizeof(*p) => sizeof(char) => 1
Similarly,
sizeof(a) => size of the character array => 5
When sizeof operator is applied to an array it returns the sizeof the array and it is
not the same as the sizeof the pointer variable
...

143
...
The macro expands to
sizeof(arr)/sizeof(int) => 10 * sizeof(int) / sizeof(int) => 10
...
int DIM(int array[])
{
return sizeof(array)/sizeof(int );
}
main()
{
int arr[10];
printf(“The dimension of the array is %d”, DIM(arr));
}
Answer:
1
Explanation:
Arrays cannot be passed to functions as arguments and only the pointers can be passed
...
The return statement becomes, sizeof(int *)/ sizeof(int)
that happens to be equal in this case
...
main()
{
static int a[3][3]={1,2,3,4,5,6,7,8,9};
int i,j;
static *p[]={a,a+1,a+2};
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf(“%d\t%d\t%d\t%d\n”,*(*(p+i)+j),
*(*(j+p)+i),*(*(i+p)+j),*(*(p+j)+i));
}
}

176

C PROGRAMS

WITH

SOLUTIONS

Answer:
1

1

1

1

2

4

2

4

3

7

3

7

4

2

4

2

5

5

5

5

6

8

6

8

7

3

7

3

8

6

8

6

9

9

9

9

Explanation:
*(*(p+i)+j) is equivalent to p[i][j]
...
main()
{
void swap();
int x=10,y=8;
swap(&x,&y);
printf(“x=%d y=%d”,x,y);
}
void swap(int *a, int *b)
{
*a ^= *b, *b ^= *a, *a ^= *b;
}
Answer:
x=10 y=8
Explanation:
Using ^ like this is a way to swap two variables without using a temporary variable and
that too in a single statement
...
So this doesn’t issue a compiler
error by the call swap(&x,&y); that has two arguments
...
In that style, the swap function will be
defined as follows,

C DEBUGGING

177

void swap()
int *a, int *b
{
*a ^= *b, *b ^= *a, *a ^= *b;
}
where the arguments follow the ()
...

147
...

148
...
Remember
that the INTEL machines are ‘small-endian’ machines
...
The integer value 258 is stored in memory as:
00000001 00000010
...
main()
{
int i=300;
char *ptr = &i;
*++ptr=2;
printf(“%d”,i);
}
Answer:
556
Explanation:
The integer value 300 in binary notation is: 00000001 00101100
...
Result of the expression *++ptr = 2 makes the
memory representation as: 00101100 00000010
...

150
...
h>
main()
{
char * str = “hello”;
char * ptr = str;
char least = 127;
while (*ptr++)
least = (*ptrprintf(“%d”,least);
}
Answer:
0
Explanation:
After ‘ptr’ reaches the end of the string the value pointed by ‘str’ is ‘\0’
...
So the value of ‘least’ finally is 0
...
Declare an array of N pointers to functions returning pointers to functions returning pointers
to characters?
Answer:
(char*(*)( )) (*ptr[N])( );

C DEBUGGING

179

152
...
rollno, &student
...
day, &student
...
month,
&student
...
year);
}
Answer:
Compiler Error: Undefined structure date
Explanation:
Inside the struct definition of ‘student’ the member of type struct date is given
...

153
...
rollno, &student
...
day, &student
...
month,
&student
...
year);
}

180

C PROGRAMS

WITH

SOLUTIONS

Answer:
Compiler Error: Undefined structure date
Explanation:
Only declaration of struct date is available inside the structure definition of ‘student’
but to have a variable of type struct date the definition of the structure is required
...
There were 10 records stored in “somefile
...

What went wrong?
void main()
{
struct student
{
char name[30], rollno[6];
}stud;
FILE *fp = fopen(“somefile
...
name);
}
}
Explanation:
fread reads 10 records and prints the names successfully
...
So it
prints the last record again
...

155
...
int foo(int *arr[]) and
2
...
The numbers that are allowed inside
the [] is just for more readability
...


C DEBUGGING

181

156
...
So p remains NULL
where *p =0 may result in problem (may rise to runtime error “NULL pointer assignment”
and terminate the program)
...
What is wrong with the following code?
int *foo()
{
int *s = malloc(sizeof(int)100);
assert(s != NULL);
return s;
}
Answer & Explanation:
assert macro should be used for debugging and finding out bugs
...
A plain if and the
corresponding remedy statement has to be given
...
What is the hidden bug with the following statement?
assert(val++ != 0);
Answer & Explanation:
assert macro is used for debugging and removed in release version
...
So the behavior of the code becomes different in
case of debug version and the release version thus leading to a subtle bug
...


182

C PROGRAMS

WITH

SOLUTIONS

159
...
This type of pointer in which the
non-availability of the implementation of the referenced location is known as ‘incomplete
type’
...
#define assert(cond) if(!(cond)) \
(fprintf(stderr, “assertion failed: %s, file %s, line %d \n”,#cond,\
__FILE__,__LINE__), abort())
void main()
{
int i = 10;
if(i==0)
assert(i < 100);
else
printf(“This statement becomes else for if in assert macro”);
}
Answer:
No output
Explanation:
The else part in which the printf is there becomes the else for if in the assert macro
...

The solution is to use conditional operator instead of if statement,
#define assert(cond) ((cond)?(0): (fprintf (stderr, “assertion failed: \ %s, file %s, line
%d \n”,#cond, __FILE__,__LINE__), abort()))

C DEBUGGING

183

Note:
However this problem of “matching with nearest else” cannot be solved by the usual
method of placing the if statement inside a block like this,
#define assert(cond) { \
if(!(cond)) \
(fprintf(stderr, “assertion failed: %s, file %s, line %d \n”,#cond,\
__FILE__,__LINE__), abort()) \
}
161
...
Because this will cause the structure declaration to be recursive without end
...
Is the following code legal?
struct a
{
int x;
struct a *b;
}
Answer:
Yes
...
The compiler knows, the size of the
pointer to a structure even before the size of the structure is determined(as you know
the pointer to any type is of same size)
...


184

C PROGRAMS

WITH

SOLUTIONS

163
...

164
...

165
...
This is known as ‘incomplete types’
...
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 *));
}
Answer:
sizeof (void *) = 2
sizeof (int *) = 2
sizeof (double *) = 2
sizeof(struct unknown *) = 2
Explanation:
The pointer to any type is of same size
...
char inputString[100] = {0};
To get string input from the keyboard which one of the following is better?
1) gets(inputString)
2) fgets(inputString, sizeof(inputString), fp)
Answer & Explanation:
The second one is better because gets(inputString) doesn’t know the size of the string
passed and so, if a very big input (here, more than 100 chars) the charactes will be
written past the input string
...

168
...
If the str contains any format characters like %d then it will result
in a subtle bug
...
void main()
{
int i=10, j=2;
int *ip= &i, *jp = &j;
int k = *ip/*jp;
printf(“%d”,k);
}
Answer:
Compiler Error: “Unexpected end of file in comment started in line 5”
...
To force what is intended by the programmer,
int k = *ip/ *jp;
// give space explicity separating / and *
//or
int k = *ip/(*jp);
// put braces to force the intention will solve the problem
...
void main()
{
char ch;
for(ch=0;ch<=127;ch++)
printf(“%c %d \n”, ch, ch);
}
Answer:
Implementaion dependent
Explanation:
The char type may be signed or unsigned by default
...
Thus ch is always smaller than 127
...
Is this code legal?
int *ptr;
ptr = (int *) 0x400;
Answer:
Yes
Explanation:
The pointer ptr will point at the integer in the memory location 0x400
...
main()
{
char a[4]=“HELLO”;
printf(“%s”,a);
}
Answer:
Compiler error: Too many initializers
Explanation:
The array a is of size 4 but the string constant requires 6 bytes to get stored
...
main()
{
char a[4]=“HELL”;
printf(“%s”,a);
}
Answer:
HELL%@!~@!@???@~~!
Explanation:
The character array has the memory just enough to hold the string “HELL” and doesnt
have enough space to store the terminating null character
...

174
...
No pointer arithmetic can be done
on it and you cannot apply indirection operator (*) on void pointers
...
main()
{
extern int i;
{

int i=20;
{
const volatile unsigned i=30; printf(“%d”,i);
}
printf(“%d”,i);
}
printf(“%d”,i);
}
int i;

176
...

Answer:
Variable length argument lists
177
...

178
...

Explanation:
Both the functions suffer from the problem of dangling pointers
...
This is created dynamically as the function is called, so is also
deleted dynamically on exiting the function so the string data is not available in the
calling function main() leading to print some garbage values
...

179
...
com”;
char *k2;
k2=(char*)malloc(20);
memset (k2, 0, 20);
while(*k2++ = *k1++);
printf(“%s\n”,k2);
}
Answer: empty string
...
What will be printed as the result of the operation below?
main()
{
int a=20,b=35;
a=b++ + a++;
b= ++b + ++a;
printf(“%d%d\n”,a,b);
}
Answer: 5794
181
...
What will be printed as the result of the operation below?
#define swap(a,b) a=a+b;b=a-b;a=a-b;
void main()
{
int m=5, n=10;

C DEBUGGING
swap (m,n);
printf(“%d %d\n”,m,n);
swap2(m,n);
printf(“%d %d\n”,m,n);
}
int swap2(int x, int y)
{
int temp;
temp=x;
y=x;
x=temp;
return 0;
}
Answer: 10, 5
10, 5
183
...
What will be printed as the result of the operation below?
main()
{
char s1[]=“SC”;
char s2[]= “Systems”;

191

192

C PROGRAMS

WITH

SOLUTIONS

printf(“%s”,s1);
}
Answer: SC
185
...
The following variable is available in file1
...
c can access the variable
...
What will be the result of the following code?
#define TRUE 0 // some code
while(TRUE)
{
// some code
}
Answer: This will not go into the loop as TRUE is defined as 0
...
What will be printed as the result of the operation below?
int x;
int modifyvalue()

C DEBUGGING
{
return(x+=10);
}
int changevalue(int x)
{
return(x+=1);
}
void main()
{
int x=10;
x++;
changevalue(x);
x++;
modifyvalue();
printf(“First output:%d\n”,x);
x++;
changevalue(x);
printf(“Second output:%d\n”,x);
modifyvalue();
printf(“Third output:%d\n”,x);
}
Answer: 12 , 13 , 13
189
...
How many times main is get called?
main()
{
printf(“Jumboree”);
main();
}
Answer: Till stack overflow
191
...
h>
main()
{
int *p,*q,i;
p=(int *)100;
q=(int *)200;
i=q-p;
printf(“%d”,i);
}
a) 100 b) 25 c) 0

d) compile error

Answer : b) 25
192
...
h>
#define swap(a,b) temp=a,a=b,b=temp;
main()
{
int a=5,b=6;
int temp;
if(a>b)
swap(a,b);
printf(“a=%d,b= %d”,a,b);
}

C DEBUGGING
a) a=5 b=6 b) a=6 b=5 c) a=0 b=6 d) None
Answer: a) a=5 b=6
193
...
h>
main()
{
unsigned char i;
for( i=0;i<300;i++)
{
printf(“*”);
}
}
a)299 b)300 c)infinite

d)none

Answer: c) (infinite)
194
...
h>
main()
{
int n=2;
int sum=5;
switch(n)
{
case 2:sum=sum-2;
break;
case 3:sum*=5;
break;
default :sum=0;
}
printf(“%d”,sum);
}
a)15 b)0 c)6
Answer: a) 15

d)none

195

196

C PROGRAMS

WITH

SOLUTIONS

195
...
h>
main()
{
int a=10,b=5;
if(a=a&b)
b=a^b;
printf(“a=%d,b=%d”,a,b);
}
a)a=0,b=5 b)a=10 b=5

c)a=0,b=0 d)none

Answer: a) a=0,b=5
196
...
h>
main()
{
int a[5],i,*ip;
for(i=0;i<5;i++)
a[i]=i;
ip=a;
printf(“%d”,*(ip+3*sizeof(int)));
}
a)0

b)5 c)1 d)none

Answer: d) none
197
...
h>
main()
{
struct
{
char a;
short b;
int c;
}temp;

C DEBUGGING

197

}
a)7 b)8 c)12

d)120

Answer: b)8
198
...

Answer:

void *(*f)(char *)

199
...
Find the output of the following program
...
2f”,a);
}
a) 0
...
0
c) 0
...
5
Answer: a) 0
...
Find the output of the following program
...
Find the output of the following program
...
Find the output of the following program
...
7f ”,v());
}
a) 0
...
00
c) Error
d) None
Answer: a) 0
...
Find the output of the following program
...
Find the output of the following program
...
Find the output of the following program
...
Find the output of the following program
...
Find the output of the following program
...
What will be the output?
void main()
{
do
{

C DEBUGGING
if(0)
main();
printf(“Thaal”);
}while(0);
}
a) Thaal
b) Infinite Loop
c) Syntax error
d) Nothing get printed
Answer: a) Thaal
210
...
14*x*x)
main()
{float r1=6
...
5,a;
a=AREA(r1);
printf(“\n Area of the circle is %f ”, a);
a=AREA(r2);
printf(“\n Area of the circle is %f ”, a);
}
What is the output?
Answer: Area of the circle is 122
...
625000
211
...
What will be the output?
void main()
{

201

202

C PROGRAMS

WITH

SOLUTIONS

int i;
for(i=1;i<4,i++)
switch(i)
case 1: printf(“%d”,i);break;
{
case 2:printf(“%d”,i);break;
case 3:printf(“%d”,i);break;
}
switch(i) case 4:printf(“%d”,i);
}
Answer: 1,2,3,4
213
...
What will be the output?
void main()
{
unsigned i=1; /* unsigned char k= -1 => k=255; */
signed j=-1; /* char k= -1 => k=65535 */
/* unsigned or signed int k= -1 =>k=65535 */
if(iprintf(“less”);
else
if(i>j)
printf(“greater”);
else
if(i==j)
printf(“equal”);
}
Answer: less

C DEBUGGING

203

215
...
1000000
2
...
Error
4
...
A structure pointer is defined of the type time
...

Write the way to initialize the 2nd element to 10
...
What will be the output?
void main()
{
int i=7;
printf(“%d”,i++*i++);
}
Answer: 56
218
...

219
...
What will be the output?
#define one 0
#ifdef one
printf(“one is defined ”);
#ifndef one
printf(“one is not defined ”);
Answer: “one is defined”
221
...
What is alloca()?
Answer: It allocates and frees memory after use/after getting out of scope
...
What will be the output?
main()
{
static i=3;
printf(“%d”,i--);
return i>0 ? main():0;
}
Answer: 321
224
...

225
...
What will be the output?
main()
{int i=0;
for(i=0;i<20;i++)
{switch(i)
case 0:i+=5;
case 1:i+=2;
case 5:i+=5;
default i+=4;
break;}
printf(“%d,”,i);
}
}
a) 0,5,9,13,17
b) 5,9,13,17
c) 12,17,22
d) 16,21
e) Syntax error
Answer: (d)
227
...
What will the following program do?
void main()
{
int i;
char a[]=“String”;
char *p=“New Sring”;
char *Temp;
Temp=a;
a=malloc(strlen(p) + 1);
strcpy(a,p); //Line number:9//
p = malloc(strlen(Temp) + 1);
strcpy(p,Temp);
printf(“(%s, %s)”,a,p);
free(p);
free(a);
} //Line number 15//
a) Swap contents of p & a and print:(New string, string)

207

208

C PROGRAMS

WITH

SOLUTIONS

b) Generate compilation error in line number 8
c) Generate compilation error in line number 5
d) Generate compilation error in line number 7
e) Generate compilation error in line number 1
Answer: (b)
229
...
What will be the result of the following program ?
char *gxxx()
{static char xxx[1024];
return xxx;
}
main()
{char *g=“string”;
strcpy(gxxx(),g);
g = gxxx();
strcpy(g,“oldstring”);
printf(“The string is : %s”,gxxx());
}

C DEBUGGING
a) The string is : string
b) The string is : Oldstring
c) Run time error/Core dump
d) Syntax error during compilation
e) None of these
Answer: (b)
231
...

main()
{
char *p1=“Name”;
char *p2;
p2=(char *)malloc(20);
while(*p2++=*p1++);
printf(“%s\n”,p2);
}
Answer: An empty string
232
...

main()
{
int x=20,y=35;
x = y++ + x++;
y = ++y + ++x;
printf(“%d %d\n”,x,y);
}
Answer: 57 94
233
...

main()
{
int x=5;
printf(“%d %d %d\n”,x,x<<2,x>>2);
}
Answer: 5 20 1

209

210

C PROGRAMS

WITH

SOLUTIONS

234
...

#define swap1(a,b) a=a+b;b=a-b;a=a-b;
main()
{
int x=5,y=10;
swap1(x,y);
printf(“%d %d\n”,x,y);
swap2(x,y);
printf(“%d %d\n”,x,y);
}
int swap2(int a,int b)
{
int temp;
temp=a;
b=a;
a=temp;
return;
}
Answer: 10 5
235
...

main()
{
char *ptr = “Ramco Systems”;
(*ptr)++;
printf(“%s\n”,ptr);
ptr++;
printf(“%s\n”,ptr);
}
Answer: Samco Systems
236
...

#include ...

237
...

#include ...
Find the output for the following C program given that
[1]
...
c static int average_float;
Answer: All the functions in the file1
...

239
...

# define TRUE 0
some code
while(TRUE)
{
some code
}
Answer: This won’t go into the loop as TRUE is defined as 0
...
struct list
{
int x;
struct list *next;
}*head;
the struct head
...
What is the output of the following ?
main( )
{ int i;
i=1;
i=i+2*i++;
printf(%d,i);
}
Answer: 4
242
...
But It will over writes on same file
...
What will be the output?
#define MAN(x,y) (x)>(y)?(x):(y)
{int i=10;

C DEBUGGING

213

j=5;
k=0;
k=MAX(i++,++j);
printf(%d %d %d %d,i,j,k);
}
Answer: 10 5 0
244
...
With every use of a memory allocation function, what function should be used to release
allocated memory which is no longer needed?
Choice 1 unalloc()
Choice 2 dropmem()
Choice 3 dealloc()
Choice 4 release()
Choice 5 free() [Ans]

246
...
char* myFunc (char *ptr)
{
ptr += 3;
return (ptr);
}
int main()
{
char *x, *y;
x = “HELLO”;
y = myFunc (x);
printf (“y = %s \n”, y);
return 0;
}
What will print when the sample code above is executed?
Choice 1 y = HELLO
Choice 2 y = ELLO
Choice 3 y = LLO
Choice 4 y = LO [Ans]
Choice 5 x = O
248
...
*/

for (nPtr=sPtr; nPtr; nPtr=nPtr->next)
{
free(nPtr);
}
The sample code above releases memory from a linked list
...

Choice 2 It may fail since each node “nPtr” is freed before its next address can be
accessed
...
next”
...

Choice 5 The loop will never end
...
What function will read a specified number of elements from a file?
Choice 1 fileread()
Choice 2 getline()
Choice 3 readfile()
Choice 4 fread()(Ans)
Choice 5 gets()
...
“My salary was increased by 15%!”
Select the statement which will EXACTLY reproduce the line of text above
...
What is a difference between a declaration and a definition of a variable?
Choice 1
Both can occur multiple times, but a declaration must occur first
...

Choice 3
A definition occurs once, but a declaration may occur many times
...
[Ans]
Choice 5
Both can occur multiple times, but a definition must occur first
...
int testarray[3][2][2] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
What value does testarray[2][1][0] in the sample code above contain?
Choice 1 3
Choice 2 5
Choice 3 7
Choice 4 9
Choice 5 11[Ans]
...
int a=10,b;
b=a++ + ++a;
printf(“%d,%d,%d,%d”,b,a++,a,++a);
What will be the output when following code is executed?
Choice 1 12,10,11,13
Choice 2 22,10,11,13
Choice 3 22,11,11,11
Choice 4 12,11,11,11
Choice 5 22,13,13,13[Ans]
...
int x[] = { 1, 4, 8, 5, 1, 4 };
int *ptr, y;
ptr = x + 4;
y = ptr - x;
What does y in the sample code above equal?
Choice 1 -3
Choice 2 0
Choice 3 4[Ans]

C DEBUGGING
Choice 4 4 + sizeof( int )
Choice 5 4 * sizeof( int )
255
...
11 ^ 5
What does the operation shown above produce?
Choice 1 1
Choice 2 6
Choice 3 8
Choice 4 14 [Ans]
Choice 5 15
...
#define MAX_NUM 15
Referring to the sample above, what is MAX_NUM?
Choice 1 MAX_NUM is an integer variable
...


217

218

C PROGRAMS

WITH

SOLUTIONS

Choice 3 MAX_NUM is a precompiler constant
...
[Ans]
Choice 5 MAX_NUM is an integer constant
...
Which one of the following will turn off buffering for stdout?
Choice 1 setbuf( stdout, FALSE );
Choice 2 setvbuf( stdout, NULL );
Choice 3 setbuf( stdout, NULL ); [Ans]
Choice 4 setvbuf( stdout, _IONBF );
Choice 5 setbuf( stdout, _IONBF );
259
...
bin”, “b” );
FILE *f = fopenb( “test
...
bin”, “wb” );
FILE *f = fwriteb( “test
...
bin”, “bw” ); [Ans]

260
...
int x = 2 * 3 + 4 * 5;
What value will x contain in the sample code above?
Choice 1 22
Choice 2 26[Ans]
Choice 3 46
Choice 4 50
Choice 5 70
262
...
Which one of the following
correctly analyzes it?
Choice 1 If the arguments to memcpy() refer to overlapping regions, the destination
buffer will be subject to memory corruption
...

Choice 3 The memory obtained from alloca() is not valid in the context of the caller
...
[Ans]
Choice 4 size_t is not a Standard C defined type and may not be known to the compiler
...
Functions cannot be defined using
this syntax
...
int var1;
If a variable has been declared with file scope, as above, can it safely be accessed globally
from another file?
Choice 1 Yes; it can be referenced through the register specifier
...

Choice 3 No; it would need to have been initially declared using the global
keyword
...

Choice 5 Yes; it can be referenced through the extern specifier
...
time_t t;
Which one of the following statements will properly initialize the variable t with the current
time from the sample above?
Choice 1 t = clock();[Ans]
Choice 2 time( &t );
Choice 3 t = ctime();
Choice 4 t = localtime();
Choice 5 None of the above
265
...
C is which kind of language?
Choice 1 Machine
Choice 2 Procedural[Ans]
Choice 3 Assembly
Choice 4 Object-oriented
Choice 5 Strictly-typed
267
...
int x = 0;
for (x=1; x<4; x++);
printf(“x=%d\n”, x);
What will be printed when the sample code above is executed?
Choice 1 x=0
Choice 2 x=1
Choice 3 x=3
Choice 4 x=4[Ans]
Choice 5 x=5
269
...
char *ptr;
char myString[] = “abcdefg”;
ptr = myString;
ptr += 5;
What string does ptr point to in the sample code above?
Choice 1 fg [Ans]/*because string*/
Choice 2 efg

221

222

C PROGRAMS

WITH

SOLUTIONS

Choice 3 defg
Choice 4 cdefg
Choice 5 None of the above
271
...
5, y = 3
...
0f : %
...
0f : %
...
2=4 floor =>rounds down 3
...
Which one of the following will declare a pointer to an integer at address 0x200 in memory?
Choice 1 int *x; *x = 0x200;[Ans]
Choice 2 int *x = &0x200;
Choice 3 int *x = *0x200;
Choice 4 int *x = 0x200;
Choice 5 int *x( &0x200 );
273
...
x = 3, counter = 0;
while ((x-1))
{
++counter;
x--;
}
Referring to the sample code above, what value will the variable counter have when
completed?
Choice 1 0
Choice 2 1
Choice 3 2[Ans]
Choice 4 3
Choice 5 4
275
...
Which one of the following definitions and initializations of p
is valid?
Choice 1 char ** (* p) [12][12] = array; [Ans]
Choice 2 char ***** p = array;
Choice 3 char * (* p) [12][12][12] = array;
Choice 4 const char ** p [12][12][12] = array;
Choice 5 char (** p) [12][12] = array;
276
...
All of the following choices represent syntactically correct function definitions
...
struct customer *ptr = malloc( sizeof( struct customer ) );
Given the sample allocation for the pointer "ptr" found above, which one of the following
statements is used to reallocate ptr to be an array of 10 elements?
Choice 1 ptr = realloc( ptr, 10 * sizeof( struct customer)); [Ans]
Choice 2 realloc( ptr, 9 * sizeof( struct customer ) );
Choice 3 ptr += malloc( 9 * sizeof( struct customer ) );
Choice 4 ptr = realloc( ptr, 9 * sizeof( struct customer ) );
Choice 5 realloc( ptr, 10 * sizeof( struct customer ) );
279
...

Choice 2 A pointer of type void * can be used to directly examine or modify an object
of any type
...

Choice 4 A C program knows the types of its pointers and indirectly referenced data
items at runtime
...


226

C PROGRAMS

WITH

SOLUTIONS

280
...
short testarray[4][3] = { {1}, {2, 3}, {4, 5, 6} };
printf( “%d\n”, sizeof( testarray ) );
Assuming a short is two bytes long, what will be printed by the above code?
Choice 1 It will not compile because not enough initializers are given
...
char buf [] = “Hello world!”;
char * buf = “Hello world!”;
In terms of code generation, how do the two definitions of buf, both presented above, differ?
Choice 1 The first definition certainly allows the contents of buf to be safely modified at
runtime; the second definition does not
...

Choice 3 The first definition is not legal because it does not indicate the size of the array
to be allocated; the second definition is legal
...
[Ans]
Choice 5 The first definition does not allocate enough space for a terminating NULL
character, nor does it append one; the second definition does
...
In a C expression, how is a logical AND represented?
Choice 1 @@
Choice 2 ||
Choice 3
...

Choice 4 && [Ans]
Choice 5
...
How do printf()’s format specifiers %e and %f differ in their treatment of floating-point
numbers?
Choice 1 %e always displays an argument of type double in engineering notation; %f
always displays an argument of type double in decimal notation
...

Choice 3 %e displays a double in engineering notation if the number is very small or
very large
...

Choice 4 %e displays an argument of type double with trailing zeros; %f never displays
trailing zeros
...
%e is left over from K&R C; Standard C prefers %f for new code
...
Which one of the following Standard C functions can be used to reset end-of-file and error
conditions on an open stream?
Choice 1 clearerr()
Choice 2 fseek()(Ans)
Choice 3 ferror()
Choice 4 feof()
Choice 5 setvbuf()
286
...
#include ...

Choice 2 It will print out: i=9
...

Choice 4 It will print out: i=11
...
[Ans]
288
...

Choice 2 There will be a memory leak
...

Choice 4 Not enough space is allocated by the malloc
...

289
...
Which one of the following C operators is right associative?
Choice 1 = [Ans]
Choice 2 ,
Choice 3 []
Choice 4 ^
Choice 5 ->
291
...

Choice 2 It indicates that a variable's memory will automatically be preserved
...

Choice 4 It automatically initializes a variable to NULL
...


230

C PROGRAMS

WITH

SOLUTIONS

292
...
h in a C source file?
Choice 1 #include ...
h”
Choice 3 #includefile
Choice 4 #include sysheader
...
h>
293
...
4e
Choice 2 %4
...
30f
Choice 4 %-30
...
4f
294
...
According to the Standard C specification, what are the respective minimum sizes (in bytes)
of the following three data types: short; int; and long?
Choice 1 1, 2, 2
Choice 2 1, 2, 4
Choice 3 1, 2, 8

C DEBUGGING
Choice 4 2, 2, 4[Ans]
Choice 5 2, 4, 8
296
...

297
...
char txt [20] = “Hello world!\0”;
How many bytes are allocated by the definition above?
Choice 1 11 bytes
Choice 2 12 bytes
Choice 3 13 bytes
Choice 4 20 bytes[Ans]
Choice 5 21 bytes
299
...
2f\n”, z);
What will print when the sample code above is executed?
Choice 1 z=0
...
00[Ans]
Choice 3 z=1
...
00
Choice 5 z=NULL
300
...
int a [8] = { 0, 1, 2, 3 };
The definition of a above explicitly initializes its first four elements
...
The
compiler writer has the freedom to decide how the remaining elements will be
handled
...
[Ans]
Choice 3 It is illegal to initialize only a portion of the array
...

Choice 4 As with an enum, the compiler assigns values to the remaining elements by
counting up from the last explicitly initialized element
...

Choice 5 They are left in an uninitialized state; their values cannot be relied upon
...
Which one of the following is a true statement about pointers?
Choice 1 They are always 32-bit values
...
(Ans)
Choice 3 With the exception of generic pointers, similarly typed pointers may be
subtracted from each other
...

Choice 5 With the exception of generic pointers, similarly typed pointers may be added
to each other
...
Which one of the following statements allocates enough space to hold an array of 10 integers
that are initialized to 0?
Choice 1 int *ptr = (int *) malloc(10, sizeof(int));
Choice 2 int *ptr = (int *) calloc(10, sizeof(int));
Choice 3 int *ptr = (int *) malloc(10*sizeof(int)); [Ans]
Choice 4 int *ptr = (int *) alloc(10*sizeof(int));
Choice 5 int *ptr = (int *) calloc(10*sizeof(int));
304
...
u32 X (f32 f)
{
union {
f32 f;
u32 n;
} u;
u
...
n;
}
Given the function X(), defined above, assume that u32 is a type-definition indicative of a 32bit unsigned integer and that f32 is a type-definition indicative of a 32-bit floating-point number
...

Choice 2 X() effectively performs a standard typecast and converts f to a roughly
equivalent integer
...

Choice 4 Since u
...
This function is
therefore a primitive pseudorandom number generator
...
n is automatically initialized to zero (0) by the compiler, X() is an
obtuse way of always obtaining a zero (0) value
...
long factorial (long x)
{
????
return x * factorial(x - 1);
}
With what do you replace the ???? to make the function shown above return the correct
answer?
Choice 1 if (x == 0) return 0;
Choice 2 return 1;
Choice 3 if (x >= 2) return 2;
Choice 4 if (x == 0) return 1;
Choice 5 if (x <= 1) return 1; [Ans]{more probable}
307
...
*/
void increment_ints (int p [/*n*/], int n)
{
assert(p != NULL); /* Ensure that ‘p’ isn't a null pointer
...
*/
while (n) /* Loop over ‘n’ elements of ‘p’
...
*/

p++, n--;

/* Increment p, decrement n
...
Despite its significant inline
commentary, it contains an error
...

Choice 2 An array is a nonmodifiable lvalue, so p cannot be incremented directly
...

Choice 3 *p++ causes p to be incremented before the dereference is performed, because
the autoincrement operator has higher precedence than the indirection
operator
...
The condition
should be n != 0
...
The subscript n should be
removed from the definition of the parameter p
...
How is a variable accessed from another file?
Choice 1 The global variable is referenced via the extern specifier
...

Choice 3 The global variable is referenced via the global specifier
...

Choice 5 The global variable is referenced via the ext specifier
...
When applied to a variable, what does the unary “&” operator yield?
Choice 1 The variable’s value
Choice 2 The variable’s binary form
Choice 3 The variable’s address [Ans]
Choice 4 The variable’s format
Choice 5 The variable’s right value
310
...
h */
#if

defined(__STDC__) || defined(__cplusplus)

#define __P(protos) protos
#else
#define __P(protos) ()
#endif
/* stdio
...
h>
div_t div __P((int, int));

236

C PROGRAMS

WITH

SOLUTIONS

The code above comes from header files for the FreeBSD implementation of the C library
...
It should be removed from further releases of the C library
...

Choice 3 Identifiers that begin with two underscores are reserved for C library
implementations
...

Choice 4 The __P() macro provides backward compatibility for K&R C compilers,
which do not recognize Standard C prototypes
...

311
...
int read_long_string (const char ** const buf) {
char * p = NULL;
const char * fwd = NULL;
size_t len = 0;
assert(buf);
do
{
p = realloc(p, len += 256);
if (!p)
return 0;
if (!fwd)
fwd = p;
else
fwd = strchr(p, ‘\0’);

C DEBUGGING

237

} while (fgets(fwd, 256, stdin));
*buf = p;
return 1;
}
The function read_long_string(), defined above, contains an error that may be particularly
visible under heavy stress
...

Choice 2 If the null pointer for char is not zero-valued on the host machine, the implicit
comparisons to zero (0) may introduce undesired behavior
...

Choice 3 The symbol stdin may not be defined on some ANCI C compliant systems
...
(Ans)
Choice 5 If the call to realloc() fails during any iteration but the first, all memory
previously allocated by the loop is leaked
...
FILE *f = fopen( fileName, “r” );
readData( f );
if( ???? )
{
puts( “End of file was reached” );
}
Which one of the following can replace the ???? in the code above to determine if the end of
a file has been reached?
Choice 1 f == EOF[Ans]
Choice 2 feof( f )
Choice 3 eof( f )
Choice 4 f == NULL
Choice 5 !f
314
...

Which one of the following correctly completes the sentence above?
Choice 1 Deprecated by Standard C
Choice 2 Internal to the current translation unit

238

C PROGRAMS

WITH

SOLUTIONS

Choice 3 Visible to all translation units
Choice 4 Read-only subsequent to initialization
Choice 5 Allocated on the heap[Ans]
double read_double (FILE * fp) {
double d;
assert(fp != NULL);
fscanf(fp, “ %lf ”, d);
return d;
}
The code above contains a common error
...

Choice 2 The format specifier %lf indicates that the corresponding argument should be
long double rather than double
...

Choice 4 The format specifier %lf is recognized by fprintf() but not by fscanf()
...

315
...
According to Standard C, what is the type of an unsuffixed floating-point literal, such as
123
...
Which one of the following is true for identifiers that begin with an underscore?
Choice 1 They are generally treated differently by preprocessors and compilers from
other identifiers
...
(Ans)
Choice 3 They are reserved for usage by standards committees, system implementers,
and compiler engineers
...

Choice 5 They are deprecated by Standard C and are permitted only for backward
compatibility with older C libraries
...
Which one of the following is valid for opening a read-only ASCII file?
Choice 1 fileOpen (filenm, “r”);
Choice 2 fileOpen (filenm, “ra”);
Choice 3 fileOpen (filenm, “read”);
Choice 4 fopen (filenm, “read”);
Choice 5 fopen (filenm, “r”);[Ans]
319
...
If there is a need to see output as soon as possible, what function will force the output from
the buffer into the output stream?
Choice 1 flush()
Choice 2 output()(Ans)
Choice 3 fflush()
Choice 4 dump()
Choice 5 write()

240

C PROGRAMS

WITH

SOLUTIONS

321
...
void crash (void)
{
printf(“got here”);
*((char *) 0) = 0;
}
The function crash(), defined above, triggers a fault in the memory management hardware
for many architectures
...
This may explain why printf() apparently fails
...
(Ans)
Choice 3 printf() always buffers output until a newline character appears in the buffer
...

Choice 4 There is insufficient information to determine why the output fails to appear
...

Choice 5 printf() expects more than a single argument
...
puts() should be used instead
...
char * dwarves [] = {
“Sleepy”,
“Dopey” “Doc”,
“Happy”,
“Grumpy” “Sneezy”,

C DEBUGGING

241

“Bashful”,
};
How many elements does the array dwarves (declared above) contain? Assume the C
compiler employed strictly complies with the requirements of Standard C
...
Which one of the following can be used to test arrays of primitive quantities for strict equality
under Standard C?
Choice 1 qsort()
Choice 2 bcmp() [Ans]
Choice 3 memcmp()
Choice 4 strxfrm()
Choice 5 bsearch()
325
...
) {
extern FILE * logfile;
va_list args;
assert(fmt);
args = va_arg(fmt, va_list);
return vfprintf(logfile, fmt, args);
}
The function debug(), defined above, contains an error
...
In accordance with Standard C, the
declaration of args should be moved into the parameter list, and the K&R C
macro va_arg() should be deleted from the code
...

Choice 3 Library routines that accept argument lists cause a fault on receipt of an empty
list
...

Choice 4 The argument list args has been improperly initialized
...

326
...
char * get_rightmost (const char * d)
{
char rightmost [MAXPATHLEN];
const char * p = d;
assert(d != NULL);
while (*d != ‘\0’)
{
if (*d == ‘/’)
p = (*(d + 1) != ‘\0’) ? d + 1 : p;
d++;
}
memset(rightmost, 0, sizeof(rightmost));
memcpy(rightmost, p, strlen(p) + 1);
return rightmost;
}
The function get_rightmost(), defined above, contains an error
...


C DEBUGGING

243

Choice 2 The code does not correctly handle the situation where a directory separator '/'
is the final character
...

Choice 4 memcpy() cannot be used safely to copy string data
...

328
...
004
Choice 5
...
void freeList( struct node *n )
{
while( n )
{
????
}
}
Which one of the following can replace the ???? for the function above to release the
memory allocated to a linked list?
Choice 1 n = n->next; free( n );
Choice 2 struct node m = n; n = n->next; free( m );
Choice 3 struct node m = n; free( n );
Choice 4 free( n );

n = m->next;

n = n->next; [Ans]

Choice 5 struct node m = n; free( m );

n = n->next; (Ans)

330
...

Choice 2 Declaration allocates storage for a variable, but definition only informs the
compiler as to the variable’s type
...
[Ans]

244

C PROGRAMS

WITH

SOLUTIONS

Choice 4 Variable definition must precede variable declaration
...

331
...
/*sum_array() has been ported from FORTRAN
...
Which one of the following
accurately describes it?

C DEBUGGING

245

Choice 1 The range of the loop does not match the bounds of the array d
...

Choice 3 total is initialized with an integer literal
...
[Ans]
Choice 4 The code above fails to compile if there are no registers available for i
...

333
...
h>
void func()
{
int x = 0;
static int y = 0;
x++; y++;
printf( “%d -- %d\n”, x, y );
}
int main()
{
func();
func();
return 0;
}
What will the code above print when it is executed?
Choice 1 1 -- 1 1 -- 1
Choice 2 1 -- 1 2 -- 1
Choice 3 1 -- 1 2 -- 2
Choice 4 1 -- 0 1 -- 0
Choice 5 1 -- 1 1 -- 2 [Ans]
334
...

Which one of the following describes the deficiency illustrated above?
Choice 1 For some values of n, the environment will almost certainly exhaust its stack
space before the calculation completes
...

Choice 3 A break statement should be inserted after each case
...

Choice 4 The fibonacci() function includes calls to itself
...

Choice 5 Since the default case is given first, it will be executed before any case
matching n
...
When applied to a variable, what does the unary “&” operator yield?
Choice
Choice
Choice
Choice
Choice

1
2
3
4
5

The variable’s address [Ans]
The variable’s right value
The variable’s binary form
The variable’s value
The variable’s format

336
...
int x = 011 | 0x10;
What value will x contain in the sample code above?
Choice 1 3
Choice 2 13 [Ans]
Choice 3 19
Choice 4 25
Choice 5 27
338
...
txt for reading by fgetc?
Choice 1 fopen( “test
...
txt” )
Choice 3 fileopen( “test
...
txt” )
Choice 5 freopen( “test
...
int m = – 14;
int n = 6;
int o;
o = m % ++n;
n += m++ – o;
m <<= (o ^ n) & 3;
Assuming two’s-complement arithmetic, which one of the following correctly represents the
values of m, n, and o after the execution of the code above?
Choice 1 m = – 26, n = – 7, o = 0
Choice 2 m = – 52, n = – 4, o = – 2 (Ans)
Choice 3 m = – 26, n = – 5, o = – 2
Choice 4 m = – 104, n = – 7, o = 0
Choice 5 m = – 52, n = – 6, o = 0
340
...

Choice 2 %e displays a double in engineering notation if the number is very small or
very large
...


248

C PROGRAMS

WITH

SOLUTIONS

Choice 3 %e always displays an argument of type double in engineering notation; %f
always displays an argument of type double in decimal notation
...

Choice 5 %e and %f both expect a corresponding argument of type double and format it
identically
...

341
...
K
...
Which one of the following will define a function that CANNOT be called from another
source file?
Choice 1 void function() {
...
}
Choice 3 const void function() {
...
} [Ans]
Choice 5 static void function() {
...
Base class has some virtual method and derived class has a method with the same name
...

Ans
...
For the following C program
#define AREA(x)(3
...
25,r2=2
...
Area of the circle is 122
...
625000
3
...

Ans
...
d”, s);
}
249

250

C P ROGRAMS

WITH

SOLUTIONS

4
...
Undefined
5
...
1,2,3,4
6
...
6
7
...
less
8
...
1000000
2
...
Error
4
...
4
9
...
The first part of this question can be answered in at least three ways:
1
...
Build the declaration up incrementally, using typedefs:
typedef char *pc;

/* pointer to char */

typedef pc fpc();

/* function returning pointer to char */

typedef fpc *pfpc;

/* pointer to above */

typedef pfpc fpfpc();

/* function returning
...
*/
pfpfpc a[N];

/* array of
...
Use the cdecl program, which turns English into C and vice-versa:
cdecl> declare a as array of pointer to function returning pointer to function returning pointer
to char
char *(*(*a[])())()
cdecl can also explain complicated declarations, help with casts, and indicate which set of
parentheses the arguments go in (for complicated function definitions, like the one above)
...


252

10
...

12
...

13
...

14
...

15
...
When the parameters have complicated types, declarations can *really*
get messy
...
)
A structure pointer is defined of the type time
...

Write the way to initialize the 2nd element to 10
...

Write the statement to initialize the 3rd element of the 2 element to 10;
int f()
void main()
{
f(1);
f(1,2);
f(1,2,3);
}
f(int i,int j,int k)
{
printf(“%d %d %d”,i,j,k);
}
What are the number of syntax errors in the above?
None
...
20 20 20
16
...
It allocates and frees memory after use/after getting out of scope
...
main()
{
static i=3;
printf(“%d”,i--);
return i>0 ? main():0;
}
Ans
...
char *foo()
{
char result[100]);
strcpy(result,“anything is good”);
return(result);
}
void main()
{
char *j;
j=foo()
printf(“%s”,j);
}
Ans
...

19
...
“harma” (p->add(dharma) && (*p)->harma)
“harma” (after printing, p->add(hewlett-packard) &&(*p)->harma)
“ewlett-packard”
20
...
(d)
21
...
(c)
22
...
(b)

255

256

C P ROGRAMS

WITH

SOLUTIONS

23
...
(a)
24
...
(b)
25
...

main()
{
char *p1=“Name”;

SAMPLE QUESTIONS
char *p2;
p2=(char *)malloc(20);
while(*p2++=*p1++);
printf(“%s\n”,p2);
}
Ans
...
Find the output for the following C program
...
57 94
27
...

main()
{
int x=5;
printf(“%d %d %d\n”,x,x<<2,x>>2);
}
Ans
...
Find the output for the following C program
...
10 5
29
...

main()
{
char *ptr = “Ramco Systems”;
(*ptr)++;
printf(“%s\n”,ptr);
ptr++;
printf(“%s\n”,ptr);
}
Ans
...
Find the output for the following C program
...
h>
main()
{
char s1[]=“Ramco”;
char s2[]=“Systems”;
s1=s2;
printf(“%s”,s1);
}
Ans
...
Find the output for the following C program
...
h>
main()
{
char *p1;
char *p2;

SAMPLE QUESTIONS
p1=(char *) malloc(25);
p2=(char *) malloc(25);
strcpy(p1,“Ramco”);
strcpy(p2,“Systems”);
strcat(p1,p2);
printf(“%s”,p1);
}
Ans
...
Write a function in C to calculate n!
Ans
...
Find the output for the following C program
...
This won’t go into the loop as TRUE is defined as 0
34
...
x =100
Is the above assignment to pointer is correct or wrong ?
Ans
...
What is the output of the following ?
int i;

259

260

C P ROGRAMS

WITH

SOLUTIONS

i=1;
i=i+2*i++;
printf(%d,i);
Ans
...
FILE *fp1,*fp2;
fp1=fopen(“one”,“w”)
fp2=fopen(“one”,“w”)
fputc(‘A’,fp1)
fputc(‘B’,fp2)
fclose(fp1)
fclose(fp2)
}
Find the Error, If Any?
Ans
...
But It will over writes on same file
...
What is the output for the following ?
Program:
main()
{
int x = 5;
while (x= =1)
x = x – 1;
printf (“%d\n”, x);
}
Output:
The while loop will not be executed because the condition is false and the value of x will be
printed
...

38
...

main()
{
float x;
scanf(“%f ”, &x);
printf(“\n square root of %
...
2f is %6
...
#define MAN(x,y) (x)>(y)?(x):(y)
{int i=10;
j=5;
k=0;
k=MAX(i++,++j);
printf(%d %d %d %d,i,j,k);
}
Ans
...
void main()
{
int i=7;
printf(“%d”,i++*i++);
}
Ans
...
What is C language?
Ans
...
It
has since spread to many other operating systems, and is one of the most widely used
programming languages
...
What is the output of printf(“%d”)?
Ans
...
When we write printf(“%d”,x); this means compiler will print the value of x
...
When we use %d the compiler internally uses it to access the argument in the stack
(argument stack)
...
Now when we write printf(“%d”,a) then compiler first accesses
the top most element in the argument stack of the printf which is %d and depending on the
format string it calculated to offset to the actual data variable in the memory which is to be
printed
...

3
...
) and scanf(
...
What is the difference between “calloc(
...
)”?
Ans
...
calloc(
...
By
default the block is initialized to 0
...

malloc(
...
malloc(
...

2
...
) allocates memory blocks and returns a void pointer to the allocated space, or
NULL if there is insufficient memory available
...
) allocates an array in memory with elements initialized to 0 and returns a pointer to
the allocated space
...
) calls malloc(
...

262

SHORT QUESTIONS

AND

ANSWERS

263

4
...
)” and “sprintf(
...
sprintf(
...
) writes data to the standard
output device
...
How to reduce a final size of executable?
Ans
...

6
...
Create two pointers, and set both to the start of the list
...
Either way, its either 1 or 2 jumps until they meet
...
“union” Data Type What is the output of the following program? Why?
#include
main() {
typedef union {
int a;
char b[10];
float c;
}
Union;
Union x,y = {100};
x
...
b,“hello”);
x
...
50;
printf(“Union x : %d %s %f n”,x
...
b,x
...
a,y
...
c);
}
8
...
For example,
abc would give you abc, acb, bac, bca, cab, cba
...
What will print out?
main()
{
char *p1=“name”;
char *p2;
p2=(char*)malloc(20);
memset (p2, 0, 20);
while(*p2++ = *p1++);
printf(“%s\n”,p2);
}
The pointer p2 value is also increasing with p1
...
So when the loop exits (ie when address p1
reaches next character to “name” ie null) p2 address also points to next location to “name”
...

e
...
:
initially p1 = 2000 (address) , p2 = 3000
*p1 has value “n”
...
where no data is present … that’s why its printing null
...
empty string
...
What will happen in these three cases?
if(a=0){
//somecode
}
if (a==0){
//do something
}

266

C PROGRAMS

WITH

SOLUTIONS

if (a===0){
//do something
}
What are x, y, y, u
#define Atype int*
typedef int *p;
p x, z;
Atype y, u;
Ans
...
y is a pointer to int but u is just an integer variable
...
What does static variable mean?
Ans
...

1
...
If it is declared for a function name:
By default function is extern
...
it is invisible for the outer files
3
...
that variable
is limited to with in the file
...
Advantages of a macro over a function
...
Macro gets to see the Compilation environment, so it can expand __ __TIME__ __FILE__
#defines
...

For example, you can’t do this without macros
#define PRINT(EXPR) printf( #EXPR “=%d\n”, EXPR)
PRINT( 5+6*7 ) // expands into printf(”5+6*7=%d”, 5+6*7 );
You can define your mini language with macros:
#define strequal(A,B) (!strcmp(A,B))
Macros are a necessary evils of life
...

13
...
There are 2 differences
...
malloc() takes a single argument(memory required in
bytes), while calloc() needs 2 arguments(number of variables to allocate memory, size in
bytes of a single variable)
...


SHORT QUESTIONS

AND

ANSWERS

267

14
...
C has three types of storage: automatic, static and allocated
...

Variables with block scope, and with static specifier have static scope
...
e
...

Memory obtained from calls to malloc(), alloc() or realloc() belongs to allocated storage
class
...
What is the difference between strings and character arrays?
Ans
...

Actually, a string is a character array with following properties:
* the multibyte character sequence, to which we generally call string, is used to initialize an
array of static storage duration
...

* it not specified what happens if this array, i
...
, string, is modified
...
For example, in the following
declarations:
char *s1 = “Calvin and Hobbes”;
char *s2 = “Calvin and Hobbes”;
the strings pointed by s1 and s2 may reside in the same memory location
...

16
...

Ans
...
Which bitwise operator is suitable for checking whether a particular bit is on or off?
Ans
...
Here is an example:enum {
KBit0 = 1,
KBit1,

KBit31,
};

268

C PROGRAMS

WITH

SOLUTIONS

if ( some_int & KBit24 )
printf ( “Bit number 24 is ON\n” );
else
printf ( “Bit number 24 is OFF\n” );
18
...
The bitwise AND operator, again
...

some_int = some_int & ~KBit24;
19
...
The bitwise OR operator
...
Does there exist any other function which can be used to convert an integer or a
float to a string?
Ans
...

#include
char *itoa(int value, char *string, int radix);
DESCRIPTION
The itoa() function constructs a string representation of an integer
...

string:
Points to the buffer that is to hold resulting string
...

radix:
Is the base of the number; must be in the range 2 - 36
...
One can use sprintf():
char s[SOME_CONST];
int i = 10;
float f = 10
...
Why does malloc(0) return valid memory address? What's the use?
Ans
...

An implementation is free to behave in a manner it finds suitable, if the allocation size
requested is zero
...

* The behavior is same as if a space of non-zero size was requested
...

22
...
For implementations that return non-NULL values, a typical usage is as follows:
void
func ( void )
{
int *p; /* p is a one-dimensional array,
whose size will vary during the
the lifetime of the program */
size_t c;
p = malloc(0); /* initial allocation */
if (!p)
{
perror (”FAILURE” );
return;
}
/* … */
while (1)
{
c = (size_t) … ; /* Calculate allocation size */
p = realloc ( p, c * sizeof *p );
/* use p, or break from the loop */
/* … */
}
return;
}
Notice that this program is not portable, since an implementation is free to return NULL for
a malloc(0) request, as the C Standard does not support zero-sized objects
...
How do I write code that reads data at memory location specified by segment and
offset?
Ans
...
This function returns byte(s) read from specific segment and offset
locations in memory
...
In this program
from VDU memory we have read characters and its attributes of the first row
...


270

C PROGRAMS

WITH

SOLUTIONS

#include ...
h>
main( )
{
char far *scr = 0xB8000000 ;
FILE *fp ;
int offset ;
char ch ;
if ( ( fp = fopen ( “scr
...
dat”, “rb” ) ) == NULL )
{
printf ( “\nUnable to open file” ) ;
exit( ) ;
}
// reads and writes to file
for ( offset = 0 ; offset < 160 ; offset++ )
{
fscanf ( fp, “%c”, &ch ) ;
printf ( “%c”, ch ) ;
}
fclose ( fp ) ;
}
24
...
class can have a public method for specific data type conversions
...
now conversion operator
gets called to assign the value
...
What is the difference between malloc()/free() and new/delete?
Ans
...

new allocates memory and also invokes constructor to initialize the object
...
e
...
If an array of objects was created using
new, then delete must be told that it is dealing with an array by preceding the name with an
empty []:Int_t *my_ints = new Int_t[10];

...
What is the difference between “new” and “operator new” ?
Ans
...


272

C PROGRAMS

WITH

SOLUTIONS

27
...
There is no way for the compiler to verify that the macro parameters are of compatible
types
...

If macro parameter has a postincremented variable ( like c++ ), the increment is performed
two times
...
Also, the macro will show up in
expanded form during debugging
...
What are advantages and disadvantages of external storage class?
Ans
...

29
...
A void pointer is a C convention for a raw address
...
If you write
int *ip;
ip points to an int
...
For
example, if you have a char*, you can pass it to a function that expects a void*
...
In C (but not in C++), you can use a void* any time you need any kind
of pointer, without casting
...


SHORT QUESTIONS

AND

ANSWERS

273

A void pointer is used for working with raw memory or for passing a pointer to an unspecified
type
...
When C was first invented, character pointers (char *)
were used for that
...

30
...
A type-insensitive macro is a macro that performs the same basic operation on different
data types
...
The following program
provides an example:
#include
#define SORT(data_type) sort_ ## data_type
void sort_int(int** i);
void sort_long(long** l);
void sort_float(float** f);
void sort_string(char** s);
void main(void);
void main(void)
{
int** ip;
long** lp;
float** fp;
char** cp;

...

}
This program contains four functions to sort four different data types: int, long, float, and
string (notice that only the function prototypes are included for brevity)
...
Thus, the
string

274

C PROGRAMS

WITH

SOLUTIONS

sort(int)(ip);
translates into
sort_int(ip);
after being run through the preprocessor
...
When should a type cast not be used?
Ans
...
Overriding these
type modifiers can cause the program to fail to run correctly
...
In the rare events in which this action is beneficial, using a union to hold the values
makes the programmer’s intentions clearer
...
When is a switch statement better than multiple if statements?
Ans
...

33
...
A storage class is an attribute that changes the behavior of a variable
...

There are five types of storage classes
1) auto
2) static
3) extern
4) register
5) typedef
...
What is a static function?
Ans
...
Scope refers
to the visibility of a function or variable
...
If the function or variable is
not visible outside of the current source file, it is said to have local, or static, scope
...
How can I sort things that are too large to bring into memory?
Ans
...
Exactly how to sort large data depends
on what is meant by too large to fit in memory
...
After the key/
value pairs are sorted, the data is rearranged on disk into the correct order
...
A
sort such as a radix sort can also be used as an external sort, by making each bucket in the

SHORT QUESTIONS

AND

ANSWERS

275

sort a file
...
The data can be partitioned by writing
it to two smaller files
...

36
...
A pointer variable is a variable that may contain the address of another variable or any valid
address in the memory
...
What is a pointer value and address?
Ans
...
Each memory location is
numbered in the memory
...

38
...
A Modulus operator gives the remainder value
...

This operator is applied only to integral operands and cannot be applied to float or double
...
The form and place of declaration where the variable is declared in a
program determine the linkage of variable
...
What is a function and built-in function?
Ans
...
Each
subprogram specifies one or more actions to be performed for a large program
...

The function supports only static and extern storage classes
...
functions have global scope
...
Built-in functions that predefined and supplied along
with the compiler are known as built-in functions
...

40
...
A macro is a preprocessor directive that provides a mechanism for token replacement in
your source code
...

Here is an example of a macro: Macros can also utilize special operators such as the stringizing
operator (#) and the concatenation operator (##)
...
n, v)
In your program, you can check the value of a variable by invoking the DEBUG_VALUE
macro:

...


276

C PROGRAMS

WITH

SOLUTIONS

The preceding code prints x is equal to 20
...
This example shows that the stringizing
operator used with macros can be a very handy debugging tool
...
What is the difference between goto and longjmp() and setjmp()?
Ans
...

Generally, a jump in execution of any kind should be avoided because it is not considered
good programming practice to use such statements as goto and longjmp in your program
...

To use the goto statement, you give it a labeled position to jump to
...
You cannot implement gotos between functions
...
Later, your program can call the longjmp() function to restore the program’s
state as it was when you called setjmp()
...

However, there is a major drawback to using these functions: your program, when restored
to its previously saved state, will lose its references to any dynamically allocated memory
between the longjmp() and the setjmp()
...
It is highly recommended that you avoid using functions
such as longjmp() and setjmp() because they, like the goto statement, are quite often an
indication of poor programming practice
...
Is it acceptable to declare/define a variable in a C header?
Ans
...
In addition, such a variable must be defined in one source file
...
The ANSI C
standard will allow multiple external definitions, provided that there is only one initialization
...

Global variables that do not have to be accessed from more than one file should be declared
static and should not appear in a header file
...
Why should I prototype a function?
Ans
...
This approach helps
the compiler ensure that calls to a function are made correctly and that no erroneous type
conversions are taking place
...
What is the quickest searching method to use?
Ans
...
A hashing
algorithm can provide even faster searching
...
A digital trie offers the prospect of being
able to search for an item in essentially a constant amount of time, independent of how many
items are in the data set
...
The term
digital trie refers to the data structure used to hold the items to be searched
...

45
...
1) The same auto variable name can be used in different blocks
2) There is no side effect by changing the values in the blocks
3) The memory is economically used
4) Auto variables have inherent protection because of local scope
...
What are the characteristics of arrays in C?
Ans
...

2) Array elements are stored in subsequent memory locations
...

4) Array name represents the address of the starting element
...
Array size must be a constant expression
and not a variable
...
How do you print only part of a string?
Ans
...
*/
printf(First 11 characters: ‘%11
...
In C, what is the difference between a static variable and global variable?
Ans
...
However, a global variable can be accessed
by any function (including the ones from different files)
...
In C, why is the void pointer useful?
Ans
...

50
...
‘Polymorphism’ is an object oriented term
...
In
other words, polymorphism means taking more than one form
...
Overloading is the practice of supplying more than one definition for a given
function name in the same scope
...
Overriding refers to the

278

C PROGRAMS

WITH

SOLUTIONS

modifications made in the sub class to the inherited methods from the base class to change
their behavior
...
What is Operator overloading ?
Ans
...

But it can still retain all of its old meanings
...

2) In a stack class it is possible to overload the + operator so that it appends the contents of
one stack to the contents of another
...

52
...
C++ Templates allow u to generate families of functions or classes that can operate on a
variety of different data types, freeing you from the need to create a separate function or
class for each type
...

Many data structures and algorithms can be defined independently of the type of data they
work with
...

53
...
Dynamic Binding :
The address of the functions are determined at runtime rather than @ compile time
...

Static Binding :
The address of the functions are determined at compile time rather than @ run time
...

54
...
C does not have a class/object concept
...

C++ supports all C syntax
...
c in C while
...
(C++ compiler compiles the files with
...
In C++ structures are like
classes, so declaring functions is legal and allowed
...


SHORT QUESTIONS

AND

ANSWERS

279

c++ is C with Classes hence C++ while in c the closest u can get to an User defined data
type is struct and union
...
However,
to get the correct output, we should use an explicit cast to force long arithmetic as shown
below:
long int z = ( long int ) x * y ;
Note that ( long int )( x * y ) would not give the desired effect
...
Why doesn’t the following statement work?
Ans
...
The basic difference
between a string and a character is that a string is a collection of characters, represented by
an array of characters whereas a character is a single character
...
How do I know how many elements an array can hold?
Ans
...
In DOS
environment, the amount of memory an array can consume depends on the current memory
model (i
...
Tiny, Small, Large, Huge, etc
...
Consider following program, which shows the maximum number of elements an array
of type int, float and char can have in case of Small memory model
...
What is a compiler?
2
...
How is a C program compiled usually?
4
...
What the two different kinds of error which can be in a program?
6
...

7
...

8
...

9
...
What is an operating system for?
11
...
If you had a C source program which you wanted to call ‘accounts’ what name would you
save it under?
13
...
How would this program be run?
15
...
Name the most common library file in C
...
Is it possible to define new functions with the same names as standard library functions?
18
...
What is a block?
20
...

21
...
What happens when a program comes to a } character? What does this character signify?
23
...
What happens if a comment is not ended? That is if the programmer types /*
...
*/ to close?
280

QUESTIONS

281

25
...

26
...
What happens if a function returns a value but it is not assigned to anything?
28
...
How can a function be made to quit early?
30
...
Say which of the following are valid C identifiers:
1
...
80shillings
3
...
A%
5
...
_off
32
...

33
...
What is the difference between the types int and unsigned int?
35
...

36
...
If we want to declare a function to return long float, it must be done in, at least, two
places
...
Write a statement, using the cast operator, to print out the integer part of the number 23
...

39
...
Name two ways that values and results can be handed back from a function
...
Where are parameters declared?
42
...
Does it mean anything to use a function directly as a variable parameter?
44
...
Do actual and formal parameters need to have the same names?
46
...

47
...
h
...
A macro is always a number
...
A macro is always a constant
...
What is a pointer?
51
...
What data types can pointers “point to”?
53
...

(This is not as pointless as it seems
...
)
54
...
65; ?
55
...
23e+00
...
Investigate what happens when you type the wrong conversion specifier in a program
...
g
...
This is bound to go wrong
- but how will it go wrong?
57
...
printf (x);
2
...
printf ();
4
...
What is a white space character?
59
...

Print out the answer
...

60
...

61
...

62
...
True or false?
63
...
Write a statement which prints out the remainder of 5 divided by 2
...
Write a short statement which assigns the remainder of 5 divided by 2 to a variable called
“rem”
...
Write a statement which subtracts -5 from 10
...
Write in C: if 1 is not equal to 23, print out “Thank goodness for mathematics!”
68
...
When is the condition tested in each of the loops?
70
...
Write a program which copies all input to output line by line
...
Write a program to get 10 numbers from the user and add them together
...
Given any array, how would you find a pointer to the start of it?
74
...
Write a statement which declares an array of type double which measures 4 by 5
...
What are the two main ways of declaring strings in a program?
77
...
Write a program which gets a number between 0 and 9 and prints out a different message
for each number
...

79
...
All calculations are performed using long variables
...
What information is returned by strlen()?
82
...
Name five kinds of error which can occur in a mathematical function
...
Which operators can be hidden inside other statements?
85
...

86
...
Write a statement which declares a file pointer called fp
...
Enumerated data are given values by the compiler so that it can do arithmetic with them
...
Does void do anything which C cannot already do without this type?
90
...
Write a statement which declares a new type “real” to be like the usual type “double”
...
Variables declared const can be of any type
...
What distinguishes a bit pattern from an ordinary variable? Can any variable be a bit pattern?
94
...

96
...

98
...
7 & 2
2
...
15 & 3
4
...
15 & 7 & 3
Try to explain the results
...
)
99
...
1 | 2
2
...
Find out the values of:
1
...
23 & (~23)
3
...
Use short type variables for all the numbers)
...
What are the following?
1
...
File pointer
3
...
What is the difference between high and low level filing?
103
...

104
...

105
...
Valid characters are ASCII
codes 10,13,and 32
...
Anything else is illegal for programs
...
What statement performs formatted writing to text files?
107
...
What is the difference between a structure and a union?
109
...
If x is a variable, how would you find out the value of a member called mem
...
If ptr is a pointer to a structure, how would you find out the value of a member called mem
...
A union is a group of variables in a single package
...
What is a structure diagram?
114
...
Every separate struct type in a data structure has its own variable name
...
How are the members of structures accessed in a data structure?
117
...
Store that address in a variable which is declared as follows:
struct BinaryTree *ptr;
118
...
What is a null string?
120
...
Can you automate this program with a loop? Can you make it work for any
number of structures?
121
...
What will happen if I say delete this?
123
...


QUESTIONS

285

124
...

125
...
Explain the need for “Virtual Destructor”
...
Can we have “Virtual Constructors”?
128
...
What are Virtual Functions? How to implement virtual functions in “C”?
130
...
What is Namespace?
132
...

133
...

134
...
Can we generate a C++ source code from the binary file?
136
...
Talk sometiming about profiling
...
How many lines of code you have written for a single program?
139
...
How to write Multithreaded applications using C++?
141
...

142
...

143
...
What is a “RTTI”?
145
...
Why preincrement operator is faster than postincrement?
147
...
What will happen if I allocate memory using “new” and free it using “free” or allocate sing
“calloc” and free it using “delete”?
149
...
Explain working of printf
...
Differentiate between “printf ” and “sprintf”
...
What is “map” in STL?
153
...
What are the techniques you use for debugging?
155
...
Give 2 examples of a code optimization
...
Is it possible to use multiple else with if statement?

286

C P ROGRAMS

WITH

SOLUTIONS

158
...
Why goto statement is avoided?
160
...
Can we put default statement anywhere in the switch () case structure?
162
...
Is it possible to create a for loop that is never executed?
164
...
Is it possible to nest while loop within for loops?
166
...
What are the values of NULL and !NULL?
168
...
Write the definition of a function
...
How do functions help to reduce the program size?
171
...

172
...
Explain How arguments are passes and results are returned?
174
...

175
...
What are the uses of return statements?
177
...
What are void functions?
179
...
What is recursion? Explain its advantages
...
Explain types of recursions
...
Is it possible to call library functions recursively?


Title: C Programing
Description: Some Basic Programs Og C Programing