0% found this document useful (0 votes)
35 views12 pages

C 2marks With Ans

The document discusses various topics related to C programming language including operators, loops, data types, functions, arrays, pointers and more. It provides examples of writing for loops, defining macros, declaring variables and arrays, different input/output functions, and more.

Uploaded by

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

C 2marks With Ans

The document discusses various topics related to C programming language including operators, loops, data types, functions, arrays, pointers and more. It provides examples of writing for loops, defining macros, declaring variables and arrays, different input/output functions, and more.

Uploaded by

AARTHY R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 12

CS8251 - PROGRAMMING IN C

UNIT-I
1. What are the various types of operators?
C supports the following types of operators
Unary
Unary Plus +
Unary Minus -
Increment ++
Decrement --
Binary
Arithmetic +,-,*,/,%
Relational <,>,<=,>=,==,!=
Logical &&,||,!
Bitwise &,|,^,<<,>>
Assignment =
Shorthand assignment +=, -=,*=,/=,%=
Ternary
?:
Special
Sizeof(), *. ->

2. Write a for loop to print from 10 to 1


for(i=10;i>0;i--)
printf(“%d”,i);

3. Write any two preprocessor directives in C


Preprocessor directive instructions are used to instruct the preprocessor to expand/translate the
source program before compilation
The two types of preprocessor directives are,
#define to define Macro , Global constant
#include to include library files

4. List different datatypes available in C


Data types are used to specify the type of a variable. In c, the data types are classified into 3
category. They are,
Primary or Built-in : int , char, float
Derived : array, enum, pointer
User defined : function, structure

5. Write a C program to find factorial of a given number using Iteration


void main()
{
int N=5,I,fact=1;
for(i=1;i<=N;i++)
fact=fact*i;
printf(“The factorial value of %d is =%d”,N,fact);
}
6. What is the use of preprocessor directive?
- Used to translate one high level language statement into another high level language statement.
- Used to instruct the preprocessor that how it performs the translation before compilation.
- Used to perform conditional compilation.
- Used to include other C files or library files.

7. What is the variable? Illustrate with an example


- Variable is a named storage area
- Used to assign a name to a value
- To declare a variable, we need to specify the data type of the value and the variable name
Data type variable _name ;
- Example
int reg; float avg;

8. Define static storage class


- Storage class specifies the visibility & life time of a variable
- Static storage class initializes a variable to 0.
- Longer life time – Exists throughout the execution of program
- Visibility to all-Any function can access the variable- Shared by all

9. What is the use of #define preprocessor


The #define preprocessor directive is used to define a
Global constant #define PI 3.14
Macro #define big(a,b) a>b?a:b
When a compiler reads the macro name, it replaces the macro name by its expansion. When it reads the
constant label, it replaces the label by its value.

10. What is the importance of keywords in C?


Keywords are reserved identifiers
They performs a specific task , specifies the data type
Keyword can not be used as an identifier
Ex: for , if , int

11. List out various Input & output statements in C


The input & output statements are classified into formatted & unformatted I?O
Formatted I/O : User can able to design/format the output
Unformatted I/O: doesn’t allow the users to design the output
Type Input Output
Formatted scanf() printf()
Unformatted Getch(), getche() putch(), putchar()
getchar() puts()
gets()
12. What is meant by linking process?
Linking is a process of binding the function call to its definition and binding the label to its reference.
During the linking process the object file is created. This file can be loaded into memory for execution

UNIT- II
1. Define Array
Array is a collection of similar type of values
All values are stored in continuous memory locations
All values share a common name
Linear data structure. The elements are organized in a sequential order.

2. Name any two library functions for handling string


strlen() – finds the length of a string. It returns an integer value. It counts the no. of characters except
null character & returns the count
strlen(str)
strcpy() – copies the source string into destination string. So, the source string should be enough to store
the destination string.
strcpy(source,destination)

3. Declare a float array of size 5 and assign 5 values to it


Declaration : float price[5];
Initialization : float price[5]={200.50,150.25,25.5,55.75,40.00}; (or)
float price[]={1.2,3.4,6.5,7.8,9.8};

4. Give an example for initialization of string array


