Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C Programming Theory Selected

Download as pdf or txt
Download as pdf or txt
You are on page 1of 72

1. Define software. Explain different types of software.

 Software is a collection of machine readable instructions that directs a computer to perform some
specific tasks. It is an ordered sequence of instructions given for changing the state of the computer
hardware in a certain predefined sequence. Generally software can be categorized as system
software and application software. The detail descriptions of system software and application
software along with their sub-categories are given below:
 System software: It is a type of computer software designed to operate the computer
hardware, to provide basic functionality and to provide a platform for running application
software. System software include device drivers, operation systems etc. It is responsible for
controlling, integrating and managing the individual hardware components of a computer
system so that they can work together harmoniously. Its purpose is to hide the complex details
of the hardware.
 Operating system is the main system software which controls all parts of the computer
system. The major function of OS are to handle all the hardware connected to the system,
coordinate and manage use of other resources and provide common services for computer
programs. Application programs usually require an operating system to function.
 Device driver is a computer program that operates or controls a particular type of device
that is attached to a computer. A device driver simplifies programming by acting as
translator between a hardware device and the applications that use it.
 Application software: It is a type of computer software that causes a computer to perform
useful tasks that a user wishes to perform. It utilizes capacities of a computer directly to a
dedicated task. Application software includes word processing software, database software,
multimedia software, graphics software etc. It can be categorized as:
 Tailored (custom) software is software that is specially designed for some specific
organizations or other user. It is developed for a single user that accommodates the
particular preferences and expectations of the user.
 Packaged (off the shelf) software is software which performs some specific function or
calculation which is useful for more than one computer user and is sufficiently well
documented to be used without modifications on a defined configuration of some computer
system.

1
2. Compare application software with system software.
 The comparisons of application and system software are:
 Application software utilizes the capacities of a computer to perform a dedicated task to benefit
the user whereas system software manages and integrates computer’s capabilities but doesn’t
utilize the capacities in the performance to benefit the user.
 System software provides the platform for the application software to run on the system
whereas application software provides the platform for the end users to use the capacities of
the system to solve various problems.
 System software deals with the hardware (architecture of the system) whereas the application
software interacts with end user.
 System software consists of low level programs that interact with the computer at a very basic
level.
3. What is a programming language? Explain different types of programming language.
 Programming Language is a standardized communication technique for describing instructions to a

computer. Each programming language has a set of syntactic and semantic rules used to define
computer programs. The different types of programming language are described below.
 Low Level Languages are those languages which are closer to the hardware. They are specific to
the hardware so cannot run on different hardware. Knowledge of hardware is required to
develop such programs using low level languages. It can be divided into Machine language and
Assembly language.
 Machine Language is the closest language to the hardware in which the instructions are
given in the form of 0’s and 1’s.
Advantages:
o It makes fast and efficient use of computers.
o Translator is not required.
Disadvantages:
o Programmer should have hardware knowledge.
o All memory addresses and operation codes are needed to be remembered.
o Testing and Debugging are difficult to carry out.
o They are machine dependent.

2
 Assembly Languages are those languages which used mnemonics in place of 0’s and 1’s.
Each instruction is represented by symbols instead of just using bits. The program written in
assembly languages must be converted to machine language.
Advantages:
o Easier to understand and use as compared to machine language.
o Programs are normally very fast and very compact.
o Timings can be calculated very precisely and program flow is easily controlled.
Disadvantages:
o Good Understanding of the hardware is required.
o Machine dependent
 High Level language is a language with strong abstraction from the details of the computer and
uses natural language elements, making the process of developing a program simpler and more
understandable relative to a lower level language. These languages are English like and are very
close to the human languages. They are machine independent. High level languages are
required to convert into machine level languages with the help of the translators. Rather than
dealing with registers, memory addresses and stacks, they deal with variables, arrays, objects,
functions, loops, threads etc. it can be categorized as:
 Procedural oriented languages (Imperative languages): In these languages one or more
related blocks of statements that perform some complete function are grouped together
into a procedure. If the same sequence of operations is needed elsewhere in the program, a
simple statement can be used to refer back to that procedure. A procedure may be a list of
instructions directing a computer, step by step, what to do, usually having a linear order of
execution from the first statement to the second and so forth with occasional loops and
branches. Procedural programming languages include C, C++, FORTRAN, Pascal and BASIC.
 Problem Oriented Languages (Declarative languages): These languages were developed to
solve specific problems or develop specific applications. These languages focus on what
work is to be performed rather than how to perform the work. These languages are usually
limited to a very specific application and it might use syntax that is never used in other
programming languages. These languages are specially focused on database management
systems. SQL, CSS, FUSION is some of the examples of problem oriented languages.
 Natural Languages: There languages are supposed to have the form of human cognition and
human intelligence. With these languages human can easily communicate or interact with

3
computers without the requirement of knowledge of any special programming languages.
These are generally used in Artificial Intelligence and Expert System. LISP and PROLOG are
few natural languages commonly in practice.
Advantages of High level Languages
 Support high level of abstraction.
 Easier to learn and use. Since the languages are very close to human languages.
 Easier to test and debug.
 They are machine independent. Software written in high level language can be used in
any computer system with different architecture.
Disadvantages of High Level Languages
 Requires more memory space and time.
4. Compare assembly language with machine language.
 Assembly language and machine language are both low level language. Its comparison is as shown.
 Assembly languages used mnemonics while machine language uses 0’s and 1’s to represent
operational codes and operand.
 Assembly languages need a translator to convert into machine language.
 Comparatively assembly languages are easier to understand and use than machine language.
But machine languages are a bit fast and efficient.
 Both are machine dependent and programmer must have the knowledge about hardware
before using each language.
5. Write the difference between high level and low level language.
 The difference between high level and low level language are:
 Low level languages are machine oriented whereas high level languages are problem oriented.
 Programs developed using low level languages run faster and take less storage space.
 Low level languages are used to develop system software whereas high level languages are used
to design application software.
6. Explain, briefly, about the generations of programming language.
 The various generations of programming language are explained below.
 First Generation: The first generation of programming languages is all about machine code.
Code of the first generation programming language was entered through physical switches on
the computer and involved commands to move data bits to and from registers, compute on
these and more. Machine language can be taken as first generation programming language.

4
 Second Generation: To minimize the difficulty, the operational codes were represented by a
mnemonics which in some way describes the action of the machine code (such as save, mov,
add, load). The source codes were needed to be assembled into machine code before it can be
executed by a processor with the help of an assembler. Such languages are sometimes still used
for kernels and device drivers, i.e. the core of the operating system and for specific machine
parts. Assembly language was used as a second generation languages.
 Third Generation: Languages of third generation were closer to human languages. The flaws of
first and second generation were dealt by making the language machine independent and
including programmer friendly features. These languages require a compiler to make machine
code for the processor. Third generations which are high level languages are sometimes referred
as imperative languages. Imperative means that the code is executed line by line in sequence.
Few Examples are FORTRAN, C, C++, Java, C# etc.
 Fourth Generation Languages are designed to reduce programming effort and the time it takes
to develop software, resulting in a reduction in the cost of software development. Languages
have been designed with a specific purpose which includes query language, report generators
etc. These languages are referred as declarative languages since it describes what computation
should be performed but not how to perform it. Characteristics of fourth generation languages
can be summarized as portable, closer to human language, database supportive, simple and
requires less effort, non procedural. SQL, NOMAD, FOCUS are some of the examples of fourth
generation language.
 Fifth Generation Language also known as natural language provides a visual or graphical
interface to develop software. It allows user to interact with computers without needing any
specialized knowledge. These languages are generally used for writing programs for artificial
intelligence, neural network, plasma computing etc. LISP, PROLOG, Mercury are some of the
examples of fifth generation languages.
7. What are the characteristics of a well written program?
 A feature of software defines the distinguishing characteristics of software based on performance,
portability or functionality. Some of the important characteristics of well written computer
programs can be:
 Integrity refers to the accuracy of the calculations.
 Clarity refers to the overall readability of the program.

5
 Simplicity: The structure and logic of the program must be as simple as possible to enhance
the clarity and accuracy of the program.
 Efficiency is concerned with execution speed and efficient memory utilization.
 Modularity means dividing the program into small modules which are independent of each
other. It enhances the accuracy and clarity and facilitates future program alterations.
 Interoperability is the ability of the software to exchange information with other
applications and make use of information transparently.
 Portability is the ability of the software to function in different platforms and environments
Some others desirable characteristics may be security, flexibility, scalability, reliability etc.
8. Explain about recent trends of software.
 In the early days of software development, software was difficult to develop as they used machine
languages which made them efficient and faster but on the other hand became non portable and
lacked lot of user friendly features. But as the programming language developed, the software has
been very user friendly and provides a visual interface or a graphical user interface which has made
it much easier for user to interact.

Development of software has taken a huge stride in modern era. In recent years, DevOps and agile
development methodology has been heavily used for software development [1]. Nowadays the focus
is on cloud computing which in general means a virtual hard drive that is accessible to the network
of computers.

Cloud computing is a computing paradigm in which tasks are assigned to a combination of


connections, software and services accessed over a network. This network of servers and
connections is collectively known as cloud. Using different medium as an access point, users can
reach into the cloud for resources whenever required.
9. Explain different phases or steps of developing software.
 The following phases are included in a software development.
 Problem Analysis: This is the first step of software development in which we define our
objectives, analyze our input, processing and output requirements. Depending on the size and
complexity of the problem, a clear statement of the problem is made. And the types and
number of inputs and outputs are evaluated. Finally, a mechanism to convert available
resources into final productive results must be determined.

6
 Algorithm Development and Flow Diagram: In this phase, a general outline of the problem is
sketched using algorithm and flow chart. Algorithms are used to define a set of steps or
procedures to be followed to solve a given problem while flowcharts are the diagrammatic
representation of the steps to solve a particular problem.
 Coding: It is the process of writing a program using a particular programming language. Though
high level languages are more preferred, low level language can be used as well to write a
program. Depending upon the ease and accessibility, the programmer may use any platform to
write a program.
 Compilation and Execution: When the programs are written into high level language, then it
needs to be converted into low level language. This conversion is done by compiler and the
process is called compilation. After the compilation process, an executable program will
generate which when opened is set to execution. Different inputs are provided to check if the
defined objectives are fulfilled or not.
 Debugging and Testing: Testing is the process of finding errors in the program while debugging
is the mechanism to remove the different errors that are present in the program. General syntax
error will be pointed by the compiler, but the run time errors must be checked by providing
different sets of inputs to the program and tracing the output.
 Program Documentation: It is done for future reference which can be analyzed for better
software development in later days. Documentation includes all the information about the
program.
10. List the advantages and disadvantages of using flowchart.
 The various advantages and disadvantages of using flowchart are listed as:
Advantages:
 Communication: As diagrams are better way to provide information, flowchart will
communicate the logic of the whole system concisely and efficiently.
 Effective Analysis: Problem can be analyzed more effectively resulting in reduction in cost
and time
 Proper Documentation: As flowchart contains information about the working of the system,
it helps to make documentation better.
 Efficient Coding: the flowchart acts as a guide for the programmer to write a code in more
efficient manner, since the steps and requirements are clearly defined in diagram.
 Proper Debugging: The flowchart, sometimes, can be helpful in debugging process.

7
 Efficient Program Maintenance: The maintenance of operating program becomes easy with
the help of flowchart. It helps the programmer to put efforts more efficiently on that
section.
Disadvantages:
 Complex and clumsy: when the program gets quite complicated, the flowchart can be more
complex than it is imagined to be.
 Difficulty in modifications: When some alterations are to be done, the flowchart may
require re-drawing.
11. List different symbols used for drawing a flowchart.
 The basically used symbols in flowchart are tabulated as:
SN Symbol Name of shape Purpose
1. Oval Start/Stop: Used to indicate the start and
stop of the flow diagram.
2. Parallelogram Input/Output: Used to represent the input
and output of the program
3. Rectangle Processing: Used for data manipulation

4. Diamond Decision: Used when there are more than


one options for the user to select

5. Circle Connector: use to connect two different


distant sections of a flowchart
6. Arrow head Flow line: used to connect two symbols

