c program question bank
c program question bank
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
(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
(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
{
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.
.
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;
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.
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,
In the above example, the list node is a self-referential structure – because the *next is of the
type struct list node.
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 ];
Memory Array elements are stored in Structure elements may not be stored in a
contiguous memory location. contiguous memory location.
Operator Array declaration and element accessing Structure element accessing operator is
operator is "[ ]" (square bracket). "." (Dot operator).
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;
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
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.
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.
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");
}
}
Example: Example:
fseek( p,10L,0) ftell(fp);
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
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)
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);
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?
ANS: Value of (a + b) * c / d is : 90
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)
PART A
[Link] Questions
1. List out the features of Arrays.
5. What will happen when you access the array more than its dimension?
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)
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)
PART A
[Link] Questions
1. Define pointer. How will you declare it?
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)
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)
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
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)
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.
13. Mention the functions required for Binary file I/O operations.
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)
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)