Vous êtes sur la page 1sur 23

Sample interview questions from C language:

BASICS

1. What are the important aspects (properties) of programming


language?

Four important aspects of any language are the way it stores data, the way it
operates upon this data, how it accomplishes input and output and how it lets
you control the sequence of execution of instructions in a program.

2. What is problem solving?

Problem solving is a creative process. It is an act of defining a problem,


determining the cause of the problem, identifying, prioritizing, and selecting
alternatives for a solution and implementing a solution.

3. What are the steps involved in program development?

The various steps involved in Program Development are:

a. Defining or Analyzing the problem e. Compiling and Running the


Program
b. Design (Algorithm)
f. Testing and Debugging
c. Coding
g. Maintenance
d. Documenting the program

4. How do you analyse the problem?

Tasks in defining a problem:

Specifying the input requirements.

Specifying the output requirements and

Specifying the processing requirements.

5. What is design and how to design a program?

A design is the path from the problem to a solution in code. Program Design is
both a product and a process. The process results in a theoretical framework for
describing the effects and consequences of a program as they are related to its
development and implementation.

6. What is algorithm?

An algorithm is a step-by-step description of the solution to a problem. It is


defined as an ordered sequence of well-defined and effective operations which,
when carried out for a given set of initial conditions, produce output, and
terminate in a finite time. The term “ordered sequence” specifies, after the
completion of each step in the algorithm, the next step must be unambiguously
defined.
An algorithm must be: Definite, Finite, Precise and Effective and Implementation
independent ( only for problem not for programming languages).

7. What is pseudo code?

Pseudo code is an informal high-level description of an algorithm that uses the


structural conventions of programming languages, but omits language-specific
syntax. It is an outline of a program written in English or the user's natural
language.

8. What is flow chart? Explain the symbols used?

Flowchart is a diagrammatic representation of an algorithm. It uses different


symbols to represent the sequence of operations, required to solve a problem. It
serves as a blueprint or a logical diagram of the solution to a problem.

9. What is coding?

An algorithm expressed in programming languages is called Program. Writing a


program is called Coding. The logic that has been developed in the algorithm is
used to write the program.

10. What is documentation? What is the need of documenting the


program?

Documentation explains how the program works and how to use the program.
Documentation can be of great value, not only to those involved in maintaining
or modifying a program, but also to the programmers themselves. Details of
particular programs, or particular pieces of programs, are easily forgotten or
confused without suitable documentation.
Documentation comes in two forms:
* External documentation, which includes things such as reference manuals,
algorithm descriptions, flowcharts, and project workbooks
* Internal documentation, which is part of the source code itself (essentially, the
declarations, statements, and comments)

11. What is need of compiling the program?

Compilation is a process of translating a source program into machine


understandable form. The compiler is system software, which does the
translation after examining each instruction for its correctness. The translation
results in the creation of object code. After compilation, Linking is done if
necessary. Linking is the process of putting together all the external references
(other program files and functions) that are required by the program. The
program is now ready for execution. During execution, the executable object
code is loaded into the computer’s memory and the program instructions are
executed.

12. What is testing?

Testing is the process of executing a program with the deliberate intent of


finding errors. Testing is needed to check whether the expected output matches
the actual output. Program should be tested with all possible input data and
control conditions. Testing is done during every phase of program development.
Initially, requirements can be tested for its correctness. Then, the design
(algorithm, flow charts) can be tested for its exactness and efficiency. Structured
walk through is made to verify the design.

13. What is debugging?

Debugging is a process of correcting the errors. Programs may have logical


errors which cannot be caught during compilation. Debugging is the process of
identifying their root causes. One of the ways to ensure the correctness of the
program is by printing out the intermediate results at strategic points of
computation. Debugging is the hardest part of programming because of
improper documentation.

14. What is the difference between debugging and testing?

Testing means detecting errors. Debugging means diagnosing and correcting the
root causes.

15. What is a Programming Language?

Computer Programming is an art of making a computer to do the required


operations, by means of issuing sequence of commands to it.

16. What are the types of programming languages?

There are two major types of programming languages:

Low Level Languages and High Level Languages.

17. What is C?

C is a programming language developed at AT & T’s Bell Laboratories of USA in


1972. It was designed and written by a man named Dennis Ritchie. It is often
know as middle level language as it inherits both the features of high level and
low level language.

18. What are the characteristics of c languages?

Characteristics of C Language
The increasing popularity of C is due to its various desirable qualities:
*C language is well suited for structured modular programming.
* C is a robust language with rich set of built-in functions and operators.
* C is smaller which has minimal instruction set and programs written in C are
efficient and fast.
* C is highly portable (code written in one machine can be moved to other).
* C is highly flexible.
* C allows access to the machine at bit level (Low level (Bitwise) programming).
* C supports pointer implementation - extensive use of pointers for memory,
array, structures and functions.

19. What are called escape sequence?


Escape sequences are non printable characters, which begin with backward slash
and followed by one or more special characters. The frequently used escape
sequences are given below:
Horizontal tab (\t) Form feed (\f)
Vertical tab (\v) Back Space (\b)
Carriage return (\r) Back Slash (\\)
New line (\n) Null (\0)

20. Define a constant?

A constant is an entity that doesn’t change. A constant in C refers to the fixed


values that do not change during the execution of a program.
There are two types of constants:
Symbolic constants and Constant variables, also called read-only variables.

21. How many types of constants are there? What are they?

There are mainly two types of constants

a. Primary (integer, float, char)

b. Secondary (array, pointer, structure, union)

22. Define the term Variable.

Variable is a named memory location. It can store one value at a time. Every
time new value is assigned, the old value is overwritten

23. Define datatype.

Data types are used to indicate the type of value represented or stored in a
variable, the number of bytes to be reserved in memory, the range of values that
can be represented in memory, and the type of operation that can be performed
on a particular data item.

24. Define the term “key word”. Why can’t we use key word as
variable’s name?

Keywords are the words whose meaning has already been explained to the C
compiler (or in a broad sense to the computer). The keywords cannot be used as
variable names because if we do so we are trying to assign a new meaning to
the keyword, which is not allowed by the computer.

25. What is an identifier?

Identifiers are names given to various programming elements such as variables,


constants, and functions. It should start with an alphabet, followed by the
combinations of alphabets and digits. No special character is allowed except
underscore (_). An Identifier can be of arbitrarily long. Some implementation of C
recognizes only the first eight characters and some other recognize first 32
characters.
26. How many no. of keywords are there in C language? What are the
different control structures available in C?

There are 32 keywords available in C language. The decision control statements


are: if statement, if-else statement and the conditional operator.

27. What are the different operators available in c?

The following are the different operators available in C:


Arithmetic operators Assignment operators
Relational operators Unary operators
Logical operators Bitwise operators

28. What is the “Order of Precedence”?

________________________________________________________________________

Operator Name Association

________________________________________________________________________

( ) [ ] -> . Parentheses, Index, member access operators Left to


Right

! – sizeof()

(Typecast) * & Logical NOT, unary minus, indirection, address Right to


Left

++ -- Increment and decrement operators. Right to Left

*/% Multiplicative operators. Left to Right

+- Additive operators. Left to Right

< > <= >= Inequality comparators. Left to Right

== != Equality comparators Left to


Right

&& Logical AND. Left tot Right

|| Logical OR. Left to Right

?: Conditional. Right to Left

= op= Assignment. Right to Left

, Comma Left to Right

_________________________________________________________________________

29. What is typecasting?


C provides a mechanism for allowing the programmer to change the default data
type of a given expression. This is called Typecasting. Typecasting allows a
variable to behave like a variable of another type.
C provides two types of type conversions: Implicit and Explicit type conversions.

30. Name different IF statements.

The if statement has three basic forms: Simple if-else, Nested if and if-else if
ladder.

31. What is Short circuit evaluation?

Whenever the expression with the operators && and || are evaluated, the
evaluation process stops as soon as the outcome, true or false is known.

32. What is the hierarchy of operators?