String is a character array.
Collection of one or more characters- enclosed with in double quotes
Declaration : char name[10];
Initialization : char name[10]=”India”;
car name[10]={‘I’,’n’,’d’,’i’,’a’};
The char array is terminated by ‘\0’

5. How a character array is is declared


Declaration : char name[n];
This array can store n-1 characters.
Initialization : char name[10]=”India”;
car name[10]={‘I’,’n’,’d’,’i’,’a’};
The char array is terminated by ‘\0’

6. Write example code to declare two dimensional array


Two dimensional array is an array with two subscript values. First subscript specifies the row & second
subscript specifies the column. Used to process matrix operations.
Declaration : datatype array_name [r][c];
int matrixA[10][10];
This matrixA can store 100 elements in a row major order.
7. What is mean & median of a list of elements?
Mean : Average of the N elements can be computed by
sum of N elements/N
Ex: 2,1,3,4,5
Mean = (2+1+3+4+5)/5 = 3
Median : Middle element of a list. To find the median, the list must be sorted first.
If N is odd then Median= (N+1)/2
Ex: 1,2,3,4,5
Median= 6/2 . The element at 3rd position is the median

If N is even then then Median is the average of


Median= (a[(N+1)/2]+a[(N-1)/2])/2
Ex: 1,2,3,4,5,6
Median=(a[3]+a[2])/2
=4+3/2
=3.5
8. Define Searching
Searching is a process of finding the position of a given element in a list. The searching is successful if
the element is found. There are two types of searching.
Linear Search
Binary Search

9. Define Sorting
Sorting is a process of arranging the elements either in ascending order or descending order.

10. Sort the following elements using selection sort method. 23,55,16,78,2
Step1:Find smallest element in the list & exchange the element with first element of the list
2,55,16,78,23
Step2: Find second smallest value & exchange it with the second element of the list
2,16,55,78,23
Step 3: Continue the process until all the elements are arranged in the order
2,16,23,78,55
Step 4: 2,16,23,55,78

UNIT-III
1. What is a function?
Function is a set of instructions
Self contained block
Performs a specific task
Used to avoid redundancy of code
2. What is the need for functions?
To reduce the complexity of large programs
To increase the readability
To achieve reusability
To avoid redundancy of code
To save Memory

3. What are the uses of pointer?


Saves Memory Space
Used for dynamic memory allocation
Faster execution
Used to pass array of values to a function as a single argument

4. Define recursion
Recursion is a process by which a function calls itself. Recursive function is a function that calls itself.

5. What is an Address operator & Indirection operator?


Address operator: & -used to assign the address to a pointer variable, Referencing operator
Indirection operator: *- Dereferencing operator is used to access the value at the pointer variable
Ex: int a=5;
int *p=&a;
printf(“%d”,*(p));

6. What is the difference between Pass-by-value & Pass-by-reference

Pass-by-value Pass-by-reference
Copy of actual arguments are passed Address of actual arguments
are passed
Changes to formal arguments doesn’t Changes to formal arguments
reflect to actual argument reflect to actual argument
Need more memory Saves memory space

7. Compare actual parameter & formal argument


Actual argument: Specified in the function call statement. Used to supply the input values to the
function either by copy or reference
Formal argument: Specified in the function definition statement. It takes either copy or address of
the actual arguments

8. How is pointer arithmetic done?


Pointer Arithmetic:
Valid operation
Pointer can be added with a constant
Pointer can be subtracted with a Constant
Pointer can be Incremented or Decremented
Not Valid
Two pointers can not be added,subtracted,multiplied or divided
Ex: int a=10
int *p=&a; p 2000 a 10
p=p+1; 2000

2002

The pointer holds the address 2000. This value is added with 1. The data type size of the constant is
added with the address.
p= 2000+(2*1)=2002

9. List out any 4 math functions


pow(x,y) : used to find power of value of xy .Returns a double value
log10(x) : used to find natural logarithmic value of x
sqrt(x) : used to find square root vale of x
sin(x) : returns sin value of x

10. What is a function prototype?


Function prototype is a function declaration statement.
It consists of 3 things
Return type function-name ( param list)
Ex: int factorial(int);