12. Explain compilation process with relevant diagram.


 The process of translation of high level language to low level language is called compilation process.
In this process, source code is converted into executable file. It basically consists of two phases.
 Compilation: First, the compiler converts the source code, which is written using high level
language, to object code.
 Linking: Secondly, the linker combines the object code with library modules that are used in
the program and also replaces the symbolic addresses with real addresses. And finally, it
generates a machine code in the form of executable file.

8
Source File Source File Source File

Compiler

Object File Object File Object File

Executable
Library Linker Program

Figure 1: Compilation Process

13. Write the difference between compiler and interpreter.


 The difference between compiler and interpreter are:
SN Compiler Interpreter
1. Scans the entire program and translates it as a Translates program one statement at a
whole into machine code time
2. Generates intermediate object code which No intermediate object code is generated,
further requires linking, hence requires more hence are memory efficient
memory
3. It takes large amount of time to analyze the It takes less amount of time to analyze the
source code but the overall execution time is source code but the overall execution time
fast is slow
4. It generates the error message only after When error is detected while translating, it
scanning the whole program. Hence debugging stops at that point. Hence debugging is
is comparatively hard. easy
5. Examples: C, C++ use compilers Examples: BASIC uses interpreters

9
14. Define the term source code, object code, compiler, and linker.
 Source codes are the programs written using a particular programming language. The file with .c
extensions includes source code written in C programming language. Object codes are the
intermediate code built by the compiler during compilation process. The file with extension .obj
includes object code. Compiler is used to convert the high level language to low level language.
Linker is a program that combines different modules to form an executable file.
15. Explain different types of error in programming.
 The different types of error in programming are:
 Compile errors: it occurs at the compilation time. It includes syntax errors and semantic errors.
Syntax error occurs when rules of programming language are not followed. Missing semicolon,
no declaration of variables etc are few examples. Semantic errors occur when the statements
written in the program are not meaningful to the compiler.
 Logical errors: it occurs in the logic of the program. The compiler cannot detect logical errors.
The program runs but leads to undesired output.
 Runtime errors: it occurs due to some illegal operation performed during the execution of the
program. Dividing a number by zero, opening a file that does not exist, lacking memory space
etc are few examples of runtime error.
16. Describe different debugging techniques used in programming.
 The various debugging techniques used in programming are mentioned below.
 Error Isolation: In this method, a particular section is isolated by making them comments. If
error doesn’t occur after isolating certain part of code, then we may predict that the part of
code has some error.
 Tracing: Using this method, we display the value of the variables at different places to see how
they change. And undesired value of such variables will help to locate the error.
 Watch values: A watch value represents a value of a variable or expression, whose updated
values are continuously shown to the programmer during the execution of the program.
Inspecting the unexpected changes in the variable can help to determine what the fault is.
 Breakpoints: These are the temporary stopping point of the program execution. The program
stops its execution at the breakpoint. It can be used with watch values to inspect the value of
different variables to the particular point.
 Stepping: It is the process of executing one statement at a time. It will be easier to determine
which instruction is causing problem by stepping through the entire program.

10
17. Explain constants, variable, data types and qualifiers with example
 CONSTANTS are fixed values that do not change during the execution of a program. Constants,
leaving few exceptions, are assigned to the variable of their corresponding type. It may be in the
form of
 Integer Constant: Every whole number: 4, -5, 66, 235
 Floating Constant: Fractional numbers: 4.334, 757.3458
 Character Constant: Alphabets, digits, operators, symbols written in single quote: ‘3’, ‘+’, ’a’
 String Constant: Any combination of characters within double quote: “Nepal32”
VARIABLES are simply a named area of storage that can hold a single value. In C programming
variables are needed to be declared before making any use of it.
 int num; - declaration of an integer variable, with name num and data type int.
 char ch; - declaration of a character variable, with name ch and data type char.
DATA TYPE is an extensive system for declaring variables, and represents the type of data the
declared variable will hold.
 int num; char ch; - int and char are data types; int data type represents variable num can
hold only integer value while char data type symbolizes variable ch can accept only
character value
o character and integer values can be used interchangeably.
QUALIFIERS are keywords used to modify the attribute of any declared variable. Generally used
qualifiers are sign and size along with const; sign qualifier includes signed and unsigned, size
qualifier include short and long.
 unsigned int count; - unsigned is a qualifier which makes the variable count – which is of
integer data type- hold only positive values.
 long double amount; - long is a size qualifier which increases the range of values that can be
hold by variable amount which is of type double.
18. Describe about all fundamental data types in C.
 The basic types of data types used in C are as follows:
Character Data Type:
 Keyword char is used to define characters in C which consists of ASCII character.
 It requires 1 byte (8 bit) memory and has the range of -128 to 127.
 Qualifier signed and unsigned can be applied. Char and signed char are similar.
 Unsigned char has the range of 0 to 255.

11
Integer Data Type:
 Keyword int is used to represent integer data type which in general requires 2 bytes of
memory (may vary from one compiler to another).
 The range of an integer is limited from -32768 to +32767.
 In general the range is given by -2n-1 to 2n-1-1, where n represents the no. of bits.
 Different qualifiers can be applied to int varying the size and range of it.
 If short int and int have same memory requirements (2 bytes) then long int will have double
the requirements (4 bytes).
 If int and long int have the same memory requirements (4 bytes) then short int will have half
the requirements (2 bytes).
 Signed int and int is similar with 2 bytes requirements and range is -32768 to 32767.
 Unsigned int also require 2 bytes but range varies from 0 to 65535.
 Unsigned qualifier can be applied to int as unsigned short int and unsigned long int.
Single Precision Real Data type (float):
 Keyword float is used to represent float data type which require 4 bytes of memory and the
range is limited from -3.4e-38 to +3.4e38.
 Floating point numbers are stored in 32 bits with 6 digits of precisions.
 The precision describes the number of significant decimal places that a real value carries.
 Qualifiers are not required to apply since long float is equivalent to double.
Double Precision Real Data type (double):
 A double precision number is required when very high precision is required i.e. accuracy of
float is not sufficient.
 Keyword double is used to represent double precision real data type.
 A double data type requires 8 bytes of memory giving a precision of 14 digits and the range
of -1.7e-308 to 1.7e+308.
 Qualifier long can be applied to extend the range in case required.
19. Differentiate between identifier and keyword.
 The general difference that can be observed in C programming are listed as:

SN Identifier Keywords
1 Names given to various program elements; Reserved words with predefined meaning in
variables, functions and arrays C programming
2 Formed with letters and digits; but cannot In general consists of only alphabets.
start a name with a digit

12
3 Identifiers can be of any case; lowercase, Keywords, usually, are represented by
uppercase, combination of both lowercase characters
4 Examples: Examples:
int num1; Basic data types: int, float, char
char str_name[20]; If, else, switch, do, while, for etc that are
num1 and str_name are examples of identifier used in control statements

20. List the rules for writing a name of an identifier.


 Rules for naming any identifier are as listed below:
 Name can use only alphanumeric characters and underscore; A-Z, a-z, 0-9 and _ can be
used; _digit, num1, first_result etc
 The first character must be alphabet of underscore; A-Z, a-z, _; _name, roll_no, salary
 Its name should not be same to that of any keyword; while cannot be used as identifier.
 White spaces are not included in any name; number of books, as an identifier, is invalid.
 Only first 32 characters are significant; if the length of identifier’s name is more than 32 then
only 32 characters will be taken as its name, rest ignored.
21. How can we calculate the range of any data type? What is the size and range of signed int, float,
long double?
 General form for the range calculation is given by
Lower limit = -2n-1
Upper limit = +2n-1 - 1;
Where n is the number of bits representing any data type.
For instance: int is represented by 2 bytes which is 16 bits, so range is given as
Lower limit = -215 = -32768 Upper Limit = 215 - 1 = 32767
Size and Range for few types are:
SN Type Size (bytes) Size (bits) General Form Lower Limit Upper Limit
1 signed int 2 16 0 65535
2 float 4 32 -231 to +231 – 1 -2147483648 2147483647
1023 1023
3 long double 10 1024 -2 to +2 –1 - -
*Note: when there is a qualified data type there will be variation in size and range which depends on
the type of qualifiers used.

13
22. Define statement. Explain different types of statements with examples.
 Statement is the smallest standalone element of an imperative programming language that
expresses some action to be carried out.
Different types of statements in C programming are:
 Labeled Statements: statements with labels, which are ended with a colon, are labeled
statements.
 Expression statements: consists of an expression followed by a semicolon.
 Selection statements: the sub-statement of the selection statement will be executed only if
the expression in selection statement is non-zero. If else and switch case are examples of
selection statements.
 Iteration statements: the sub-statement of any iteration statement will be executed
repeatedly as long as the control expression results in non-zero value. while loop and for
loop are two examples.
 Jump Statements: changes the control of the program from one position to another within
the same program. The goto, which is seldom used, along with break, continue and return
statements are examples of jump statements.
23. Describe about escape sequence and escape characters with example.
 The back slash character ‘\’, which modifies the usual meaning of the succeeding character, is called
the escape character. The escape character juxtaposed with another character forms an escape
sequence defining a specific function.

Characters Escape sequence ASCII value


Null character \0 0
Back space \b 8
New line \n 10
Back slash \\ 92
vertical tab \v 11
Horizontal tab \t 9

24. What are operators? Explain, in brief, different types of operators with appropriate example.
 Operators, in any expression, are characters that are used to manipulate the data. The data may be
in the form of constant or variable while the manipulation includes logical and arithmetical
operations, in general. The different types of operators are:
 Arithmetic Operators: symbols or characters used for arithmetic operations such as
addition, subtraction, division and so on. Few examples can be +, -, /, %, *. Division operator

14
(/) gives the quotient after division while modulus (%) operator results in remainder after
division. For eg: 5/3 = 1 whereas 5%3 = 2.
 Relational Operator: it provides the relation of two operands whether they are equal,
greater or lesser and other possible relations. Few examples are > (greater), < (lesser), ==
(equal), != (not equal). If the relation is true then it results in non-zero value else results
zero. If a = 4, b = 5 and c = a > b, then c= 0, for instance.
 Logical Operators: used for logical operations and combine multiple conditions into one.
AND (&&), OR (||) and NOT (!) are logical operators.
 Assignment operators: Used to assign the result of an expression to a variable. It includes =,
+=, -=, /=, %=. For instance, a = 6 uses = as an assignment operator. Also a % = b is
equivalent to a = a % b.
 Increment and decrement operators: It increases or decreases the value of an operand by
one. It includes ++ and --. If the operator precedes the operand then it is called pre
increment or decrement whereas if the operand precedes the operator then it is called post
increment or decrement. For example, a++ is post increment while --a is pre decrement.
 Conditional Operator: It is used to test a particular condition. Its general form is:
variable = expression?expression1:expression2
For example, x = a > b? a : b here, if the expression (a > b) is true then x= a
(expression1) else x = b (expression2)
 Other operators
 Address operator (&): gives the address of an operand
 sizeof operator (sizeof()): provides the size of the operand
 dot operator (.): use to access the member in structure
 Bitwise operator: for bitwise operations
25. Demonstrate the difference between post increment and pre increment operator.
 The function of both post and pre increment is to increase the value of operand by one but the
operation is different when it is used in some expression and assigned to another variable.
For example, let us assume, x = 5
Pre Increment Post Increment
p = ++x; is equivalent to q = x++; is equivalent to
x = x+1; (x = 6) q = x; (q = 5)
p = x; (p = 6) x = x + 1; (x = 6)

15
Hence in both cases the final value of x will be 6 but the value of p is 6 and q is 5.
26. What is the function of sizeof operator? Is it possible to use modulus operator with all data types?
 The sizeof operator is used to determine the amount of space a designated data type would occupy
in memory. Its general form is
S = sizeof (data type or expression)
For example,
s = sizeof(int) results in s = 2, since int requires two bytes.
r = sizeof(a) depends on the type of variable a.
Modulus operator can be used only on integers but cannot operate on float and double values.
Using modulus operator on type other than integer can result some kind of error; “illegal use of
floating points” in case of turbo C.
27. Illustrate the difference between binary plus and unary plus operator.
 Binary plus operator is used for addition while unary plus gives represents positive sign of an