Operators Type
! Logical NOT
*/% Arithmetic and modulus
+- Arithmetic
< > <= >= Relational
== != Relational
&& Logical AND
|| Logical OR
= Assignment

33. What is a conditional operator (ternary operator)? What is its


syntax?

It is shortened form of if-statement and its syntax:

Expression 1? Expression 2 : expression 3

34. What are the different types of loop control instructions available in
C?

There are 3 loop control instructions. Those are

1. For

2. While

3. Do...while

35. How does a loop work?

The loop (loop control instruction) involves repeating some portion of the
program either a specified number of times or until a particular condition is being
satisfied.

36. What is the use of BREAK statement?


When break is encountered inside any loop, control automatically passes to the
first statement after the loop. A break is usually associated with an if.

37. What is the use of continue statement?

If we want to take the control to the beginning of the loop, bypassing the
statements inside the loop, which have not yet been executed. The keyword
continue allows us to do this. When continue is encountered inside any loop,
control automatically passes to the beginning of the loop. A continue is usually
associated with an if.

38. What is the difference between an entry controlled loop and an exit
controlled loop?

If the condition of the loop is tested before the control enters into the loop then it
is called entry control loop (While)and if the condition is tested at exit then it is
exit controlled loop(do-while).

39. What is switch statement?

The control statement that allows us to make a decision from the number of
choices is called a switch, or more correctly a switch-case-default

40. What is the need of break statement in switch?

If the break is not used in a case statement the control will not come out of the
switch and it goes executing the following cases till it encounters a break
otherwise it all the statements in the switch.

41. What is goto statement?

Takes the control where ever you want, is done by using goto statement. Better
don’t use it.

42. Why is goto statement not preferred in programming?

The big problem with goto’s is that when we do use them we can never be sure
how we got to a certain point in our code. They obscure the flow of control.

43. What does a exit () function do?

The exit ( ) function is a standard library function which terminates the execution
of the program.

FUNCTIONS AND POINTERS

44. What is a function?

A function is a self-contained block of statements that perform a coherent task of


some kind.

45. Why do we use functions?

We use functions because


1. Writing functions avoids rewriting the same code over and over.
2. Using functions it becomes easier to write programs and keep track of
what they are doing. If the operation of a program can be divided into
separate activities, and each activity placed in a different function,
then each could be written and checked more or less independently.

46. What is the mechanism used to convey message to the function?

The mechanism used to convey information to the function is the ‘argument’.

47. What are the different parameter passing mechanisms available?

There are two parameter passing mechanism available. Those are: Call by value
and Call by address

48. What is the use of return statement?

The return statement serves two purposes.


1. On executing the return statement it immediately transfers the control back to
the calling program.
2. It returns the value present in the parentheses after return, to the calling
program. In the above program the value of sum of three numbers is being
returned

49. What is the default return type any function?

The default return type of any function is int.

50. What is call by value mechanism?

Whenever we called a function and passed something to it we have always


passed the ‘values’ of variables to the called function. Such function calls are
called ‘calls by value’. By this we mean, on calling a function we are passing
values of variables to it.

51. What is a pointer?

Pointer is a variable which holds the address of another variable.

52. What is recursion?

A function is called ‘recursive’ if a statement within the body of a function calls


the same function.

53. Explain the terms associated with a function.

Take a function as below


Void main()
{
Int n,p;
Int reverse (int);/* function prototype*/
Set of statements;
n=reverse (p); /* function is called with actual parameters*/
Set of statements;
}

Int reverse(int n)/* function heading with formal parameters*/


{
Set of statements;
Return(x); /* control goes back to calling function*/
}

1. In the above code snippet main () is calling function because the function
reverse is called and reverse is called function
2. If a function (here reverse ()) is written below main () its prototype must be
included in the calling function otherwise it should be declared globally so that
the function call does not raise any error. It informs the compiler about the
function.
3. The parameters present in the function call are called actual parameters and
the parameters which are there in function heading are formal parameters
4. Return statement in function is the last executable statement. If we write any
statements after if those are not going to be executed
5. Return type of a function is the type of value that is returned by the function
in the present example int is the return type because reverse function returns
int.