UNIT-IV
STRUCTRES
1. What do you mean by structure?
Structure is a user defines data type. It is a collection of different types of values.
It is a heterogeneous data type. C allows the programmer to create a new data type using structure.
Different types of vales stored under a common name. The values in a structure are called structure
member. These members are accessed by structure variable.
2. Define self referential structure?
A structure is said to be self referential structure if it contains a pointer to its same structure type. This
self referential structure is used to create linked list nodes.
Example:
struct node
{
int value;
struct node * next;
};

3. How will you allocate memory dynamically?


Memory space is allocated either during the compile time & run time. The memory space can be
allocated during run time with the help of following functions
malloc : Memory Allocation : (type*) malloc (size of type)
It allocates the specified size of memory.
calloc : Contiguous Memory Allocation : (type *) calloc (size of type)
It allocates the specified size of memory & initialize the blocks to zero.
Realloc: Re allocation : (type *) realloc(size of type)
It is used to reallocate the space that is already allocated by malloc & calloc function, if the
space allocated by these functions are not enough to store the values.

4. What is the use of typedef?


Type def is a user defined data type. It is used to define a new data type.
Syntax: typedef old-type new-type

Example: typedef int I;


void main()
{
I a=2,b=3;
printf(“%d”,a+b);
}
5. What is Nested Structure?
Structures can be nested in C. A structure contains structure members. A structure can be declared with
in another structure. Nested structure is a structure which contains other structure as its members.
Nested structure is used to represent and process complex data.
Example:
structure Marksheet //Outer Structure
{
int m1,m2;
struct student //Inner strcture
{
int regno;
char name[20];
}s1;
}m1;

The inner structure members can be accessed by outer structure variable.


Ex: m1.s1.name={“raju”};

6. Define Data structure & state its types


Data structure is a way of organizing data items into memory. The types of data structures are,
Linear Data structure : elements are in sequential order Array,Linked list,stack 7 queue
Non Linear Data structure ; elements are stord in random order and a relationship is maintained between
the elements.Ex:Ttree & Graph

7. How will you implement data structure?


Data structures can be implemeted either by
Array implementation
Size is fixed. Spaces are allocated during compile time. Elements are stored in continuous
memory location
Linked List Implementation
Spaces are allocate dynamically. List size can be shrink or grow during execution time.
Elements are stored in memory wherever free space is available. Pointer is used to link the elements.

8. What is Linked List? & List out its types


Linked list is a collection of nodes. A node consists of a value and a next field. The next field points next
node in the list. The types of linked lists are,
singly linked list – node has 2 fields, value & next link
Doubly linked list – node has 3 fields, value, previous link & forward link
Circularly linked list – the next field of last node points first node of the list

9. Define a structure called ID card to hold the student details


struct IDcard
{
char stuname[30];
int regno;
char DOB[20],dept[10],class[20];
char address[100];
int monile;
};

10. How will you declare & initialize a structure?


Structure declaration
Syntax: struct structname Example: struct employee
{ {
Datatype member1; int empid;
Datatype member2; char empname[40];
Datatype member3; float salary;
}; };
Initialization of a structure
Syntax: struct structname
{
Members;
}var={values};
(or)

struct structname
{
Members;
};
void main()
{
struct structname structvar={values};
}
Example:
struct employee
{
int empid;
char empname[40];
float salary;
}e={101,abc,60000};

11. Define pointer to structure


Pointer is a variable that hold the address of another variable. C allows us to declare a pointer for a
structure.
Syntax: struct structname *structvar;
struct employee *e;
e is a pointer to a structure of type employee.

12. Create a structure for a complex number


struct comples
{
float real
float img;
};
UNIT-V
FILE PROCESSING

1. Define File
File is a collection of related records. File is used to store the data. A collection of data which is
stored on a secondary device like a hard disk is known as a file. A file is generally
used as real-life applications that contain a large amount of data.

2. Differentiate types of files


Types of files:
Text file : In text file the content is represented in terms of characters. It can be easily readable.
Ex: .txt, .xls ,.doc ,.c ,.java
Binary file : In binary file , the content is represented in terms of binary form. It can not be easily
readable. It occupies less memory than text files. Ex: .bin, .obj, .bmp, .exe

