0% found this document useful (0 votes)
3 views34 pages

c program question bank

C program question answer

Uploaded by

2513055
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views34 pages

c program question bank

C program question answer

Uploaded by

2513055
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT-I 2 MARKS

1. Define Compilationprocess.
Compilation refers to the processing of source code files (.c, .cc, or .cpp) and the creation of an 'object'
file. The compiler merely produces the machine language instructions that correspond to the source code
file that was compiled and also identifies syntax errors in the source program.
2. What do you meant bylinking?
Linking refers to the creation of a single executable file from multiple object files. In this step, it is
common that the linker will complain about undefined functions (commonly, main itself).
3. Define Constants in C. Mention thetypes.
The constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after their
definition.
4. Whatarethe differentdata types available in„C‟?
Therearefour basic datatypes availablein „C‟.
 int
 float
 char
 double
1. What is meant by Enumerated datatype.
Enumerated data is a user defined data type in C language.
Enumerated data type variables can only assume values which have been previously declared.
Example :enum month { jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec };
2. What areKeywords?
Keywords are certain reserved words that have standard and pre-defined meaning in
“C‟.These keywords can be used only for their intended purpose.
3. What do you mean by variables in„C‟?
 A variable is a data name used for storing a data value.
 Can be assigned different values at different times during program execution.
 Can be chosen by programmer in a meaningful way so as to reflect its function in the program.
 Some examples are: Sum, result, average etc…
4. Difference between Local and Global variable inC.
Local:These variables only exist inside the specific function that creates them. They are unknown to
otherfunctions and to the main program. As such, they are normally implemented using a stack. Local
variables cease to exist once the function that created them is completed. They are recreated each time a
function is executed orcalled.
Global:These variables can be accessed (ie known) by any function comprising the program. They are
implemented by associating memory locations with variable names. They do not get recreated if the function
is recalled.
5. What are Operators? Mention their types inC.
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C language is rich in built-in operators and provides following type of operators:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Unary Operators
Ternary Operator

6. Whatisthe differencebetween„=‟ and„==‟ operator?


where
= is an assignment operator
and
== is a relational operator
Example:
while (i=5) is an infinite loop because it is a nonzero value and while (i==5) is true only when i=5.
7. What is typecasting?
Type casting is the process of converting the value of an expression to a particular data type.
Example:
intx,y;
c = (float) x/y;
where a and y are defined as integers. Then the result of x/y is converted into float.

8. What is the difference between ++a anda++?


++a means do the increment before the operation (pre increment) a++ means do the increment after the
operation (post increment)
Example:
a=5;
x=a++; /* assign x=5*/
y=a;/*now y assignsy=6*/
x=++a; /*assigns x=7*/

9. Distinguish between while..do and do..while statement in C. (JAN2009)


While DO..while

(i) Executes the statements within the while blockif (i) Executes the statements within thwhile block
only the condition is true. atleast once.

(ii) The condition is checked at the starting of (ii) The condition is checked at the end of the loop
theLoop

[Link] the various Decisions making statement available inC.


Statement Description
if statement An if statement consists of a boolean expression followed by one or
more statements.
if…else An if statement can be followed by an optional else statement, which
statement executes when the boolean expression is false.
nested if You can use one if or else if statement inside another if or else if
statements statement(s).

switch A switch statement allows a variable to be tested for equality


statement against a list of values.
nested switch You can use one swicthstatement inside another switch
statements statement(s).

15. What do you meant by conditional or ternaryoperator?


Text expression ? : If Condition is true ? Then value X : Otherwise value Y
Example:
Assume that f, g and y are the floating point variables in the conditional expression given below
y = (f<g) ?g : f ;
This expression will store value of g in y if less than g; otherwise it will store value of f in y.
16. What is the use of sizeof() operator inC.
Sizeof operator is used to return the size of an variable.
Example :
sizeof(a), Where a integer, will return 4.
17. Define Looping in C.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general from of a loop statement in most of the programming languages:

18. What are the types of looping statements available inC


C programming language provides following types of loop to handle looping requirements. Click the
following links to check their detail.
Loop type Description
while loop Repeats a statement or group of statements while a given condition is true. It
tests the condition before executing the loop body.
for loop Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
do...while loop Like a while statement, except that it tests the condition at the end of the
loop body
nested loops You can use one or more loop inside any another while, for
ordo..while loop.

19. What are the types of I/O statements available in„C‟?


There are two types of I/O statements availablein„C‟.
 Formatted I/O Statements
 Unformatted I/O Statements
20. Write short notes about main() function in‟C‟program.(MAY2009)
 Every C program must have main ( ) function.
 All functions in C, has to end with „( )‟ parenthesis.
 It is a starting point of all „C‟ programs.
 The program execution starts from the opening brace „{„ and ends with closing brace
„}‟, within which executable part of the program exists.

21. Define delimiters in „C‟.


A delimiter is a sequence of one or more characters used to specify the boundary between
separate independent regions in the program statements.
Delimiters Use
: Colon
; Semicolon
( ) Parenthesis
[ ] Square Bracket
{ } Curly Brace
# Hash
, Comma
22. Why header files are included in „C‟programming?
· Thissectionisusedtoincludethefunctiondefinitionsusedintheprogram. · Eachheaderfilehas„h‟
extension andinclude using‟# include‟directive atthebeginningof aprogram.
23. What is the difference between scanf() and gets()function?
In scanf() when there is a blank was typed, the scanf() assumes that it is an end. gets() assumes the
enter key as end. That is gets() gets a new line (\n) terminated string of characters from the keyboard and
replaces the „\n‟ with „\0‟.
24. What are the Escape Sequences presentin„C‟
\n - New Line
\b-Backspace
\t - Formfeed
\‟Single quote
\\ Backspace
\t - Tab
\r - Carriage return
\a - Alert
\” - Double quotes
25. What is the difference between if and whilestatement?
If While

