0% found this document useful (0 votes)
0 views60 pages

C PROGRAMMING final notes

The document outlines key concepts and components of the C programming language, including the structure of a C program, the main function, data types, variables, operators, and control statements. It also discusses the evolution of C, keywords, constants, and input/output statements. Additionally, it provides examples and explanations of various programming constructs such as loops, conditionals, and storage classes.

Uploaded by

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

C PROGRAMMING final notes

The document outlines key concepts and components of the C programming language, including the structure of a C program, the main function, data types, variables, operators, and control statements. It also discusses the evolution of C, keywords, constants, and input/output statements. Additionally, it provides examples and explanations of various programming constructs such as loops, conditionals, and storage classes.

Uploaded by

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

Dr.

NNCE I / 02 C / QB

CS3251- PROGRAMMING IN C

I YEAR / II SEMESTER

PREPARED BY

Mrs. T.THENDRALKANI, CSE Asst PROFESSOR.

VERIFIED BY

HOD PRINCIPAL MD/DIRECTOR

DEPARTMENT OF COMPUTER SCIENCE ENGINEERING AND INFORMATION TECNOLOGY

DR. NAVALAR NEDUNCHEZHIYAN COLLEGE OF ENGINEERING

THOLUDUR- 606 303

1
Dr.NNCE I / 02 C / QB

PART- A 2 Marks
1. Write down the steps involved in writing a program to solve a problem.
To design a program, a programmer must determine three basic steps:
a. The instruction to be performed.
b. The sequence in which those instructions are to be performed.
c. The data required to perform those instructions.

2. List out the various stages in evolution of C.


The various stages in evolution of C are as follows

Language Year Founder


ALGOL 1960 International group
BCPL 1967 Martin Richards
B 1970 Ken Thompson
C 1972 Dennis Ritchie
K & RC 1978 Kernighan and Ritchie
ANSIC 1989 ANSI Committee
ANSI/ISO C 1990 ISO Committee

3. What is the use of main ( ) function in C program? (May 2009)