3. What is sequential & Random access

4. What are the modes of operation


“r” It opens an existing file for reading only.

“w” It opens a new file for writing. If the filename does not exist
it will be created and if the file already exists then its
contents are deleted.
“a” It appends the existing file. If the filename does not exist it
will be created.

“r+” It opens an existing file for reading and writing. It indicates


that the file is to be read before writing.

“w+ It opens a new file for reading and writing. If a file with the
” current filename exists then it is destroyed and a new file
name is created.

“a+” It opens an existing file for reading and appending. Its


stream is positioned at the end of the file content.

For Binary File the mode of operations are: rb,wb,ab,rb+,wb+,ab+

5. List out the functions used to perform random access


Random access functions are used to access the records in a file randomly.
The functions are:
1.fseek(): This function is used to move a file pointer to a desired location.
Syntax: fseek ( file pointer, offset, whence);
Where, file pointer is the pointer created for a file
Offset: specifies no. of bytes to be skipped (+ve value- forward direction, -ve value:
backward direction)
Whence : position from where the file pointer has to be moved.
(SEEK_CUR,SEEK_SET,SEEK_END)
2.ftell() : returns the current position of file pointer ftell(fp)
3. rewind() : move the file pointer to the beginning of the file.

6. What are the functions used to read & write a file content?
 fgetc() : fgetc(fp) - reads a single character from a file
 fputc() : fputc(ch,fp) - writes single character into a file
 fgets(): fgets(char array,no. of bytes,fp) : reads a string from a file
 fputs() : fputs(char array,fp) ; writes a string into a file
 fscanf() : fscanf(fp,”format string”,address of variables): reads different types of values form file
 fprintf(); fprintf(fp,”format string”,variables): writes different types of value into a file
 fread() : fread(ptr,size of record,no.of records,fp) : reads record from a file
 fwrite(): fwrite(ptr,size of record,no.of records,fp): writes record into a file

7. Describe command line arguments


Command line argument is a parameter supplied to the program when it is invoked. It is used to pass
arguments to main() function.
Syntax: void main(int argc,char *argv[])
argc : specifies the total number of arguments passed to the main function
argv[]: It is a char array. It is used to hold the input values
8. Differentiate text file & random file
Text File Binary File

Bits represent character. Bits represent a custom data.

Less prone to get corrupt as changes

reflect as soon as the file is opened Can easily get corrupted, even a single

and can easily be undone. bit change may corrupt the file.

Can store different types of data

Can store only plain text in a file. (image, audio, text) in a single file.

Developed especially for an application

Widely used file format and can be and may not be understood by other

opened using any simple text editor. applications.

Mostly .txt and .rtf are used as Can have any application defined

extensions to text files. extension

9. List out the file handling operations


To access files in C
1. Creating a file pointer : FILE is file structure which consists of file related information. Create a file
pointer to this structure to access a file using c program.File pointer is a pointer variable that points
the content of a file. FILE *filepointer.
2. Opening a file: fopen() function is used to open a file. This function returns the file reference if
success, otherwise it returns error. Fileptr=fopen(“filename,”mode”)
3. Reading & writing : To read from a file or write into a file the following functions are used,
fgetc(),foutc(),fgets(),fputs(),fscnf(),fprintf(),fread() & fwrite().
4. Closing a file : When we close a file the file is released from memory and the file resides in hard disk
get updated. Fclose(fileptr).

10. Define EOF & feof()


Bothe EOF & feof() are used to check whether the file pointer is at the end of the file content.
EOF indicates "end of file".The value of EOF is -1 .
feof() : The function feof() is used to check the end of file after EOF. It tests the end of file indicator. It
returns non-zero value if successful otherwise, zero.
11. What is random access?
A random-access data file enables you to read or write information anywhere in the file.
We can read or modify any desired record. The file pointer can be moved to any desired position in the
file.

12. What is sequential access?


Read and write operation is done sequentially, starting from the beginning of the file. The file pointer
can not be moved to any desired position. The file pointer can move to next byte after reading the
previous byte.

You might also like