(i) It is a conditional statement (i) It is a loop control statement

(ii) If the condition is true, it executesome (ii) Executes the statements within thewhile block if
statements. the condition is true.

(iii) If the condition is false then it stopsthe (iii) If the condition is false the control istransferred
execution the statements. to the next statement of the loop.

26. Differentiate between formatted and unformatted you input and outputfunctions?
Formatted I/P functions:
These functions allow us to supply the input in a fixed format and let us obtain the output in the specified
form. Formatted output converts the internal binary representation of the data to ASCII characters which are
written to the output file.
Unformatted I/O functions:
There are several standard library functions available under this category-those that can deal with a string
of characters. Unformatted Input/Output is the most basic form of input/output. Unformatted input/output
transfers the internal binary representation of the data directly between memory and the file.
Function Formatted Unformatted

Input scanf() getchar(),


gets()

Output printf() putchar(),


puts()

27. What are storageclasses?


A storage class defines the scope (visibility) and life time of variables and/or functions
within a C Program.
28. What are the storage classes available inC?
There are following storage classes which can be used in a C Program
o auto
o Register
o static
o extern
29. What is register storage in storageclass?
Register is used to define local variables that should be stored in a register instead of RAM. This
means that the variable has a maximum size equal to the register size (usually one word) and cant have
the unary '&' operator applied to it (as it does not have a memory location).

{
registerint Miles;
}
30. What is static storageclass?
Static is the default storage class for global variables. The two variables below (count and road) both

staticint
Count; int Road;
{
printf("%d\n", Road);
}
have a static storage class.
UNIT II ARRAYS AND STRINGS
Part A -2 marks:
1. What is an array? (JAN 2013) (JAN 2014)
 Array is data structure
 It stores objects/variables of same data types in contiguous memory locations
 Array elements can be accessed using index/subscript numbers
 Example: int arr[10];
2. Give the general form of array declaration.
 Syntax: datatype arrayName [ arraySize ];
 Example: int arr[10];
4. Why is it necessary to give the size of an array in an array declaration?
When an array is declared, the compiler allocates a base address and reserves enough space in
the memory for all the elements of the array at compile time. Therefore size must be specified in array
declaration inorder to allocate the required space.
5. Declare a float array of size 5 and assign 5 values to it. [DEC 2014]
float arr[5];
arr[0]=0.1;
arr[1]=0.2;
arr[2]=0.3;
arr[3]=0.4;
arr[4]=0.5;
6. What are the classifications of array?
 ONE-Dimensional array. (Example: arr[10])
 TWO- Dimensional array. (Example: arr[10][20])
 Multi-Dimensional array. (Example: arr[10][20][15])
7. Write the features of array.
 Array contains data elements of same data type.
 Array stores fixed number of data elements.
 The elements in the array can be accessed by the index of the array.
 The elements are stored in contiguous location in an array
8. Give an example of initialization of string array. [DEC 2014]
There are different ways of initializing String in C Programming:
 Initializing Unsized Array of Character
char name [] = {'P','R','I','T','E','S','H','\0'};
 Initializing String Directly
char name [ ] = "PRITESH";
 Initializing String Using Character Pointer
char *name = "PRITESH";
9. What will happen when you access the array more than its dimension?
When you access the array more than its dimensions(size),no error will be caused but garbage values
will be displayed for those locations
10. Define String.
A string in C is merely an array of characters. The length of a string is determined by a
terminating null character: '\0'. So, a string with the contents, say, "abc" has four characters: ‘a’, ‘b’,
‘c’, and the terminating null character. Eg: char name [] = {‘a’,’b’,’c’,’\0’};
11. What is the use of strcat() function?
The strcat() function joins two strings. Its a library function, and has its declaration in string.h
header file. Eg: strcat(s1,s2) It shall append a copy of the string pointed to by s2 (including
the terminating null byte) to the end of the string pointed to by s1.
#include <stdio.h>
#include <string.h>
int main()
{
char a[10], b[10];
printf("\n Enter the first string: ");
gets(a);
printf("\n Enter the second string: ");
gets(b);
strcat(a,b);
printf("String obtained on concatenation is %s\n",a);
}
Output:
Enter the first string: hello
Enter the second string: world
String obtained on concatenation is helloworld
12. How does array variable differ from an ordinary variable?
Array variable can store group of elements of the same data type under a common name
where as ordinary can be able to store only one value at a time.
Example: int a; // variable ‘a’ can store single integer value
int a[5]; // here in ‘a’ we can save 5 integer values
13. Give the declaration for the string “welcome” in c
Syntax: char array_name[size] = “String”;
Example:
 char mes[]= { ‘w‘,‘e‘,‘l‘,‘c‘,‘o‘,‘m‘,‘e‘,‘\0‘};
 char mes[] =”Welcome”
14. Write example code to declare two dimensional array? (MAY-2014)
Syntax: <datatype> Arrayname [row size][column size];
Example:
#include<stdio.h>
voidmain()
{
int a[3][3]; //2-d Array with 3 row and 3 column
}
15. What is a null character? What is its use in a string?
A null character is specified as ‘\0’. It is used as terminator in the string. It avoids storage of garbage
values in character arrays.
16. Name any four library functions used for string handling.(JAN-2014)(MAY-2014)
Function Work of Function
strlen() Calculates the length of string
strcpy() Copies a string to another string
strcat() Concatenates(joins) two strings
strcmp() Compares two string
strlwr() Converts string to lowercase
strupr() Converts string to uppercase
17. What is meant by Sorting?What are its types?
Sorting refers to ordering data in an increasing or decreasing fashion according to some linear
relationship among the data items. Sorting can be done on names, numbers and records.