operand. Binary plus uses two operands whereas unary plus uses single operand.
For example: a+b uses binary plus operator and +x uses unary plus operator
28. Define precedence and associativity. List precedence and associativity of different commonly used
operators in C.
 Precedence is the rule of priority of operators when multiple operators are involved in an
expression. Precedence of operators determines which operations to be evaluated first, and then
the second and it goes on.
Associativity is the ordering of the operations of operators of same precedence in an expression.
The different operators along with their precedence and Associativity is given as:

Operator Description Associativity


() Parentheses (function call) Left-to-Right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ -- increment/decrement Right-to-Left
+- Unary plus/minus
!- Logical negation/bitwise complement
(type) Cast(convert value to temporary value of type)
* Dereference
& Address(of operand)

16
Sizeof Determine size in bytes of this implementation
*/% Multiplication/Division/Modulus Left-to-Right
+- Addition/Subtraction Left-to-Right
<< >> Bitwise shift left, Bitwise shift right Left-to-Right
< <= Relational less than/less than or equal to Left-to-Right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to Left-to-Right
& Bitwise AND Left-to-Right
^ Bitwise exclusive OR Left-to-Right
| Bitwise inclusive OR Left-to-Right
&& Logical AND Left-to-Right
|| Logical OR Left-to-Right
?: Terminal conditional Right-to-Left
= Assignment Right-to-Left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
, Comma(separate expressions) Left-to-Right

29. Explain about preprocessor directives and its types with examples.
 Preprocessor, in C and C++ programming languages, is just a text substitution tool which instructs
