C-Programming Theory Notes

Following PDF Contents Solution of Theory Based on IOE:

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.

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.


 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

c0mputers 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.

 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.

 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.

 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.

 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:



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.



13. Write the difference between compiler and interpreter.

 The difference between compiler and interpreter are:



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.

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 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.

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 -2

n-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:



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 = -2

n-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 = -2

15

= -32768 Upper Limit = 215


- 1 = 32767

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.

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

(/) 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)

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:


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.)
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
Relational greater than/greater than or equal to

Left-to-Right
== != 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
Addition/subtraction assignment
Multiplication/division assignment
Modulus/bitwise AND assignment
Bitwise exclusive/inclusive OR assignment
Bitwise shift left/right assignment

Right-to-Left

, Comma(separate expressions) Left-to-Right

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 typecasting 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:
33. Explain the structure of C program.
 The general structure of C program is given as:
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);

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.

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.

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

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
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.
 
* 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().

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 

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

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.

else if ladder

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

Nested if ladder

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.

False

True False

True

False True

Next Statements
Condition1

Statement 2

Condition3

Statement 1 Statement 3

Condition2

26

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.

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)
{

28

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.

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
 While loop
 Do while loop

 The various types of loop are explained below:
a. For loop:
Syntax:
for(initialization;condition;update)
{
statements; //Body of loop;
}

Working flow with example:

b. while loop:

initialization;
while(condition)
{
Statements;
Update;
}

Working flow with example


c. do while loop:

Syntax:

Initialization;
do
{
Statements;
Update;
}while(condition);

Working flow with example: 

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

do
{

} while ( );
printf(“%d”, x);

x < = 10
x = 1;

x + +; T

F
True

Figure 3: Flowchart of do while loop
False

Initialization

condn
Condition Statements

Update

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


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.



The following diagram demonstrates the use of break statement.

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.

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

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.

True

False
Statements

condn
Back to Loop Condition

Statements

Out of Loop

Statements

condn
Back to Loop Condition

Statements

Back to loop
True

False

 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.

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
1 2 3 4 5

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.

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


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:

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.


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


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

 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.


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:

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);

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.

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.

The different storage class and their descriptions are listed in the table below.


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++;

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’}};


 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.

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

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);

 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:

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];


51


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:

Post a Comment

0 Comments