Every C program must have main () function. All functions in C, has to begin with (and 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.

4. List out the delimiters in C.


The delimiters in C are
a. : Colon
b. ; Semicolon
c. ( ) Parenthesis
d. [ ] Square Bracket
e. { } Curly Brace
f. # Hash
g. , Comma

5. What is the purpose of main( ) in C?


main ( ) is a special function used by the C system to tell the computer where the program
starts. Every program must have exactly one main function. The empty parenthesis
immediately following main indicates that the function main has no arguments.

2
Dr.NNCE I / 02 C / QB

6. Following are the escape sequences in C


a. \n -new line
b. \t –tab
c. \a –alert
d. \0 –null

7. What do you meant by C Tokens?


C tokens are the basic buildings blocks in C language which are constructed together to write
a C program. Each and every smallest individual unit in a C program are known as C tokens.
„C‟ language contains the individual units called C tokens. C tokens are of six types. They are as
follows
a. Keywords (Ex: int, while)
b. Identifiers (Ex: main, total)
c. Constants (Ex: 10, 20)
d. Strings (Ex: “total”, “hello”)
e. Special symbols (Ex: (), {})
f. Operators (Ex: +, /,-,*)

8. What is a variable? Illustrate with an example. (Nov 2014)


A variable is an entity whose value can vary during the execution of a program. A variable can be
assigned different data items that at various places within the program. A variable is a data name
used for storing a data value. It can be assigned different values at different times during program
execution. Ex: a=3, b=5.

9. What are the different data types available in C? (June 2014)


Basic /Primitive Data Types Derived Data Types
Integer types (signed int, unsigned int) Arrays
Floating Type (float, double) Pointers
Character types (signed char) Structures, Enumeration

User Defined Data Types Void


Structure, Union

10. What is meant by Enumerated data type?


Enumerated data type is a user defined data type in C language. Enumerated data type
variables can only assume values which have been previously declared.
Ex. enum month { jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec};

3
Dr.NNCE I / 02 C / QB

11. What are Keywords? What is the importance of keywords in C? (May 2015) Keywords
are pre-defined / reserved words in a C compiler. Each keyword is meant to can be used only for a
specific function in a C program. Since keywords are referred names for compiler, they can‟t be
used as variable name. Ex. auto, break, const, else

12. Define Constants in C. Mention the types.


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 constant. Ex. const int LENGTH = 10

13. Differentiate between Local and Global Variable.


Local Variable Global Variable
a. Variables are declared inside a function. a. Variables are declared outside any
b. They are accessed only by the statements, function.
inside a function in which they are b. They are accessed by any statement in the
declared. entire program.
c. Local variables are stored on the stack, c. Stored on a fixed location decided by a
unless specified. compiler.
d. Created when the function block is d. Remain in existence for the entire time
entered and destroyed upon exit. your program is executing.
e. They are unknown to other functions and e. They are implemented by associating
to the main program. memory locations with variable names.
f. They are recreated each time a function is f. They do not get recreated if the function
executed or called. is recalled

14. What is different between a constant and variable? (Jan 2010)


Variable Constant
a. A variable is a space reserved in the a. A constant is value stored in the
machine memory for storing values in application code itself and is not stored in
runtime. the memory
b. The stored value can be changed anytime. b. The value of a constant cannot be
c. Variables are comparatively slow when changed.
compared to constants c. Constants are slightly faster than
variables because constants are stored in
the code not running the memory.

15. Is ‘main’ a keyword in C language? Justify your answer. (May 2011)


The name main is not a keyword in C. From the compiler's perspective, main() is a function.
Just like any other function that you may define in your program, such as factorial(), sort(). The
simplest way to prove is that you can create a variable "main" in the program and that will work.

4
Dr.NNCE I / 02 C / QB

#include <stdio.h> int Output


main()
The value of main is: 10
{
int main = 10;
printf("The value of main is: %d \n", main);
}

16. List out the rules to be followed in forming in identifier. (June 2010)
a. First letter should be alphabets.
b. Both numeric and alphabets are permitted.
c. Both lower case and upper case are allowed.
d. No special symbols are permitted except underscore ( _ ).
e. Keywords are not permitted, blank space is not allowed.

17. What is identifier? Give any two examples for an identifier. (Jan 2009)
Identifiers are the names given to variable program elements such as variables, functions and
arrays. Ex. STDNAME, sub, TOT_MARKS,sub123

18. Define Operator. List out the types of Operator.


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
a. Arithmetic Operators d. Bitwise Operators
b. Relational Operators e. Assignment Operators
c. Logical Operators f. Special Operators

19. What is the difference between ++a and a++?


• ++a means do the increment before the operation (pre increment)
• a++ means do the incrementafter the operation (post increment).

20. Give two examples for logical and relational expression. (Jan 2011)
Relational Expression Logical Expression

(a>b) if((a>b)&&(a>c))
(a==b) if((a>b)||(a>c))

21. Write the following conditions using ternary operator. (Jan 2009)
4x+100 for x<40
Salary= 300 for x=40
Salary= x<40?4*x+100:x>40?4.5*x+150:300;

5
Dr.NNCE I / 02 C / QB

22. What are the Bitwise Operators available in C? (Jan 2011)


It is used to manipulate the data at bit level. It operates only integers.

Operator Meaning
& Bitwise AND
! Bitwise OR
^ Bitwise XOR
<< Shift Left
>> Shift Right
~ One‟s complement

23. What is type casting?


Type casting is a way to convert a variable from one data type to another data type. For
example, if you want to store a long value into a simple integer then you can typecast long to
int. You can convert values from one type to another explicitly using the cast operator.
int x,y;
c = (float) x/y;
where x and y are defined as integers. Then the result of x/y is converted into float.

24. What do you meant by conditional or ternary operator? Give an example for Ternary
operator. (Nov 2014)
Conditional or ternary operator‟s returns one value if condition is true and returns another
value is condition is false. Using ?: reduce the number of line codes and improve the performance
of application.
Syntax: (Condition? true_value: false_value);
Ex: a<b ? printf("a is less") : printf("a is greater");
is allocated to that data types. sizeof(char);
//1

25. What is use of Sizeof() Operators in C?


sizeof() is used with the data types such as int, float, char… it simply return amount of memory is
allocated to that data types.
sizeof(int); //4
sizeof(float); //4
sizeof(double); //8
sizeof() is used with the expression, it returns size of the expression. int a
= 0;
double d = 10.21; printf("%d",
sizeof(a+d)); //8

6
Dr.NNCE I / 02 C / QB

26. Mention the various decisions making statement available in C.


a. if statement
b. if...else statement
c. nested if statements
d. switch statement
e. nested switch statements

27. What is the difference between if and while statement?


If While
a. It is a conditional statement. a. It is a loop control statement.
b. If the condition is true, it executes b. Executes the statements within the while
some statements. block if the condition is true.
c. If the condition is false then it stops c. If the condition is false the control is
the execution the statements. transferred to the next statement of the loop.

28. What are the types of looping statements available in C?


C programming language provides following types of loop to handle looping requirements.
a. for loop
b. while loop
c. do...while loop

29. Distinguish between while and do..while statement in C. (Jan 2009)


While Do..while
a. Executes the statements within the while a. Executes the statements within the while
block, if only the condition is true. block at least once.
b. The condition is checked at the starting of b. The condition is checked at the end of the
the loop. loop.
c. It is an entry controlled loop. c. It is an exit controlled loop.

30. Write a for loop statement to print numbers from 10 to 1. (Jan 2014)
#include <stdio.h>
Output:
void main(void)
{ 10 9 8 7 6 5 4 3 2 1
int count; // Display the numbers 10 to 1
Press any key to continue . . .
for(count = 10; count >= 1; count--)
printf("%d ", count);
}

7
Dr.NNCE I / 02 C / QB

31. What are the two types of I/O Statements in C?


There are two types of I/O Statements in C.
1. Formatted I/O Statements
2. Unformatted I/O Statements
3.
32. Differentiate between formatted and unformatted functions.
Formatted I/O functions Unformatted I/O functions
a. Formatted data requires more space than a. Unformatted input/output is usually the
unformatted to represent the same most compact way to store data.
information. b. Unformatted input/output is the least
b. Formatted input/output is very portable. portable form of input/output.
c. It is a simple process to move formatted data c. Unformatted data files can only be moved
files to various computers, even computers easily to and from computers that share
running different operating systems, as long the same internal data representation.
as they all use the ASCII
character set.

33. List the various input and output statements in C. (May2015)


The various input and output statements in C are

Input Statements Output Statements


a. gets() a. puts()
b. getch() b. putch()
c. getchar() c. putchar()
d. scanf() d. printf()
e. getche()

34. Write the limitations of using getchar() and scanf() functions for reading strings.(Jan 2009)
getchar(): It is written in standard I/O library. It reads a single character only from a standard input
device. This function is not use for reading strings.
Scanf: It is use for reading single string at a time. When there is a blank was typed, the scanf()
assumes that it is an end.

35. What are the pre-processor directives? (Jan 2014, May 2014, 2015)
Preprocessor directives are the commands used in preprocessor and they begin with “#” symbol.
Before a C program is compiled in a compiler, source code is processed by a program called
preprocessor. This process is called preprocessing.
Macro Syntax: #define
This macro defines constant value and can be any of the basic data types.
Header file Syntax: #include <file_name>
inclusion The source code of the file “file_name” is included in the main program at
the specified place.
8
Dr.NNCE I / 02 C / QB

Conditional Syntax: #ifdef, #endif, #if, #else, #ifndef


compilation Set of commands are included or excluded in source program before
compilation with respect to the condition.
Unconditional Syntax: #undef, #pragma
compilation #undef is used to undefine a defined macro variable. #Pragma is used to call
a function before and after main function in a C program.
36. What is meant by storage Class?
A storage class is the one that defines the scope (visibility) and life time of variables and/or functions within
a C program.

37. What are the storage classes available in C?


Storage classes are categorized in four types as,
Automatic Storage Class - auto
Register Storage Class - register
Static Storage Class - static
External Storage Class – extern

38. What is register storage in storage class?


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 can‟t
have the unary '&' operator applied to it (as it does not have a memory location). Ex. register int
a=200;

39. What is static storage class? (Nov 2014)


Static is the default storage class for global variables. The static storage class object will be
stored in the main memory.
Ex. static int Count=19;

40. Define Auto storage class in C.


Auto is the default storage class for all local variables. The auto storage class data object will be
stored in the main memory. These objects will have automatic (local) lifetime.
Ex. auto int Month;

41. Define Macro in C. What is the use of #define preprocessor? (Nov 2014)
A macro can be defined as the facility provided by the C preprocessor by which a token can be
replaced by the user defined sequence of characters. Macros are defined with the help of define
directive. Its format is: #define identifier replacement.
#define TABLE_SIZE 100

42. What are conditional Inclusions in Preprocessor Directive?


The conditional inclusion directives are the one that is used to control the preprocessor with
conditional statements. Ex: #ifdef, #else, #endif
9
Dr.NNCE I / 02 C / QB

43. Define Compilation process.


Compilation process is defined as the processing of source code files and the creation of an object'
file. The compiler produces the machine language instructions that correspond to the source code
file that was compiled.

44. What will be the output for the following program when the value of i is 5 and 10?(June-2012)
#include<stdio.h>
void main()
{
int I; scanf(“%d”,&i); Output
if(i=5) Five (if I is 5)
{ No output if I is 10
printf(“five”);
}

PART-B
1. Explain in detail about the Structure of C Program.
STRUCTURE OF C PROGRAM

Documentation section

Preprocessor section

Definition section

Global declaration section


main()
{
Declaration
part;
Executable
part;
Subprogram
Section
{
Body of
the
subprog

‘C’ program may Documentation Section :


It consists of set of comment lines used to specify the name of the program etc.
Comments:
➢ Comments are used to identify the program features and logic of the program.
10
Dr.NNCE I / 02 C / QB

➢ The lines begins with ‘/*’ and ending with ‘*/’ are known as comments lines.
These lines are not executable.
There are two types of comment lines,
➢ Single comment line eg., /* abcd….
➢ Nested comment line (or) multiple comment line (e.g, /*…….. abcd…..... */
Preprocessor Section :
It is used to link system library files for defining the macros and for defining the
conditionalinclusion.
C program depends upon some header file .
Header file is extended with ‘.h’.
This file should be included using #.
Eg., #include<stdio.h>
Global Declaration Section:
The section declares some variables that are used more than one function.
These variables are known as global variables.
These variables must be declared outside of the main function.
Function main:
contain one or more section.

Every C program must contain main function.


After main function empty parenthesis are necessary.
Main () is the starting point of every ‘C’ program.
The execution starts with opening brace ‘{’ & closing brace ‘}’
In between these braces the programmer should write executable and declaration part.
Executable part:
it contains a set of statements or a single statement.
These statements are enclosed between the braces.
Declaration part:
It declares the entire variables that are used in executable part.
Variable initialization is done in declaration section.
Sub program section (or) User defined function
These section defined by user are called user defined functions.
These functions are defined after the main function (or) before the main function.
PROGRAMMING RULES:
All statements should be written in lowercase letters.
Uppercase letters are only used for symbolic constants.
Blank space may be inserted between words.
But it is not used while declaring a variable, keyword, constant and function.
The programmers can write the statement anywhere between the two braces.
We can write one or more statements in one line by separating each statement with semicolon (;)
The opening and closing braces should be balance

11
Dr.NNCE I / 02 C / QB

2. Explain in detail abut the Storage classes with example.


STORAGE CLASS:
It refers to the scope of the variables with in the program.
Through declaration statement memory is allocated temporarily for variables.
The size of the allocated memory varies with respect to the type of variable.
C language supports 4types of storage class. they are ,
• Auto
• Static
• Extern
• Register

Automatic Variable:
The variables without any specification are considered as automatic variables.
They are defined inside a function.
They are called as automatic because their memory space is automatically allocated
as thevariable is declared.
These variable has only temporary memory space .
after execution all automatic variables are disposed. It can not be accessed directly.
Syntax:
storage_class_type data_type var1,var2,…varn;
Example:
auto int a,b;
auto float x,y;
auto char sex
Example Program: Output:
#include<stdio.h> c=340
#include<conio.h> c=458
void main() c=340
{
int c=340;
clrscr();
printf(“c=%
d”,c);
{
int c=458;
printf(“c=%
d”,c);
}
printf(“c=%
d”,c);
getch();
}

Static Variable:
Static variables are the variables for which contents of variables available
throughout theprogram.
12
Dr.NNCE I / 02 C / QB

It may be an internal or external type, depending upon where it is declared.


If declared outside of the body , it will be a static or global.
If it is declared inside the body or block it will be auto variable.
These are permanent with in the function.
Syntax:
storage_class_type data_type var1,var2,…varn;
Example:
static int a,b;
static float x,y;
static char sex;

Example Program: Output:


# include<stdio.h> p=1
#include<conio.h> p=2
void main() p=3
{ p=4
clrscr (); p=5
for(;;;) p=6
print(); p=7
} p=8
print()
{
int
static
p;
p++;
printf(“p=%
d”,p);
getch();
if(
p=
=8
)
ex
it(
1);
}
External Variable:
They are declared outside of the main() function.
The availability of the variable through out the program.(both in main and user defined function).
Compiler does not allocate memory for that variable.
It is already allocated when it is declared as a global.
Syntax:
Storage_class_type data_type var1,var2,…varn;

Example:
extern int a,b;
extern float x,y;
13
Dr.NNCE I / 02 C / QB

extern char sex;


Example Program: Output
#include<stdio.h> in fun1() d=124
#include<conio.h> in fun2() d=510
int d=510; in main() d=510
void main()
{
clrscr();
fun1();
fun2();
printf(“in main()
d=%d”,d);getch();
}
fun1()
{
int d=124;
printf(“in fun1() d=%d”,d);
}
fun2()
{
printf(“in fun2() d=%d”,d);
}
Register Variable
It is a special storage area in central processing unit.
The arithmetic and logical operations are carried out with in these register.
Register access is faster than memory access.
The values of register variable stored with in the registers of computer cpu rather
than inmemory.
Syntax:
Storage_class_type data_type var1,var2,…varn;
Example:
register int a,b;

Example Program: Output:


#include<stdio.h>
#include<conio.h> value of i is: 0
void main() value of i is: 1
{ value of i is: 2
register int
i=0;
clrscr();
for(i=0;i<=
2;i++)
{
printf(“value of i is:%d”,i);
}
getch();
}

14
Dr.NNCE I / 02 C / QB

3. Explain various types of operators in C language with suitable example.


OPERATORS
• An operator is a symbol that specifies an operation to be performed on the operands.
• The data items that operators act upon are called operands.
• Operators that require two operands are called binary operators.
• Operators that act upon only one operand is called unary operators.

Example: a+b
Here a, b -> Operator + -> Operand
Types of operators

a) Arithmetic Operators
b) Relational Operators
c) Logical Operators
d) Assignment Operators
e) Increment/ Decrement Operators
f) Conditional Operators(Ternary Operator)
g) Bitwise Operators
h) Special Operators