the compiler to do require pre-processing before the actual compilation. All preprocessor directives
begin with a hash symbol (#). Generally used preprocessor are
 File inclusion directive
 #include<stdio.h> is an example of file inclusion directive, which is replaced with the
text of the file stdio.h; definition of different functions.
 #include<math.h> is another example of file inclusion directive.
 Macro definition and expansion
 #define PI 3.1416 is an example of object-like macros, which creates a symbolic
constant PI.
 #define SQR(x) (x*x) is an example of function-like macros, which creates a function
as defined by user.
(*One of the types of preprocessor directive – conditional compilation– has not been discussed.)

17
30. What are header files? Why are they required?
 A header file is a file with extension .h which contains C function declarations and macro definitions
to be shared among various source files. Few examples of header files are stdio.h, conio.h, math.h
and others unmentioned. Since, header files are the sources of definitions of different library
functions and as every program uses library functions, header files are required to be included in the
program.
31. What are symbolic constants? How are they defined?
 Symbolic constants, conventionally written in uppercase, are the names which substitute a
sequence of character that cannot be changed. The character may be a numeric constant, a
character constant, or a string constant.
General Form : #define NAME VALUE
Example : #define PI 3.1416
32. Define type casting and type promotion. Write the difference between implicit and explicit type
casting with examples.
 The mechanism of converting the type of an expression into another type is referred as type casting.
The process by which values of lower type are converted to higher type is type promotion.
The differences between implicit and explicit type casting are listed as:

Implicit Type Casting Explicit Type Casting


Implicit type casting happens whenever the Explicit type casting is the use of direct and
compiler expects data of a particular type, specific notation in the source code to request
but the data is given as a different type, a conversion or to specify a member from an
leading to an automatic conversion by the overloaded class.
compiler without an explicit indication by
the programmer.
Implicit casting is done automatically. Explicit casting is done programmatically.
In Implicit conversion, no data loss takes In explicit conversion, data loss may or may
place during the data conversion. not be take place during data conversion.
Hence there is a risk of information loss.
Implicit conversion does not require Explicit conversion do require cast operator to
any special syntax. perform conversion.

18
33. Explain the structure of C program.
 The general structure of C program is given as:
Documentation Section  Information about program, author and other details
Link Section  Link functions from library to the program
Definition Section  Defines symbolic constants
Global Declaration Section  Variables, functions are declared
Main function Section  Entry point of the program
Local Declaration part  All the variables used in the execution part are declared
Executable part  Statements for input, processing and output

Subprogram Section  Definition of all the user defined functions


Function 1  Functions can be called from any other function
Function 2  Functions, initially, must be declared before it is called
………………
Function n

34. Write the purpose and syntax of formatted I/O functions.


 Two functions, namely printf() and scanf(), are generally used formatted I/O function. Since it allows
the formatting of inputs/outputs such as width, alignment, precision and so on, it is referred as
formatted I/O functions.
 scanf() function
 Purpose: reads values from the keyboard as given by the user
 Syntax: scanf(“control string”, argument list);
1. Control String: contains one or more format specifier
2. Argument list: contains address of one or many variables corresponding to
number of format specifier
 Examples:
1. scanf(“%c”,&ch);  %c as character specifier, & to represent address
2. scanf(“%c %d %f”, &c, &num, &fnum);
 printf() function
 Purpose: outputs the values onto the screen
 Syntax: printf(“control string”, argument list);

19
1. Control String: contains information and one or more format specifier
2. Argument list: contains one or many variables corresponding to number of
format specifier
 Examples:
1. printf(“Enter any number”);  To display the information
2. printf(“Sum is %d”, sum);  To display information along with value of sum
3. printf(“%d %d”, a, b);  Displays two values without any other information
35. Define format specifier. List the format specifier for different data types used in C
 Format specifier is a special combination of characters that defines what kind of values is being read
or displayed using I/O functions. The generally used format specifiers are listed in the table below.

SN Format Specifier Description


1 %c Single character
2 %d Signed integer value
3 %f Floating value without exponent
4 %s Strings
5 %i Signed integer value
6 %x Hexadecimal form
7 %u Unsigned integer value
8 %o Octal value
9 %ld Long integer value
10 %lf Double value
11 %Lf Long double value

36. Explain the meaning of & operator in scanf. What happens if we use & operator in printf function?
 The & operator, also known as reference operator, is an address operator which gives the address in
memory of the operand that uses it. In simple, it is used to represent the address in which the
entered value from the user is stored.

If we want to display the value of a variable then using & operator along with variable will not
display the correct value. But in case we want to display the address of a variable then we ought to
use & operator and corresponding format specifier (%u) to display the address of a variable.

20
37. “The number and types of argument must be same to that of number and types of format
specification used”, clarify the statement with example
 For example,
int num1 = 2, num2 = 5, sum;
printf(“%d + %d = %d”, num1, num2, sum); is a valid output statement.
Here,
Number of format specifier = Number of arguments = 3
Type of format specifier = Type of arguments = integer

However, printf(“%d * %d = %d”, num1); is an invalid statement since the number of arguments do
not match with the number of format specifier used. Also, printf(“%d %f”, num1, num2); is an
invalid statement. Since the type of format specifier does not match with the type of variable used
in arguments.

Hence, for any input or output statement using formatted I/O functions to be valid, the number and
types of argument must be same to that of number and types of format specifier used.
38. Why is precision and field width required? What happens if the field width given is less than that
of the length of the variable, explain in case of scanf() and printf()?
 Precision, in any real number, is used to define how many numbers after decimal point to be used to
represent a real number. While the field width, in real and integer numbers, is used to assign the
number of spaces to display the given number.
If the width given is less than that of the length of the variable, then the following outcomes can be
observed.
 scanf(“%3d”, &num);
if the given input is 14324 then, it takes only 143 and other numbers will be ignored.
 printf(“Num = %3d”, num);
if the value of num is 12492 then still it displays 12492 regardless of the width defined.
39. Explain about flags with few examples
 Flags are used to format the results. It comes along with the format specifier. Commonly used
formatting flags are listed as
SN Flag Description
1. - Used for left justification
2. + Used to display the signed of any number

21
3. 0 Causes leading zeros to appear, if space is available
4. # Used to represent in octal and hex form

printf(“%-8.2f”, fnum); where fnum = 82.4432 will result in


8 2 . 4 4 If flag – is not used
8 2 . 4 4 When flag – is used

40. What are unformatted I/O functions? Write the syntax of putchar(), getchar(), getch(), getche().
 Unformatted I/O functions are those functions which do not have provisions to format the given
values; defining width, precision, alignments and others formatting options are not available. For
example, gets(), puts(), getchar() to name the few.
Sn Function Purpose Syntax Example
1. getchar() Read a single character char_var = getchar(); char ch;
ch = getchar();
2. putchar() Display a single putchar(char_var); char ch = ‘p’;
character putchar(ch);
3. gets(); Read a string gets(string_var); char name[20];
gets(name);
4. puts(); Displays string puts(string_var); char name[] = “check”;
puts(name);
5. getch() Reads a single char_var = getch(); char ch;
character, but doesn’t ch = getch();
echo it on the screen
6. getche() Reads a single char_var = getche(); char ch;
character, echoes it on ch = getche();
the screen
* char_var represents the character variable, while string_var represents string type variable
* Clarifying getchar(), getch() and getche():
 After the user enters the key, the entered character can be seen in the screen in case of
getchar() and getche() but not in case of getch().
 After pressing any key, enter key must be pressed in case of getchar() but not in case of
getch() and getche().

22
41. What do you mean by selective structure? When are they used?
 Selective structures are those statements which are used to change the order of execution of
statements based on certain decision out of many conditions. These structures are used when we
have to make decisions; which operation to carry out for a given situation.
42. Write the syntax, working flow and flowchart for the following
 Simple if
 Syntax:
if(condition) True
Condition
{
True statements;
False
} True Statements
Next statements;
Next Statements

 Working flow: when the condition is true then the true statements will be executed and
then the next statements will follow but if the condition is false then the true
statements are bypassed executing next statements.
 if else statement
 Syntax:
if(condition)
False True
{ Condition
Statements_T ;
}
else Statements_F Statements_T
{
Statements_F;
Next Statements
}

 Working flow: If the condition is true then Statements_T will execute but in case if the
condition is false then the Statements_F will be in execution.
 Examples where if else can be used:
o To check if the number is even or odd.
o To determine if a number is greater than another given value.

23
 else if ladder
 Syntax:
if(Condition 1) True
{ Condition 1 Statements_1
Statement_1;
} False
else if(Condition 2)
{ True
Statement_2; Condition 2 Statements_2
}
else if(Condition n) False
{
Statement_n; True
Condition n Statements_n
}
else
{ False
Default_Statements;
Default_Statements
}

 Working Flow:
o When particular condition is true, then its corresponding statements will get
executed and subsequent remaining conditions will not be checked.
o If condition 1 is true then its corresponding statement is executed but if it is
false then condition 2 is checked.
o In case, condition 2 results in true then statement_2 will be executed otherwise
condition 3 will be checked and the flow will just go on.
o If all conditions are checked and none of them are true then, the statement
within the else block will be executed.
o This structure works without the use of else block as well.
 Examples than can use else if ladder:
o To determine whether the number is positive, negative or zero.
o To find the relation of two numbers; greater, equal or less.
o To calculate roots of quadratic equations; real and equal, real and unequal, and
imaginary roots

24
 Nested if ladder
 Syntax:
if(condition 1)
{
if(condition 2)
{
Statement 1;
}
}
else
{
If(condition 3)
{
Statement 2;
}
else
{
Statement 3;
}
}
 Flow Diagram:

False True
Condition1

True False False True


Condition2 Condition3

Statement 1 Statement 3 Statement 2

Next Statements

 Working flow:
o As its structure can vary, the flow can be different based on the type of nested if
structure used. Here, we have used simple if within if statement while if else
statement within else part to form a nested if structure.

25
o In above case, first the condition 1 is checked, if it’s true then condition 2 will be
examined and statement 1 will be executed in true case.
o If the condition 1 is false then condition 3 will be checked, if it is true then
statement 2 is executed otherwise statement 3 will be executed.
 Example that can use nested if:
o To check whether the year is leap year or not
43. In which case, simple if and if else should be used? Give few examples
 When only one condition is to be checked then simple if is used. But if there are two conditions
which are mutually exclusive (both condition cannot be true at the same time) then if else
statement must be used. Look at the following case:
Case 1: To check even or odd
 A number can either be even or odd but cannot be both at the same time, so this condition
is a mutually exclusive condition.
 Since there are only two conditions, if else should be used.
Case 2: To find the sum of even numbers out of 10 numbers
 In this problem, only sum of even numbers is required so the condition for odd part is not
required, so simple if can be used.
44. When is else if ladder needed?
 When more than two mutually exclusive conditions are to be checked then else if ladder is required.
Example 1: Determine whether a number is positive, negative or zero.
In this case, there are three mutually exclusive (only one can be true for a given number) conditions,
so else if ladder should be used.
Example 2: Check the relation of two number; greater, smaller or equal.
Similarly, in this problem, there are three mutually exclusive conditions, so use else if ladder.
45. What sort of conditions necessitates the use of nested if?
 When there are two or more conditions which are not mutually exclusive then nested if should be
used.
Example 1: To check whether the number is even and it is greater than 30
Since a number can be even and also be greater than 30, this condition is not mutually exclusive, so
in this case, nested if should be used. First check if the number is even or not and then check if it is
greater than 30 or not, constructing a nested structure of if.

26
46. Demonstrate the conversion of nested if structure to a else if ladder with the help of logical
operators
 Let us take an example to demonstrate the conversion.
Write a program to find the largest among 3 numbers.
First using nested if
if(a>b)
{
if(a>c)
{
largest = a; // a>b and a>c
}
else
{
largest = c; //a>b and c>=a
}
}
else
{
if(b>c)
{
largest = b; //b>=a and b>c
}
else
{
largest = c; //b>=a and c>=b
}
}
In above code, the possible conditions can be listed as
a>b and a>c  a largest
a>b and c>=a  c largest
b>=a and b>c  b largest
b>=a and c>=b  c largest
Now the same problem can be solved using else if ladder with the help of logical operators
if(a>b && a>c)
{
largest = a;
}
else if(b>=a && b>c)
{

27
largest = b;
}
else
{
largest = c;
}
47. Write the general form of switch case.
 The general form of switch case is:
switch(expression)
{
case constant-1:
statement-1;
break;
case constant-2:
statement-2;
break;
default:
default statement;
break;
}
48. What kind of condition determines whether the switch or if else is to be used?
 If the condition given is in the form of range, such as greater than zero, less than zero then it is
better to use if else statement, but if the condition to be checked is an integer constant or character
constant then either if else or switch can be used. So, it is always better to use switch case when the
given condition is in the form of constants rather than range.
49. What kind of variables or expressions can be used within the expression of switch?
 In general, those variables or expressions which results in either integer or character value must be
used within the expression of switch.
50. What can be the values of case label/constant in switch case?
 It can either be integer constant or character constant.
51. Explain the role of break statement in switch case. What happens if break statement is not used in
any case of switch statement?
 Break statement is used to skip the part of code in switch case statement. When one case is true
then break statement of that case will cause other remaining case not to be checked. But if the
break statement is not used then each case will be checked and statements within true case along
with the default case will get executed.

28
52. Write the general form and working flow of conditional operator?
 The general form of conditional operator is given as:
Variable = expression1 ? expression2 : expression 3;
Here, expression 1 is a condition while expression 2 and expression 3 can be arithmetic, logical or
conditional itself. If the condition is true then the value given by expression2 will be assigned to the
variable, else value resulted by expression 3 will be assigned.
For example:
X = a>4 ? (a+3): (a-2)
Assuming, a = 5, since 5>4 is true, (a+3) will be assigned to X. so, X = 8
53. Explain why repetitive structures are required?
 When certain operations are needed to be done repeatedly then we need a mechanism to repeat
such operations and it is made possible by using repetitive structures. The operations may be input,
procession or output depending upon the problem.
54. What are the basic requirements for operating a loop? What is running variable?
 There are three basic requirements for loop to operate.
 Initialization: starting point of the loop
 Condition: terminating point of the loop
 Update: represents how the value changes from starting to terminating point
Running variable is one that is used to operate the loop. It is used in initialization, condition as well
as in update.
55. Write the syntax for compound statements, working flow and flowchart for
 For loop
Initialization
 While loop
 Do while loop
 The various types of loop are explained below:
False
a. For loop: Update
Condition
condn

Syntax:
True
for(initialization;condition;update)
Statements
{
statements; //Body of loop;
}
Figure 1: Flowchart of for loop

29
Working flow with example:

for ( x=1 ; x < = 10 ; x++ )

{
T
F
printf(“%d”, x);

b. while loop:
Syntax: Initialization

initialization;
while(condition)
False
Condition
{ Update condn

Statements; True

Update;
Statements
}

Working flow with example: Figure 2: Flowchart of while loop

x = 1;

while ( x < = 10 )

{ T
printf(“%d”, x);

F x + +;
}

30
c. do while loop:
Syntax: Initialization

Initialization;
True
do
False Statements
{ Condition
condn

Statements;
Update
Update;
}while(condition);

Working flow with example:


Figure 3: Flowchart of do while loop

x = 1;

do
{
printf(“%d”, x);

x + +;
T

} while ( x < = 10 );
F

56. When should we use for loop? Explain how it differs from while loop.
 Usually, for loop is used when the number of iteration to be done is known in advance. Let us take
an example of finding the sum of 10 numbers. In this case, we have prior information that the sum
needs to be repeated 10 times, hence for loop is better to use. All kind of loop, however, can be
used interchangeably. To differentiate for loop with while loop, for loop is used when there is prior
information about how many times a loop to be executed. On the other hand, while loop is used
when there is no prior information about how many times a loop will get executed.
57. Explain when is while loop used? What happens if the initialization of running variable is done
within the body of loop? And what results if the update of running variable is not done?
 When the number of iteration is not known in advance rather it is known during execution of
program. For instance, to determine the sum of all digits in any given integer, the number of times

31
the sum to be done will be determined by the input given by user during execution. If the entered
number is 3 digit then sum is to be done 3 times, if the number is of 5 digits then sum should be
done 5 times. Since, in this problem the number of iteration is not fixed since user can give input of
any length. Hence, it is better to use while loop in such case as this.
Initialization of running variable should be done before its corresponding loop; otherwise it will lead
to infinite loop. Similarly, update should be done within the body of loop; else it results in infinite
loop.
58. Distinguish between while and do while loop.
 The following table shows the difference between while and do while loop
SN while loop do while loop
1 Entry Controlled Loop Exit Controlled Loop
2 Condition is checked before the execution Condition is checked at the end of the after
of statements within loop the execution of statements
3 Body of loop may or may not execute Body of loop will execute at least once
4 In syntax, while terminated by semicolon while is terminated using semicolon as a part
gives a different meaning or can give error of syntax; gives error if semicolon is not used
5 Its flowchart is: Its flowchart is:
Entry
Entry

False Body of Loop


Condition
condn

True
False
Condition
Body of Loop condn

True

Exit Exit

59. Explain briefly about break and continue statement with example
 Break and continue statements are, in general, used in loops to exit the loop and to skip the certain
statements respectively.
Break Statement: Whenever there is a break statement in a loop, then that particular loop will get
terminated after the execution of break statement.

32
The following diagram demonstrates the use of break statement.

x = 0; Output:

while ( x < = 10 ) 123456

{ In this example, the loop


T will terminate when the
x + +; value of x becomes 7.
So, only values from 1 to
F if ( x == 7 ) 6 will be displayed.
T
break; F

printf(“%d ”, x);
}

Continue Statement: Whenever continue statement gets executed in a loop, then the statements
below the continue statement with not execute but it continues another iteration of the loop.
The following flow diagram demonstrates the use of continue statement in a loop.

x = 0;
Output:
while ( x<=9 )
12346789
{ T In this example, the continue
x + +; statement will skip the statement
printf(“%d ”, x) when the value of
F if ( x == 5 ) x becomes 5. But the loop
continues for next iteration.
T continue;
F
printf(“%d ”, x);
}

33
60. Compare break and continue statements.
 The comparison of break and continue statements is as shown below.

SN Break Statement Continue Statement


1. Used in loop and switch case Used in loop
2. Terminates the loop, skips the statements Skips the statements in loop but continues the
in switch case loop
3. Condition is required before break Condition is required before continue
statement, otherwise the loop will run statement, otherwise can lead to infinite loop
only once and gets terminated
4. Its flow diagram within a loop Its flow diagram within a loop

Statements
Statements

Back to loop
True
Back to Loop Condition True
Back to Loop Condition
condn
condn
Out of Loop
False
False
Statements
Statements

61. What are nested loops? When are they used?


 Nested loops are the combination of loops in which body or statements of one of the loops contain
another loop. Nested loops can be formed combining different types of loop.
 Presence of for loop within a for/while/do while loop
 Inclusion of while loop within a while/for/do while loop
 Including do while loop within a do while/while/for loop
Nest loops are used in following cases, in general.
 A particular problem requires a loop, and the same problem to be repeated to number of
other samples. For example, to determine if the number is prime number or not requires a
single loop but if the range of numbers is to be checked then nested loop comes into action.

34
 Working with two or more dimensional structure such as in case of matrices. Accessing each
element of two dimensional arrays requires nested loop.
62. Demonstrate how to change for loop to a while loop?
 The following demonstration shows a change of for loop to a while loop.

statement 1;
statement 1; initialization;
for(initialization ; condition ; update) while(condition)
{ {
statements; statements;
} update;
statement 2; }
statement 2;

63. Explain the working flow of nested for loop with example.
 The diagram shown below demonstrates the working flow of nested for loop.
Let us take an example to display the following pattern
1
1 2
1 2 3
1 2 3 4
for ( x=1 ; x<=5 ; x++ )
1 2 3 4 5

F {
T

for( z=1 ; z<=x ; z++ )


{
T
F printf(“%d ”, z);

printf(“\n”);
}

35
64. What happens if nested loop contain same running variable?
 It is always better to use different variable as a running variable when it comes to nested loop. If the
loops of nested structure use the same running variable then it will cause problem during runtime.
The second loop will change the value of running variable of first loop, causing the nested structure
behave erroneously.
65. Which condition will cause a loop to run infinite times? State few examples
 The following condition will cause a loop to run infinite times
When condition of loop is always true, it occurs when
 Initialization of running variable is not done, or done within the body of loop
 Update of running variable is not done
 Placing non zero value in condition part of loop; while(1)
 Incompatibility in condition and update value.
66. Define function. Mention the advantages of using function.
 A function is a module containing set of instructions that performs a specific task. It is referred to as
sub routines that can be processed independently. For instance, sqrt() is a function which contains
set of statements/code that calculates the square root of given number.
Various advantages of function can be listed as:
 Reuse of code: The same set of codes can be used by any program which requires the
similar task to carry out.
 Reduced program length: Since same set of codes can be used many times, whenever
required, the length of source program will be reduced.
 Facilitates top-down modular programming: The main function consists of only the function
calls representing the high level approach to the problem while details of function
definitions are addressed later.
 Easy to debug: Since the program will be in modular form, commenting the function call will
make the corresponding function inactive. Hence, it makes easy to locate and isolate the
faulty set of instructions within a particular function.
 Division of tasks: Different tasks of the problem can be assigned to different personnel. Each
task is solved using a function and finally all functions are combined into a single program.
67. Explain main function. How it differs from other functions?
 The main function is the entry point of any program. Every program must have a main function to
indicate the beginning of the execution of the program.

36
It differs from library functions as well as user defined functions. The library functions are simply
used in programs with no definition required but a header file needs to be addressed, while the user
defined function needs a function declaration, function call and function definition. But in case of
main function, the user writes the definition part only, and it is called by the operating system. Also
the main function is only the entry point to the program while other types of functions are not.
68. Describe about the function declaration (prototype), function call, and function definition.
 Every user defined function, in general, consists of three elements, which are described below:
 Function Declaration: it gives the information about what the function does, what it takes as
arguments, what it returns after execution. It consists of:
 Function name: identifier or name given based on its task
 Return type: represents what type of value it returns after processing
 Argument list: indicates what type and how many values it requires to execute
 Semicolon: used to terminate the declaration
 General syntax is:
o Return_type function_name(argument list);
 Example:
o float sum(float, float); this declaration indicates, the function calculates the
sum of two float values and returning the result from where the function is
called.
 Function Call: It is used to make the function do its task. The function is called using the
name given in declaration, followed by the number and types of arguments as in
declaration. The function call need not to be assigned if the function does not returns any
value after processing. But when the function returns a value after execution, it better to
assign to a variable if the value returned is required later. After the function is called, the
control is transferred to the function definition. Then the function gets executed line by line
and the value is returned if there is presence of return statement.
 General syntax:
o variable = function_name(argument list); if the function returns a value
o function_name(argument list); if the function doesn’t return a value
 Example:
o S = sum(a,b); where a, b and S are of float type

37
 Function Definition: It is the part where the working of the function is defined. It consists of
return type, function name, list of arguments, local variable declaration, and return
statement. After the execution of the statements the control is returned to the point from
where the function is called.
 General Syntax:
o return_type function_name(argument list)
{
Local variable declaration;
Statements;
Return statement;
}
 Example:
o float sum(float num1, float num2)
{
float s;
s = num1 + num2;
return s;
}
69. What do you mean by arguments? Differentiate formal arguments with actual arguments.
 An argument is an expression passed to the function to carry out its specified task. It is an
expression which is written, and separated with comma if more than one, within the parenthesis of
function call, function declaration and function definition.
The difference between format and actual arguments can be listed as:
SN Actual arguments Formal arguments
1. Arguments passed in the function call Arguments in the function definition
2. Defined in the calling function It belongs to the called function
3. Change in actual arguments will change Changing the value of formal arguments does
the value of formal arguments not change the value of actual arguments,
unless reference is used.

38
70. Explain the use of return statement. Is it mandatory to use return statement?
 Whenever a function needs to return a value, then return statement can be used. The return
statement, however, can return only a single value.
If the function is built to return a certain value to the calling function then it is mandatory to use a
return statement. But if the function has void as a return type then return statement can be
avoided.
71. What happens to the statements written after return statement?
 The statements after the return statement will not execute. Since the return statement sends the
control back to the calling function, the control never reaches the statements written after return
statement.
72. What does return type symbolizes in function definition and declaration? How is it related to
return statement?
 Return type in function declaration and definition symbolizes whether the function returns a value
to the calling function or not. If the return type is void, it represents function doesn’t return a value
while other data types such as int, float, char in return type represent that the function returns a
value.
The return statement can be avoided if the return type is void. But if the return type in not void then
in return statement, the expression to be returned must be of same type to that of the return type
of the function.
73. What difference can be observed in arguments portion of function declaration, function call and
function definition?
 The difference in arguments that can be seen is
 In function declaration: only data type of variables is written
 In function call: only the name of variables is written
 In function definition: data type along with name of variables is written
74. What does function declaration suggest? How are function called?
 Function declaration provides the following information.
 Name of the function, generally, defines what its function is.
 Return type symbolizes whether the function returns a value after processing.
 List of argument or parameter represents what type of and how many values are required
by the function to operate.

39
Functions are called with their name followed by the list of parameters or arguments. Function call
must be used or assigned if the returned value should be taken into considerations. But if the
function does not return any value or it returns a value which is not of much use then the function
call need not be assigned to or used.
For example, simply calling power function which returns a value does not make any sense.
pow(x,y);
But if it is assigned to a variable or used in some calculations then only it gives some meaning.
z = pow(x,y);
z = a * pow(x,y)/b;
printf(“x to the power y is %f”, pow(x,y));
75. “The number and type of arguments must be same in function declaration, function call and
function definition”, clarify the statement.
 The number and type of arguments must be same in function declaration, function call and function
definition; this statement can be clarified using following demonstration.
Let us take an example to calculate the largest number of three numbers, then
Function declaration: int large(int, int, int);
Function call: l = large(a, b, c);
Function Definition: int large( int x, int y, int z) { }
Since, the type and number of arguments match in function declaration, call and definition, there
would be no error. But if the number of arguments is changed, let us say in function call; l =
large(a,b), then the compiler would give error. Similarly if the type of either variable a, b, c is not
integer then again, it would result some kind of error. Hence, the number and type of arguments
must be same in function declaration, function call and function definition.
76. Is it mandatory to have function declaration? “Any entity must be declared first before it is used”,
explain the statement.
 Function declaration can be omitted, if the function definition is written before its call. So function
declaration is not mandatory.
Every entity in C programming must be declared before it is used. Declaration gives information not
only to the user but also to the compiler about the type and name of the entity we are using. With
such information, the compiler will interpret statements correctly. Also the compiler can decide how
much storage space to allocate. Hence, every entity such as variables, functions must be declared
first prior to its use. For example, without declaration, statement sum = num1 + num2 can represent

40
sum of integers or sum of float numbers or even combining of characters or strings. This can cause
problem to compiler.
77. Describe different types of functions based on return type and arguments.
 Based on return type and argument, the function can be categorized into four types. The description
is based on where the input, processing and output will take place.
 Function with no arguments and no return type: This kind of function can have no
information exchange with other functions unless global variables are used. Generally, all
the operations such as input, processing and output are done within the function.
 General form:
void function_name(void);
 Example:
clrscr(); is used to clear the screen with no arguments and no return type.
 Function with no arguments but with return type: In this kind of function, the inputs along
with the processing, if required, will be done within the function but the result will be
returned to the called function.
 General form:
return_type function_name(void); where return type is not void
 Example:
ch = getchar();
 Function with arguments but with no return type: Such functions take input values in the
form of arguments, but processing and output part of the problem will be within the
function.
 General form:
void function_name(argument list);
 Example:
putchar(ch);
 Function with arguments and return type: This function, usually, contains only the
processing part. The input and output of the problem will be in the calling function. The
inputs will be passed as arguments while the result will be returned through return
statement of function.
 General form:
Return_type function_name(argument list); where return type is not void

41
 Example:
sq = sqrt(num);
78. What are library functions? How it differs from user defined functions?
 Library functions are inbuilt functions which consist of line of codes to carry out particular
operation. Library functions are declared in header files, so inclusion of corresponding header file is
a must whenever the library functions are used.
The difference between library function and user defined function are listed below.
SN Library Function User Defined Function
1. Inbuilt functions for specific purpose Defined by user based on problem specified
2. Requires header file to be included Header file not required
3. Definition is already written Definition should be written by the user
4. It cannot be modified It can be modified as required
5. clrscr(), getchar(), scanf(), pow() etc are Functions not defined in library such as sum(),
examples of library functions prime() etc are few examples

79. What do you mean by passing reference? When are they used?
 Passing reference in a function means to pass the address of the variable rather than its value.
When a function needs to return more than one value, which it cannot do through the return
statement, then in such situations passing reference are used.
80. Differentiate between pass by value and pass by reference.
 The differences between pass by value and pass by reference can be summarized as:
SN Pass by value Pass by reference
1. Value of variable is passed Address of variable is passed
2. Changes of formal arguments in called Any changes made in formal arguments in the
function does not the value of actual called function changes the value of actual
arguments in calling function arguments in calling function
3. Return statement should be used to Return statement is not required in this case
return value but can be used
4. Only one value can be returned to the More than one value can be returned to the
calling function calling function
5. Pointer is not required Pointer is required since it is used to hold the
address of the variable

42
6. Used when no values are to be returned Generally used when function needs to return
or single value is needed to return to the more than one value.
calling function
7. Example to demonstrate pass by value and pass by reference:
void check(int, int*);
void main();
{
int x = 2, y = 5;
check(x, &y);
printf(“The final value of x is %d and y is %d”, x, y);
getch();
}
void check(int a, int *b)
{
a = a+ 3;
*b = *b + 2;
}

Here in this program, value of x is passed where address of y is passed. Variable a holds the
value of x while pointer variable b holds the address of y. So, change in variable b
represents change in variable y of main function but change in variable a does not change
value of x in main function. Hence, the final value of x is 2 but the value of y is 7.

81. What changes can be seen in the function declaration, function call and function definition while
using pass by reference?
 When using pass by reference following changes can be seen:
 Function declaration: use of pointer notation to hold the address
void function_name(datatype *, datatype *);
void swap(int *, int *);
 Function call: use of address operator to pass the address.
Function_name(&var_name1, &var_name2);

43
swap(&num1, &num2);
 Function definition: use of pointer notation to hold the address.
void function_name(datatype *var_name1, datatype *var_name2)
{ }
void swap(int *a, int *b)
{ }
82. What sort of variables require address operator in function call while using pass by reference?
 Address operator is required by those variables whose value needs to be changed in the called
function but its changed value is required in the calling function. For example: To find the sum and
difference of two numbers, then there are two inputs, which don’t require change, and two outputs,
which require change. So the function call would be like:
calc(num1, num2, &sum, &diff);
83. Explain different ways of returning multiple values from a function.
 The different ways of returning multiple values from a functions are:
 Using pass by reference: It works directly on the location of actual arguments, so change can
be seen in calling function when changes are made in called function. So, it can return
multiple values.
 Using array: Since array name, in itself, is an address of the first element. It is also a kind of
pass by reference.
 Using structure: since structure can contain multiple members, returning a single structure
results in returning multiple values
84. Define recursion. Explain how it differs from iteration
 Recursion is a process when a function calls itself repeatedly. The difference between recursion and
iteration is listed in the table below.

SN Recursion Iteration
1 It is a function that calls itself unless the base Iterative Instructions are loop based
condition is reached repetitions of a process
2 Infinite recursion occurs if the recursive An infinite loop occurs with iteration if the
solution does not reduce the problem in a loop-condition is always true
manner that converges on base condition
3 It terminates when a base case is recognized It stops when the loop-condition is false

44
4 It is usually slower than iteration due to It does not use stack so it is faster than
overhead of maintaining stack recursion
5 It uses more memory It consumes less memory
6 Infinite recursion can crash the system Infinite looping uses CPU cycles repeatedly
7 It makes program smaller It makes program longer

85. What are the requirements to solve a problem recursively?


 The requirements to solve a problem recursively are:
 Base condition: it is the known value to the programmer which is used to terminate the
recursion. For example: to calculate factorial, we know that 0! = 1 or 1! = 1, so either case
can be taken as a base condition.
 Recursive solution: It is the solution that converges towards the base condition after each
execution. For example: to calculate factorial of number n, we know that
5! = 5 x 4 x 3 x 2 x 1
5! = 5 x 4!
n! = n x (n-1)!
In programming, fact(n) = n * fact(n-1), here n*fact(n-1) is the recursive solution to calculate
the factorial of given number.
86. List the merits and demerits of using recursive function
 Advantages and disadvantages of the recursion can be listed as:
Advantages:
 Problem can be solved in easier way
 It makes program small; less coding to be done
Disadvantages:
 Difficult to find the converging solution
 It uses more memory
 It is usually a slower process; push pop operation in stack causes it to be a bit slower
87. Define storage class. Compare automatic, extern, and static variables
 Storage class in C programming represents the scope along with the life time of a variable. It also
represents the where the value is stored and what is its initial value when first declared. All variables
except register type are stored in main memory. Auto variables are equivalent to local variables; all
local variables are auto by default. Extern variables are equivalent to global variables.

45
The different storage class and their descriptions are listed in the table below.
SN Storage Class Initial Value Scope Life
1. auto Garbage value Local Within the function only
2. extern Zero Global Till the end of the program
3. static Zero Local Retains the value of the variable
between different function calls

88. Demonstrate the use of global variables and static variables.


 The following program demonstrates the use of global variables and static variables.
# include<stdio.h>
# include<conio.h>
void globalCheck();
void staticCheck();
int x = 5;
void main()
{
clrscr();
printf("\nValue of x in main function is %d",x);
globalCheck();
staticCheck();
staticCheck();
staticCheck();
getch();
}
void globalCheck()
{
printf("\n\nThe value of x in another function is %d\n",x);
}
void staticCheck()
{
static int i = 0;
i++;

46
printf("\nThe value of i is %d",i);
}
In this program, the variable x is a global which is accessed in main function as well as in
globalCheck() function. Also, the variable i is declared as static which retains its value between
different function call.
89. What do you mean by derived data type?
 Data types that are derived from fundamental data types are called derived data types. They simply
add some functionality to the basic data types. Array and pointer are the basic examples of derived
data types.
90. Define array. When and why are array required?
 An array is simply a list or collection of variables of same type which share the common name but
are accessed through different index within a square bracket. The variables are assigned a
contagious memory location.
When the problem is related to not one or two variables but the collection of numbers then arrays
are used. Use of array ensures efficient programming. For example: if we need to add 100 numbers
then declaration of 100 variables individually would be tedious and impractical, but use of array
makes it easier and more efficient by making the declaration and access of numbers short and easy.
91. Explain about array declaration and initialization for different data types.
 The array declaration and initialization for different data types are listed below:
 One dimensional Array:
 Declaration: data_type array_name[size];
 Examples: int num[5]; char list[10]; float marks[20];
 Initialization at declaration:
o int num[5]={1, 2, 3, 4, 5};
o char list[] = {‘a’, ’b’, ’c’, ’d’};
 Initialization: num[0] = 1, num[1] = 2, list[0] = ‘a’, list[1] = ‘b’;
 Two dimensional Array:
 Declaration: data_type array_name[row_size][col_size];
 Examples: int num[5][5]; char list[10][10];
 Initialization at declaration:
o int num[2][2] = {{1, 2},{3, 4}};
o char list[][]={{‘a’, ’b’}, {‘c’, ’d’}};

47
 Initialization: num[0][0] = 1, list[1][1] = ‘c’;
92. What does the name of an array represent? Explain with example how to access elements of an
array
 The name of an array holds the address of first element of an array. So, it represents the base
address of that array.
For one dimensional array, the elements are accessed by using array name followed by an index
within a square bracket. For example: if an array is declared as: int num[5]; then num[0], num[1] are
used to access first and second element respectively.
For two dimensional array, the elements are accessed using array name followed by two square
bracket within which row index and column index should be given. For example: if an array is
declared as: int list[3][3]; then to access the value we use list[0][1] to access the value of first row
and second column.
93. Demonstrate the difference that can be seen in the function declaration, function call and
function definition, when a single array element is passed and when complete array is passed.
 Let us consider a simple example to demonstrate the difference.
Assuming, Array declaration and initialization: int num[5] = {1 , 2, 3, 4, 5}; And a function check() to
do some operation.
SN Section Passing Single Element Passing Complete Array
1. Function declaration void check(int); void check(int[]);
2. Function call check(num[1]); check(num);
3. Function definition void check(int x) { } void check(int x[]) { }

Here, we can see that, in function declaration and definition the square brackets are not required
but square brackets with index are required in function call when single element is passed. On the
other hand, there is a presence of square bracket without index in function declaration and
definition while passing complete array. And in function call, only the name of an array is passed
without pair of square brackets. Since name of an array represents the address of first element, it
exhibits pass by reference whereas passing single element represent pass by value.
94. “Passing single element of an array indicates passing by value whereas passing complete array
(array name) represents pass by reference”, explain the statement with example.
 When we pass a single element, we use array name with index. For instance, let num be an array
defined as: int num[10]; then num[2] represents the third element of an array. Since it stores value

48
only, passing in such way symbolizes passing by value. But when array name is passed, it passes the
starting address of an array, as we know that name of an array represents the address of first
element. For example, passing array name num to the function represents passing of the address of
num[0]; as num = &num[0]. Using that base address, all other elements can be accessed. Hence
passing array name or complete array represents pass by reference.
95. Define string and null character. Explain, with example, about string constants and string
variables.
 A string is an array of characters terminated with a null character. The null character represents the
end of a string. The null character is written as ‘\0’ in C programming.
Let us take an example to demonstrate string constants and variable.
char name[20] = “Johnson”;
Here, the variable name is declared as array of characters, which can be used as a string variable.
But to use it as a string variable, it must be assigned a string constant or a set of characters with a
null character at the end. The set of characters defined within double quotation marks is a string
constant. There will be a default null character in a string constant. While string formed from set of
characters must be terminated with null character manually.
96. How are string declared? Demonstrate the different ways of initializing strings.
 Strings are declared using an array, with char as data type.
char str[10]; here, str is a string variable.
Stings are initialized as
 char str[] = “Johnson”;
 char str[] = {‘N’,’E’,’P’,’A’,’L’,’\0’};
Size of an array is optional, when strings are initialized in the declaration. The size of the string will
be equal to the number of elements. If size needs to be declared then it must be equal or greater
than the number of characters initialized.
97. What is the drawback of using %s in scanf to read a string? Illustrate different ways of reading a
string.
 When %s is used as format specifier in scanf then it does read a string with a space. All characters
before the space character will be read but others characters will be ignored.
Different ways of reading a string are as follows.
 Using unformatted input function: gets(string_variable);
 Using formatted input function: scanf(“%s”, string_variable);

49
 Character search sets can be used
scanf(“%[^\n]”, string_variable); reads characters unless new line is detected.
 Reading character wise
i = 0;
while(string_variable[i]!=’\n’)
{
string_variable[i] = getchar();
i++;
}
string_variable[i] = ‘\0’;
98. Explain why address operator (ampersand) is not used while reading a string?
 String is the name of an array of character. Since name of an array represents the address of the first
elements, string also symbolizes the address of first character. Hence address operator is not used
while reading a string using scanf().
99. Describe the general form, purpose, and return value (if any) of the following string functions:
strlen(), strcat(), strcpy(), strcmp()
 The description of different string functions are listed in the table below:
SN Functions General Form Purpose Returning value
1. strlen() len = strlen(str1); Givens the length of a string Length as integer
(str1)
2. strcpy() strcpy(str1, str2); Copy value of one string None
(str2) to another string (str1)
3. strcat() strcat(str1, str2); Combines two string(str1 and None
str2) into one (str1)
4. strcmp(); c = strcmp(str1, str2); Compares two strings (str1, Difference of ASCII
str2) value of character

100. Explain briefly about array of strings.


 As one dimensional array of characters represent a string, two dimensional arrays of characters
represent an array of strings.
 General Form:
char string_name[number_of_strings][Number of characters in each string];

50
char namelist[10][20]; it represents an array of strings with total 10 strings with each 20
characters long.
 Initialization:
char namelist[10][10] = {“Johnson”,
“Sarah”,
“Holmes”
};

In two dimensional declarations of arrays of characters, if the variable is followed with two pair
of square brackets then it represents a single character. For instance, namelist[1][1] represents
the character ‘a’. In simple, it selects the second row and then second column, pointing to
character ‘a’. But if the variable is followed with single pair of square brackets then it represents
a string. For example, namelist[2] symbolizes a string “Holmes”.
101. What is a pointer? Differentiate pointer with an array.
 A pointer is a variable which holds the address of another variable. Like other variable, it must
be declared before using it. Its general form is:
data_type *var_name;
int *p; it represents a pointer declaration with variable name p and integer as its type.
The differences between pointer and array are as follows:
SN Array Pointer
1. Collection of similar types of variables A variable which hold the address of another
which hold certain value variable
2. It is static in nature; size is fixed at It is dynamic in nature, size can be allocated
declaration which cannot be modified based on requirement
3. Size is defined simply using an integer Size is define using library functions; such as
within square bracket in declaration malloc(), calloc()
4. It can be initialized as It can be initialized as
int num[] ={1, 3, 5}; int num;
int *p = &num;
5. Total space in memory depends on its Total space required by pointer is always
declaration size fixed

51
102. List the advantages of using pointer.
 The various advantages of pointer are:
 It provides direct access to memory
 It provides a way to return more than one value to a function
 It reduces storage space and complexity of the program
 It reduces the execution time of the program
 It provides an alternate way to access array elements
 It helps to build complex data structures like linked list, stack, queues, trees etc.
103. Explain the role of ‘*’ and ‘&’ operator in C programming.
 The reference operator (&) is used to provide the address of variable, whereas the dereference
operator (*), when used with a variable, provides the value stored in the corresponding address.
For example: Let us consider
a 4 1000
int *p;
1002
int a = 4; 1004
p = &a; p 1000 1006

Here, &p gives the address of pointer variable p, &a gives the address of variable. But *p gives
the value 4, since p gives the address of a.
104. Compare array and pointer. Describe how array and pointer can be used interchangeably.
 Array and pointer is not the same thing, but their notations can be used interchangeably. And
the name of an array represents the address of first element, so it can be taken as a pointer.
int num[5]; here num = &num[0], so num is a pointer.
The following table shows the details about how array and pointer can be used interchangeably.
SN Access Array Notation Pointer Notation
1. Address of ith element &num[i] (num+i)
2. Value of ith element num[i] *(num+i)
3. Address of element at ith row and jth column &num[i][j] (*(num+i)+j)
4. Value of element at ith row and jth column num[i][j] *(*(num+i)+j)

105. Explain about null pointer and void pointer.


 A null pointer is one which is not pointing to anything. Whereas the void pointer is one which
does not have any data type associated with it but can be assigned an address of any type. Null
pointer cannot be dereferenced, while to dereference void pointer, it needs type casting.

52
Null Pointer is declared as:
int *p = NULL;
Void Pointer is declared as:
void *p;
A null pointer is a value that any type of pointer may take to indicate that it is pointing nowhere,
while a void pointer is a special type of pointer that can point to somewhere without a specific
type.
106. What is user defined data type?
 User defined data type is a kind of data type which uses the built-in data types and other user-
defined data types that model the structure and behavior of data in applications.
107. Define structure and explain briefly why it is required.
 Structure is a heterogeneous user defined data type which contains members of different data
types grouped under a single name. Many real time problems, such as Player’s Record, Library
management require information to be saved. The information will be of different types, and
such information can be grouped together for easier handling. Since many problems require
combining of data items of different kinds, structure are required.
108. Write the general syntax of structure. What will be the size of a structure?
 The general syntax of structure is
struct tag_name struct profile
{ {
data_type member 1; char name[30];
data_type member 2; int age;
… };
data_type member n;
};
The size of a structure will be the sum of size of all members of structure. In the above example,
the size of structure profile will be 32.
109. What is the significance of dot operator in C programming?
 Dot operator is used to access the member of a structure.

53
110. Write the difference between structure and array.
 The differences between structure and array are listed below.
SN Arrays Structures
1. It is a collection of related data It can have elements of different types.
elements of same type.
2. It is a derived data type. It is a user defined data type.
3. Name of an array represents the Name of the structure represents the user
address of the first element defined data type
4. Elements are accessed using index Elements are accessed using a dot operator
within the square bracket

111. When are array of structure used? Illustrate the difference in passing a single structure and
array of structure to a function with example.
 When it is required to work with list of records containing various information, array of
structure are used. The following table shows the difference that can be seen while passing a
single structure and passing array of structure. Let us consider a function name record() and a
structure named profile, then
SN Section Passing single structure Passing array of structure
1. Variable declaration struct profile p; struct profile p[20];
2. Function Declaration void record(struct profile); void record(struct profile[]);
3. Function call record(p); record(p);
4. Function definition void record(struct profile x){ } void record(struct profile y[]){ }

112. What are the ways of returning an array of structure from a called function to the calling
function?
 The following methods can be used to return array of structures to the calling function.
 Pass the array of structure, which needs to be returned, as an argument in function call.
 Let us take an example, where there are 50 records of an employee and a function
should return the records whose salary is greater than 20000. Since the number of
records to be returned is not known, it is better to pass the array from the calling
function to list the required records. Also the count of records will be required
which can be returned through return statement. The different section of function
looks like:

54
o Variable declaration: struct employee e1[50], e2[50];
o Function declaration: int salary(struct employee[], struct employee[]);
o Function Call: count = salary(e1, e2);
o Function Definition: int salary(struct employee x[], struct employee y[]){ }
 Return the reference of the arrays of structure from the called function to the calling
function through return statement.
113. Explain briefly about the nested structure along with its syntax.
 Whenever there is a presence of structure as a member of another structure then it forms a
nested structure. Also when one structure is declared inside of another structure then a nested
structure is formed. The following example illustrates the concept of nested structure.
Nested Structure 1 Nested Structure 2
struct profile struct date
{ {
char name[20]; int mm,dd,yy;
int age; };
struct date struct profile
{ {
int mm, dd, yy; char name[20];
}dob; int age;
}; struct date dob;
};
Variable declaration: struct profile p;
Accessing members: p.age, p.dob.mm, p.dob.yy; the member of structure date should be
accessed through its own variable.
114. Illustrate the difference between structure and union.
 The differences between structure and union are:
SN Structure Union
1. Keyword struct is used Keyword union is used
2. Each member is allocated a memory Memory is allocated based on the size of the
space. The size of structure equals the highest space requirement. Its size is equal
sum of sizes of its member. to the size of largest member.
3. Each member within a structure is Memory allocated is shared by individual

55
assigned unique memory location members of union
4. Altering the value of a member will not Altering value of any of the member will
affect other members change other member values
5. Each member can be accessed at a time Only one member can be accessed at a time

115. What is a file? Why are files required?


 Sometimes information can be stored in the auxiliary memory devices, which is in the form
known as data files.
Files are required
 To store data permanently
 To access and alter the information whenever necessary
116. Explain briefly about the structure FILE and FILE pointer.
 FILE structure provides the necessary information about a FILE or stream which performs input
and output operations. File structure is defined in stdio.h header file. A pointer of type FILE is a
FILE pointer, which is used to represent the file to be worked with.
117. Describe different modes of opening a file.
 The different modes of opening a file are listed as:
SN Mode Description
1. “r” Opens a file for reading, but the file must exist.
2. “w” Creates an empty file for writing. If the file already exists, then the content will
be overwritten.
3. “a” Adds data at the end of the file. Also creates a file, if file does not exist
4. “r+” Opens a file for both reading and writing. The file must exist.
5. “w+” Creates an empty file for both reading and writing.
6. “a+” Opens a file for reading and appending.

118. Where will be the position of the FILE pointer for different file opening modes?
 The position of the FILE pointer will be at the beginning for reading and writing modes whereas
the FILE pointer will be positioned at the end of the file for append mode.
119. How can we access a file randomly? Write a one line code for the following access.
 Accessing 23rd byte from the beginning of the file
 Accessing 5th block of a file from the start of a file.

56
 The function fseek() is used to access the file randomly. It is used to position the file pointer at
the specified location as required.
To access 23rd byte from the beginning of the file: fseek(fp, 23, SEEK_SET);
To access 5th block of a file from the start of a file: fseek(fp, 5*size_of_block, SEEK_SET);
120. What is error handling? Why is it done?
 Error Handling refers to the anticipation, detection and resolution of programming errors. Error
handling is done to prevent unexpected termination of the program.
121. What are the different errors during file I/O operations? How are errors handled during
different file operations?
 Only few, out of many, errors during file I/O operations are listed below:
 No such file or directory
 Permission denied
 Bad file number
 File already exists
 Too many open files
 Path not found
 Not enough memory
Following assumptions are made during I/O operations:
 File that we are trying to work with exists.
 There is enough space on the disk.
 The file handling functions such as fseek, fread, fwrite, carry out requested task.
The following methods can be used to handle different types of error during file operations.
 Check for NULL pointer: the function fopen returns NULL pointer if it cannot open the
file. So if the file pointer contains the value NULL then there is some kind of error. It can
be done as:
fptr = fopen(“demo.txt”,”r”);
if(fptr == NULL)
{
printf(“Error Occurred”);
exit(-1);
}

57
 Using ferror() macro: it tests the given file for a read or write error. It returns a non-zero
value if an error is detected on the file. It is used by passing a file pointer as its
argument.
if(ferror(file_pointer)!=0)
{
print(“Error Detected”);
}
The type of error that has occurred can be display using following methods:
 Using global variable errno and function strerror(): whenever an error occurs in a
system call, errno is set to a value indicating the type of error. The corresponding type
of error as represented by errno can be displayed using strerror() function.
if(fp == NULL)
{
printf(“Error : %s”, stderror(errno));
exit(-1);
}
 Using perror() function: this function displays the string passed to it, followed by a
colon, a space, and then the string representing the type of error.
if(fp == NULL)
{
perror(“Error”);
exit(-1);
}

122. Explain about different types of functions that are generally used.
 The various functions along with their descriptions are listed below:
 fopen(“String1”,”String2”) :
 String1 is a name of a file which we are trying to open. If only the file name is given
then the default path will be c:\tc\bin\. The path of the file can be used as
d:\\myfolder\\demo.txt.

58
 String2 is the mode in which the file has to be opened. r for reading, w for writing, a
for appending. r+ , w+ and a+ can be used for reading and writing at the same time
when the file is opened.
 If the function fopen() finds the intended file or is able to create new file as required
then it will return the file pointer. On failure it returns the NULL value.
Eg. FILE *fp;
fp = fopen(“demo.txt”,”w”); - it will open/create demo.txt in writing mode.
 fclose(file_pointer): After all the processing is done on the file, it must be closed using a
function fclose(). Eg : fclose(fp);
 putc(arg1,arg2): arg1 can be either character constant or character variable, arg2 is the file
pointer which points to the file where the character is to be written.
Eg: putc(c, fp) – writes the content of variable c on file pointed by fp.
 getc(arg1) : arg1 is the file pointer, this function returns a character from a file pointed by
the file pointer. Hence the function is generally assigned to a character variable. Eg:
c=getc(fp); - here c is a character variable and it stores the value returned by the function
getc() which is the character stored in file pointed by fp.
 fprintf(file_pointer,”control string”,arg1,arg2,…argn) : This function is similar to that of
printf but file pointer must be added as an argument which points to the file in which the
data are to be written. It is used to write data on to the file.
Eg : fprintf(fp," %s %d”,name,age); - it will write the content of variable name and
age on the file pointed by fp.
 fscanf(file_pointer,”control string”,arg1,arg2,arg3…argn) : This function reads the data
from a file. The file pointer must be used as an argument which points to the file from
where data is to be read.
Eg: fscanf(fp,”%s %d”, name, &age); - it will read a string and a integer from the file
pointed by fp and stores the data on the variable name and age respectively.
 fwrite(address of data block, size of block, number of blocks, file pointer) : This function is
used to write the block of data on to the file. It takes four arguments the first argument is a
constant pointer which is the address of the block which is to be written on to the file,
second argument is the size of the data block to be written on the file pointed by the file
pointer. Third argument represents the number of such blocks to be written on the file, and
finally the last argument is the file pointer pointing to the file where data is to written. Eg :

59
fwrite(&s, sizeof(s), 1,fp); - Here s is the structure variable which may consist of several
members. The content of structure (s) is written on the file pointed by fp.
 fread(address of data block, size of block, number of blocks, file pointer) : It is used to read
a block of data from a file. Eg: fread(&s, sizeof(s), 1, fp); Here the function reads the block of
data from the file and stores the content on the structure variable s;
 feof(file_pointer) : This function is used to detect the end of file condition. This function
returns a non-zero value (true) if an end of file condition has been detected and a value zero
(false) if an end of file is not detected.
 rewind(file_pointer) : This function is used to move the file pointer to the starting position
of the file(buffer). It is generally used when the file is opened in writing and reading
(multiple modes) mode. Such that after writing into the file the pointer will be at the last so
we need to rewind the file pointer to the starting positions.
 fseek(FILE_pointer, offset, whence) : The function fseek() is used to access the file
randomly. This function can be used to position the file pointer as required. The second
argument is the number of bytes the pointer to be moved from a particular position
specified by the third argument. The third argument specifies from where the position of
the pointer is to be repositioned. The third argument can be:
 SEEK_END (2) – with reference to the end of file.
 SEEK_CUR (1) – with reference to the current position of the pointer on the file.
 SEEK_SET (0) – with reference to the starting position of the file.

Eg: fseek(fp, 10, SEEK_SET); It will move the file pointer by 10 bytes with respect to the
starting point. If we read a character from a file then the 11th character will be read.

Eg: fseek(fp, -20, SEEK_END): It will move the file pointer 20 bytes backwards from the end
of the file.
123. Write the difference between
 Writing mode and Appending Mode
SN Writing Mode Appending Mode
1. File Pointer points at the beginning File Pointer points at the end of the file
2. Content of file is overwritten Content is added at the end

60
 Text file and binary file

SN Text File Binary File


1. New line character is converted into The new line character does not require
carriage return and line feed combination any conversion.
before writing on the disk. And again the
combination is converted back to newline
when file is read by C program.
2. EOF (End of file) character to represent No EOF, programmer must keep track of
the terminating point of a file data being accessed.
3. Values are stored as set of characters. Same number of bytes on disks as the
Causing 35221 to occupy 5 bytes rather values occupy in memory.
than 2 bytes.

61
1. Describe briefly about FORTRAN programming language. Write its uses and application.
 FORTRAN is an acronym for FORmula TRANslation. It was designed to allow easy translation of math
formulas into code. It was the first high-level language, using the first compiler ever developed.
Some of the features of this language are as listed below:
 Simple to learn
 Machine independent
 Efficient execution
 Natural ways to express mathematical functions
FORTRAN is useful for applications that are computational-bound rather than I/O bound. Some of its
applications are:
 Used in processing mathematical equations, since its execution time is fast.
 Other applications include scientific, statistical and engineering problems.
2. Illustrate the difference between FORTRAN and C programming language.
 The differences between FORTRAN and C programming language are as listed below:
SN FORTRAN C Programming
1. Designed for numerical computation Designed for many other purposes
2. Easier to learn It is comparatively difficult to learn
3. It allows maximal speed of execution It is comparatively slower in execution than
FORTRAN
4. FORTRAN compilers emit much better Compilers are universally available but produces
diagnostic messages less better diagnostic messages
5. It is very specific in its scope. It is very broad in scope and is more powerful
due to facility of pointers and manipulation of
strings.
6. It is case insensitive. It is case sensitive.
7. It follows one statement per line One line can contain more than one statement.
principle.
8. Statements are not terminated by Statements are terminated by semicolon.
semicolon.
9. Variable declaration is optional due to Variable must be declared before it is used.
implicit declaration feature.

62
10. Implied do loop facility increases Such feature is not available.
flexibility.
11. Supports arithmetic of complex number. Arithmetic of complex number is not supported.
12. Array index ranges from 1 to N Array index ranges from 0 to N-1

3. Define FORTRAN constants, variables and data type. List the rules for naming a variable.
 FORTRAN constants, variables and data type are not much different to those of C language.
Constants are the fixed values that remain same throughout the program. Variables are simply the
name of the memory location which is used for storing data. Data types are those entities which
give the information about what type of value a variable can hold and also represents how much
memory space is required by the variable in the memory. The generally used data types in FORTRAN
are integer, real, and character.
The rules for naming a variable are:
 First character must be an alphabet.
 FORTRAN verbs should not be used as name of variables
 Special characters are not allowed.
4. List different types of constants with examples.
 The different types of constants in FORTRAN are:
 Numeric Constants: constants related to numbers are numeric constants.
 Integer constants: There are whole numbers, written without decimal point. The numbers 1,
13, 45, -35 etc are examples of integer constants.
 Real constants: These are numbers with fractional part. It can further be represented in two
forms
o Fractional form: 12.4, 44.12, -82.615
o Exponential form: it contains mantissa, which is real constant, and exponent – which
is an integer constant. It is represented as:
0.375E14: Here, 0.375 is mantissa and 14 is exponent. 0.375E14 is equivalent to
0.375 x 1014
 Character constants: can contain single character or list of characters. These constants are
enclosed by pair of singe quotation mark. For example: ‘a’, ‘1’, ‘sample’ etc.

63
5. Explain briefly about the implicit declaration of variables in FORTRAN language.
 Implicit declaration of variables is special feature of FORTRAN language. According to this feature,
when variables are not declared, then all variables starting with alphabets i, j, k, l, m, or n are, by
default, considered as integer variables while those starting with others letters are real type
variables. Also, implicit type declaration can be done using implicit verb of FORTRAN. Its general
form is:
implicit type(..), type(..)
For example, implicit integer(a) symbolizes that variables starting with a will be an integer. Similarly,
implicit real(i-k), integer(a-f, x-z): this declaration will cause all variables starting from i, j, and k to be
real while variables starting with a, b, c, d, e, f, x, y, z are taken as integer.
6. Is it necessary to declare a variable in FORTRAN? Give reasons to support your answer.
 It is not necessary to declare a variable if we follow the convention of implicit declaration. But not
following the convention can cause problem in the program. Since there can be mix of different
types inadvertently. For example, an integer variable may be assigned a real value after some data
manipulation, which causes the values to be truncated and gives undesired results. So, it is always
better to declare a variable.
7. What are FORTRAN verbs? Explain how it differs from a variable.
 FORTRAN verbs similar to keywords in C language. These are set of words having a predefined
meaning and are used for specific purpose. Some examples of verbs include integer, read, write, if,
else, then, continue, stop.
Variables and verbs are completely distinct elements of FORTRAN language. Variables represent the
storage space while verbs are simply words with predefined meaning. Verbs cannot be used to
name a variable.
8. Explain arithmetic operators with examples. How does the operator ** work in FORTRAN
language.
 The different arithmetic operators are +, -, *, /, and **. For addition of two operands, + symbol is
used, while -, * and / are used for subtraction, multiplication and division purpose respectively. For
example these operators can be used as: a + b, x – y, x*2*c, y/x etc. The ** operator is used for the
exponentiation. For example we need to determine the value of 47 then we can use ** operator as:
4**7 which represents 4 multiplied 7 times.

64
9. What are library functions? Give few examples. Explain how function max() works in FORTRAN
language.
 The predefined functions which are used for specific purpose are called library functions. These
functions can be directly used in our calculations. For example, abs(), exp(), sqrt(), max() etc are few
library functions. Function max() returns the maximum value from the list of numbers provided to it.
For example: m = max(a, b, c, d) returns the maximum of four variables and assigns to variable m.
10. Describe about the FORTRAN coding sheet. Explain what can be done for the continuation of the
statement in next line.
 The coding sheet of FORTRAN can be explained using the following diagram.
1 5 6 7 72 73 80

Line Comment
number FORTRAN codes are written in this section are written
in this
section

 Coding sheet has 80 columns.


 Columns 1 to 5 are used to write line numbers which must be a positive integer.
o Writing C or * in Column 1 indicates that line in coding section as comment.
 Column 6 is used for continuation. If a statement is long enough and cannot adjust in
columns 7 – 72 then next line can be used for continuing the statement by placing the last
character of last statement in the next line of 6th column. The symbol $ can also be used for
continuation.
 Columns 7 – 72 are used for writing codes
 Columns 73 – 80 are used for writing comments

65
11. What do you mean by format statement? Explain different types of format used in FORTRAN with
examples.
 Format statement is a non executable statement, which is used to specify the different format for
formatted input and output. There are different types of format available in FORTRAN but few
commonly used are:
 I format: It is for integer numbers. Its general form is Iw, where w is the width for the
integer data. For example: FORMAT (I5, I7) represents two integer numbers with width 5
and 7 respectively.
 F format: It is used for fractional numbers. Its general form is Fw.d, where w is the total
width for the number and d represents the number of decimal number after decimal point.
For example: FORMAT (F7.3, F6.2) represents two real numbers; one with total width of 7
and 3 numbers after decimal point, another number with total width of 6 and 2 numbers
after decimal point.
 E format: It is used for real numbers with exponential form. The general form for this format
is Ew.d, where w is the total width of the number and d represents the decimal width of the
mantissa. For example: FORMAT (E7.2) represents a real number having a total width of 7
and mantissa has two numbers after decimal point.
 A format: It is used for characters. The general form is Aw, where w is the width. For
example: FORMAT (A5) represents the only five characters to be read or displayed. But
FORMAT (A) represents the width as defined in declaration.
 X format: It is used to skip columns for displaying data on the screen. Its general form is nX,
where n is the number of columns to be skipped. For example: FORMAT (I5, 3x, I3) is used to
display two integers with width 5 and 3 respectively and three spaces in between them.
12. Write the general syntax for the following and also explain the meaning of symbols used in it.
 Format statement:
N FORMAT(f1, f2, f3… fn)
Where N is the statement number, which will be of same value to that in READ and WRITE for
corresponding format. And f1, f2, f3… fn are the format specifications which varies depending
upon the number and types of variables in READ and WRITE statement.
 Formatted input and formatted output:
READ(h, n) list of variables  READ(*, 20) a, b
WRITE(h, n) list of variables  WRITE(*, 30) ‘a = ‘, a, ‘b = ‘, b

66
Here, h represents the hardware number. We place asterisk (*) in place of hardware number (h)
to represent keyboard and screen as the default input and output devices. And n represents the
line number where format statement is written. The format statement defines the formatting of
inputs and outputs. In case formatting is not required then we can replace line number (n) with
asterisk (*).
 Unformatted input and unformatted output
READ *, list of variables  READ *, a, b, c
PRINT *, list of variables/items  PRINT *, ‘a = ’, a
In READ, generally list of variables are present but in PRINT the list may contain variables as well
as constants
 Unconditional GOTO
GOTO n
Where n is any line number, if the line number is below the GOTO n statement then it skips the
statements but if the line number is above the GOTO n then it creates a loop.

Skipping Statements Creating a Loop


…… 10 ……….
GOTO 10 ……….
….. ……….
….. GOTO 10
10 ….. ……….

 Computed GOTO
GOTO(K1, K2, K3…Kn), Expression
If value of expression is 1, then the control goes to line number K1. Similarly, the value of
expression 2, 3 … n will cause the control to go to line number K2, K3 … Kn respectively. If
expression is less than one and greater than n then control goes to next line.
For example:
GOTO(10, 20, 30), I
If value of I is 1 then the control goes to line number 10. For I = 2, control will be at line 20 and
for I = 3, control moves to 30. If value of I is other than 1, 2, or 3 then the control goes to next
line.

67
 Arithmetic IF, Logical IF, IF THEN ELSE, ELSE IF THEN
 ARITHMETIC IF
IF(arithmetic Expression) K1, K2, K3
Here K1, K2, K3 represents line number. If the expression gives negative value then, the
statements at line number K1 will execute. Similarly, statements at line number K2 and K3
will execute for zero and positive value of expression respectively. Its example is shown as:

IF(a-b*c) 10, 20, 30 Unconditional GOTO comes in


10 Statement for negative conjunction with ARITHMETIC IF,
since part of the code must be
GOTO 40
skipped. When statement for
20 statements for zero negative expression is executed,
GOTO 40 then other statements for zero and
positive cases must be skipped.
30 statements for positive
40 STOP
END

 LOGICAL IF
IF(Logical Expression) Statements for true
Statements for false
When logical expression is true, then its corresponding statement for true condition will
execute but skips the next statement which is for false condition. But if the condition is false
then the statements for false condition will be executed ignoring the statements for true
conditions.
For example:
IF(MOD(n,2).eq.0) WRITE(*,*) n, ‘ is even’
WRITE(*,*) n, ‘ is odd’
 IF THEN ELSE
IF(condition)THEN
Statements_T ! These statements will execute if the condition is true
ELSE
Statements_F ! This section will execute if the condition is false
END IF

68
In IF THEN ELSE structure, IF is always followed by condition and THEN. END IF should not be
missed from the structure. The ELSE part, however, can be omitted from the structure. The
structure without ELSE would be like:
IF(condition)THEN
Statements ! These statements will execute if the condition is true
END IF
These forms are similar to that of simple if and if else in C programming language. The
statements within the IF and ELSE block can contain IF THEN ELSE statement making a
nested IF THEN ELSE.
 ELSE IF THEN
IF(condition 1) THEN
Statement 1
ELSE IF(condition 2) THEN
Statement 2
ELSE IF(condition n) THEN
Statement n
ELSE
Default Statement
END IF
This structure is similar to that of else if ladder in C programming. First, condition 1 is
checked, if it is true then statement 1 is executed. If condition 1 is false then condition 2 is
checked. Statement 2 will execute if condition 2 is true. But statement n will execute if
condition n is true. If none of the conditions is true then Default statement will execute. The
statements may contain IF ELSE THEN making the structure NESTED IF.
 DO LOOP
Syntax:
DO N I = start, stop, update
…….
…….
N CONTINUE
Here, N represents the valid statement number representing the last statement of the loop.
Integer variable (I), as running variable, is used to control the loop. Start represents the starting

69
point of the loop, while stop indicates the terminating point of the loop. The update is a value
which represents increment or decrement from start point to end point. If update is not given
then its default value will be taken as one.
13. Write the difference between
 Formatted and unformatted input/output statements
SN Formatted input/output statements Unformatted input/output statements
1. The width and precision can be defined Here, width and precision cannot be
for inputs and outputs defined for inputs and outputs
2. Format statement is used in Format statement is not required
conjunction
3. Its general form is: Its general form is:
Read(h, N) list of variables Read *, list of variables
Write(h, N) list of variables Print *, list of variables
Here, N represents the line number Here, line number is not specified. So,
where format statement is written. The formatting is not possible in this case.
format statement defines the
formatting of inputs and outputs.
The symbol asterisk(*) is used in place
of N if formatting is not required.

 Unconditional GOTO and Computed GOTO


SN Unconditional GOTO Computer GOTO
1. Changes control of statement without Changes control of statement based on
any condition value of an integer expression
2. It is used to skip certain portion of code It is used to executed particular set of
and can be used to create a loop in statements from list of instructions based
conjunction with IF statement. on the result of an integer expression
3. Its general form is: Its general form is
GOTO n GOTO(K1, K2, K3…Kn), Expression
Where n is any line number, if the line If value of expression is 1, then the control
number is below the GOTO n goes to line number K1. Similarly, the
statement then it skips the statements value of expression 2,3 … n will cause the

70
but if the line number is above the control to go to line number K2, K3 … Kn
GOTO n then it creates a loop. respectively. If expression is less than one
and greater than n then control goes to
next line.

 Logical IF and Arithmetic IF


SN Logical IF Arithmetic IF
1. It uses relation and logical expression It uses arithmetic expression
2. Expression generates true or false Expression generates positive, negative or
based on operator and operands used zero value based on operation
3. Its general form is: Its general form is:
IF(condition) True statement IF(expression) K1, K2, K3
False statement Here K1, K2, K3 represents line number. If
If condition is true the true statement the expression gives negative value then,
will execute, otherwise the false the statements at line number K1 will
statement will execute execute. Similarly, statements at line
number K2 and K3 will execute for zero
and positive value of expression
respectively

 Do Loops and Implied do loops


SN Do loops Implied do loops
1. It is used to repeat a block of code that It is used to repeat only read and write
can be any statements statement in arrays
2. Verbs DO and CONTINUE are used Verbs DO and CONTINUE are not used
3. Using do loop to read and write Using implied do loop to read and write
elements of arrays makes program elements of arrays makes program
longer comparatively shorter

 Stop and End Statement


SN STOP Statement END Statement
1. Used to stop program execution Indicates the end of the program
2. Can be placed anywhere within the program It is placed at the end of the program

71
3. There can be more than one stop There will always be one end
statements in a program statement in the program

14. How iteration are done without using do loops. Explain briefly about CONTINUE statement.
 Iterations can be done using LOGICAL IF and unconditional GOTO. Its general forms are:
10 IF(logical condition) GOTO 20 10 STATEMENTS
STATEMENTS …..
…. OR ….
GOTO 10 IF(logical condition) GOTO 10
20
In first looping structure, if the logical condition is true, then the loop exits. But in second
looping structure, true in logical condition will cause the loop to continue. This type of loop
structure can be used to solve the problem which requires while loop in C programming. Let us
take an example: to find the sum of all digits of a given number. Only loop structure is shown.
In C language In FORTRAN language

while(n!=0) 10 IF(n.eq.0) GOTO 20


{ r = MOD(n,10) 10 r = MOD(n,10)
r = n%10;
s=s+r s=s+r
s = s + r;
n = n/10 n = n/10
n = n/10;
GOTO 10 IF(n.ne.0) GOTO 10
}
20
CONTINUE statement is used in conjunction with DO loops. It represents end of do loop structure.
15. What are arrays? How is it declared in FORTRAN?
 Arrays are list of variables occupying consecutive memory location. It shares the same name among
all the variables but the variables are differentiated with the help of index. In FORTRAN the indexing
of array starts from 1. The declaration of array can be done as:
dimension array_name(size)
dimension array_name(row size, column size)
Use of dimension follows the implicit declaration of FORTRAN. Instead of dimension, other data type
such as integer, real, character etc can also be used.
For example: dimension a(5) represents an array declaration of real type. It can hold maximum of
five values as its declaration creates five variables a(1), a(2), a(3), a(4), and a(5).

72

You might also like