Types of sorting available in C:


 Insertion sort.
 Merge Sort.
 Quick Sort.
 Radix Sort.
 Heap Sort
 Selection sort
 Bubble sort
18. Define Searching.
Searching for data is one of the fundamental fields of computing. Search is an operation in which a
given list is searched for a particular [Link] location of the searched element is informed.
Various types of searching techniques in C are
 Linear search
 Binary search
19. What is linear search?
In Linear Search the list is searched sequentially and the position is returned if the key
element to be searched is available in the list, otherwise -1 is returned. The search in Linear Search
starts at the beginning of an array and move to the end, testing for a match at each item.
20. What is Binary Search?
A search algorithm which repeatedly divides an ordered search array in half and compared the
required (key) value with the middle element of the array.
 If the Key value is equal to middle element then it returns the middle element.
 If the Key value is less than the middle element it Searches only from low to mid-1.
 If the Key value is greater than the middle element it Searches only from mid+1 to high.
UNIT III FUNCTIONS AND POINTERS
Part A
1. Define Recursion? (MAY-2014)
A function that calls itself is known as recursive function and the process of calling function
itself is known as recursion in C programming.
Example:
void rec( )
{
rec( );
}
void main( )
{
rec( );
}
2. What is a Pointer? How a variable is declared to the pointer?
Pointer is a variable which holds the address of another variable.
Pointer declaration: x
datatype *variable-name;
Example: 2000 5
int *x, c=5; x=&c; Addr:
1000
3. What are the uses of Pointers? (JAN2014)
 Pointers are used to return more than one value to the function
 Pointers are more efficient in handling the data in arrays
 Pointers reduce the length and complexity of the program
 They increase the execution speed
 The pointers saves data storage space in memory
4. What are * and & operators ? (DEC 2014)
 * operator - value at the address[indirection/dereferencing operator]. The indirection operator (*)
accesses a value indirectly, through a pointer. The operand must be a pointer value. The result
the operation is the value addressed by the operand; that is,
the value at the address to which its operand points. The type of the result is the type that the
operand addresses.
 & operator - address of operator [referencing operator]. It’s a pointer address operator is
denoted by ‘&’ symbol. When we use ampersand symbol as a prefix to a variable name
‘&’, it gives the address of that variable
[Link] is the difference between an array and pointer?
Array Pointer
Its a data structure that stores elements of same It’s a variable that stores address of another
data type in contiguous memory locations variable
Array declaration: int a[6]; Pointer declaration: int *a;
Memory allocation is static Memory allocation can be dynamic
Array can be initialized at definition. Example Pointers can’t be initialized at definition
int num[] = { 2, 4, 5}
Array elements are accessed using subscripts Pointers variables can be accessed using
indirection operator(*)

.
6. What is a null pointer?
Null pointer does not point anywhere and does not hold address of any object
or function It has numerical value 0
Eg: int *p=0 or int *p=NULL
7. How do you use a pointer to a function?
The format of a function pointer goes like this: return_type (*pointer_name)(parameter_list);
#include<stdi
o.h> int func
(int a)
{
printf("\n a = %d\
n",a); return 0;
}
int main(void)
{
int(*fptr)(int); // Function pointer
fptr = func; // Assign address to function pointer
func
(2);
retur
n 0;
}
9.. What is the difference between call by value and call by reference?(MAY-2014)
Call by Value Call by Reference
The value of variables are passed as parameters The address of the variables are passed as
in the function call parameters in the function call
Changes made in the formal parameters (in called Changes made in the formal parameters (in called
function) will not affect the actual arguments in function) will affect the actual arguments in the
the calling function calling function
10. What is a function? (DEC 2014)
 Function is a group of statements that together performs a task.
 Every C program has atleast one function called main( )
 Functions can be classified into 2 types:
 User defined functions: functions defined by user
 Library functions: inbuilt functions in C
11. What is return statement
A return statement returns result of computations performed in called function and
transfers the program control back to the calling function, assigns returned value to the variable in
the left side of the calling function. If a function does not return a value, the return type in the
function definition and declaration is specified as void.
Two forms:
return;
return expression;
[Link] is it necessary to give the size of an array in an array declaration?
When an array is declared, the compiler allocates a base address and reserves enough space in the
memory for all the elements of the array. The size is required to allocate the required space. Thus,
the size must be mentioned.
[Link] are the features of Pointers?
 Pointers are efficient in handling data and associated with array.
 Pointers are used for saving memory space.
 Pointers reduce length and complexity of the program
 Since the pointer data manipulation is done with address, the execution time is faster.
[Link] are the advantages of using a pointer?
 Pointers are more compact and efficient.
 Pointers are used to achieve clarity and efficient code.
 Pointers enable to access the memory directly.
 Pointers are used to pass information between function and its reference point.
[Link] are the elements of user defined function?
 Function Definition
 Function Declaration
 Function Call
UNIT-IV-STRUCTURES 2MQ&A
1. What is structure? Write the syntax for structure.
Structure is a collection of different data type which are grouped together and
each element in a C structure is called member.
Struct keyword is used to define a structure
Syntax Example
struct structure_name struct book
{ {
datatype member1; char name[25];
datatype member2; char author[25];
------------ int page;
datatype memberm; float price;
} variable 1, variable 2 --------- variable n; }b1;

2. Write the various operations on structure.


 define structures
 declare variables of structure typea
 select the members of structure
 assign entire structures