ARITHMETIC OPERATOR

OPERATOR MEANING EXAMPLE


+ Addition 2+9=11
- Subtraction 9-2=7
* Multiplication 2*9=18
/ Division 9/3=3
% Modulo Division 9%2=1

Arithmetic Operators can be classified into

i) Unary Arithmetic-It requires only one operand. Ex: +x,-y


ii) Binary Arithmetic-It requires two operands. Ex: a+b, a-b
iii) Integer Arithmetic- It requires both operands are integer values for arithmetic operation.
Ex: a=5, b=4
Expression Result
a+b 9
a-b 1
iv) Floating Point Arithmetic: It requires both operands are float type for arithmetic

operation.Ex: a=6.5, b=3.5


Expression Result

a+b 10.0

a-b 3.0
15
Dr.NNCE I / 02 C / QB

Program For Arithmetic Operators

#include
<stdio.h>int
main()
{
int a = 9,b = 4, c; output
c = a+b; a+b=13
printf("a+b = %d \n",c); a-b=5
c = a-b; a*b=36
printf("a-b = %d \n",c); a/b=2
c = a*b; Remainder when a divided
by b=1printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d
\n",c);c = a%b;
printf("Remainder when a divided by b = %d
\n",c);return 0;
}
RELATIONAL OPERATORS:
Used to compare two or more operands.
Operato Meaning Exampl Return
r e Values

< is less than 2<9 1

<= is less than or equal to 2<=2 1

> is greater than 2>9 0

>= is greater than or equal 3>=2 1


to

== is equal to 2==3 0

!= is not equal to 2!=2 0

Syntax:
Program For Relational Operators

#include<stdio.h>
#include<conio.h>
void main ()
{
clrscr();

16
Dr.NNCE I / 02 C / QB

printf(“\N Condition : Return Values \n”);


printf(“\n5!=5 :%5d”, 5!=5);
printf(“\n5==5 :%5d”, 5==5);
printf(“\n5>=50 :%5d”, 5>=50);
printf(“\n5<=50 :%5d”, 5<=50);
printf(“\n5!=3 %5d”, 5!=3);
}
LOGICAL OPERATOR: Used to combine the results of two or more conditions.

Operator Meaning Example Return


Value

&& Logical (9>2)&&(17>2 1


AND )

|| Logical OR (9>2)||(17==7) 1

! Logical NOT 29!=29 0

Logical AND(&&): Used when two or more expressions are TRUE.


Ex: (expr1) && (expr2)
Logical OR(||): Used when atleast one expression is TRUE.

Ex: (expr1) || (expr2)


Logical NOT(!): Reverses the value of expression it operates on.
Ex: !( expr1)
Program For Logical Operators
#include<stdio.h>
#include<conio.h>
void main ()
{
int c1,c2,c3;
clrscr();
printf(“enter the values of c1,c2,c3:”);
scanf(“%d %d %d”,&c1,&c2,&c3);
if((c1<c2)||(c1<c3))
printf(“c1 is less than c2 and c3”);
else if(c2<c3)
printf(“c2 is less than c3”);
else
printf(“c3 is greater than c1 and c2”);
getch();
}

17
Dr.NNCE I / 02 C / QB

ASSIGNMENT OPERATOR:
It is used to assign a value of a variable to another variable
Syntax:
Variable=expression(or)value;
Example:
X=10;
X=a+b;
Program For Assignment Operator

#include<stdio.h>
#include<conio.h>
void main ()
{
int i,j,k;
clrscr();
k=(i=4,j=5);
printf(“k=%d”, k);getch();
}
INCREMENT AND DECREMENT OPERATORS
++ is a increment operator
--is a decrement operator
It is also called as unary operator
Operator Meaning
++x Pre increment
--x Pre decrement
x++ Post increment
x-- Post decrement

Program For Increment And Decrement Operator


#include<stdio.h>
void main ()
{
int a=10;
printf(“a++ = %d”, a++); printf(“++a = %d”, ++a);
printf(“a-- = %d”, a--);
printf(“--a = %d”, --a);
}

18
Dr.NNCE I / 02 C / QB

4. Explain different types of conditional statement OR Explain in detail about Decision making
andcontrol statements.
DECISION MAKING STATEMENT

Conditions are placed in the program using decision making statements.


Decision making statements check the condition and then executes its sub blocks.
‘C’ language provides the following conditional statements.

if statements
if…..else statements
nested if….else statements
if……else ladder

IF STATEMENTS
The if statement is a decision making statement
Used to control the flow of execution by executing statements when the condition is true (or) false.
Properties of If statement:
✓ If condition is true, it execute true statement
FLOW CHART:
✓ If condition is false it does not do anything.
✓ Condition must be in parenthesis

SYNTAX: EXAMPLE:

if(condition) #include<stdio.h> Condition


{ void main()
True statement; {
} int a;
True statement
printf(“enter the value”);
scanf(“%d”,&a);
True statement
if(a==10)
{
printf(“Both are equal”);
}
}

IF…..ELSE STATEMENT
It is two way decision making statement
It has two block if & else
if block is executed when the condition is true, else block is executed when the condition is false.

19
Dr.NNCE I / 02 C / QB

SYNTAX: EXAMPLE:
if(condition is true) #include<stdio.h>
{ #include<conio.h>
True statement; void main()
} { condition
else int num,rem;
{ clrscr();
False statement; printf(“Enter ur number”); True statement False statement
} scanf(“%d”,&num);
rem=num%2;if(rem==0)
printf(“the number is even”);
else
printf(“the number is odd”);getch();
}

NESTED IF……ELSE STATEMENT


✓ if…..else statement is written in another if….else statement called as called nested
if elsestatement
SYNTAX: EXAMPLE FLOWCHART
if(condition 1) #include<stdio.h>
{ #include<conio.h>
if(condition 2)
void main()
{
{
True statement 2;
int
}
a,b,c,sma
else
ll;
{
clrscr();
false statement 2;
printf(“Enter three numbers”);
} scanf(“%d%d%d”,&a,&b,&c);
} if(a<b)
else {
{ if(a<c) small=a;else small=c;
false statement 1; }else
}
{
if(b<c)
small=b;
else
small=c;
}
printf(“the smallest value is”)
}}

20
Dr.NNCE I / 02 C / QB

IF….ELSE LADDER

• Number of logical conditions is checked for executing various statements.


• If three are more than three alternatives and indentation is not consistent, it may be different for you
to determine the logical structure of the if statement

SYNTAX: FLOW CAHRT EXAMPLE