54. What is the main difference between call by value and call by
reference (address)?

The difference between call by value and call by address is


1. The changes made to formal parameters are not reflected in the calling
function in the call by value. Where as in the call by address changes will be
reflected
2. By using call by value at most we can change a single value by return
statement from called function where as by the use of call by address we can
change many values in the calling function

55. What is the difference among int, short and long data types?

Short is at least 2 bytes big, long is at least 4 bytes big, short is never bigger
than int’s and int’s are never bigger than longs.

56. What is the difference between int and unsigned int?

Declaring an integer as unsigned almost doubles the size of the largest possible
value that it can otherwise take.

57. What does a storage class tell us?

A storage class tells us:


1. Where the variable would be stored.

2. What will be the initial value of the variable, if initial value is not specifically
assigned? (i.e. the default initial value).

3. What is the scope of the variable; i.e. in which functions the value of the
variable would be available.
4. What is the life of the variable; i.e. how long would the variable exist.

58. What are the different classes available in C?

There are 4 storage classes available in c. Those are

Automatic storage class (local) (default value is garbage)


Register storage class (default value is garbage)
Static storage class (default value is zero)
External storage class (global) (default value is zero)

59. When do we use a static variable?

Use static storage class only if you want the value of a variable to persist
between different function calls.

60. When do we register variables? Give an example.

Use register storage class for only those variables that are being used very often
in a program. A typical application of register storage class is loop counters,
which get used a number of times in a program.

PRE PROCESSOR

61. What is a pre processor?

It is a program that processes our source program before it is passed to the


compiler.

62. What is the function of pre-processor?

Pre-processor expands Macro expansion and File inclusion.

63. What is pre processor directive?

# is called pre processor directive. Its job is to expand macros and files (headers)

64. What is a macro?

Macro is a named constant. It is defined using #define


Ex. # define A 5
Where ever A is found in the program 5 is substituted there
We can have macro with arguments
Ex. #define AREA(x) (3.14 * x * x)
Macro call leads to substitution

65. What is the difference between “goto.c” and <goto.c>?

#include "goto.c" This command would look for the file goto.c in the
current directory as well as the specified list of
directories as mentioned in the include search path
that might have been set up.
#include <goto.c> This command would look for the file goto.c in the
specified list of directories only.

66. What is a search path?

They include search path is nothing but a list of directories that would be
searched for the file being included. Different C compilers let you set the search
path in different manners. If you are using Turbo C/C++ compiler then the
search path can be set up by selecting ‘Directories’ from the ‘Options’ menu. On
doing this a dialog box appears. In this dialog box against ‘Include Directories’
we can specify the search path.

67. Is there any provision in c language to start execution from other


than main ()?

Yes we can. By using #pragma directive we can do it


Ex.
Void fun1 ( );
Void fun2 ( );
#pragma startup fun1
#pragma exit fun2
main ( )
{
printf (“\nInside maim”);
}
void fun1 ( )
{
printf (“\nInside fun1”);
}
void fun2 ( )
{
printf (“\nInside fun2”);
}

Output :
Inside fun1
Inside main
Inside fun2

ARRAYS

68. What is the need for going an array?

If there are situations in which we would want to store more than one value at a
time in a single variable.

Ex. For example, suppose we wish to arrange the percentage marks obtained by
100 students in ascending order. In such a case we have two options to store
these marks in memory:
1. Construct 100 variables to store percentage marks obtained by 100 different
students, i.e. each variable containing one student’s marks.
2. Construct one variable (called array or subscripted variable) capable of storing
or holding all the hundred values.
Obviously, the second alternative is better. A simple reason for this is, it would
be much easier to
handle one variable than handling 100 different variables.

69. What is an array?

An array is a collection of similar elements. The first element in the array is


numbered 0, so the last element is 1 less than the size of the array. An array is
also known as a subscripted variable. Before using an array its type and
dimension must be declared.

70. Is there any boundary check available for arrays in c?

No, there is no boundary checking for arrays in c.

71. Discuss the call by value and call by reference with arrays.