3. How the members of structure object is accessed?
Members of structure object is accessed by using dot operator.
Example
Struct book
{
int pages;
char author[25];
}b1;
[Link]=15;
[Link]=”G”;
4. Write the use of size operator on structure.

sizeof operator is used to calcualte the size of data type or variables.


Example:
Printf(“Size of integer : %d”,sizeof(i));
Printf(“Size of character : %c”,sizeof(c));

Might generate the following output :


Size of integer : 2
Size of character :4
5. What is a nested structure?
 Structure written inside another structure is called as nesting of two structures.
 Nested Structures are allowed in C Programming Language.
 We can write one Structure inside another structure as member of another structure.
Example
struct date
{
int date;
int month;
int year;
};
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date doj;
}emp1;
6. What is the need for typedef ?
The typedef is an advance feature in C language which allows us to create an alias or new
name for an existing type or user defined type. The syntax of typedef is as follows:

Syntax: typedef data_type new_name;

typedef: It is a keyword.
data_type: It is the name of any existing type or user defined type created using structure/union.
new_name: alias or new name you want to give to any existing type or user defined type.
Let's take an example:
typedef int myint;
Now myint is an alias of int. From now on we can declare new int variables
using myint instead of int keyword.
7. Interpret the term Union in C.

A union is a special data type available in C that allows to store different data types in the
same memory location.

union [union tag]


{
member definition;
member definition;
...
member definition;
} [one or more union variables];
8. What is mean by Self referential structures.

A self-referential structure is one of the data structures which refer to the pointer to (points)
to another structure of the same type. For example, a linked list is supposed to be a self-referential
data structure. The next node of a node is being pointed, which is of the same struct type. For
example,

typedef struct node


{
void *data;
struct node *next;
} linked_list;

In the above example, the list node is a self-referential structure – because the *next is of the
type struct list node.

9. Point out the meaning of Dynamic memory allocation.

Dynamic memory allocation in c language enables the C programmer to allocate memory at


runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header
file.

1. malloc() -Used to allocate memory to structures(user define datatype) dynamically.


2. calloc() -Used to allocate memory to arrays(derived datatype) dynamically.
3. realloc() -Used to increase or decrease size to arrays dynamically.
4. free() -Used to delete the memory dynamically.
10. Mention any two application linked list.
 Linked Lists can be used to implement Stacks , Queues.
 Linked Lists can also be used to implement Graphs. ...
 Implementing Hash Tables :- Each Bucket of the hash table can itself be a linked list.
 Undo functionality in Photoshop or Word
11. Generalize the operators used in access the structure members.
Member access operators allow access to the members of their operands.

Operator Operator name Example Description

[] array subscript a[b] access the bth element of array a


dereference the pointer a to access the object or
* pointer dereference *a
function it refers to
create a pointer that refers to the object or
& address of &a
function a
. member access a.b access member b of struct or union a
member access access member b of struct or union pointed to
-> a->b
through pointer by a
13. Discover the meaning of Array of structure.
Structure is collection of different data type. An object of structure represents a single record
in memory, if we want more than one record of structure type, we have to create an array of
structure or object. As we know, an array is a collection of similar type, therefore an array can be of
structure type.

Syntax for declaring structure array

struct struct-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};
struct struct-name obj [ size ];
Example for declaring structure array

#include<stdio.h>
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};

struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
struct Employee Emp[ 3 ];

16. Show a structure called ID_Card to hold the details of a student.


struct IDcard
{
char name[25];
int regnum;
int dob;
char address[20];
} id1;
14. Show the difference between Structure from Array.

BASIS FOR COMPARISON


ARRAY STRUCTURE

Basic An array is a collection of variables of A structure is a collection of variables of

same data type. different data type.

Syntax type array_name[size]; struct sruct_name


{
type element1; type element1;
.
.
} variable1, variable2, . .;

Memory Array elements are stored in Structure elements may not be stored in a
contiguous memory location. contiguous memory location.

Access Array elements are accessed by their index number.


Structure elements are accessed by their names.

Operator Array declaration and element accessing Structure element accessing operator is
operator is "[ ]" (square bracket). "." (Dot operator).

Size Every element in array is of same size. Every element in a structure is of


different data type.

Keyword There is no keyword to declare an array. "struct" is a keyword used to declare the
structure.

Accessing Accessing array element requires less Accessing a structure elements require
time. comparatively more time.

Searching Searching an array element takes less Searching a structure element takes
time. comparatively more time than an array
element.
15. Inventtheapplicationofsizeofoperatortothisstructure.
Consider thedeclaration:
struct
{
char name;
int num;
} student;

ANS: Size of the structure is 6 bytes.


17. Summarize the different types of memory allocation functions.
1. malloc() -Used to allocate memory to structures(user define datatype) dynamically.
2. calloc() -Used to allocate memory to arrays(derived datatype) dynamically.
3. realloc() -Used to increase or decrease size to arrays dynamically.
4. free() -Used to delete the memory dynamically.

18. Difference between Malloc() and Calloc() Functions In C:


malloc() calloc()
It allocates only single block of requested It allocates multiple blocks of
memory requested memory

int *ptr;
int *ptr; Ptr = calloc( 20, 20 * sizeof(int) );
ptr = malloc( 20 * sizeof(int) ); For the above, 20 blocks of memory
For the above, 20*4 bytes of memory will be created and each contains 20*4
only allocated in one block. bytes of memory.
Total = 80 bytes Total = 1600 bytes

malloc () doesn’t initializes the allocated calloc () initializes the allocated


memory. It contains garbage values memory to zero

type cast must be done since this function