if(condition 1) #include<stdio.h>
{ main()
Statement 1; {
}
int a,b,c,d;
else if(condition 2)
{ printf(“enter the four numbers”);
Statement 2; scanf(“%d%d%d%d”,&a,&b,&c,&d);
} if((a<b)&&(a<c)&&(a<d))
else if(condition 3) printf(“a is greater”);
{ else
Statement 3; if((b>a)&&(b>c)&&(b>d))
}
printf(“b is greater”);
else
{ else
default-statement; if((c>a)&&(c>b)&&(c>d))
} printf(“c is greater”);
else
printf(“d is greater”);
return(0);

SWITCH CASE STATEMENTS:

• Switch statement is a multi-way branch statements.


• Used to make a choice from a number of options,
• it requires only one variable which is checked with number of case options.
• If the value matches with case constant this particular case statement is executed if not default is
executed.
• Every case statements terminate with:
• break statement is used to exit from the current case structure.

21
Dr.NNCE I / 02 C / QB

SYNTAX: FLOW CHART

Switch (variable (or) expression)


{
case constant 1:
statement 1;
break;
case constant 2:
statement 2;
break;
case constant 3:
statement 3;
break;
default:
EXAMPLE:
statement;
}

#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c, option;
printf(“\n 1.Addition”);
printf(“\n 2.subtraction”);
printf(“\n 3.multiplication”);
printf(“\n 4.Division”);
printf(“\n 5.Exit”);
printf(“\n Enter two number”);
scanf(“%d %d”, &a, &b);
printf(“\n Enter your option”)
scanf(“%d”, &option);
switch(option)
{
Case 1:
c=a+b;
printf(“\n Addition=%d” ,c);break;
case 2:
c=a-b;
printf(“\n subtraction=%d”,c);
break;

22
Dr.NNCE I / 02 C / QB

case 3:
c=a*b;
printf(“\n multiplication=%d”,c);break;
case 4:
c=a/b;
printf(“\n division=%d”,c);
break; case 5:
Exit(0);break; default:
printf(“Invalid Choice”);
}
getch();

5. Describe the statements for looping OR Explain the various looping constructs.
BRANCHING AND LOOPING:

Loop:
✓ A loop is defined as a block of statements which are repeatedly executed for certain
number oftimes. They are three types of loop control statements
➢ for
➢ while
➢ do-while

WHILE LOOP:
✓ It is repetitive control structure used to executed the statements within the body
until thecondition becomes false. The while loop is an entry controlled loop
statement
✓ In that condition is evaluated first ,if it is true, then the body of the loop is executed.

SYNTAX: EXAMPLE FLOWCHART:

while(test condition)
{ #include<stdio.h>
body of the loop; void main()
} { condition
int number, digit, rev=0;
printf(“Enter the number:”);
while(number!=0)
{
digit=number%10;
rev=rev*10+digit;
number=number/10; Body of the loop
}
printf(“%d”,rev);
getch();
}

23
Dr.NNCE I / 02 C / QB

DO….WHILE
Here the condition is checked at the end of the loop.
The do while loop will executed at least one time even if the condition is false initially.
The do-while loop executes until the condition becomes false.
SYNTAX: EXAMPLE FLOWCHART:

do #include<stdio.h>
{ #include<conio.h>
Statement; void main()
} { Body of the loop
while(condition); int i=2,sum=0;
do
{
sum=sum+i;
i++; condition
}
while(i<=10)
printf(“sum of the numbers upto 10 is=%d”,sum);
getch();
}

FOR LOOP
✓ It is used to execute set of instructions repeatedly until the condition becomes false.
✓ Initialize counter:
➢ It is used to initialize the counter variable
✓ Test condition:
➢ It is used to test the condition.
✓ Increment / decrement counter:
➢ It is used to Increment / decrement the counter variable
SYNTAX:

For(initialize counter; test condition; increment/decrement counter)


{
statement 1;
statement 2;
}
#include<stdio.h>
#include<conio.h>
main()
{
int i, sum=0;
for(i=1;i<=10;i++)
{
sum=sum+i;
}
printf(“The addition of numbers upto 10 is %d”,sum);
getch();
}
24
Dr.NNCE I / 02 C / QB

Other Looping statements


Continue Statement:
The condition statement is used for continuing next iteration of loop statements.
It is useful when we want to continue the program without executing any part of the program.

SYNTAX: EXAMPLE
Continue; #include<stdio.h>
void main()
{
int i,n,sum=0;
for(i=1;i<=5;i++)
{
printf(“Enter any number”);
scanf(“%d”,&n);
if(n<0)
continue;
else
sum=sum+n;
}
printf(“sum is….%d”,sum;);
}
Goto Statement:
This statement does not require any condition.
This statement passes control any where the program
ie., control is transferred to another part of program without testing the application.
Break statement:
✓ It is used to terminate the loop.
✓ When break is used inside loop, control is automatically transferred to first statement after the loop.

SYNTAX(goto): EXAMPLE(goto) SYNTAX(break):


#include<stdio.h>
goto label; #include<conio.h> Break;
………… void main() EXAMPLE:
………… {
int a,b;
label: printf(“Enter a number”); #include<stdio.h>
scanf(“%d %d”,&a,&b);
SYNTAX(goto): {EXAMPLE(goto) #include<conio.h>
if(a==b) void main()
goto label; { {
………… goto equal; int i;
} for(i=1;i<=10;i++)
………… else {
label: {
if(a==b)
printf(“A & B are equal”);
exit(0); break;
} printf(“%d”,i);
equal: }
printf(“A & B are not equal”);
}
25
Dr.NNCE I / 02 C / QB

6. Write a program to check whether a given number is prime or not.

#include <stdio.h>
main()
{
int n, i, c = 0;
printf("Enter any number n:");
scanf("%d", &n);
//logic
for (i = 1; i <= n; i++)
{
if (n % i == 0)
{
c++;
}
}

if (c == 2) {
printf("n is a Prime number");
}
else {
printf("n is not a Prime number");
}
return 0;
}

OUTPUT:

Enter any number

n:55 n is not a

Prime number

Write a program quadratic equation using c


#include<stdio.h>
#include<math.h>
int main(){
float a,b,c;
float d,root1,root2;
printf("Enter quadratic equation in the format ax^2+bx+c: ");
scanf("%fx^2%fx%f",&a,&b,&c);
d = b * b - 4 * a * c;
if(d < 0){

26
Dr.NNCE I / 02 C / QB

printf("Roots are complex number.\n");return 0;}


root1 = ( -b + sqrt(d)) / (2* a);
root2 = ( -b - sqrt(d)) / (2* a)
printf("Roots of quadratic equation are: %.3f , %.3f",root1,root2);return 0;
}
Output

Enter quadratic equation in the format ax^2+bx+c: 2x^2+4x+-1

Roots of quadratic equation are: 0.000, -2.000

UNIT-II
PART- A
1. Define array. Give example. (Jan 2009, 2014)
Array can be define as a collection of similar data elements of similar data type that arestored in
consecutive memory locations. They are referenced by an index/subscript.
Syntax: data_type array_name [size] Ex.: int rollno[10];

2. Why is it necessary to give the size of an array in an array declaration?


i. When an array is declared, the compiler allocates a base address and reserves
enoughspace in the memory for all the elements of the array.
ii. The size is required to allocate the required space. Thus, the size must be mentioned.

3. What is the difference between an array and pointer?


Arrays Pointers

a. Array allocates space automatically. a. Pointer is explicitly assigned to point to an


b. It cannot be resized. allocated space.
c. It cannot be reassigned. b. It can be resized using realloc().
d. Sizeof (array name) gives the number c. Pointers can be reassigned.
of bytes occupied by the array. d. Sizeof (pointer name) returns the number
of bytes used to store the pointer variable.

4. List the characteristics of Arrays. (Jan 2013)


i. The elements of array share the same name and they are distinguished
from oneanother with helps of an elements number.
ii. An elements of array a[] can be assigned
iii. The array elements are stored in continuous memory locations.

27
Dr.NNCE I / 02 C / QB

5. What are the types of Arrays?


i. One-Dimensional Array
ii. Two-Dimensional Array
iii. Multi-Dimensional Array

6. Write the features of array. (Jan 2013)


i. An array is a derived data type. It is used to represent a correction of elements of the
same data type.
ii. The elements can be accessed with base address and the subscript defined for the
position of elements.
iii. The elements are stored in continuous memory location
iv. The starting memory location is represented by the array name and it is known as
thebase address of the array.

7. Define One dimensional Array.


One dimensional array can be defined as the collection of data item that can be stored under
aone variable name using only one subscript. Ex. int a[10];

8. Define Two Dimensional Array.


Two dimensional arrays can be defined as an array with two subscripts. A two dimensional
array enables us to store multiple row of elements. Ex. int a[10][10

9. Give example for array initialization.


An array can be initialized at the time of declaration is known as compile timeinitialization.
Ex. int a[5]={5,3,5,4,1};

10. Why do you need to use array? (Jan 2012)


In many cases, we need to declare a set of variables that are of the same data type. Instead of
declaring each variable separately, we can declare all variable collectively in the format of an array.
Each variable, as an element of the array, can be accessed either through the array elements
references or through a pointer that references the array.

11. List out the disadvantages of an array.


a. The elements in the array must be same data types.
b. The size of an array is fixed.
c. If we need more space at run time, it Is not possible to extend array.
d. The insertion and deletion an operation is an array require shifting of elements whichtakes
times.

28
Dr.NNCE I / 02 C / QB

12. What are the limitation of one-dimensional and two dimensional arrays?
The limitations of one dimensional array are
a. There is no easy method to initialize large number of array elements
b. It is difficult to initialize selected array element The
limitations of two dimensional arrays are
a. Deletion of any element from an array is not possible
b. Wastage of memory when it is specified in large array size

13. Why array elements must be initialized?


After declaration array elements must be initialized otherwise it holds garbage value. There are
two types of initialization
a. compile time initialization(initialization at the time ofdeclaration) int a[5]={12,34,23,56,12};
b. run time initialization (when the array has large number of elements it can be initialized at
run time)
for(i=0;i<10;i++)
scanf(“%d”,&a[i]);

14. What is the value of b in the following program?(Jan2012)


main()
{int a[5]={1,3,6,7,0}; Output: 6
int *b;
b=&a[2];
printf(“%d”,*b);
}

15. Write a C Program to calculate power of number.

#include <stdio.h>int
main() Output
{
Enter a base number: 3
int base, exponent; long Enter an exponent: 4
long result = 1; Answer = 81
printf("Enter a base number: ");
scanf("%d", &base); printf("Enter an
exponent: "); scanf("%d",
&exponent);
while (exponent != 0)
{
result *= base;
--exponent;
}
printf("Answer = %lld", result);
29
Dr.NNCE I / 02 C / QB

return 0;
}
16. Write a C program to generate Pascal triangle.
#include <stdio.h>
void main()
{
int array[30], temp[30], i, j, k, l, num; //using 2 arrays
printf("Enter the number of lines to be printed: ");
scanf("%d", &num);
temp[0] = 1;
array[0] = 1; Output
for (j = 0; j < num; j++) Enter the number of lines to be printed: 41
{ 1 1
printf(" "); 1 21
} 1 3 3 1
printf(" 1\n");
for (i = 1; i < num; i++)
{
for (j = 0; j < i; j++)
printf(" ");
for (k = 1; k < num; k++)
{
array[k] = temp[k - 1] + temp[k];
}
array[i] = 1;
for (l = 0; l <= i; l++)
{
printf("%3d", array[l]);
temp[l] = array[l];
}
printf("\n");
}
}

17. Write a C program to find the number of elements in an array.


#include <stdio.h>
int main()
{ Output
int array[] = {15, 50, 34, 20, 10, 79, 100};
int n; Size of the given array is 7
n = sizeof(array);
printf("Size of the given array is %d\n",
30
Dr.NNCE I / 02 C / QB

n/sizeof(int)); return 0;
}

18. What is the use of ‘\0’ character?


When declaring character arrays (strings), “\0” (NULL) character is automatically added at
end. The “\0‟ character acts as an end of character array.

19. Define string.h.


String.h is a header file which includes the declarations, functions, constants of string handling
utilities. Ex.: strlen(), strrev(), strncpy().

20. How strings are represented in C language?(Jan 2010)


Strings in C are represented by arrays of characters. The end of the string is marked with a
special character, the null character, which is simply the character with the value 0. (The null
character has no relation except in name to the null pointer. In the ASCII character set, the null
character is named NUL.) Ex.: char string1[] = "Hello, world!";

21. How strings are declared and initialized in C?


Strings are declared as a array of characters Initialization of strings
Syntax: char string_name[size]; Char name[6]=”RAMKI”;
Example: char text[30];

22. Write important string handling functions in C.


Some of the important strings handling functions in C are as follows
a. strcat()-concatenates two strings
b. strcmp()-compares two strings
c. strcpy()-copies one string over other
d. strlen()-finds length of a string
e. strrev()-reverse the string
23. What is the difference between a string and an array?
String Array
a. String can hold only char data a. Array can hold any data type
b. String size can be changed if it is a b. Array size cannot be changed
character pointer c. The last element of an array is an element
c. The last character of string is a null – of the specific type
„\0‟character d. The length of an array is specified in [] at
d. The length of the string is the number of the time of declaration (except char[])
characters + one
24. Define Strings.
Strings or character arrays can be defined as the group of characters, digit and symbols enclosed
within quotes. Strings are always terminated with “\0” (NULL) character. The compiler
automatically adds “\0” at the end of the strings.
31
Dr.NNCE I / 02 C / QB

PART-B
1. Explain in detail about Array
ARRAY
✓ Array is collection of similar data items ,that are stored under a common name.
✓ A value in an array is identified by index or subscript enclosed in square brackets
with arrayname.
✓ Ex: n elements in array q is q[0],q[1],q[2]..q[n]
ARRAY TYPES
✓ One Dimensional Array
✓ Two Dimensional Array
✓ Multidimensional Array
TWO DIMENSIONAL ARRAY
✓ Two dimensional arrays are stored in row –column matrix, where the left index
indicates therow and right index indicates the column.
✓ Two pair of square brackets are required.
✓ Ex: int a[3][3];
Program For Two Dimensional Array(Matrix Multiplication)
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j,k;
clrscr();
printf("\n enter the a
matrix\n");for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("a[%d][%d] : ",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
printf("\nenter the b
matrix\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("b[%d][%d] : ",i+1,j+1);
scanf("%d",&b[i][j]);
}}
printf("\nmultiplication of the 2 matrices

32
Dr.NNCE I / 02 C / QB

:\n\n");for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=0;
for(k=0;k<3
;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
printf("\t%d",c[i][j]);
}
printf("\n\n");
}
getch();
}
2. Explain in detail about string handling functions

STRING:
The group of characters, digit and symbols enclosed within quotes is called as String (or)
character Arrays. Strings are always terminated with ‘\0’ (NULL) character. The compiler automatically
adds ‘\0’ at the end of the strings.
Example:
char name[]={‘C’,’O’,’L’,’L’,’E’,’G’,’E’,’E’,’\0’};

S.No Function Purpose


1 strcpy(s1, s2); Copies string s2 into string s1.
2 strcat(s1, s2); Concatenates string s2 onto the end of string s1.
3 strlen(s1); Returns the length of string s1.
4 strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater
than 0 if s1>s2.
5 strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string
s1.
6 strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.
7 strlwr() Used to convert string to lower case
8 strupr() Used to convert string to upper case
9 strdup() Used to Used to duplicate a string
duplica
te a
string.

33
Dr.NNCE I / 02 C / QB

10 strrev() Used to Used to reverse a string


reverse
a string
C Program using string functions:
#include <stdio.h>
#include <string.h>
void main()
{
char a[100],b[100],c[200],d[100];
int scmp,slen,length;
clrscr();
printf("Enter the first string:\n");
gets(a);
printf("Enter the second string:\n");
gets(b);
strcpy(c,a); //String Copy
printf("\nString copy %s ",c);
scmp=strcmp(a,c); //String
Compare
printf("\nString Compare of %s & %s",&a,&c);
if(scmp==0)
printf("\nEntered strings are equal"); else
printf("\nEntered strings are not equal");
strcat(a,b); //String Concatenation
printf("\nString concatenation is %s",a);
length=strlen(a); //String Length
printf("\nLength of the string %s is =%d",a,length);
printf("\nReverse string is %s",strrev(b));
printf("\nEnter the string to check
palindrome"); gets(d);
strcpy(b,d);
strrev(b); //String Reverse
if(strcmp(d,b)==0)
printf("\nEntered string is a palindrome."); else
printf("\nEntered string is not a palindrome.");
getch();
strupr(d); //String Upper
printf("\n String Upper is %s",d);
strlwr(d); //String Lower
printf("\n String Lower is %s",d);
}

34
Dr.NNCE I / 02 C / QB

3.Write Program for Numbers in Ascending Order

#include <stdio.h>
void main()
{
int i, j, a, n, number[30]; printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
a = number[i]; number[i] = number[j];
number[j] = a;
}
}
}
Output:
Enter the value of N3
Enter the numbers25
35
45
The numbers arranged in ascending order are given below
25 5 45

4. Write a C Program for Binary Search:


#include <stdio.h>
void binary_search();
int a[50], n, item, loc, beg, mid, end, i;
void main()
{
printf("\nEnter size of an array: ");
scanf("%d", &n);
printf("\nEnter elements of an array in sorted
form:\n"); for(i=0; i<n; i++)
scanf("%d", &a[i]);
printf("\nEnter ITEM to be searched: ");
35
Dr.NNCE I / 02 C / QB

scanf("%d", &item);
binary_search();
getch();
}
void binary_search()
{
beg = 0;
end = n-1;
mid = (beg + end) / 2;
while ((beg<=end) && (a[mid]!=item))
{
if (item < a[mid]) end = mid - 1;
else
beg = mid + 1;
mid = (beg + end) / 2;
}
if (a[mid] == item)
printf("\n\nITEM found at location %d", mid+1);
else
printf("\n\nITEM doesn't exist");
}
Output:
Enter size of an array: 3
Enter elements of an array in
sorted form: 25
36

45
Enter ITEM to be
searched: 36 ITEM
found at location 2

5. Program for Transpose of Matrix

#include<stdio.h>
int main()
{
int a[10][10], b[10][10], i, j, m, n;

printf("\nEnter the number of rows and columns of the matrix:\n");


scanf("%d %d", &n, &m);

36
Dr.NNCE I / 02 C / QB

printf("\nEnter the elements of the matrix:\n");


for(i = 0; i < n; ++i)
for(j = 0; j < m; ++j)
scanf("%d", &a[i][j]);

// Transposing the matrix


for(i = 0; i < m; ++i)
for(j = 0; j < n; ++j)
b[i][j] = a[j][i];

printf("\nTranspose of the matrix:\n");


for(i = 0; i < m; ++i)
{
for(j = 0; j < n; ++j)
printf("%d ", b[i][j]);
printf("\n");
}

return 0;
}
Output:
Enter the number of rows and columns of the matrix:
33
Enter the elements of the matrix:
213
897
153
Transpose of matrix:
281
195
373
6. Write a C Program for Linear Search:

#include<stdio.h>
#include<conio.h>
void main()
{
int arr[20];
int i,size,key;
printf("\n\t-- Linear Search --\n\n");
printf("Enter total no. of
elements : ");
37
Dr.NNCE I / 02 C / QB

scanf("%d",&size);
for(i=0; i<size; i++)
{
printf("Enter %d
element : ",i+1);
scanf("%d",&arr[i]);
}
printf("Enter the element to be
searched: "); scanf("%d",&key);
for(i=0; i<size; i++)
{
if(key==arr[i])
{
printf("Element exits in the list at position : %d",i+1);
break;
}
}

getch();
}
Output:
-- Linear Search --
Enter total no. of elements : 3
Enter 1 element : 25
Enter 2 element : 36
Enter 3 element : 45
Enter the element to be
searched: 36 Element exits in
the list at position : 2
7. Explain in detail about the sorting with an example.
There are many different techniques available for sorting, differentiated by their efficiency and
space requirements. Following are some sorting techniques which we will be covering in next few
tutorials.

1. Bubble Sort
2. Insertion Sort
3. Selection Sort
4. Quick Sort
5. Merge Sort
6. Heap Sort

3.SELECTION SORT
38
Dr.NNCE I / 02 C / QB

PROGRAM
#include <stdio.h>
int main()
{
int arr[10]={6,12,0,18,11,99,55,45,34,2};
int n=10;
int i, j, position, swap;
for (i = 0; i < (n - 1); i++)
{
position = i;
for (j = i + 1; j < n; j++)
{
if (arr[position] > arr[j])
position = j;
}
if (position != i)
{
swap = arr[i];
arr[i] = arr[position];
arr[position] = swap;
}
}
for (i = 0; i < n; i++)
printf("%d\t", arr[i]);
return 0;
}
OUTPUT:
0 2 6 11 12 18 34 45 99

8. C PROGRAM FOR MATRIX SCALING

#include<stdio.h>
int main()
{
int i, j, rows, columns, a[10][10], Number;
printf("\n Enter Number of rows and columns\n");
scanf("%d %d", &i, &j);
printf("\n Please Enter the Matrix Elements \n");
for(rows = 0; rows < i; rows++)
{
for (columns = 0;columns < j;columns++)
{
39
Dr.NNCE I / 02 C / QB

scanf("%d", &Multiplication[rows][columns]);
} }
printf("\n Enter the Multiplication Value : ");
scanf("%d", &Number);
for(rows = 0; rows < i; rows++)
{
for(columns = 0; columns < j; columns++)
{
a[rows][columns] = Number * a[rows][columns];
}
}
printf("\n The Result of a Scalar Matrix Multiplication is : \n");
for(rows = 0; rows < i; rows++)
{
for(columns = 0; columns < j; columns++)
{

printf("%d \t ", a[rows][columns]);


}
printf("\n");
}
return 0;
}
OUTPUT:
Enter Number of rows and columns:
3 3Enter the Matrix elements
10 20 30
40 50 60
70 80 90
Enter the multiplication value: 3
30 60 90
120 150 180

210 240 270

9. C PROGRAM FOR DETERMINANT OF A MATRIX:


#include<stdio.h>
int main(){
int a[3][3], i, j;
long determinant;
printf("Enter the elements of matrix: ");
for(i = 0 ;i < 3;i++)
for(j = 0;j < 3;j++)
40
Dr.NNCE I / 02 C / QB

scanf("%d", &a[i][j]);
printf("\nThe matrix is\n");
for(i = 0;i < 3; i++){
printf("\n");
for(j = 0;j < 3; j++)
printf("%d\t", a[i][j]);
}
determinant = a[0][0] * ((a[1][1]*a[2][2]) - (a[2][1]*a[1][2])) -a[0][1] * (a[1][0]

* a[2][2] - a[2][0] * a[1][2]) + a[0][2] * (a[1][0] * a[2][1] - a[2][0] * a[1][1]);

printf("\nDeterminant of 3X3 matrix: %ld", determinant);

return 0;
}

OUTPUT:
Enter the elements of matrix:

123

451

234
The matrix is

1 2 3
4 5 1

2 3 4

Determinant of 3X3 matrix: -5

10. C PROGRAM FOR COMPUTING MEAN, MEDIAN, MODE

#include<stdio.h>
main()
{
int
i,j,a[20]={0},sum=0,n,t,b[20]={0},k=0,c=1,max=0,m
ode;float x=0.0,y=0.0;
printf("\nEnter the limit\n");
scanf("%d",&n);
printf("Enter the set of numbers\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
41
Dr.NNCE I / 02 C / QB

x=(float)sum/(float)n;
printf("Mean\t= %f",x);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i]; a[i]=a[j];
a[j]=t;
}
}
} if(n%2==0)
y=(float)(a[n/2]+a[(n-1)/2])/2;
else
y=a[(n-1)/2]; printf("\nMedian\t= %f",y);
for(i=0;i<n-1;i++)
{
mode=0; for(j=i+1;j<n;j++)
{
if(a[i]==a[j])
{
mode++;
}
}
if((mode>max)&&(mode!=0))
{
k=0;
max=mode;
b[k]=a[i];
k++;
}
else if(mode==max)
{
b[k]=a[i];
k++;
}
}
for(i=0;i<n;i++)
{
if(a[i]==b[i])
c++;
}
if(c==n)
printf("\nThere is no mode");else
{
42
Dr.NNCE I / 02 C / QB

printf("\nMode\t= ");
for(i=0;i<k;i++)
printf("%d ",b[i]);
}
}

OUTPUT:

Enter the limit5


Enter the set of numbers1 2 3 4 5
Mean = 3.000000

Median = 3.000000
There is no mode
11. C PROGRAM FOR MATRIX ADDITION:

#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &first[i][j]);
printf("Enter the elements of second matrix\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &second[i][j]);
printf("Sum of entered matrices:-\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
sum[i][j] = first[i][j] + second[i][j];
printf("%d\t", sum[i][j]);
}
printf("\n");
}
return 0;
}

OUTPUT:
Enter the number of rows and columns of
matrix2

43
Dr.NNCE I / 02 C / QB

2
Enter the elements of first
matrix1 2
34
Enter the elements of second
matrix5 6
21
Sum of entered
matrices:
6 8
5 5
UNIT-III
PART-A
1. What is a function? (Nov 2014)
A function is a group of statements that together perform a task. Every C program has at least one
function which is main(), and all the most trivial programs can define additional functions.

2. How will define a function in C?


The general form of a function definition in C programming language is as
follows return_type function_name (parameter list)
{
body of the function
}

3. What does a function header and function body consist of?


A function definition consists of The Function header consists of
a. Function header a. Return Type
b. Function body b. Function Name
c. Parameters
The Function body consists of
a. Declarations and statements necessary for performing the required task.

4. What are the steps in writing a function in a program?


a. Function Declaration/Prototype: Every user-defined functions has to be declared before the
main().
b. Function Callings: The user-defined functions can be called inside any functions like main(),
user-defined function.
c. Function Definition: The function definition block is used to define the user-defined functions
with statements.

44
Dr.NNCE I / 02 C / QB

5. What is the need for functions? (Jan 2014)


a. Functions are self-contained block or sub program of one or more statements that
performs a specific task.
b. It increases the modularity, reusability of a program.

6. What is the purpose of the main ()? (May 2009)


The main () invokes other functions within it. It is the first function to be called when theprogram
starts execution.
7. What are the elements of user-defined function?
a. Function Definition.
b. Function Declaration.
c. Function call

8. List the types of functions in C programming.


Depending on whether a function is defined by the user or already included in C compilers,there are two
types of functions in C programming
a. Standard library functions
b. User defined functions

9. What are standard library function?


The standard library functions are built-in functions in C programming to handle tasks such as
mathematical computations, I/O processing, string handling. These functions are defined in the header file.
When you include the header file, these functions are available for use. For example: The printf() is a standard
library function to send formatted output to the screen (display output on the screen). This function is defined
in "stdio.h" header file.

10. List the advantages of user-defined function.


Theadvantages of user defined functions are as follows
a. The program will be easier to understand, maintain and debug.
b. Reusable codes that can be used in other programs
c. A large program can be divided into smaller modules. A large project can be divided
among many programmers.

11. Is it better to use a macro or a function?


Macros are more efficient than function, because their corresponding code is inserted directly at
the point where the macro is called. There is no overhead involved in using a macro like there is in
placing a call to a function. Macros are generally small and cannot handle large, complex coding
constructs. In cases where large, complex constructs are to handled, functions are more suited,
additionally.

12. Classify the functions based on arguments and return values.


Depending on the arguments and return values, functions are classified into four types.
45
Dr.NNCE I / 02 C / QB

a. Function without arguments and return values.


b. Function with arguments but without return values.
c. Function without arguments but with return values.
d. Function with arguments and return values.
13. What are address operator and indirection operator? (Nov 2014)
a. The address operator (&) - It represents the address of the variable.
b. Indirection pointer (*) - When a pointer is dereferenced, the value stored at that
address by the pointer is retrieved.
14. What is function prototyping? Why it is necessary? (May 2011)
Many built in functions can be used in C programs. The prototype of these functions is given in
the respective header files. With the help of a function prototype, the compiler can automatically
perform type checking on the definition of the function, which saves the time todelay the program

15. What are actual parameters and formal parameters? (May 2015)
Actual Parameters: The parameters in the calling program or the parameters in the function call are
known as actual parameters.
Formal Parameters: The parameters in the called program or the parameters in the function header
are known as formal parameters.

16. State the advantage of using functions.


The advantages of using functions are as follows
a. Reduces the size of the program: The length of the source program can be reduced byusing
functions at appropriate places.
b. Avoids rewriting the code: As function can be called many times in the program.
Improves re-usability: Same function may be used later by many other programs.
c. Improves re-usability: Same function may be used later by many other programs.
d. Program testing becomes easy: Each function can be tested separately and it is easy to
locate and isolate a faculty function for further investigation.
e. Increases program readability.

17. Differentiate library functions and User-defined functions.


Library Function User- defined functions

a. The library functions are predefined set a. The user defined functions are defined by
of functions. the user.
b. Their task is limited b. Their task is based on user requirement.
c. The user can use the functions but c. The user can modify the function
cannot change or modify them. according to the requirement.

18. What is a recursive function?


If a function calls itself again and again, then that function is called Recursive function. Thistechnique is known
as recursion.

46
Dr.NNCE I / 02 C / QB

void recursion()
{ recursion(); /* function calls itself */
}
int main()
{ recursion(); }

19. What are the applications of recursive function?


The applications of the recursive function are
a. Calculating Fibonacci Series.
b. Calculating Factorial of a program.

20. State the advantage and disadvantage of recursive function.


Advantage of recursive function Disadvantage of recursive function
a. Reduce unnecessary calling of function. a. It is very difficult to trace (debug and
understand)
b. Through recursion one can solve problem
in easy way while its iterative solution is b. Takes a lot of stack space.
very big and complex. c. Uses more processor time.

21. What is a Pointer? How a variable is declared to the pointer? (Jan 2013, May
2009) Pointer is a variable which holds the address of another variable.
Syntax: data_type *variable_name;Ex.: int
*x, a=5;
x=&a;

22. List the key points to remember about pointers in C.


The key points to remember about pointers in C are
a. The content of the C pointer always be a whole number i.e. address.
b. Always C pointer is initialized to null i.e., int *p=null.
c. The value of null pointer is 0.
d. The size of any pointer in 2 byte.

23. What are the uses of pointer?


The uses of pointers as follows
a. Pointers are used to return more than one value to the function
b. Pointers are more efficient in handling the data in arrays ·Pointers reducethe
length and complexity of the program ·
c. They increase the execution speed
d. The pointers save data storage space in memory

47
Dr.NNCE I / 02 C / QB

24. What is dangling pointer?


In C, a pointer may be used to hold the address of dynamically allocated memory. After this memory
is freed with the free() function, the pointer itself will still contain the address of the released block.
This is referred to as a dangling pointer. Using the pointer in this state is a serious programming error.
Pointer should be assigned NULL after freeing memory to avoid this bug.

25. What is the output of the following program? (May 2015)


main ()
{
int a=8, b=4, c, *p1=&a, *p2=&b; Output
c=*p1**p2-*p1/ *p2+9; c: 39
printf (“%d”,c); }

26. List the pointer operators.


* Value at Operator Gives values stored at particular address
& Address Operator Gives address of variable

27. What is the output for the


following? #include<stdio.h>int Output
fun() 38353229262320171411852
{
static int num = 40;
return num--;
}
int main()
{
for(fun(); fun(); fun())
{
printf("%d", fun());
}
getchar();
}

28. What is a pointer variable?


The variables that hold the memory address are called pointer variables.int *p;
P = &n;
P stores the address of n.

29. What will be the output of the following program?


include<stdio.h> Output
int main() 20
1260034844
48 20
Dr.NNCE I / 02 C / QB

{
int n=20;
printf(“\n %d “, n);
printf(“\n %u“, &n);
printf(“\n %d “, *(&n));
}
30. What are the possible arithmetic operations on pointers in C language?
a. Increment
b. Decrement
c. Subtraction
d. Comparison

31. What are null pointers?


A pointer that does not point to any valid memory address is called nullpointer.
Ex: int * ptr =NULL;

32. List out the applications of pointers.


a. We can section multiple values from function using pointer.
b. Supports dynamic management.

33. What are pointers to pointers?


Pointer variable contains the address of another variable. Similarly another pointer variable can
store the address of a pointer variable. The pointer variable is said to be pointer to pointer.

34. What is pointer arithmetic?


One of the uses of pointer is pointer arithmetic. Like an ordinary variable, pointer variable can also be
used in arithmetic expressions. Assume x, y and z are pointer variables, and the values are 10, 20, 30
respectively. Then the following is an example of pointer expression.

Expression Result
C =*y + 10 Value of c is 30
C = *z + *y Value of c is 50
C = *x + 10 + *y Value of c is 40
C = ++*x Value of c is 11

49
Dr.NNCE I / 02 C / QB

35. Distinguish between Call by value Call by reference. (May 2014)


Call by Value / Pass by value Call by reference / Pass by reference
a. In Call by value, the value of actual a. In Call by reference, the address of
agreements is passed to the formal actual arguments values is passed to
arguments and the operation is done on formal argument values.
formal arguments. b. Formal arguments values are pointers
b. Formal arguments values are photocopies to the actual arguments values.
of actual arguments values. c. Since address is passed, the changes
c. Changes made in formal arguments valued made in the formal arguments will be
do not affect the actual argument values reflected back to the actual arguments.

PART-B
1. Explain in detail about the function with an example.
Function:
function is itself a block of code which can solve simple or complex task/calculations.
A function performs calculations on the data provided to it is called "parameter" or "argument".A
function always returns single value result.
Types of function:
1. Built in functions(Library functions)
a.) Inputting Functions.
b.) Outputting functions.
2. User defined functions.
a.) fact();
b.) sum();
Parts of a function:
1. Function declaration/Prototype/Syntax.
2. Function Calling.
3. Function Definition.
1.Function Declaration:
Syntax: <return type > <function name>(<type of argument>)
The declaration of function name, its argument and return type is called function declaration.
2.) Function Calling:
The process of calling a function for processing is called function calling.
Syntax: <var_name>=<function_name>(<list of arguments>).
3.) Function definition:
The process of writing a code for performing any specific task is called function definition.
Syntax:
<return type><function name>(<type of arguments>)
{
statement-1> <statement-2>

50
Dr.NNCE I / 02 C / QB

return(<vlaue>)
}
Example: program based upon function:
WAP to compute cube of a no. using function.#include<stdio.h>
#include<conio.h>void
main()
{ int c,n; int cube(int); printf("Enter
a no."); scanf("%d",&n); c=cube(n);
printf("cube of a no. is=%d",c);
} int cube(intn)
{
c=n*n*n;
return(c);
}

WAP to compute factorial of a no. using function:


#include<stdio.h>
#include<conio.h>
void main()

{ int n,f=1; int fact(int) printf("Enter ano.");


scanf("%d",&n); f=fact(n); printf("The
factorial of a no. is:=%d",f);
}
int fact(int n) intf=1;
{
for(int i=n;i>=n;i--)
{
f=f*i;
}
return(f);
}

51
Dr.NNCE I / 02 C / QB

UNIT IV
STRUCTURES
PART – A
1. Distinguish between arrays and structures.
Arrays Structures
a. An array is a collection of data items of a. A structure is a collection of data items
same data type. Arrays can only be of different data types. Structures can be
declared. declared and defined.
b. There is no keyword for arrays b. The keyword for structures is struct.
c. An array name represents the address of c. A structure name is known as tag. It is a
the starting element Shorthand notation of the declaration.
d. An array cannot have bit fields d. A structure may contain bit fields
1.
2. Differentiate between Structures and Union.

Structure Union
a. Every member has its own memory. a. All members use the same memory.
b. The keyword used is struct. b. The keyword used is union.
c. All members occupy separate memory c. Different interpretations for the same
location, hence different interpretations of memory location are possible.
the same memory location are not possible.
d. Consumes more space compared to union. d. Conservation of memory is possible.
Structure can be defined as a collection of different data types which are grouped together and each
element in a C structure is called member. To access structure members in C, structure variable should
be declared. The keyword used is struct.

3. How will you define a structure?


A structure can be defined as
struct tag
{
datatype member 1;
datatype member 2;
………
………
datatype member n;
};
where struct is a keyword, tag is a name that identifies structures, member 1, member 2,…..member n
are individual member declarations.

4. How will you declare structure variables? struct library_books


{
char title[20];
52
char
author[15];int
pages;
Dr.NNCE I / 02 C / QB

Declaration of structure variables includes the following


statements
a. The keyword struct
b. The structure name
c. List of variable names separated by commas
d. A terminating semicolon

5. What is meant by Union in C? (May 2014)


A union is a special data type available in C that enables to store different data types in the same
memory location. Union can be defined with many members, but only one member can contain a value
at any given time. Unions provide an efficient way of using the same memory location for multi-
purpose.

6. How to define a union in C.


The format of the union statement is as followsunion tag
{
member definition;
member definition;
...
member definition;
} one or more union variables;

7. How to define a union in C.


The format of the union statement is as followsunion tag
{
member definition;
member definition;
...
member definition;
} one or more union variables;

8. How can you access the member of union?


To access any member of a union, use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member to access.Union keyword is used to
define variables of union type.

9. List the features of structures. (May 2015)


The features of structures are as follows
a. All the elements of a structure are stored at contiguous memory locations

53
Dr.NNCE I / 02 C / QB

b. A variable of structure type can store multiple data items of different data types underthe
one name
c.
10. List the main aspects of working with structure.
a. Defining a structure type (Creating a new type).
b. Declaring variables and constants (objects) of the newly created type.
c. Initializing structure elements

11. What are the two ways of passing a structure to function in C?


a. Passing structure to a function by value
b. Passing structure to a function by address(reference)

12. Write any two advantage of Structure.


a. It is used to store different data types.
b. Each element can be accessed individually.
13. How to initialize a structure variable? Give it’s syntax.
Static storage class is used to initialize structure. It should being and end with curly braces.
Syntax: Static structure tag-field structure variable = {value1, value2,...value 3};

14. Define Anonymous structure.


Unnamed anonymous structure can be defined as the structure definition that does not contain a
structure name. Thus the variables of unnamed structure should be declared only at the time of structure
definition.

15. What are the operations on structures?


The operations on structures are
a. Aggregate operations: An aggregate operation treats an operand as an entity andoperates on
the entire operand as whole instead of operating on its constituent members.
b. Segregate operations: A segregate operation operates on the individual members of a
structure object.
c.
16. How to access members of a structure object?
a. Direct member access operator (dot operator)
b. Indirect member access operator(arrow operator)

17. What is the use of ‘period (.)’ in C?


To access any member of a structure, we use the member access operator (.). The memberaccess
operator is coded as a period between the structure variable name and the structure member that we wish to
access.. The members of structure can be accessed individually using period operator. Ex: S1.roll.no;

18. How will you access the structures member through pointers?
The structures member can be accessed through pointers by the following ways

54
Dr.NNCE I / 02 C / QB

a. Referencing pointer to another address to access memory


b. Using dynamic memory allocation

19. Define Nested structure.


Nested structure can be defined as the structure within structure. One structure can be declared inside
other structure as we declare structure members inside a structure. The structure variables can be
a normal structure variable or a pointer variable to access the data.

20. Define array of structures.


Each elements of an array represent a structure variable. If we want to store more array objects in a
structure, then we can declare “array of structure”.

21. Consider the declaration and illustrate the application of size of operator to this structure.
(Nov 2010)
struct student
{ Size of this is 3 bytes:1 byte for name and 2 bytes for integer num.
char name;int
num;
} S;

22. Define Dynamic memory allocation.


The process of changing the array size during program execution is called as dynamicmemory
allocation.

23. What are various dynamic memory allocation functions in C?


a. malloc() – Used to allocate blocks of memory I required size of bytes
b. free() – Used to release previously allocated memory space
c. calloc() –Used to allocate memory space for an array of elements
d. realloc()-Used to modify the size of previously allocated memory space

24. What is a volatile and non-volatile memory?


Volatile memory: also known as volatile storage is computer memory that requires power to
maintain the stored information, unlike non-volatile memory which does not require a maintained
power supply. It has been less popularly known as temporary memory. Non-volatilememory: nonvolatile
memory, NVM or non-volatile storage, is computer memory that can retain the stored information even
when not powered.

25. What is Linked List?


A linked list is a set of nodes where each node has two fields „data and „link‟. The data fieldis
used to store actual piece of information and link field is used to store address of next node.

55
Dr.NNCE I / 02 C / QB

26. Write down the steps to modify a node in linkedlists.


The steps to modify a node in linked lists are
a. Enter the position of the node which is to be modified.
b. Enter the new value for the node to be modified.
c. Replace the original value of that node by a new value
d. Display the message as “The node is modified”.

27. List the operations on singly linked list.


a. Create function
b. Display function
c. Search function
d. Insert function
e. Delete function
28. What are the pitfalls encountered in singly linked list?
The singly linked list has only forward pointer and no backward link is provided. Hence the
traversing of the list is possible only in one direction. Backward traversing is not possible.
Insertion and Deletion operations are less efficient because for inserting the element at desired
position the list needs to be traversed. Similarly, traversing of the list is required for locating the
element which needs to be deleted.

29. Define doubly linked list.


Doubly linked list can be defined as a kind of linked list in which each node has two link fields.One
link field stores the address of previous node and the other link field stores the address ofnext node.

30. Differentiate between arrays and lists.


In arrays any element can be accessed randomly with the help of index of array, whereas in
lists any element can be accessed by sequential access only. Insertions and deletions of data is
difficult in arrays on the other hand insertion and deletion of data is easy in lists.

31. Write syntax of calloc() and relloc().


Calloc() is for allocating the required amount of memory.
Syntax: Void *calloc(size_t nitems,size_t size)
Relloc() function modifies allocated memory size by malloc() and calloc().
Syntax:Void *relloc(void *ptr,size_t size)

32. What is the use of typedef?


Typedef is used for renaming data types. It redefines the name of existing variable type. Itprovides
a short and meaningful way to call a data type.

56
Dr.NNCE I / 02 C / QB

FILE PROCESSING
UNIT V
PART-A
1. What is a file?
A file is a collection of related data stored on a secondary storage device like hard disk. Everyfile contains data that is
organized in hierarchy as fields, records, and databases. Stored as sequence of bytes logically contiguous (may not be
physically contiguous on disk

2. List out the types of files.


Thefollowing are the types of files
a. Text file or ASCII text file: collection of information or data which are easily
readable by humans. Ex. .txt, .doc, .ppt, .c, .cpp
b. Binary file: It is collection of bytes. Very tough to read by humans. Ex. .gif, .bmp,
.jpeg, .exe, .obj.
3. What are file attributes?
a. File name
b. File Position
c. File Structure
d. File Access Methods
e. Attributes flag

4. What is the use of functions fseek(), fread(), fwrite() and ftell()?


a. fseek(f,1,i)Move the pointer for file f of a distance 1 byte from location i.
b. fread(s,i1,i2,f)Enter i2 dataitems, each of size i1 bytes from file f to string s.
c. fwrite(s,i1,i2,f)send i2 data items,each of size i1 bytes from string s to file f.
d. ftell(f)Return the current pointer position within file f.
e. The data type returned for functions fread,fseek and fwrite is int and ftell is long int.

5. How is a file opened and file closed?


a. A file is opened using fopen()function. Ex: fp=fopen(filename,mode);
b. A file closed using fclose()function. Ex: fclose(fp);

6. What are the statements used for reading a file? (Nov 2014)
a. FILE*p;Initialize file pointer.
b. fp=fopen(“File_name” ”r”);Open text file for reading.
c. Getc(file_pointer_name);Reads character from file.
d. fgets(str,length,fp); Reads the string from the file.
7. What is the difference between getc() and getchar()? (May 2015)
int getc(FILE * stream) gets the next character on the given input stream „s file pointer to pointto the
next character.
int getchar(void) returns the next character on the input stream stdin.
57
Dr.NNCE I / 02 C / QB

8. Differentiate text file and binary file.


Text file Binary File
a. Data are human readable characters a. Data is in the form of sequence of bytes.
b. Each line ends with a newline character. b. There are no lines or newline character.
c. Ctrl+z or Ctrl+d are end of file character c. An EOF marker is used.
d. Data is read in forward direction only d. Data may be read in any direction.
e. Data is converted into the internal format e. Data stored in file are in same format
before being stored in memory that they are stored in memory

9. What is random access file?


A file can be accessed at random using fseek() function fseek(fp,position,origin);fp file pointer
position number of bytes offset from origin 0,1 or 2 denote the beginning current position or end of file
respectively.
10. What does the syntax depicts fread(&my_record,sizeof(struct rec), ptr_myfile);
(May 2015)
a. In the above statement, my_record is a pointer to an area of memory that will receivethe
data from the file.
b. Size of (struct rec) indicates that number of bytes required for structure rec to be read.
c. Paramater „1‟ indicates that only one time bytes required for structure rec to be read.
d. ptr _myfile is pointer to previously opened file.

11. State the two types of data files.


a. Steam oriented or standard data files.
b. System oriented or low level data files.

12. State the two categories of standard data files.


The two categories of standard data files are
a. Text files.
b. Unformatted data files (Binary files).

13. What are unformatted data files or binary files?


The files that organize data into blocks of contiguous bytes of information are calledbunformatted data
files or binary files.

14. State the parameter of fopen function.


The parameter of fopen function are
a. Name of the file to be open
b. Mode of use

15. Define text files.


Text files are more restrictive than binary files since they can only contain textual data. However,
58
Dr.NNCE I / 02 C / QB

unlike binary files, they are less likely to become corrupted. While a small error in a binary file may
make it unreadable, a small error in a text file may simply show up once thefile has been opened.

16. Define binary files.


Binary files typically contain a sequence of bytes, or ordered groupings of eight bits. When
creating a custom file format for a program, a developer arranges these bytes into a format thatstores the
necessary information for the application.
17. What do you mean by data file?
The data was written to the standard output and data was read from the standard input. As long as
only small amount of data are being accessed in the form of simple variables and a characterstrings. This
type of I/O is sufficient. With large amount of data, the information has to be written to or read from
auxiliary device. Such information is stored on the device in the form of a data file.
18. What is the use of rewind function?
rewind(): This function is used to move the file pointer to the beginning of the given file.
Syntax : rewind(fptr); Where fptr is a file pointer.

19. List the different modes of opening a file.


The function fopen() has various modes of operation that are listed below

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 appended mode.
r+ Opens a text file in both reading and writing mode.
w+ Opens a text file in both reading and writing mode.

20. Define logical file.


A logical file determines how data records are selected and defined when read by an application
program. A logical file can be a simple, multiple formats, or join logical file.

21. What are command line arguments?


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.
#include <stdio.h>
int main( int argc, char *argv[] ) Output
{ $./a.out testing
if( argc == 2 ) { The argument supplied is testing
printf("The argument supplied is %s\n", argv[1]);
} $./a.out testing1 testing2
Too many arguments supplied.
else if( argc > 2 ) {
printf("Too many arguments supplied.\n"); $./a.out
One argument expected
59
Dr.NNCE I / 02 C / QB

}
else {
printf("One argument expected.\n");
}
}
22. Which methods are used to write in to binary files?
The following are the methods are used to write in to binary files
a. fread() function is used to read a binary file.
b. fwrite() functions is used to write a binary file.
23. What is the basic file operation in C?
There are four basic operations that can be performed on any files in C programminglanguage.
a. Opening / Creating a file.
b. Closing a file
c. Reading a file.
d. Writing in a file.
24. State the fflush() method.
fflush() is typically used for output stream only. Its purpose is to clear (or flush) the output and
move the buffered data to console (in case of stdout) or disk (in case of file output stream). Syntax.
fflush(FILE*ostream);

25. What is the difference between printf() and sprint()?


sprint() writes data to the character array whereas printf(…) writes data to the standard output
device.
26. What is the different file extensions involved when programming in C?
Source codes in C are saved with .C file extensions. Header files or library files have the .H file
extension. Every time a program source code is successfully compiled, it creates an.OBJ object file,
and an executable .EXE file.

27. What is a sequential access file?


When writing programs that will store and retrieve data in a file, it is possible to designate that
file in to different forms. A sequential access file is such that data are saved in sequential access file,
one data is placed in to the file after another. To access a particular data within the sequential
access, data has to be read one data at a time, until the right one is reached.

28. Is it possible to create your own header files?


Yes, it is possible to create a customized header file. Just include in it the function prototypes
that you want to use in your program, and use the #include directive followed by the name of your
header file.

29. How do you search data in a data file using random access method?
Use the fseek() function to perform random access input / output on a file. After the file was
opened by the fopen() function, the fseek would require three parameters to work: a file pointer to the
file, the number of bytes to search, and the point of origin in the file.
60

You might also like