In the call by value we pass values of array elements to the function, whereas in
the call by reference we pass addresses of array elements to the function.

72. How a pointer is associated to an array?

Ex. Int a [10];


Int *p;
p=a;
p [1] is same as a [1]
Here in the above snippet p is pointer and it is pointing to an array called a; we
can access the whole array with the help of the pointer

73. How do we pass an entire array to a function?

Just passing the address of the zeroth element of the array to a function is as
good as passing the entire array to the function. It is also necessary to pass the
total number of elements in the array

74. What is a two dimensional array?

The two-dimensional array is also called a matrix.


Ex. Int a [4] [5];
It is two dimensional arrays of 4 rows and 5 columns
Indirectly two dimensional arrays is nothing but collection of 1D arrays

75. What is an array of pointers?

Since a pointer variable always contains an address, an array of pointers would


be nothing but a collection of addresses. The addresses present in the array of
pointers can be addresses of isolated variables or addresses of array elements or
any other addresses. All rules that apply to an ordinary array apply to the array
of pointers as well.

76. What is a 3D array?

A three-dimensional array can be thought of as an array of arrays of arrays. The


outer array has three elements.
77. What are the things that can be done on pointers?

Addition of two pointers, Multiplication of a pointer with a constant and Division


of a pointer with a constant.

78. Different sorting techniques in C.

Bubble sort, selection sort, insertion sort, quick sort, merge sort and heap sort.

STRING FUCTIONS

79. What is a string?

A string constant is a one-dimensional array of characters terminated by a null


(‘\0’). For example,
char name [ ] = {‘H’, 'A', 'E', 'S', 'L', 'E', 'R', '\0’} ;
or
char name [] =”UGY” /* \0 is appended by c*/
The terminating null (‘\0’) is important, because it is the only way the functions
that work with a string can know where the string ends.

80. What is the format specifier used to print strings on to the screen?

The %s used in printf ( ) is a format specification for printing out a string. The
same specification can be used to receive a string from the keyboard.

81. What are the different pre defined string functions available in C?

Function Use
strlen Finds length of a string
strlwr Converts a string to lowercase
strupr Converts a string to uppercase
strcat Appends one string at the end of another
strncat Appends first n characters of a string at the end of
another
strcpy Copies a string into another
strncpy Copies first n characters of one string into another
strcmp Compares two strings
strncmp Compares first n characters of two strings
strcmpi Compares two strings without regard to case ("i"
denotes that this function ignores case)
stricmp Compares two strings without regard to case
(identical to strcmpi)
strnicmp Compares first n characters of two strings without
regard to case
strdup Duplicates a string
strchr Finds first occurrence of a given character in a string
strrchr Finds last occurrence of a given character in a string
strstr Finds first occurrence of a given string in another
string
strset Sets all characters of string to a given character
strnset Sets first n characters of a string to a given character
strrev Reverses string

STUCTURES

82. Why do we use structure?

A structure contains a number of data types grouped together. These data types
may or may not be of the same type.

83. Define structure.

Structure is collection of variables of different data type name under single


entity.

84. What are the terms associated with structure?

Example 1:

Struct emp

Int empno;

Char ename [20];

Float sal;

};

This is called structure definition. Memory is not allocated to the members when
the structure is defined.

Struct emp a; a is structure variable of tag emp;

Memory is allocated to the members when the structure is instantiated.

In the above structure the total memory allocated to it is 2+20+4 i.e. 26

Example 2:

We can instantiate a structure at the time of definition it self

Struct emp {

Int empno;

Char ename [20];

Float sal;

} a, b, c;

a, b, c are structure variables


Example 3:

See these examples to have a better idea about declarations

struct book
{
char name;
float price;
int pages;
};
struct book b1, b2, b3;
Is same as...

struct book
{
char name;
float price;
int pages;
} b1, b2, b3;
Or even...

struct {
char name;
float price;
int pages;
} b1, b2, b3;

85. Why are the structures defined globally?