returns void pointer int *ptr;ptr = Same as malloc () function int *ptr;ptr
(int*)malloc(sizeof(int)*20 ); = (int*)calloc( 20, 20 * sizeof(int) );

19. Ifwehavestructure Bnestedinsidestructure A,whendowe declare structure B?

Either inside the structure A or in main function.

[Link] to create a node in singly liked list?


A linked list is a way to store a collection of elements. Like an array these can be character
or integers. Each element in a linked list is stored in the form of a node.

Node:

A node is a collection of two sub-elements or parts. A data part that stores the element and
a next part that stores the link to the next node.
Linked List:

A linked list is formed when many such nodes are linked together to form a chain. Each node
points to the next node present in the order. The first node is always used as a reference to traverse
the list and is called HEAD. The last node points to NULL.

Declaring a Linked list :

In C language, a linked list can be implemented using structure and pointers .

struct LinkedList
{
int data;
struct LinkedList *next;
};
UNIT 5 FILE PROCESSING 2MQA
1. Define file.
File is a bunch of bytes stored in a particular area on some storage devices like floppy
disk, hard disk, magnetic tape and cd-rom etc., which helps for the permanent storage.

2. Mention different type of file accessing.


There are 2 ways of accessing the files. These are:

Sequential access: the data can be stored or read back sequentially.


Random access: the data can be access randomly.
2. Distinguish between Sequential access and Random access.
Comparing random versus sequential operations is one way of assessing application
efficiency in terms of disk use. Accessing data sequentially is much faster than accessing it
randomly because of the way in which the disk hardware works.
The seek operation, which occurs when the disk head positions itself at the right disk
cylinder to access data requested, takes more time than any other part of the I/O process.
Because reading randomly involves a higher number of seek operations than does sequential
reading, random reads deliver a lower rate of throughput. The same is true for random
writing.

3. What is meant by command line argument.? Give an example.


It is possible to pass some values from the command line to your C programs when they
are executed. These values are called command line argumentsand many times they are
important for your program especially when you want to control your program from outside
instead of hard coding those values inside the code.
The command line arguments are handled using main() function arguments
where argc refers to the number of arguments passed, and argv[] is a pointer array which
points to each argument passed to the program.
Example:
#include <stdio.h>
int main( int argc, char *argv[] ) {

if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}

4. List out the various file handling function.


Function Descriptio
n
fopen() Opens a file.
fclose() Closes a file.
putc() Writes a character.
fputc() Writes a character.
getc() Reads a character.
fgetc() Reads a character.
fseek() Seeks a specified byte in a file.
fprintf() Is to a file what printf() is to the
console.
fscanf() Is to a file what scanf() is to a console.
feof() Returns TRUE if end-of-file is reached.
ferror() Returns TRUE if an error is detected.
rewind() Resets file position to beginning of file.
remove() Erases a file.
fflush() Flushes a file.

5. Compare fseek() and ftell() function.


fseek() ftell()
Seeks a specified byte in a file. ftell function is used to get current
position of the file pointer
Declaration : Declaration:
fseek( file pointer, displacement,pointer position); long int ftell(FILE *fp)

Example: Example:
fseek( p,10L,0) ftell(fp);

6. How to create a file in C ?


fopen() function is used to create a new file or to open an existing file.

General Syntax:
*fp = FILE *fopen(const char *filename, const char *mode);

Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or
created) file.
filename is the name of the file to be opened and mode specifies the purpose of opening
the file. Mode can be of following types,
7. Identifythevarious fileoperationmodesandtheirusage.
mode description

r opens a text file in reading mode

w opens or create a text file in writing mode.

a opens a text file in append mode

r+ opens a text file in both reading and writing mode

w+ opens a text file in both reading and writing mode

a+ opens a text file in both reading and writing mode

rb opens a binary file in reading mode

wb opens or create a binary file in writing mode

ab opens a binary file in append mode

rb+ opens a binary file in both reading and writing mode

wb+ opens a binary file in both reading and writing mode

ab+ opens a binary file in both reading and writing mode

8. How to read and write the file.?


To read and write data types which are longer than one byte, the ANSI standard
provides fread() and fwrite(). These functions allow the reading and writing of blocks of
any type of data. The prototypes are:

size_t fread (void *buffer, size_t num_bytes, size_t count, FILE *fp);
size_t fwrite (const void *buffer, size_t num_bytes, size_t count, FILE *fp);
For fread(), buffer is a pointer to a region of memory which will receive the data
from the file. For fwrite(), buffer is a pointer to the information which will be written.
The buffer may be simply the memory used to hold the variable, for example, &l for a
long integer.
The number of bytes to be read/written is specified by num_bytes. count determines
how many items (each num_bytes in length) are read or written.
fread() returns the number of items read. This value may be less than count if the end of
file is reached or an error occurs. fwrite() returns the number of items written.
One of the most useful applications of fread() and fwrite() involves reading and writing
user- defined data types, especially structures. For example, given this struct ure:
struct struct_type
{
float balance;
char name[24];
}cust;
The following statement writes the contents of cust:
fwrite (&cust, sizeof(struct struct_type), 1, fp)

9. Compare the terms Field, Record and File.


A field is single unit of data that is unique within each entry/row, but the overall data
category is common to all entries. ...
A database record is, basically, a row that contains unique data in each of the fields.
A database will usually contain a large number of records but only a small number
of fields.
File is a collection of records.

11. Examine the following:‐


(i) getc() and getchar() (ii)scanf and
fscanf() getc():
It reads a single character from a given input stream and returns the corresponding integer
value (typically ASCII value of read character) on success. It returns EOF on failure.
Syntax:
int getc(FILE *stream);
getchar():
The difference between getc() and getchar() is getc() can read from any input stream, but
getchar() reads from standard input. So getchar() is equivalent to getc(stdin).
Syntax:
int getchar(void);

12. Distinguish between following:‐


(i).printf () and fprintf() (ii).feof() andferror()
printf ()
printf() is used to print the data onto the standard output which is often a computer
monitor(screen).
Syntax: printf("format", args);
fprintf()
fprintf() is like printf() again. Here instead on displaying the data on the monitor, or saving it in
some string, the formated data is saved on a file which is pointed to by the file pointer which is used as
the first parameter to fprintf. The file pointer is the only addition to the syntax of printf.

Syntax: fprintf(FILE *fp, "format", args);

feof():
It checks ending of a file. It continuously return zero value until end of file not come and return non zero
value when end of file comes.
Syntax:
feof(file pointer);
ferror():
It checks error in a file during reading process. If error comes ferror returns non zero value. It
continuously returns zero value during reading process.
Syntax:
ferror(file pointer);

13. Mentionthe functionsrequiredfor Binaryfile I/Ooperations.


1. fread()
[Link]()
[Link]()
[Link]()
14. Identify the different types of file.
1. Text files
Data stored as ASCII Values
Eg. .txt,.docx,.doc
2. Binary files
Data stored as 0s and 1s
Eg. .bin,.exe
15. Identifythedifferencebetween AppendandWrite Mode.
 Write (w) mode and Append (a) mode, while opening a file are almost the same. Both
are used to write in a file. In both the modes, new file is created if it does not already
exist.
 The only difference they have is, when you open a file in the write mode, the file is
reset, resulting in deletion of any data already present in the file.
 While in append mode this will not happen. Append mode is used to append or add
data to the existing data of file, if any.
 Hence, when you open a file in Append (a) mode, the cursor is positioned at the end
of the present data in the file.
16. What is the use of rewind() functions.
rewind function sets the file position to the beginning of the file for the stream pointed to
by stream. It also clears the error and end-of-file indicators for stream.
Syntax
void rewind(FILE *stream);
17. Write a C Program to find the Size of a File.
#include <stdio.h>
void main(int argc, char **argv)
{
FILE *fp;
char ch;
int size = 0;
fp = fopen(argv[1], "r");
if (fp == NULL)
printf("\nFile unable to open ");
else
printf("\nFile opened ");
fseek(fp, 0, 2); /* file pointer at the end of file */
size = ftell(fp); /* take a position of file pointer un size variable */
printf("The size of given file is : %d\n", size);
fclose(fp);
}
Output:
File opened The size of given file is : 3791744

18. Write the Steps for Processing a File


1. Creating a new file
2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file.

19. Write a code in C to defining and opening a File.


#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("[Link]","r") // Open file in Read mode
fclose(fp); // Close File after Reading
return(0);
}

20. Why do we use command line arguments in C?

It is possible to pass some values from the command line to your C programs when they
are executed. These values are called command line arguments and many times they are
important for your program especially when you want to control your program from outside
instead of hard coding those values inside the code.
The command line arguments are handled using main() function arguments
where argc refers to the number of arguments passed, and argv[] is a pointer array which
points to each argument passed to the program.
Example:
#include <stdio.h>
int main( int argc, char *argv[] )
{
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.\n");
}
else
{
printf("One argument expected.\n");
}
}
QUESTION BANK
SUBJECT : Programming in
C
SEM / YEAR : Second Semester / 1st Year
UNIT I - BASICS OF C PROGRAMMING
Introduction to programming paradigms - Structure of C program - C programming: Data Types –Storage
classes - Constants – Enumeration Constants - Keywords – Operators: Precedence and Associatively -
Expressions - Input/output statements, Assignment statements – Decision making statements - Switch
statement – Looping statements – Pre-processor directives - Compilation process

PART A
[Link] Questions
1. Define programming paradigm.
2. Give two examples for assignment statements.
3. Distinguish between character and string.
4. What are keywords? Give an example.
5. What do you mean by variables in ‘C’?
6. Identify the use of ternary or conditional operator.
7. What is mean by Operators precedence and associative?

8. What is a compilation process?


9. How to create enumeration constants ?
10. Differentiate between an expression and a statement in C.
11. What is the output of the programs given below? #include
<stdio.h>
main()
{
int a = 20, b = 10, c = 15, d = 5;
int e;
e = (a + b) * c / d;
printf("Value of (a + b) * c / d is : %d\n", e );
}

ANS: Value of (a + b) * c / d is : 90

12. Generalize the types of I/O statements available in


‘C’.
13. Classify the different types of storage classes.
14. Discover the meaning of C pre-processor.
15. Invent the difference between ++a and a++.
16. Differentiate switch( ) and nested-if statement.
17. Summarize the various types of C operators.
18. Recommend the suitable example for infinite loop
using while.
19. What is a global variable?
20. Differentiate break and continue statement.
Part B
1. Describe the structure of a C program with an example.(16)

2. Discuss about the constants, expressions and statements in ‘C’. (16)

3. Illustrate about the various data types in ‘C’. (16)

4. Summarize the various types of operators in ‘C’ language along with its priority. (16)

5. Explain about the various decision making and branching statements. (16)

6. Write short notes on the following: (6+5+5)


a. ‘for’ loop
b. ‘while’ loop
c. ‘do…while’ loop
7. Illustrate the storage class specifiers with example. (16)
8. Discuss about pre processor directive with example program. (16)
9. Explain the following:
i. Keywords (3)
ii. Identifiers (4)
iii. C character set (4)
iv. Constants and volatile variables (5).
10. Write a C program for the following :
a. To check whether a given year is leap or not.(4)
b. To find the roots of a quadratic equation.(8)
c. To convert the temperature given in Fahrenheit to Celsius(4)
11. Develop a C program for the following :
a. To find the area and circumference of a circle with radius r.(4)
b. To find the sum of first 100 integers.(6)
c. To reverse the digits of a number. (123 => 21).(6)