Usually structure type declaration appears at the top of the source code file,
before any variables or functions are defined. In very large programs they are
usually put in a separate header file, and the file is included (using the pre-
processor directive #include) in whichever program we want to use this structure
type.

86. How do we access structure members?

Let us take the structure


struct book {
char name [20];
float price;
int pages;
} b1, b2, b3;

B1 is the name of the structure


We use dot operator to access structure members
Ex. B1.name=”yugander”;

Syntax is
Structure name. field name;

87. What is an array of structure?

struct book {
char name [20];
float price;
int pages;
} b [100];
B is array of structures where each element is nothing it is structure.
Some times like this a lot of variables (b1 to b100 for storing data about hundred
books) needed to be handled. Therefore he allowed us to create an array of
structures; an array of similar data types which themselves are a collection of
dissimilar data types.

88. Can we assign value of structure to other structure?

Yes we can assign for example a, b are two structures we can do a=b provided
both structures belong to the same tag

89. Can we have structure within a structure?

We can use structure within a structure. But inner structure definition must be
written in above outer structure.

90. If a structure is associate with a pointer, how do we operate


members?

By using -> operator we have to operate member fields of structure.

91. Can you send a structure to a function using call by value and call
by address?

We can send a structure to a function by both the mechanisms.

92. What is a self referential structure?

If structure has one of its members type as its own type then it is called self
referential structure.

INPUT/OUTPUT FUNCTION:

93. What are the different I/O functions available?

There are numerous library functions available for I/O. These can be classified
into three broad categories:

Console I/O - Functions to receive input from keyboard and


functions write output to VDU.

File I/O - Functions to perform I/O operations on floppy


functions disk or hard disk.

94. What is console?

The screen and keyboard together are called a console.

95. How does sprint() work?


The sprintf( ) function works similar to the printf( ) function except for one small
difference. Instead of sending the output to the screen as printf( ) does, this
function writes the output to an array of characters.

96. How does a sscanf() work?

It allows us to read characters from a string and to convert and store them in C
variables according to specified formats. The sscanf( ) function comes in handy
for in-memory conversion of characters to values. You may find it convenient to
read in strings from a file and then extract values from a string by using
sscanf( ). The usage of sscanf( ) is same as scanf( ), except that the first
argument is the string from which reading is to take place.

97. What is the difference between getch() and getche()?

These functions return the character that has been most recently typed. The ‘e’
in getche( ) function means it echoes (displays) the character that you typed to
the screen. As against this getch( ) just returns the character that you typed
without echoing it on the screen.

98. What is the difference between getchar() and fgetchar()?

getchar( ) works similarly and echo’s the character that you typed on the screen,
but unfortunately requires Enter key to be typed following the character that you
typed. The difference between getchar( ) and fgetchar( ) is that the former is a
macro whereas the latter is a function. Here is a sample program that illustrates
the use of these functions.

99. What is union?

A "union declaration" specifies a set of variable values and, optionally, a tag


naming the union. The variable values are called "members" of the union and
can have different types. Unions are similar to "variant records" in other
languages.

A variable with union type stores one of the values defined by that type. The
same rules govern structure and union declarations. Unions can also have bit
fields.

Members of unions cannot have an incomplete type, type void, or function type.
Therefore members cannot be an instance of the union but can be pointers to
the union type being declared.

A union type declaration is a template only. Memory is not reserved until the
variable is declared.

If a union of two types is declared and one value is stored, but the union is
accessed with the other type, the results are unreliable. For example, a union of
float and int is declared. A float value is stored, but the program later accesses
the value as an int. In such a situation, the value would depend on the internal
storage of float values. The integer value would not be reliable.
100. What are the similarities between union and structure?

Structures and unions share the following characteristics:

• Their members can be objects of any type, including other structures and
unions or arrays. A member can also consist of a bit field.
• The only operators valid for use with entire structures and unions are the
simple assignment (=) and sizeof operators. In particular, structures and
unions cannot appear as operands of the equality ( == ), inequality (!=),
or cast operators. The two structures or unions in the assignment must
have the same members and member types.
• A structure or a union can be passed by value to functions and returned by
value by functions. The argument must have the same type as the
function parameter. A structure or union is passed by value just like a
scalar variable; that is, the entire structure or union is copied into the
corresponding parameter.

101. What is the difference between structure and a union?

The union is a structure. The main difference between structure and union is, the
size of the union is equal to the size of the largest member of the union where as
size of the structure is the sum of the size of all members of the structure. And
one more thing is that, at a time we can use one member of the union.

FILES

102. How do you open a file?

Before we can read (or write) information from (to) a file on a disk we must open
the file. To open the file we have called the function fopen( ).

103. How do you read file content?

To read the file’s contents from memory there exists a function called fgetc( ).

ch = fgetc ( fp ) ;
fgetc( ) reads the character from the current pointer position, advances the
pointer position so that it now points to the next character, and returns the
character that is read, which we collected in the variable ch.

104. What does a fputc() do?

The fputc( ) function is similar to the putch( ) function, in the sense that both
output characters. However, putch( ) function always writes to the VDU,
whereas, fputc( ) writes to the file.

105. What are the different file opening modes?

Read(r), write(w), append(a) modes

And r+, w+, a+ we can do read, write, append with these three.

106. How do you close a file?


By using fclose() we can close a opened file.

107. What is binary file?

A binary file is merely a collection of bytes. This collection might be a compiled


version of a C program (say PR1.EXE), or music data stored in a wave file or a
picture stored in a graphic file. A very easy way to find out whether a file is a text
file or a binary file is to open that file in Turbo C/C++. If on opening the file you
can make out what is displayed then it is a text file, otherwise it is a binary file.

108. Why do use fprintf()?

The only function that is available for storing numbers in a disk file is the
fprintf( ) function.

Text and characters are stored one character per byte, as we would expect.
Numbers are stored as strings of characters.

109. Why do we go for a binary file?

If large amount of numerical data is to be stored in a disk file, using text mode
may turn out to be inefficient. The solution is to open the file in binary mode and
use those functions (fread( ) and fwrite( ) which are discussed later) which store
the numbers in binary format. It means each number would occupy same
number of bytes on disk as it occupies in memory.

110. Why fread and fwrite are more important?

Any database management application in C must make use of fread( ) and


fwrite( ) functions, since they store numbers more efficiently, and make
writing/reading of structures quite easy. Note that even if the number of
elements belonging to the structure increases, the format of fread( ) and fwrite( )
remains same.

111. Explain rewind(),ftell(),fseek().

The rewind( ) function places the pointer to the beginning of the file, irrespective
of where it is present right now.
The fseek( ) function lets us move the pointer from one record to another.

fseek ( fp, -recsize, SEEK_CUR ) ;

If we wish to know where the pointer is positioned right now, we can use the
function ftell( ). It returns this position as a long int which is an offset from the
beginning of the file. The value returned by ftell( ) can be used in subsequent
calls to fseek( )

112. What are command line parameters?

The arguments that we pass on to main( ) at the command prompt are called
command line arguments. The function main( ) can have two arguments,
traditionally named as argc and argv. Out of these, argv is an array of pointers to
strings and argc is an int whose value is equal to the number of strings to which
argv points. When the program is executed, the strings on the command line are
passed to main.

113. What are the bitwise operators?

Operator Meaning
~ One’s complement
>> Right shift
<< Left shift
& Bitwise AND
| Bitwise OR
^ Bitwise XOR(Exclusive
OR)

114. What are enumerators?

An enumeration consists of a set of named integer constants. An enumeration


type declaration gives the name of the (optional) enumeration tag and defines
the set of named integer identifiers (called the "enumeration set," "enumerator
constants," "enumerators," or "members"). A variable with enumeration type
stores one of the values of the enumeration set defined by that type.

Variables of enum type can be used in indexing expressions and as operands of


all arithmetic and relational operators. Enumerations provide an alternative to
the #define preprocessor directive with the advantages that the values can be
generated for you and obey normal scoping rules.

In ANSI C, the expressions that define the value of an enumerator constant


always have int type; thus, the storage associated with an enumeration variable
is the storage required for a single int value. An enumeration constant or a value
of enumerated type can be used anywhere the C language permits an integer
expression.

Example:

enum DAY /* Defines an enumeration type */


{
saturday, /* Names day and declares a */
sunday = 0, /* variable named workday with */
monday, /* that type */
tuesday,
wednesday, /* wednesday is associated with 3 */
thursday,
friday
} workday;
The value 0 is associated with saturday by default. The identifier sunday is
explicitly set to 0. The remaining identifiers are given the values 1 through 5 by
default.

DYNAMIC MEMORY ALLOCATION

115. What is dynamic storage allocation?


A storage allocation technique in which the storage assigned to a computer program varies during
program execution, based on the current needs of the program and of other executing programs.

116. What is Dynamic memory allocation?

The process of allocating memory at run time is known as dynamic memory


allocation.

117. What are the dynamic memory allocation functions?

Many languages permit a programmer to specify an array size at run time. Such
languages have the ability to calculate and assign during executions, the
memory space required by the variables in the program. But c inherently does
not have this facility but supports with memory management functions, which
can be used to allocate and free memory during the program execution. The
following functions are used in c for purpose of memory management.

Function Task
Malloc Allocates memory requests size of bytes and returns a pointer to the Ist byte of allocated
space
Calloc Allocates space for an array of elements initializes them to zero and returns a pointer to the
memory
Free Frees previously allocated space
Realloc Modifies the size of previously allocated space.

118. Explain memory allocation process.

According to the conceptual view the program instructions and global and static
variable in a permanent storage area and local area variables are stored in
stacks. The memory space that is located between these two regions in available
for dynamic allocation during the execution of the program. The free memory
region is called the heap. The size of heap keeps changing when program is
executed due to creation and death of variables that are local for functions and
blocks. Therefore it is possible to encounter memory overflow during dynamic
allocation process. In such situations, the memory allocation functions
mentioned above will return a null pointer.

119. How to allocate a block of memory?

A block of memory may be allocated using the function malloc. The malloc
function reserves a block of memory of specified size and returns a pointer of
type void. This means that we can assign it to any type of pointer. It takes the
following form:

ptr=(cast-type*)malloc(byte-size);

ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an
area of memory with size byte-size.

Example: x=(int*)malloc(100*sizeof(int));

120. How to allocate multiple blocks of memory?


Calloc is another memory allocation function that is normally used to request
multiple blocks of storage each of the same size and then sets all bytes to zero.
The general form of calloc is:

ptr=(cast-type*) calloc(n,elem-size);

The above statement allocates contiguous space for n blocks each size of
elements size bytes. All bytes are initialized to zero and a pointer to the first byte
of the allocated region is returned. If there is not enough space a null pointer is
returned.

121. How to release the used space?

Compile time storage of a variable is allocated and released by the system in


accordance with its storage class. With the dynamic runtime allocation, it is our
responsibility to release the space when it is not required. The release of storage
space becomes important when the storage is limited. When we no longer need
the data we stored in a block of memory and we do not intend to use that block
for storing any other information, we may release that block of memory for
future use, using the free function.

free(ptr);

ptr is a pointer that has been created by using malloc or calloc.

122. How to alter the size of allocated memory?

The memory allocated by using calloc or malloc might be insufficient or excess


sometimes in both the situations we can change the memory size already
allocated with the help of the function realloc. This process is called reallocation
of memory. The general statement of reallocation of memory is :

ptr=realloc(ptr,newsize);

This function allocates new memory space of size newsize to the pointer variable
ptr ans returns a pointer to the first byte of the memory block. The allocated new
block may be or may not be at the same region.

Basic programs:

Write a program to find

1. Factorial using recursive function.

2. Reverse of a number

3. Armstrong number

4. Reverse of a string

5. Logic for the multiplication of the 2x2 matrix

6. Fibonacci series
7. Whether the given number is a prime or not.

8. Printing prime number up to 100.

9. How to read and write a matrix.

10. Draw Pascal triangle.

11. Print 1=One, 2=Two and so on.

12. Check whether the word or a number is a palindrome or not.

13. Swap two numbers without using the third variable.

14.

Vous aimerez peut-être aussi