12. Write a C program for the following :


a. To find the sum of the digits of a number. (123 => 1+2+3=6.(5)
b. To find the sum of all odd / even numbers between 1 and 100.(5)
c. To check whether a number is prime or not.(6)

13. Write a C program for the following :


a. To check whether a given number is a
palindrome (232) or not. (8)

b. To generate the first n numbers in a Fibonacci series. (8)

14. Write a C program for the following :


a. To generate Armstrong number between 100 and 999. (8)
[Link] Sin(x) = x - x3/3! + x5/5!- x7/7!+…..+ xn/n!. (8)
UNIT II - ARRAYS AND STRINGS
Introduction to Arrays: Declaration, Initialization – One dimensional array – Example Program: Computing
Mean, Median and Mode - Two dimensional arrays – Example Program: Matrix Operations (Addition, Scaling,
Determinant and Transpose) - String operations: length, compare, concatenate, copy – Selection sort, linear and
binary search.

PART A
[Link] Questions
1. List out the features of Arrays.

2. Define a float array of size 5 and assign 5 values to it.

3. Identify the main elements of an array declaration.

4. What are the drawbacks of Initialization of arrays in C?

5. What will happen when you access the array more than its dimension?

6. Point out an example code to express two dimensional array.

7. How to create a two dimensional array?

8. What is the starting index of an array?

9. Distinguish between one dimensional and two dimensional arrays.

10. What are the different ways of initializing array?

11. What is the use of ‘\0’ and ‘%s’?

12. Is address operator used in scanf() statement to read an array? Why?

13. What is the role of strrev()?

14. Discover the meaning of a String.

15. How to initialize a string? Give an example.

16. Differentiate between Linear search and Binary search.

17. Write the output of the following Code:


main()
{
char x; x = ‘a’; printf(“%d \n”,x);
}

18. Specify any two methods of sorting.

19. List out the any four functions that are performed on character
strings.
20. Write the output of the following Code:
main()
{
static char name[]=”KagzWrxAd” int i=0;
while(name[i]!=’\0’)
{
printf(“%c”,name[i]); i++;
}}

PART B
1. (i) Explain the need for array variables. Describe the following with respect to
arrays:-
Declaration of array and accessing an array element. (8)
(ii) Write a C program to re-order a one-dimensional array of numbers in descending
order. (8)
2. Write a C program to perform the following matrix operations:
(i) Addition (5) (ii) subtraction (5)
(iii) Scaling (6)
3. .Write a C program to calculate mean and median for an
array of elements.(8+8)
4. Write a C program for Determinant and transpose of a matrix.(8+8)

5. Describe the following with suitable examples. (8+8)


(i) Initializing a 2 Dimensional Array(ii) Memory Map of a
Dimensional Array.
6. Explain about the String Arrays and its manipulation in detail (16)
7. .(i). Write a C program to find average marks obtained by a of 30 students in a test.(10)
(ii).Write short notes on Reading and Writing string. (6)

8. Write a C program to sort the n numbers using selection sort


(16)
9. Develop a C program to search an element from the array.
(16)
10. Describe the following functions with examples. (4+4+4+4)
(i) strlen() (ii) strcpy() (iii)strcat() (iv)strcmp()

11. Write a C program to find whether the given string is palindrome or not without
using string functions. (16)

12. Write a C program to count the number of characters, spaces, vowels, constants and others
using string functions. (16)
13. Discuss about the following :-
(i).Advantages and disadvantages of linear and binary search.(8)
(ii).Discuss briefly runtime initialization of a two dimensional array.(8)

14. Explain about the following : (i).String and character array.(6)


(ii).Initialising a string variables.(4) (iii).String input and
output (6)
UNIT III-FUNCTIONS ANDPOINTERS
Introduction to functions: Function prototype, function definition, function call, Built‐in functions (string functions,
math functions) – Recursion – Example Program: Computation of Sine series, Scientific calculator using built‐in
functions, Binary Search using recursive functions – Pointers – Pointer operators – Pointer arithmetic – Arrays and
pointers – Array of
pointers – Example Program: Sorting of names – Parameter passing: Pass by value, Pass by reference – Example
Program: Swapping of twonumbersandchangingthevalue of avariableusingpassbyreference.

PART A
[Link] Questions
1. Define pointer. How will you declare it?

2. What is a pointer to a pointer?

3. Expresstheoperations that canbeperformed onpointers.

4. What is pointer arithmetic?

5. What is a void pointer and a null pointer?

6. Differentiate between address operator and indirection


operator?
7. Why is pointer arithmetic not applicable onvoid pointers?

8. Identify the use of Pointer.

9. Point out the meaning of user‐defined function.

10. What is meant by library function?

11. Write the syntax for function declaration

12. Compose the two parts of function definition.

13. What is meant by pass by value and pass by reference?

14. What is a function call? Give an example ofafunction call.

15. Invent the meaning ofdefault arguments andcommand line arguments.

16. What is a recursive function?

17. Specify the need for function.

18. Assess the meaning of function pointer.

19. What is array of pointer?

20. Mention the advantage of pass by reference.

PART B
1. Describe about pointers and their operations that can be performed on it.(16)

2. What is an array of pointers and what is pointer to an array? Explain in detail with
example(16)
3. Demonstrate about function declaration and function definition. (16)

4. Discuss about the classification of functions depending upon their inputs and output
(parameters) (16)
5. Explain in detail about Pass by Value and Pass by reference.
(16)
6. Discuss about passing arrays to function. (16)
7. Explain in detail about recursive function with sample code. (16)

8. Explain in detail about function pointers. (16)


9. Write notes on fixed argument functions and variable argument functions. (16)

10. What are the applications of recursive function? Computation of Sine series using C
program. (16)
11. Write a C program for Scientific calculator using built-in functions(16)

12. Write a C program for Swapping of two numbers and


changing the value of a variable using pass by reference(16)
13. Write a C program to sort the given N names. (16)
14. Explain any eight built in functions of math. (16)

UNIT-IV-STRUCTURES
Structure‐Nestedstructures–PointerandStructures–Arrayofstructures–ExampleProgram usingstructures and
pointers – Self referential structures – Dynamic memory allocation ‐ Singly linked list ‐typedef
PART A
[Link] Questions

1. What is structure? Write the syntax for structure.


2. Write the various operations on structure.
3. How the members of structure object is accessed?
4. Write the use of size operator on structure.
5. What is a nested structure?
6. How typedef is used in structure?
7. Interpret the term Union in C.
8. What is mean by Self referential structures.
9. Point out the meaning of Dynamic memory allocation.
10. Mention any two application linked list.
11. What is the need for typedef ?
12. Generalize the operators used in access the structure members.

13. Discover the meaning of Array of structure.


14. Show the difference between Structure from Array.
15. Invent the application of size of operator to this structure. Consider the declaration:
struct
{
char name; intnum;
} student;
16. Show a structure called ID_Card to hold the details of a student.

17. Summarize the different types of memory allocation functions.

18. Discriminate between malloc and calloc.


19. If we have structure B nested inside structure A, when do we
declare structure B?
20 How to create a node in singly liked list?
PART B
1. Describe about the functions and structures. (16)
2. Explain about the structures and its operations. (16)
3. Demonstrate about pointers to structures, array of structures and nested structures.(5+6+5)

4. Write a C program using structures to prepare the students mark statement. (16)

5. Writea Cprogram using structures to preparethe employee pay roll of a company. (16)

6. Write a C program to read the details of book name, author name and price
of 200 books in a library and display the total cost of the books.(16)

7. (i).What is a structure? Express a structure with data members of various types and
declare two structure variables. Write a program to read data into these and print the
same. (10)
(ii).Justify the need for structured data type.(6)

8. (i).What is the need for structure data type? Does structure bring additional
overhead to a program? Justify. (10)
(ii). Write short note on structure declaration(6)

9. (i).How to Accessing the structure member through pointer using dynamic memory allocation.
(8)
(ii). Referencing pointer to another address to access the memory(8)
10. Explain with an example the self‐referential structure. (16)

11. Explain singly linked list and write C Program to Implement Singly Linked List using
Dynamic Memory Allocation. (16)

12. Discuss about the following :‐


(i).Singly linked list and operation.(8) (ii).Advantage and
disadvange of Singly linked list.(8)

13. Illustrate a C program to store the employee information using structure and search a
particular employee details. (16)
14. Define a structure called student that would contain name, regno and marksoffive
subjects and percentage. WriteaC program to read the details of name, regno and
marks of five subjects for 30students andcalculate thepercentageand display the
name, regno, marks of 30 subjects and percentage of each student.(16)
UNIT-V- FILE PROCESSING
Files – Typesoffileprocessing: Sequential access, Random access – Sequential access file‐ Example Program:
Finding average of numbers stored in sequential access file ‐ Random access file‐Example Program: Transaction
processing using random access files – Command line arguments

PART A
[Link] Questions

1. Define file.
2. Mention different type of file accessing.
3. Distinguish between Sequential access and Random access.
4. What is meant by command line argument.? Give an example.

5. List out the various file handling function.


6. Compare fseek() and ftell() function.
7. How to create a file in C ?
8. Identify the various fileoperation modes and their usage.
9. How to read and write the file.?
10. Compare the terms Field, Record and File.
11. Examine the following:‐
(i) getc() and getchar() (ii)scanf and fscanf()

12. Distinguish between following:‐ (i).printf () and fprintf() (ii).feof() and


ferror()

13. Mention the functions required for Binary file I/O operations.

14. Identify the different types of file.

15. Identify the difference between Append and Write Mode.

16. What is the use of rewind() functions.

17. Write a C Program to find the Size of a File.


18. Write the Steps for Processing a File

19. Write a code in C to defining and opening a File.

20 Why do we use command line arguments in C?

PART B
1. Describe the following file manipulation functions with examples.(16)
a)rename().(2)
b)freopen().(4)
c)remove().(2)
d)tmpfile(void).(4)
e)fflush().(4)
2. Distinguish between the following functions.(16)
a)getc() and getchar().(4)
b)scanf() and fscanf().(4)
c)printf() and fprintf().(4)
d)feof() and ferror().(4)
3. Illustrate and explain a C program to copy the contents of one
file into another.(16)
4. Explain the read and write operations on a file with an
suitable program.(16)
5. Describe the various functions used in a file with example.(16)

6. Write a C Program to print names of all Files present in a Directory.(16)

7. WriteaC Programto read contentofaFileanddisplay it. (16)

8. Write a C Program to print the contents of a File in


reverse.(16)
9. Write a C Program Transaction processing using random
access files.(16)
10. Write a C program Finding average of numbers stored in
sequential access file.(16)
11. Explain about command line argument with suitable example.(16)

12. Compare Sequential access and Random access file .(16)

13. Write a C Program to calculate the factorial of a number by using the command line argument.(16)

14. Write a C Program to generate Fibonacci series by using command line arguments.(16)

You might also like