Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
34 views

Introduction To Programming Notes

Uploaded by

aditya4u9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Introduction To Programming Notes

Uploaded by

aditya4u9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

1

UNIT 1

INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING

Q 1. Definition of Computer?

• Computer is a programmable machine.

• Computer is a machine that manipulates data according to a list of instructions.

• Computer is any device which aids humans in performing various kinds of computations or Calculations

Q 2. Explain Characteristic of Computer?


Three principles characteristic of computer:

• It responds to a specific set of instructions in a well-defined manner.

• It can execute a pre-recorded list of instructions.

• It can quickly store and retrieve large amounts of data.

Q 3. Describe brief history of Computers?

Earliest Computer

• Originally calculations were computed by humans, whose job title was computers.

• These human computers were typically engaged in the calculation of a mathematical expression.

• The calculations of this period were specialized and expensive, requiring years of training in mathematics.

• The first use of the word "computer" was recorded in 1613, referring to a person who carried out calculations, or
computations, and the word continued to be used in that sense until the middle of the 20th century.

Tally Sticks A tally stick was an ancient memory aid device to record and document numbers, quantities, or
even messages.

Abacus

• An abacus is a mechanical device used to aid an individual in performing mathematical calculations.

• The abacus was invented in Babylonia in 2400 B.C.

• The abacus in the form we are most familiar with was first used in China in around 500 B.C.

• It used to perform basic arithmetic operations.

Napier’s Bones

• Invented by John Napier in 1614.

• Allowed the operator to multiply, divide and calculate square and cube roots by moving the rods around
and placing them in specially constructed boards.

Slide Rule

• Invented by William Oughtred in 1622.


2

• Is based on Napier's ideas about logarithms.

• Used primarily for

– multiplication
– division
– roots
– logarithms
– Trigonometry
• Not normally used for addition or subtraction.

Pascaline

• Invented by Blaise Pascal in 1642.

• It was its limitation to addition and subtraction.

• It is too expensive.

Arithmometer

• A mechanical calculator invented by Thomas de Colmar in 1820,

• The first reliable, useful and commercially successful calculating machine.

• The machine could perform the four basic mathematic functions.

• The first mass-produced calculating machine.

Difference Engine and Analytical Engine

• It an automatic, mechanical calculator designed to tabulate polynomial functions.

• Invented by Charles Babbage in 1822 and 1834

• It is the first mechanical computer.

First Computer Programmer

• In 1840, Augusta Ada Byron suggests to Babbage that he use the binary system.

• She writes programs for the Analytical Engine.

ENIAC

• ENIAC stands for Electronic Numerical Integrator and Computer.

• It was the first electronic general-purpose computer.

• Completed in 1946.

• Developed by John Presper Eckert and John W. Mauchl.

UNIVAC 1

• The UNIVAC I (UNIVersal Automatic Computer 1) was the first commercial computer.
3

• Designed by J. Presper Eckert and John Mauchly.

EDVAC

• EDVAC stands for Electronic Discrete Variable Automatic Computer

• The First Stored Program Computer

• Designed by Von Neumann in 1952.

• It has a memory to hold both a stored program as well as data.

The First Portable Computer

• Osborne 1 – the first portable computer.

• Released in 1981 by the Osborne Computer Corporation.

Q 4. Explain Generations of Computer in detail ?

There are five generations of computer:

• First generation – 1946 - 1958

• Second generation – 1959 - 1964

• Third generation – 1965 - 1970

• Fourth generation – 1971 - today

• Fifth generation – Today to future

The First Generation

• The first computers used vacuum tubes for circuitry and magnetic drums for memory, and were often enormous,
taking up entire rooms.

• They were very expensive to operate and in addition to using a great deal of electricity, generated a lot of heat,
which was often the cause of malfunctions.

• First generation computers relied on machine language, the lowest-level programming language understood by
computers, to perform operations, and they could only solve one problem at a time.

• Input was based on punched cards and paper tape, and output was displayed on printouts.

The Second Generation

• Transistors replaced vacuum tubes and ushered in the second generation of computers.

• One transistor replaced the equivalent of 40 vacuum tubes.

• Allowing computers to become smaller, faster, cheaper, more energy-efficient and more reliable.
4

• Still generated a great deal of heat that can damage the computer.

• Second-generation computers moved from cryptic binary machine language to symbolic, or assembly, languages,
which allowed programmers to specify instructions in words.

• Second-generation computers still relied on punched cards for input and printouts for output.

• These were also the first computers that stored their instructions in their memory, which moved from a magnetic
drum to magnetic core technology.

The Third Generation

• The development of the integrated circuit was the hallmark of the third generation of computers.

• Transistors were miniaturized and placed on silicon chips, called semiconductors, which drastically increased the
speed and efficiency of computers.

• Much smaller and cheaper compare to the second generation computers.

• It could carry out instructions in billionths of a second.

• Users interacted with third generation computers through keyboards and monitors and interfaced with an
operating system, which allowed the device to run many different applications at one time with a central program
that monitored the memory.

• Computers for the first time became accessible to a mass audience because they were smaller and cheaper than
their predecessors.

The Fourth Generation

• The microprocessor brought the fourth generation of computers, as thousands of integrated circuits

were built onto a single silicon chip.

• As these small computers became more powerful, they could be linked together to form networks, which

eventually led to the development of the Internet.

• Fourth generation computers also saw the development of GUIs, the mouse and handheld devices.
5

Q 5. What is a Computer? Explain Different types of Computers?

A computer can be defined as a fast electronic calculating machine that accepts the (data) digitized input information
process it as per the list of internally stored instructions and produces the resulting information.

List of instructions are called programs & internal storage is called computer memory.

The different types of computers are

1. Personal computers: - This is the most common type found in homes, schools, Business offices etc., It is
the most common type of desk top computers with processing and storage units along with various input and
output devices.

2. Note book computers: - These are compact and portable versions of PC

3. Work stations: - These have high resolution input/output (I/O) graphics capability, but with same
dimensions as that of desktop computer. These are used in engineering applications of interactive design
work.

4. Enterprise systems: - These are used for business data processing in medium to large corporations that
require much more computing power and storage capacity than work stations. Internet associated with
servers have become a dominant worldwide source of all types of information.

5. Super computers: - These are used for large scale numerical calculations required in the applications like
weather forecasting etc.,

Q 6. Explain Basic Organization of Computer? Describe briefly about Functional units?

A computer consists of five functionally independent main parts input, memory, arithmetic logic unit (ALU), output
and control unit.

ALU stands for arithmetic logic unit. It is responsible for performing all arithmetic and logical operations, such as
addition, subtraction, multiplication, division, AND, OR, and NOT.
Input-output units allow the computer to communicate with the outside world. They include devices such as the
keyboard, mouse, monitor, printer, and speakers.
Memory is where the computer stores data and instructions.
It is divided into two main types:
1. Random Access Memory (RAM) And
2. Read-Only Memory (ROM).
➢ RAM is used to store data and instructions that are currently being used by the CPU.
➢ ROM is used to store permanent data, such as the computer's startup instructions.
Program counter is a register that keeps track of the address of the next instruction to be executed by the CPU.
These four components work together to execute computer programs. The CPU first fetches the next instruction from
memory using the program counter. It then decodes the instruction and determines what operation needs to be
6

performed. The ALU then performs the operation and stores the result in memory. Finally, the program counter is
incremented to point to the next instruction.
Here is a simplified example of how the ALU, input-output units, memory, and program counter work together to
execute a simple program:
Program:
1. ADD 1 to A
2. PRINT A
Execution:
1. The CPU fetches the first instruction from memory (ADD 1 to A).
2. The CPU decodes the instruction and determines that it needs to perform an addition operation.
3. The CPU loads the operand A from memory.
4. The ALU adds 1 to A and stores the result back in memory.
5. The program counter is incremented to point to the next instruction.
6. The CPU fetches the next instruction from memory (PRINT A).
7. The CPU decodes the instruction and determines that it needs to print the value of A to the console.
8. The CPU loads the value of A from memory.
9. The CPU writes the value of A to the console.
10. The program counter is incremented to point to the next instruction, which is the end of the program.

Q 7. Define Programming Language? Summarize the classification of Programming languages?

➢ A programming language is a set of symbols, grammars and rules with the help of which one is able to translate
algorithms to programs that will be executed by the computer.
➢ The programmer communicates with a machine using programming languages.
➢ Most of the programs have a highly structured set of rules.

The primary classifications of programming languages are:

1. Machine Languages
2. Assembly Languages
3. High level Languages.

Machine Language

➔ Machine language is a collection of binary digits or bits that the computer reads and interprets.
➔ Machine language is the only language a computer is capable of understanding.
➔ Machine level language is a language that supports the machine side of the programming or does not provide
human side of the programming.
➔ It consists of (binary) zeros and ones.
➔ Each instruction in a program is represented by a numeric code, and numerical addresses are used
throughout the program to refer to memory locations in the computer’s memory.
➔ Microcode allows for the expression of some of the more powerful machine level instructions in terms of a
set of basic machine instructions.

Assembly language

➔ Assembly language is easier to use than machine language.


7

➔ An assembler is useful for detecting programming errors.


➔ Programmers do not have the absolute address of data items.
➔ Assembly language encourage modular programming

High level language

➔ High level language is a language that supports the human and the application sides of the programming.
➔ A language is a machine independent way to specify the sequence of operations necessary to accomplish a
task.
➔ A line in a high level language can execute powerful operations, and correspond to tens, or hundreds, of
instructions at the machine level.
➔ Consequently, more programming is now done in high level languages.
➔ Examples of high level languages are BASIC, FORTRAN etc

Q 8. Define algorithm. List out its properties.

Algorithm:

Algorithm is a step by step process to solve a problem.

OR

A procedure for solving a mathematical problem in a finite number of steps that frequently involves recursive
operations

Properties of Algorithm:

1. Input: An algorithm must accept zero or more input.

2. Output: An algorithm must produce at least one output.

3. Finiteness: An algorithm must be terminated at finite number of steps.

4. Definiteness: Every step of algorithm must be clear and unambiguous.

5. Effectiveness: Every step must be basic and easy to convert into program.

Example:

Write an algorithm to perform addition of two numbers

Algorithm:

Step-1: Start

Step-2: Read a number into A

Step-3: Read another number into B

Step-4: Perform addition and store result in total


8

Step-5: Display total value

Step-6: Stop

Q 9. What is FlowChart?

➔ A flowchart is a type of diagram that represents a workflow or process.


➔ A flowchart can also be defined as a diagrammatic representation of an algorithm,
➔ A step-by-step approach to solving a task.

Q 10. Define flowchart. List the different symbols used to draw a flowchart ?

Pictorial representation of algorithm is known as flowchart.

Symbols used in flowchart:

Q 11. What Is Pseudo-Code in C?

Programming language description of algorithm is called as pseudocode

OR
9

➔ The pseudocode in C is an informal way of writing a program for better human understanding.
➔ It is written in simple English, making the complex program easier to understand.
➔ Pseudocode cannot be compiled or interpreted.
➔ It doesn't follow the programming language's syntax;
➔ It is thus written in pseudocode so that any programmers or non-programmers can easily understand it.

Example Pseudo code:

1. Start
2. Input two numbers
3. Calculate the sum of the two numbers
4. Divide the sum by 2 to get the average
5. Display the average
6. End

Q 12. What is a Complier ? Explain about Compilation process?

➔ The compiler program translates the instructions of a high level language to a machine level language.
➔ A separate compiler is required for every high level language.
➔ High level language is simply a programmer’s convenience and cannot be executed in their source.
➔ The actual high - level program is called a source program.
➔ It is compiled (translated) to machine level language program called object program for that machine by the
compiler.
➔ Such compilers are called self-resident compilers.
➔ Compiler compiles the full program and reports the errors at the end

Compilation Process

The compilation and execution process of C can be divided in to multiple steps:


10

Preprocessing Using a Preprocessor program to convert C source code in expanded source code. "#include"
and "#define" statements will be processed and replaced actually source codes in this step.

Compilation Using a Compiler program to convert C expanded source to assembly source code.

Assembly Using a Assembler program to convert assembly source code to object code.

Linking Using a Linker program to convert object code to executable code. Multiple units of object codes are
linked to together in this step.

Loading Using a Loader program to load the executable code into CPU for execution. Compilation

LINKING

➔ After all of the files are compiled, they must be "merged together" to produce a single executable file that the
user use to run the program.
➔ In C, most compiled programs produce results only with the help of some standard programs, known as library
files that reside in the computer.
➔ This process is called linking. The result obtained after linking is called the executable file.
➔ The linker′s primary function is to bind symbolic names to memory addresses.
➔ To do this, it first scans the files and concatenates the related file sections to form one large file.
➔ Then, it makes a second pass on the resulting file to bind symbol names to real memory addresses.
➔ Loading is loading the executable into memory prior to execution.
➔ There are two types of linking: Static linking. Dynamic linking.
o Static linking occurs at compilation time; hence it occurs prior to loading a program.
o With static linking the external symbols that are used by the program (e.g. function names) are resolved
at compile time.
o Dynamic linking occurs at run time, so it occurs after or at the time of the loading of a program.
o With dynamic linking the symbols are resolved either at loading time, or at run time when the symbol
is accessed (lazy binding).

LOADING

➔ After the files are compiled and linked the executable file is loaded in the computer′s memory for executing by
the loader. This process is called Loading.
➔ Program loading is basically copying a program from secondary storage into main memory so it ′s ready to run.
➔ In some cases, loading us just not copying the data from disk to memory, but also setting protection bits, or
arranging for virtual memory map virtual addresses to disk pages.
11

Q13. Explain execution process of a c program.

➔ The file which contains c program instructions in a high-level language is said to be source code.
➔ Every c program source file is saved with .c extension, for example, Sample.c.
➔ Whenever we press compilation button the source file is submitted to the compiler.
➔ Compiler checks for the errors, if there are any errors, it returns a list of errors, otherwise generates object
code in a file with name Sample.obj and submit it to the linker.
➔ The linker combines the code from specified header file into an object file and generates executable file as
Sample.exe.
➔ With this compilation process completes. Now, we need to run the executable file (Sample.exe).
➔ To run a program, we press run button.
➔ When we press run button the executable file is submitted to the CPU.
➔ Then CPU performs the task according to the instructions written in that program and place the result into
User Screen.

Q 14. Explain in detail about structure of C Program.

➢ C is a structured programming language. Every C program and its statements must be in a particular structure.
➢ Every C program has the following general structure.
12

1. Documentation Section:
➢ This section is used to provide a small description of the program.
➢ The comment lines are simply ignored by the compiler, that means they are not executed.
➢ In C, there are two types of comments.
1. Single Line Comments: Single line comment begins with // symbol. We can write any number of single line
comments.
2. Multiple Lines Comments: Multiple lines comment begins with /* symbol and ends with */. We can write
any number of multiple lines comments in a program.
All the comment lines in a C program just provide the guidelines to understand the program and its code.
2. Pre-processing Commands:
➢ Pre-processing commands are used to include header files and to define constants.
➢ Pre-processing commands are beginning with # symbol.
➢ C Pre-processing commands are: #include, #define, #if, #else etc…,
3. Global Declarations:
➢ The global declaration is used to define the global variables, which are common for all the functions after
its declaration.
➢ We also use the global declaration to declare functions.
4. Main Function:
➢ Every C program must contain this main function.
➢ Here, main ( ) is a user-defined function which tells the compiler that this is the starting point of the
program execution.
➢ The open brace ( { ) indicates the beginning of the main function.
➢ Local declaration contains local variables which are used with in main ( ) function.
➢ Executable statements perform tasks like reading data, displaying the result, calculations, etc.,
➢ Closing Brace ( } )indicates the end of the main ( ) function.
➢ The statement return 0 returns a value zero to the Operating System after completing the main ( )
execution.
➢ If we don't want to return any value, we can use it as void.

5. User Defined Functions:

➢ This is the place where we implement the user-defined functions.

Q 15. Define Data Type. List out different Data Types in C.

➢ A data type specifies the type of data that a variable can store such as integer, floating, character, etc.
➢ There are the following data types in C language.
13

Q 16. Give brief discussion on primitive data types.


➢ The primary data types in the C programming language are the basic data types.
➢ Primary data types are also called as Built-In data types.
➢ The following are the primary data types in c programming language.

1. Integer:

➢ The integer data type is a set of whole numbers.


➢ Every integer value does not have the decimal value.
➢ We use the keyword "int" to represent integer data type in C.
➢ The following table provides complete details about the integer data type according to the 32-bit
architecture.
14

2. Floating Point:

➢ Floating-point data types are a set of numbers with the decimal value.
➢ We use the keyword "float" to represent floating-point data type and "double" to represent double data type
in C.
➢ The following table provides complete details about floating-point data types.

3. Character:

➢ The character data type is a set of characters enclosed in single quotations.


➢ The following table provides complete details about the character data type.

Q 17. Write short note on format specifiers in C.

➢ The format specifiers are used in C for input and output


purposes.
➢ Using this concept, the compiler can understand that what
type of data will be taking input using the scanf() function
and printing using printf() function.
➢ Here is a list of format specifiers
➢ The Most commonly used format specifiers
15

Q 18. Define variable. Explain how to declare and initialize a variable in C.

Variable:

A variable is a name of the memory location which can store a value.

Declaration:

Declaration of a variable tells the compiler to allocate the required amount of memory with the specified
variable name and allows only specified datatype values into that memory location.

We can declare a variable using below syntax.

Syntax:

Example:

int number;

The above declaration tells to the compiler that allocates 2 bytes of memory with the name number and allows only
integer values into that memory location.

Initialization:

➢ Initialization of a variable means assigning a value to the variable.


➢ We can initialize a variable with a value using below syntax.

Q 19. What are the rules to define a variable?

Rules to define Identifiers:

1. Variables can be a combination of letters (a to z/ A to Z) or digits (0 to 9) or an underscore ( _ ).

Example: myClass, var_1, print_this_to_screen, _number are valid variables.

2. A variable can start with a letter or an underscore ( _ ), but not with a digit.

Example: 1_variable is invalid

Variable_1 is Valid
16

3. Keywords cannot be used as variables.

Example: if is invalid variable

4. Special symbols like !, @, #, $, % etc. are not allowed in variables except one special symbol underscore ( _ ).

Example: company#name, $name, email@id are invalid variables

Q 20. Define Constant in C? Explain various types of constants in C?

A constant is a value assigned to the variable which will cannot be changed.

There are two ways of declaring constant:

1. Using const keyword

2. Using #define pre-processor


17

Q 21. Explain about Basic Input and Output formatted function in C?


➢ C language has standard libraries that allow input and output in a program.
➢ The stdio.h or standard input output library in C that has methods for input and output.
Formatted Input:
scanf()
The scanf() method, in C, reads the value from the console as per the type specified.
Syntax:
scanf(“%X”, &variableOfXType);
Explanation:
where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a variable and & is
the address operator in C, which tells the compiler to change the real value of this variable, stored at this address in
the memory.
Formatted Output:
printf()
The printf() method, in C, prints the value passed as the parameter to it, on the console screen.
Syntax:
printf(“%X”, variableOfXType);
Explanation:
where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a variable and & is
the address operator in C, which tells the compiler to change the real value of this variable, stored at this address in
the memory.
To take input and output of basic types in C?
The basic type in C includes types like int, float, char, etc. In order to input or output the specific type, the X in
the above syntax is changed with the specific format specifier of that type. The Syntax for input and output for these
are:
Example for Integer input and output:
Input: scanf("%d", &intVariable);
Output: printf("%d", intVariable);
Q 22. Write short note Type Casting and Conversion in C.
➢ In a c programming language, the data conversion is performed in two different methods as follows...
1. Type Conversion
2. Type Casting
1. Type Conversion:
➢ The type conversion is the process of converting a data value from one data type to another data type
automatically by the compiler.
➢ Sometimes type conversion is also called implicit type conversion.
➢ The implicit type conversion is automatically performed by the compiler.
18

Example:

int i = 10 ;

float x = 15.5 ;

char ch = 'A' ;

i = x ; =======> x value 15.5 is converted as 15 and assigned to variable i

x = i ; =======> Here i value 10 is converted as 10.000000 and assigned to variable x

i = ch ; =======> Here the ASCII value of A (65) is assigned to i

2. Type Casting:

➢ Typecasting is also called an explicit type conversion.


➢ Compiler converts data from one data type to another data type implicitly.
➢ When compiler converts implicitly, there may be a data loss.
➢ In such a case, we convert the data from one data type to another data type using explicit type conversion.
➢ To perform this, we use the unary cast operator.
➢ To convert data from one type to another type we specify the target data type in parenthesis as a prefix to
the data value that has to be converted.
➢ The general syntax of typecasting is as follows.

Example:
int totalMarks = 450, maxMarks = 600 ;
float average ;
average = (float) totalMarks / maxMarks * 100 ;
Explaination:
In the above example code, both totalMarks and maxMarks are integer data values. When we perform
totalMarks / maxMarks the result is a float value, but the destination (average) datatype is a float. So we use
type casting to convert totalMarks and maxMarks into float data type.
19

Q 23. What is Top-Down Approach?


➢ Top-Down Approach is an approach to design algorithms in which a bigger problem is broken down into smaller
parts.
➢ Thus, it uses the decomposition approach.
➢ This approach is generally used by structured programming languages such as C, COBOL, FORTRAN.
➢ The implementation of algorithm using top-down approach depends on the programming language and
platform.
➢ Top-down approach is generally used with documentation of module and debugging code.

Drawbacks
➢ The top-down approach is that it may have redundancy since every part of the code is developed separately.
➢ Also, there is less interaction and communication between the modules in this approach.

Q 24. What is Bottom-Up Approach?

➢ Bottom-Up Approach is one in which the smaller problems are solved, and then these solved problems are
integrated to find the solution to a bigger problem.
➢ Therefore, it uses composition approach.
➢ It requires a significant amount of communication among different modules.
➢ It is generally used with object oriented programming paradigm such as C++, Java, and Python.
➢ Data encapsulation and data hiding is also implemented in this approach.
➢ The bottom-up approach is generally used in testing modules.
20

Q 25. Difference between Top-Down Approach and Bottom-Up Approach?

S.No. Top-Down Approach Bottom-Up Approach

In this approach, the problem is broken down into In this approach, the smaller problems are solved.
1.
smaller parts.

It is generally used by structured programming It is generally used with object oriented


2. languages such as C, COBOL, FORTRAN, etc. programming paradigm such as C++, Java, Python,
etc.

It is generally used with documentation of module It is generally used in testing modules.


3.
and debugging code.

It does not require communication between It requires relatively more communication between
4.
modules. modules.

5. It contains redundant information. It does not contain redundant information.

6. Decomposition approach is used here. Composition approach is used here.

The implementation depends on the programming Data encapsulation and data hiding is implemented
7.
language and platform. in this approach.

Q 26. Explain Time Complexity of an Algorithm?

➢ Time complexity refers to the amount of time an algorithm takes to run as a function of the size of its input.
➢ It is usually expressed in terms of "big O" notation, which gives an upper bound on the growth rate of the
algorithm's running time.
➢ For example, an algorithm with a time complexity of O(n) means that its running time grows linearly with the
size of the input.
21

Q 27. Explain Space Complexity of an Algorithm?

➢ Space complexity, on the other hand, refers to the amount of memory an algorithm requires to run as a
function of the size of its input.
➢ It is also expressed in terms of big O notation.
➢ For example, an algorithm with a space complexity of O(n) means that it requires a linear amount of memory
to run as the size of the input grows.

It's important to consider both time and space complexity when analyzing algorithms, as they can have a
significant impact on the performance and efficiency of the algorithm. Generally, we want algorithms with lower time
and space complexities, as they will be faster and require less memory to run.

Important Questions

1. Explain in detail about various functional units of a computer.

2. What is an algorithm? Explain various characteristics of an algorithm.

3. Write an algorithm to find largest of 3 numbers.

4. Define flowchart. Discuss in detail about various symbols used in a flowchart.

5. Draw a flowchart to find roots of quadratic equation.

6. With an example program explain the structure of C program.

7. What is a C token? Explain various C tokens.

8. Describe in detail about various operators in C.

9. Write a C Program

i) Sum and average of 3 numbers


ii) Conversion of Fahrenheit to Celsius and vice versa
iii) Simple interest calculation

10. Write a C Program

i) Finding compound interest


ii) Area of a triangle
iii) Distance travelled by an object
22

UNIT - II
Control Structures

Q 1. Define a statement. What are the different types of statements?


Answer:
A Statement is an instruction in a program that can formed using C-Tokens. There are 3 types of statements.
i) Sequential Statements
ii) Conditional Statements (Decision Statements)
iii) Looping Statements.
➢ In Sequential, each and every statement is executed one by one without skipping.
➢ In Conditional, particular block of statements is executed based on condition.
➢ Conditional statements in C are: if and switch
➢ In Looping, a block of statements is executed up to number of times based on condition. Looping statements in C
are: do-while, while and for

Q 2. Define null statement. What is the importance of it?


Answer:

Null statement means it executes nothing in the program that means it performs no operation.

Example:

; → it is a null statement

Importance:

It is useful when the syntax of the language calls for a statement but no expression evaluation.

Q 3. Explain in detail about if statement with example.


Answer:

There are 3 types of if statement. They are:

1. Simple if

2. if-else statement

3. if-else-if statement (else-if ladder)

1. Simple if:

In simple if, if the condition is true, then True block statements are executed. Simple if does not concentrate on the
False condition.
23

Output: Enter any integer number : 20

Given number is divisible by 5.

Explanation: In the above program user need to entered integer value 20 is stored in variable “n” using if condition
modulo operation 20%5 then remainder is “0”. The given condition is True the if block statement is executed...

2. if-else statement:

In if-else-if statement, if the condition is true then True block statements are executed otherwise False block
statements are executed.
24

3. if-else-if statement (else-if ladder):

It is used in the scenario where there are multiple cases to be performed for different conditions.

In if-else-if ladder statement, if a condition is true then the statements defined in the if block will be executed,
otherwise if some other condition is true then the statements defined in the else-if block will be executed, at the last
if none of the condition is true then the statements defined in the else block will be executed.
25
26

Q 4. Write short note on nested-if statement.


Answer:

Nested-if statement:

Writing an if statement inside another if statement is called nested if statement.

Output:
27

Q 5. Explain in detail about switch statement.


Answer:

Switch statement:

The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations
for the different possible values of a single variable called switch variable.

Here, we can define various statements in the multiple cases for the different values of a single variable.

The syntax of switch statement is given below


28

Q 6. Explain in detail about looping statements.


Answer:

The looping statements are used to execute a single statement or block of statements repeatedly until the given
condition is FALSE.

C has 3 looping statements:

1. do-while

2. while

3. for

1. do-while statement:

The do-while statement is used to execute a single statement or block of statements repeatedly until given condition
is False.

The do-while statement is also known as the Exit control looping statement.

In do-while, the block of statements is executed at least once.


29

2. while statement:

The while statement is used to execute a single statement or block of statements repeatedly until given condition is
False.

The while statement is also known as the Exit control looping statement.
30

3. for statement:

The for statement is used to execute a single statement or block of statements repeatedly until given condition is
False.
31

Q 7. Write the difference between do-while and while.

Q 8. Write short note on break statement.


Answer:

In C, the break statement is used to perform the following two things:

1. break statement is used to terminate the switch case statement

2. break statement is also used to terminate looping statements like while, dowhile and for.
32

The break statement execution is as shown in the following figure.

Q 9. Write short note on continue statement.


Answer:

➢ The continue statement is used to move the program execution control to the beginning of the looping
statement.
➢ The continue statement can be used with looping statements like while, do-while and for.
➢ When we use continue statement with while and do-while statements the execution control directly jumps to
the condition.
➢ When we use continue statement with for statement the execution control directly jumps to the modification
portion (increment/decrement/any modification) of the for loop.
➢ The continue statement execution is as shown in the following figure.
33

Program:

Output:
34

Q 10. Write the difference between break and continue.


Answer:

Important Question
1. Define null statement.
2. Write syntax and flow chart for if-else statement.
3. Define conditional statements.
4. Define looping statements.
5. Write syntax for do-while statement.
6. Write differences between while and do-while
7. Write a C program to print 1 to 10 natural number using for loop?
8. Write a C program to print given pattern using while loop?
*
**
***
****
9. Write a C program to print 10 to 1 natural number using do…while loop?
10. Write a C program to find greatest among two numbers using if-else condition?
11. Write a C program to print whether even or odd number using if-else condition?
12. Write a C program to print multiplication table using for loop?
5*1=5
5*2=10..
35

Unit III
Arrays and Strings

Q.1. Define an Array. Explain how to declare and initialize an array.


➔ An array is a variable which can store more than one value of same datatype.
➔ The elements of array stored in continues memory locations.
Declaration of Array:
➔ when we want to create an array, we must know the datatype of values to be stored in that array
and also the number of values to be stored in that array.
➔ We use the following general syntax to create an array...
Syntax: datatype arrayName[ size ] ;
In the above syntax, the datatype specifies the type of values we store in that array and size
specifies the maximum number of values that can be stored in that array.
Example
int a [3] ;
Here, the compiler allocates 6 bytes of memory locations with a single name 'a' and tells the
compiler to store three different integer values (each in 2 bytes of memory).
For the above declaration, the memory is organized as follows...

Initialization of Array:
Syntax for creating an array with size and initial values.
datatype arrayName [ size ] = {value1, value2, ...} ;
Example
int a[5] = {1, 2, 3, 4, 5};
Here, an array ‘a’ stores 5 values.

Syntax for creating an array without size and with initial values
datatype arrayName [ ] = {value1, value2, ...} ;
Example
int a[ ] = {1, 2, 3, 4, 5};
Here, an array ‘a’ stores 5 values.
36

Q.2. Explain how to access elements of an array?


An element is accessed by indexing the array name. This is done by placing the index of the element within
square brackets after the name of the array.
Syntax:
arrayName [ indexValue ] ;
Example:
int a[5] = {1, 2, 3}
For the above example the individual elements can be denoted as follows

➔ We can access the elements as follows:


printf(“%d”, a[2]);
Output of the above statement is: 3
➔ We can change the individual elements of array as follows:
a[1] = 100;
➔ Then array elements are:

Q.3. Explain Memory Layout of C Programs?


A typical memory representation of a C program consists of the following sections.
1. Text segment (i.e. instructions)
2. Initialized data segment
3. Uninitialized data segment (bss)
4. Heap
5. Stack
37

A typical memory layout of a running process

1. Text Segment:

➔ A text segment, also known as a code segment or simply as text, is one of the sections of a program
in an object file or in memory, which contains executable instructions.
➔ As a memory region, a text segment may be placed below the heap or stack in order to prevent
heaps and stack overflows from overwriting it.
➔ Usually, the text segment is sharable so that only a single copy needs to be in memory for frequently
executed programs, such as text editors, the C compiler, the shells, and so on. Also, the text segment
is often read-only, to prevent a program from accidentally modifying its instructions.

2. Initialized Data Segment:

➔ Initialized data segment, usually called simply the Data Segment.


➔ A data segment is a portion of the virtual address space of a program, which contains the global
variables and static variables that are initialized by the programmer.
➔ The data segment is not read-only, since the values of the variables can be altered at run time.
➔ This segment can be further classified into the initialized read-only area and the initialized read-
write area.
➔ For instance, the global string defined by char s[] = “hello world” in C and a C statement like int
debug=1 outside the main (i.e. global) would be stored in the initialized read-write area. And a
global C statement like const char* string = “hello world” makes the string literal “hello world” to be
stored in the initialized read-only area and the character pointer variable string in the initialized
read-write area.
➔ Ex: static int i = 10 will be stored in the data segment and global int i = 10 will also be stored in data
segment

3. Uninitialized Data Segment:

➔ Uninitialized data segment often called the “bss” segment, named after an ancient assembler
operator that stood for “block started by symbol.”
➔ Data in this segment is initialized by the kernel to arithmetic 0 before the program starts executing
uninitialized data starts at the end of the data segment and contains all global variables and static
variables that are initialized to zero or do not have explicit initialization in source code.
➔ For instance, a variable declared static int i; would be contained in the BSS segment.
➔ For instance, a global variable declared int j; would be contained in the BSS segment.
38

4. Stack:

➔ The stack area traditionally adjoined the heap area and grew in the opposite direction; when the
stack pointer met the heap pointer, free memory was exhausted. (With modern large address
spaces and virtual memory techniques they may be placed almost anywhere, but they still typically
grow in opposite directions.)
➔ The stack area contains the program stack, a LIFO structure, typically located in the higher parts of
memory. On the standard PC x86 computer architecture, it grows toward address zero; on some
other architectures, it grows in the opposite direction.
➔ A “stack pointer” register tracks the top of the stack; it is adjusted each time a value is “pushed”
onto the stack.
➔ The set of values pushed for one function call is termed a “stack frame”;
➔ A stack frame consists at minimum of a return address.
Stack, where automatic variables are stored, along with information that is saved each time a
function is called.
➔ Each time a function is called, the address of where to return to and certain information about the
caller’s environment, such as some of the machine registers, are saved on the stack.
➔ The newly called function then allocates room on the stack for its automatic variables.
➔ This is how recursive functions in C can work.
➔ Each time a recursive function calls itself, a new stack frame is used, so one set of variables doesn’t
interfere with the variables from another instance of the function.

5. Heap:

➔ Heap is the segment where dynamic memory allocation usually takes place.
➔ The heap area begins at the end of the BSS segment and grows to larger addresses from there.
➔ The Heap area is managed by malloc, realloc, and free, which may use the brk and sbrk system calls
to adjust its size (note that the use of brk/sbrk and a single “heap area” is not required to fulfill the
contract of malloc/realloc/free; they may also be implemented using mmap to reserve potentially
non-contiguous regions of virtual memory into the process’ virtual address space).
➔ The Heap area is shared by all shared libraries and dynamically loaded modules in a process.
39

Q. 4. Write a C program to read and print elements of array.

Program:
#include <stdio.h>
int main()
{
int arr[N];
int i, N;
printf("Enter size of array: ");
scanf("%d", &N);
printf("Enter %d elements in the array : ", N);
for(i=0; i<N; i++)
{
scanf("%d", &arr[i]);
}
printf("\nElements in array are: ");
for(i=0; i<N; i++)
{
printf("%d, ", arr[i]);
}
return 0;
}

Output:

Enter size of array: 10


Enter 10 elements in the array : 10
20
30
40
50
60
70
80
90
100
Elements in array are : 10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
40

Q . 5 . Write a C program to print all negative elements in an array.

Program:
#include <stdio.h>
int main()
{
int arr[N];
int i, N;
printf("Enter size of the array : ");
scanf("%d", &N);
printf("Enter elements in array : ");
for(i=0; i<N; i++)
{
scanf("%d", &arr[i]);
}
printf("\nAll negative elements in array are : ");
for(i=0; i<N; i++)
{
if(arr[i] < 0)
{
printf("%d\t", arr[i]);
}
}
return 0;
}

Output:

Enter size of the array : 10

Enter elements in array : -1 -10 100 5 61 -2 -23 8 -90 51

All negative elements in array are : -1 -10 -2 -23 -90


41

Q. 6 . Write a C program to find second largest element in an array

Program:
#include <stdio.h>
# define SIZE 20
int main()
{
int size, i;
int arr[SIZE],max1, max2;
printf("Enter size of the array (1-1000): ");
scanf("%d", &size);
printf("Enter elements in the array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
max1 = max2 = arr[0];
for(i=0; i<size; i++)
{
if(arr[i] > max1)
{
max2 = max1;
max1 = arr[i];
}
else if(arr[i] > max2 && arr[i] < max1)
{
max2 = arr[i];
}
}
printf("First largest = %d\n", max1);
printf("Second largest = %d", max2);
return 0;
}
Output:

Enter size of the array (1-1000): 10


Enter elements in the array: -7 2 3 8 6 6 75 38 3 2
First largest = 75
Second largest = 38
42

Q. 7 . Write a C program to print all unique elements in the array

Program:

#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE], freq[MAX_SIZE];
int size, i, j, count;
printf("Enter size of array: ");
scanf("%d", &size);
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
freq[i] = -1;
}
for(i=0; i<size; i++)
{
count = 1;
for(j=i+1; j<size; j++)
{
if(arr[i] == arr[j])
{
count++;
freq[j] = 0;
}
}
if(freq[i] != 0)
{
freq[i] = count;
}
}
printf("\nUnique elements in the array are: ");
for(i=0; i<size; i++)
{
if(freq[i] == 1)
{
printf("%d ", arr[i]);
}
}
43

return 0;
}

Output:

Enter size of array: 8

Enter elements in array: 1 2 5 1 2 4 9 6

Unique elements in the array are: 5 4 9 6

Q. 8. Write a C program to input elements in array and find reverse of array

Program:

#include <stdio.h>
#define MAX_SIZE 100 // Defines maximum size of array
int main()
{
int arr[MAX_SIZE];
int size, i;
printf("Enter size of the array: ");
scanf("%d", &size);
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
printf("\nArray in reverse order: ");
for(i = size-1; i>=0; i--)
{
printf("%d\t", arr[i]);
}
return 0;
}
Output:

Enter size of the array: 5


Enter elements in array: 1 5 9 7 3
Array in reverse order: 3 7 9 5 1
44

Q 9. Explain the different types of arrays.

Arrays are classified into two types. They are as follows...

1. Single Dimensional Array / One Dimensional Array


2. Multi-Dimensional Array

1. Single Dimensional Array (One Dimensional Array):

✓ An array contains one subscript is known as One or Single Dimensional Array.


✓ Single dimensional arrays are used to store list of values of same datatype.
✓ Single dimensional arrays are also called as one-dimensional arrays, Linear Arrays or simply 1-D
Arrays.

Declaration of Single Dimensional Array:

We use the following general syntax for declaring a single dimensional array

Syntax: datatype arrayName [ size ] ;

Example

int rollNumbers [60];

The above declaration of single dimensional array reserves 60 continuous memory locations of 2 bytes each
with the name rollNumbers and tells the compiler to allow only integer values into those memory locations.

Initialization of Single Dimensional Array:

We use the following general syntax for declaring and initializing a single dimensional array with size and
initial values.

datatype arrayName [ size ] = {value1, value2, ...} ;


Example

int marks [6] = { 89, 90, 76, 78, 98, 86 } ;

The above declaration of single dimensional array reserves 6 contiguous memory locations of 2 bytes each
with the name marks and initializes with value 89 in first memory location, 90 in second memory location,
76 in third memory location, 78 in fourth memory location, 98 in fifth memory location and 86 in sixth
memory location.

➔ We can also use the following general syntax to intialize a single dimensional array without
specifying size and with initial values.

datatype arrayName [ ] = {value1, value2, ...} ;


45

➔ The array must be initialized if it is created without specifying any size. In this case, the size of the
array is decided based on the number of values initialized.

Example:

int marks [ ] = { 89, 90, 76, 78, 98, 86 } ;

char studentName [ ] = "GATESIT" ;

In the above example declaration, size of the array 'marks' is 6 and the size of the array 'studentName' is 16.
This is because in case of character array, compiler stores one extra character called \0 (NULL) at the end

2. Multi-Dimensional Array:
➢ If an array contains more than one subscript is known as multi-dimensional array.
➢ Multi-dimensional array can be of two dimensional array or three dimensional array or four
dimensional array or more.
➢ Most popular and commonly used multi-dimensional array is two dimensional array.
➢ The 2-D arrays are used to store data in the form of table.
➢ We also use 2-D arrays to create mathematical matrices.

Declaration of Two Dimensional Array:

➔ We use the following general syntax for declaring a two dimensional array.

Datatype arrayName [ rowSize ] [ columnSize ] ;

Example
int matrix_A [2][3] ;
The above declaration of two dimensional array reserves 6 continuous memory locations of 2 bytes each in
the form of 2 rows and 3 columns.

Initialization of Two Dimensional Array:

➔ We use the following general syntax for declaring and initializing a two dimensional array with
specific number of rows and coloumns with initial values.

datatype arrayName [rows][colmns] = {{r1c1value, r1c2value, ...},{r2c1, r2c2,...}...} ;

Example
int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ;
The above declaration of two-dimensional array reserves 6 contiguous memory locations of 2 bytes each in
the form of 2 rows and 3 columns. And the first row is initialized with values 1, 2 & 3 and second row is
initialized with values 4, 5 & 6.
46

➔ We can also initialize as follows.

Example

int matrix_A [2][3] = {

{1, 2, 3},

{4, 5, 6}

};

Accessing Individual Elements of Two Dimensional Array:

➢ To access elements of a two-dimensional array we use array name followed by row index value and
column index value of the element that to be accessed.
➢ Here the row and column index values must be enclosed in separate square braces.

➔ We use the following general syntax to access the individual elements of a two-dimensional array...

arrayName [ rowIndex ] [ columnIndex ]

Example

matrix_A [0][1] = 10 ;

In the above statement, the element with row index 0 and column index 1 of matrix_A array is assinged
with value 10.

Q 10. What are the applications of array?

1. Arrays are used to Store List of values

2. Arrays are used to Perform Matrix Operations

3. Arrays are used to implement Search Algorithms

4. Arrays are used to implement Sorting Algorithms

5. Arrays are used to implement Data structures.

6. Arrays are also used to implement CPU Scheduling Algorithms

Q 11. Define a string. Explain how to create and initialize strings in C.

String:

String is a set of characters enclosed in double quotation marks.


47

In C programming, the string is a character array of single dimension.

Creating a String:

Syntax: char string_name[size];

Example: char str1[30];


Initialization:

Syntax: string_name[size] = String

Example: 1. char str1[30] = “Hello”

2. char str2[20];

str = “Hello Hai”


Note: ‘\0’ represents end of the string.

Q 12. Explain about gets and puts functions.

➢ gets() function is used to read a string from standard input device and puts is used to display a string on
standard output device.
➢ gets() and puts() functions are defined in stdio.h header file

Example:

#include<stdio.h>
int main()
{
char s[20];
printf("Enter a String: ");
gets(s);
printf("Your String is: ");
puts(s);
return 0;
}

Output:

Enter a String: hello


Your String is: hello
48

Q.13. Explain about string handling functions.


➢ C programming language provides a set of pre-defined functions called string handling functions to
work with string values.
➢ The string handling functions are defined in a header file called string.h.
➢ Whenever we want to use any string handling function we must include the header file called
string.h.
➢ The following table provides most commonly used string handling function and their use
49

Example Programs :
14. Write a C Program to Concatenate two strings without built-in functions
Source Code:
#include<stdio.h
void main(void)
{
char str1[25],str2[25];
int i=0,j=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
}

Output:

Enter First String: Computer Science


Enter Second String:& Engineering
Concatenated String is Computer Science & Engineering
50

15. Write a C Program to Reverse a string without built-in string functions


Source Code:

#include <stdio.h>
#include <string.h>
int main()
{
char str[50]; // size of char string
int i, len, temp;
printf (" Enter the string: ");
gets(str); // use gets() function to take string
printf(" \n Before reversing the string: %s \n", str);
len = strlen(str); // use strlen() to get the length of str string
for (i = 0; i < len/2; i++)
{
temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
printf (" After reversing the string: %s", str);
}

Output:

Enter the string: COMPUTER


Before reversing the string: COMPUTER
After reversing the string: RETUPMOC
51

16. Write a C Program to Reverse a string using built-in string functions


Source Code:
#include <stdio.h>
#include <string.h>
int main()
{
char str[40]; // declare the size of character string
printf (" \n Enter a string to be reversed: ");
scanf ("%s", str);
printf (" \n After the reverse of a string: %s ", strrev(str));
return 0;
}

Output:

Enter a string to be reversed: SUPREME

After the reverse of a string: EMERPUS


52

Unit IV

Pointers & User Defined Data types

Q 1. Define a pointer. Explain how to declare and initialize a pointer.

Pointer:

A pointer is a variable which holds memory address of another variable. Pointers are powerful tools that allow direct
memory access and manipulation.

Declaring Pointer:

Declaration of pointer variable is similar to the creation of normal variable but the name is prefixed with *
symbol.

Syntax:

datatype *pointerName ;

Example:

int *ptr ;

In the above example declaration, the variable "ptr" is a pointer variable that can be used to store any integer
variable address.

Initializing a Pointer:

To assign address to a pointer variable we use assignment operator with the following syntax.

pointerVariableName = & variableName ;

Example:

int a = 50, *ptr ;

ptr = &a ;

Diagrammatic representation of above example is:

Accessing Variable Value Using Pointer

➢ Pointer variables are used to store the address of other variables.


➢ We can use this address to access the value of the variable through its pointer.
53

➢ We use the symbol "*" in front of pointer variable name to access the value of variable to which the pointer
is pointing.

Syntax:

*pointerVariableName

Example Code

#include<stdio.h>
int main()
{
int a = 10, *ptr ;
ptr = &a ;
printf("Address of variable a = %u\n", ptr) ;
printf("Value of variable a = %d\n", *ptr) ;
printf("Address of variable ptr = %u\n", &ptr) ;
return 0;
}

Output:

Address of variable a = 6487580

Value of variable a = 10

Address of variable ptr = 6487568

Q 2. How to access address of a variable?

➢ In c language, we use the reference operator "&" to access the address of variable.
➢ For example, to access the address of a variable "marks" we use "&marks".
➢ We use the following printf statement to display memory location address of variable "marks".
➢ Example:
printf("Address : %u", &marks) ;
➢ In the above example statement %u is used to display address of marks variable.
➢ Address of any memory location is unsigned integer value.

Q 3. How many bytes of memory allocated for pointer variable.

➢ Every pointer variable is used to store the address of another variable.


➢ In computer memory address of any memory location is an unsigned long integer value.
➢ In c programming language, unsigned long integer requires 4 bytes of memory.
➢ So, irrespective of pointer datatype every pointer variable is allocated with 4 bytes of memory in 32-bit
architecture.
54

Q 4. Define pointer to pointer.

➢ A pointer variable to store the address of another pointer variable is called a pointer to pointer variable.
➢ Sometimes we also call it a double pointer.

Syntax:

datatype **pointerName ;

Example:

int a;

int *p1, **p2, ***p3;

p1 = &a;

p2 = &p1;

p3 = &p2

Note:

1. To store the address of normal variable we use single pointer variable

2. To store the address of single pointer variable we use double pointer variable

3. To store the address of double pointer variable we use triple pointer variable

4. Similarly, the same for remaining pointer variables also…

Q 5. Define void pointer with example.

➢ A void pointer is a pointer variable used to store the address of a variable of any datatype.
➢ That means single void pointer can be used to store the address of integer variable, float variable, character
variable, double variable or any structure variable
➢ We use the keyword "void" to create void pointer.
Syntax:
void *pointerName ;
Example:
int a;
float b;
void *p1, *p2;
p1 = &a;
p2 = &b;
55

Q 6. What are the operations performed on pointers? Explain.


✓ Pointer variables are used to store the address of variables.
✓ Address of any variable is an unsigned integer value i.e., it is a numerical value.
✓ So, we can perform following arithmetic operations on pointer values:
1. Addition
2. Subtraction
3. Increment
4. Decrement
5. Comparison
1. Addition:
➢ When a pointer is added with an integer value, the value is first multiplied by the size of the data type and
then added to the pointer.
➢ The addition operation on pointer variables is calculated using the following formula:
AddressAtPointer + ( NumberToBeAdd * Datatype_size )
For Example:
Consider the same example as above where the ptr is an integer pointer that stores 1000 as an address. If we add
integer 5 to it using the expression, ptr = ptr + 5, then,
the final address stored in the ptr will be ptr = 1000 + sizeof(int) * 5 = 1020.

2. Subtraction:
➢ When a pointer is subtracted with an integer value, the value is first multiplied by the size of the data type
and then subtracted from the pointer similar to addition.
➢ The subtraction operation on pointer variables is calculated using the following formula:
AddressAtPointer - ( NumberToBeAdd * Datatype_Size )
For Example:
Consider the same example as above where the ptr is an integer pointer that stores 1000 as an address.
If we subtract integer 5 from it using the expression, ptr = ptr – 5, then,
the final address stored in the ptr will be ptr = 1000 – sizeof(int) * 5 = 980.
56

3. Increment:
➢ Increment: It is a condition that also comes under addition. When a pointer is incremented, it actually
increments by the number equal to the size of the data type for which it is a pointer.
➢ The increment operation on pointer variable is calculated as follows:
AddressAtPointer + Datatype_size
For Example:
If an integer pointer that stores address 1000 is incremented, then it will increment by 4(size of an int), and the new
address will point to 1004. While if a float type pointer is incremented then it will increment by 4(size of a float) and
the new address will be 1004.

4. Decrement
➢ It is a condition that also comes under subtraction. When a pointer is decremented, it actually decrements by
the number equal to the size of the data type for which it is a pointer.
➢ The decrement operation on pointer variable is calculated as follows:
AddressAtPointer - NumberOfBytesRequiresByDatatype
For Example:
If an integer pointer that stores address 1000 is decremented, then it will decrement by 4(size of an int), and the new
address will point to 996. While if a float type pointer is decremented then it will decrement by 4(size of a float) and
the new address will be 996.

5. Comparison
➢ We can compare the two pointers by using the comparison operators in C.
➢ We can implement this by using all operators in C >, >=, <, <=, ==, !=.
➢ It returns true for the valid condition and returns false for the unsatisfied condition.
➢ The comparison operation is performing between the pointers of same datatype only.
➢ In c programming language, we can use all comparison operators (relational operators) with pointers.
57

Q 7. Describe An Array Of Pointers In C?

✓ Pointers and Array representations are very much related to each other and can be interchangeably used in
the right context.
✓ An array name is generally treated as a pointer to the first element of the array and if we store the base
address of the array in another pointer variable, then we can easily manipulate the array using pointer
arithmetic in a C Program.

Syntax

*(arr + i)

we denote array elements as arr[i], where i is the index value. Below is a similar syntax in terms of pointers of how we
can represent the array elements using the dereferencing operator (*) on the array name i.e. using the pointers
property of the array.

➔ * is a dereferencing operator used to extract the value from the address (arr + i).
➔ *(arr + i) is the same as arr[i] in a C Program.
➔ arr represents the array name and i represents the index value.

Example

#include <stdio.h>
int main()
{
// array declaration and initialization
int arr[5] = {2, 4, 6, 8, 10}, i;
for(i = 0; i < 5; i++)
{
// printing the elements address and value at
// arr[i] using *(arr + i) syntax
printf("[index %d] Address : %u, Value : %d\n", i, (arr + i), *(arr + i));
}
return 0;
}
Output :
[index 0] Address : 2364420656, Value : 2
[index 1] Address : 2364420660, Value : 4
[index 2] Address : 2364420664, Value : 6
[index 3] Address : 2364420668, Value : 8
[index 4] Address : 2364420672, Value : 10

Explanation :

We have declared and initialized an integer array arr, array representation :


58

✓ (arr + i) represents the address of the value at index i, so *(arr + i) will give the value at ith index (address(arr + i)
= address(arr[i])), it is used to print the addresses of the array elements as the value of i changes from 0-4
✓ * is a dereferencing operator used for printing the value at the provided address. *(arr + i) will print the values of
the array at consecutive addresses as the value of i changes from 0-4.
Q 8. Define static memory allocation. What are its limitations.

➢ Allocation of memory during compile time is called static memory allocation.


➢ When we declare variables memory is allocated in space called stack.
➢ The memory allocated in the stack is fixed at the time of compilation and remains until the end of the
program execution.

Limitations:

➢ When we create an array, we must specify the size at the time of the declaration itself and it cannot be
changed during the program execution.
➢ This is a major problem when we do not know the number of values to be stored in an array.

Q 9. Explain about dynamic memory allocation in C.

➢ Allocation of memory during the program execution is called dynamic memory allocation.
➢ We use pre-defined functions to allocate memory dynamically.
➢ There are FOUR pre-defined functions that are defined in the header file known as "stdlib.h".

They are as follows:

1. malloc()

2. calloc()

3. realloc()

4. free()
1. malloc():

➢ malloc() is the pre-defined function used to allocate a memory block of specified number of bytes and
returns void pointer.
➢ The void pointer can be casted to any datatype. If malloc() function unable to allocate memory due to any
reason it returns NULL pointer.

Syntax:

void* malloc(size_in_bytes)

Example:
char *title;
title = (char *) malloc(15);
59

2. calloc():
➢ calloc() is the pre-defined function used to allocate multiple memory blocks of the specified number of bytes
and initializes them to ZERO.
➢ calloc() function returns void pointer.
➢ If calloc() function unable to allocate memory due to any reason it returns a NULL pointer.
➢ Generally, calloc() is used to allocate memory for array and structure.
o calloc() function takes two arguments and they are
o The number of blocks to be allocated
➢ Size of each block in bytes
Syntax:
void* calloc(number_of_blocks, size_of_each_block_in_bytes)
Example:
int *ptr;
ptr = (int*)calloc(5, sizeof(int));
3. realloc():
➢ realloc() is the pre-defined function used to modify the size of memory blocks that were previously allocated
using malloc() or calloc().
➢ realloc() function returns void pointer.
➢ If realloc() function unable to allocate memory due to any reason it returns NULL pointer.
Syntax
void* realloc(*pointer, new_size_of_each_block_in_bytes)
Example:
char *title;
title = (char *) malloc(15);
title = (char*) realloc(title, 30);
4. free():
➢ free() is the pre-defined function used to deallocate memory block that was previously allocated using
malloc() or calloc().
Syntax
void free(*pointer)
Example:
char *title;
title = (char *) malloc(15);
free(title);
60

Q 10. Define a structure. How to declare a structure in C?


Structure:
Structure is a collection of different datatype elements which can be referred under a single name.
Creating Structure:
To create structure, we use the keyword called "struct".
Syntax:
struct structure_name
{
// Structure members
data_type member1;
data_type member2, member3;
….
};
struct structure_name structure_varaibles;
Example:
struct Student
{
// structure members
char stud_name[30];
int roll_number;
float percentage;
};
// structure variables
struct Student s1,s2;
Accessing Structure Members:
We use structure variables to access structure members with dot(.) operator.
Syntax:
Structure_varaible . structure_member
Example:
s1.stud_name
s1.roll_number
Example:
#include<stdio.h>
struct employee
{
int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
61

{
//store first employee information
e1.id=101;
e1.name = "Ajay");
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Output:
employee 1 id : 101
employee 1 name : Ajay

Q 11. How much memory is allocated for a structure?


➢ The memory does not allocate on defining a structure.
➢ The memory is allocated when we create the variable of a particular structure.
➢ The size of memory allocated is equal to the sum of memory required by individual members of that
structure.

Q 12. Explain in detail about structure with arrays with example.


➢ An array of structures in C can be defined as the collection of multiple structures variables where each
variable contains information about different entities.
➢ The array of structures in C are used to store information about multiple entities of different data types.
➢ The array of structures is also known as the collection of structures.
Example:

#include<stdio.h>
struct student
{
int rollno;
62

char name[10];
};
int main()
{
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++)
{
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz
Student Information List:
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
63

Q 13. Define self-referential structure.


• Self-Referential structures are those structures that have one or more pointers which point to the same type of
structure, as their member.

Q 14. Define union. Explain creation of union and accessing union members.
Union:
Union is a collection of different datatype elements which can be referred under a single name.
Creating Union:
To create union, we use the keyword called “union”.
Syntax:
union union_name
{
// Union members
data_type member1;
data_type member2, member3;
….
};
union union_name union_varaibles;
Example:
union Student
{
// union members
64

char stud_name[30];
int roll_number;
float percentage;
};
// union variables
union Student s1,s2;
Accessing Union Members:
We use union variables to access structure members with dot(.) operator.
Syntax:
Union_varaible . Union_member
Example:
s1.stud_name
s1.roll_number
s1.percentage
Q 15 How much memory is allocated for a Union?
➢ The memory is allocated when we create the variable of a particular union.
➢ The size of memory allocated is equal to the maximum memory required by an individual member among all
members of that union.

Q 17. Write the differences between structure and union


65

Q 18. Explain about Dangling pointer?


A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer.
66

Unit V

Functions & File Handling

Q 1. Define a function. How to define and call a function in C.


➢ A function is a block of statements which perform specific task.
Every function in C has the following:
1. Function Declaration (Function Prototype)
2. Function Definition
3. Function Call
1. Function Declaration (Function Prototype):
➢ The function declaration tells the compiler about function name, the data type of the return value and
parameters. The function declaration is also called a function prototype.
➢ The function declaration is performed before the main function or inside the main function or any other
function.
Syntax:
Return_Type function_Name(parameters_List);
Example:
void add( int , int );
2. Function Definition:
The function definition is also known as the body of the function.
Syntax
Return_Type function_Name(parameters_List)
{
Actual code...
}
In the above syntax,
Return_Type specifies the value return by a function
function_Name is a user-defined name used to identify the function uniquely
parameters_List is the data values that are sent to the function definition
Example:
void add(int a, int b)
{
printf(“Addition of a and b = %d”, a+b);
}
In this example,
The function name is add, it is taking two integer variables as parameters and it is not returning any value.
67

3. Function Call:
➢ The function call tells the compiler when to execute the function definition. When a function call is executed,
the execution control jumps to the function definition where the actual code gets executed and returns to
the same functions call once the execution completes.
➢ The function call is performed inside the main function or any other function or inside the function itself.
Syntax
functionName(parameters);
Example:
add(15, 20);
Q 2. define parameter. What are its types.
➢ Parameters are the data values that are passed from calling function to called function.
➢ Parameters are also called as arguments.
➢ In C, there are two types of parameters and they are as follows...
o Actual Parameter
o Formal Parameters
➢ The actual parameters are the parameters that are specified in calling function.
➢ The formal parameters are the parameters that are declared at called function.
➢ When a function gets executed, the copy of actual parameter values are copied into formal parameters.

Q 3. Write the differences between actual parameters and formal parameters.


68

Q 4. What are the different types of functions? Explain.


Bases on function definition, functions are divided into two types:
1. Pre-Defined Functions
2. User Defined Functions
1. Pre-Defined Functions:
➢ The function whose definition is defined by the developers of language is called as system defined function.
➢ The pre-defined functions are also called as Library Functions or Standard Functions or system Functions.
➢ In C, all the system defined functions are defined inside the header files like stdio.h, conio.h, math.h, string.h,
stdlib,h etc.,
➢ For example, the funtions printf() and scanf() are defined in the header file called stdio.h
2. User Defined Functions:
➢ The function whose definition is defined by the user is called as user defined function.
Example Program:

#include<stdio.h>
int addition(int,int) ; // function declaration
int main()
{
int num1, num2,
result ;
printf("Enter any two integer numbers : ");
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("SUM = %d", result);
return 0;
}
int addition(int a, int b) // function definition
{
return a + b ;
}
Output:
Enter any two integer numbers : 23 54
SUM = 77
In the above example addition() is user defined function.
Q 5. Explain different types of functions based on parameters and return values?
Based on parameters and return types, functions are classified into 4 types:
1. Function without parameters and without return values
2. Function with parameters and without return values
3. Function without parameters and with return values
4. Function with parameters and with return values
69

1. Function without parameters and without return values:


This type of functions doesn’t contain parameters and return values.
Example Program
#include<stdio.h>
void addition() ; // function declaration
int main()
{
addition() ; // function call
}
void addition() // function definition
{
int num1, num2;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
printf("Sum = %d", num1+num2 );
}
Output:
Enter any two integer numbers : 20 30
Sum = 50

2. Function with parameters and without return values:


These types of functions having the parameters and doesn’t have the return values.

Example Program

#include<stdio.h>
void addition(int, int) ; // function declaration
int main()
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
addition(num1, num2) ; // function call
return 0;
}
void addition(int a, int b) // function definition
{
printf("Sum = %d", a+b ) ;
}
Output:
Enter any two integer numbers : 20 30
Sum = 50
70

3. Function without parameters and with return values:


These types of functions doesn’t have any parameters and contains return values.
Example Program

#include<stdio.h>
int addition() ; // function declaration
int main()
{
int result ;
result = addition() ; // function call
printf("Sum = %d", result) ;
return 0;
}
int addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
return (num1+num2) ;
}
Output:
Enter any two integer numbers : 20 30
Sum = 50
4. Function with parameters and with return values:
These types of functions contain both parameters and return values.
Example Program

#include<stdio.h>
int main()
{
int num1, num2, result ;
int addition(int, int) ; // function declaration
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("Sum = %d", result) ;
return 0;
}
int addition(int a, int b) // function definition
{
return (a+b) ;
}
Output:
Enter any two integer numbers : 20 30
Sum = 50
71

Q 6. Explain in detail about parameter passing techniques.


(Or)
Explain call by value and call by reference with example.
There are two methods to pass parameters from calling function to called function and they are:
1. Call by Value
2. Call by Reference
1. Call by Value
➢ In call by value parameter passing method, the copy of actual parameter values are copied to formal
parameters and these formal parameters are used in called function.
➢ The changes made on the formal parameters does not affect the values of actual parameters.
Example Program
#include<stdio.h>
void swap(int,int) ; // function declaration
int main()
{
int num1, num2 ;
printf("Enter two numbers: ");
scanf("%d%d",&num1,&num2);
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(num1, num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
return 0;
}
void swap(int a, int b) // called function
{
int temp ;
temp = a ;
a = b ;
b = temp ;
}
Output:
Enter two numbers: 10 20
Before swap: num1 = 10, num2 = 20
After swap: num1 = 10, num2 = 20
2. Call by reference:
➢ In Call by Reference parameter passing method, the memory address of the actual parameters is copied to
formal parameters.
➢ This address is used to access the memory locations of the actual parameters in called function. In this
method, the formal parameters must be pointer variables.
➢ Any changes made on the formal parameters effects the values of actual parameters.
72

Example Program

#include<stdio.h>
void swap(int*, int*) ; // function declaration
int main()
{
int num1, num2 ;
printf("Enter two numbers: ");
scanf("%d%d",&num1,&num2);
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
return 0;
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}
Output:
Enter two numbers: 10 20
Before swap: num1 = 10, num2 = 20
After swap: num1 = 20, num2 = 10
Q 7 Explain the Pass arrays to a function in C
➢ In C programming, you can pass an entire array to functions.
➢ To pass array to a function, only the name of the array is passed to the function (similar to one-dimensional
arrays).
Example Program:
// Program to calculate the sum of array elements by passing to a function
#include <stdio.h>
float calculateSum(float num[]);
int main()
{
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
// num array is passed to calculateSum()
result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float num[]) {
float sum = 0.0;
for (int i = 0; i < 6; ++i) {
73

sum += num[i];
}
return sum;
}
Output:
Result = 162.50
Explanation:
To pass an entire array to a function, only the name of the array is passed as an argument.
result = calculateSum(num);
However, notice the use of [] in the function definition.
float calculateSum(float num[])
{
... ..
}
This informs the compiler that you are passing a one-dimensional array to the function.
Q 8. Explain Pass Multidimensional Arrays to a Function in C.
➢ To pass multidimensional arrays to a function, only the name of the array is passed to the function (similar to
one-dimensional arrays).
Example Program:
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main() {
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
scanf("%d", &num[i][j]);
}
}
// pass multi-dimensional array to a function
displayNumbers(num);
return 0;
}
void displayNumbers(int num[2][2]) {
printf("Displaying:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
printf("%d\n", num[i][j]);
}
}
}
74

Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5
Explanation:
➢ Note the parameter int num[2][2] in the function prototype and function definition:
// function prototype
void displayNumbers(int num[2][2]);
➢ This signifies that the function takes a two-dimensional array as an argument. We can also pass arrays with
more than 2 dimensions as a function argument.
➢ When passing two-dimensional arrays, it is not mandatory to specify the number of rows in the array.
However, the number of columns should always be specified.
For example,
void displayNumbers(int num[][2])
{
// code
}
Q 9. Explain the Scope of Variables in C?
➢ The availability of a variable in a program or function is referred to as the scope of variable in C language.
➢ A variable, for example, may be accessed only within a single function/block of code (your apartment key) or
throughout the whole C program (the shared access key).
➢ We can associate the room keys with the local variables in C language because they only work in that single
room. The term global variables refers to variables (keys) that are accessible to the whole program
(apartment complex).
Q 10. Define local and global variables.
Local Variable:
➢ Local variable is declared inside a function.
➢ Local variables are created when the function has started execution and is lost when the function terminates.
➢ If a value of local variable is updated, it will effect within that function only.
Example:
#include <stdio.h>
int main()
{
int x = 30;
75

printf("\nValue of x is %d\n", x);


{
int x = 20;
printf("\n\tValue of x is %d\n", x);
{
int x = 10;
printf("\n\t\tValue of x is %d\n\n", x);
}
}
return 0;
}
Output:
Value of x is 30
Value of x is 20
Value of x is 10
Global Variable:
➢ Global variable is declared outside the function.
➢ Global variable is created as execution starts and is lost when the program ends.
➢ If a value of global variable updated, it will effect on entire program.
Example:
#include <stdio.h>
int x=300;
int main()
{
printf("\nValue of x is %d\n", x);
{
int x = 20;
printf("\n\tValue of x is %d\n", x);
{
printf("\n\t\tValue of x is %d\n\n", x);
}
}
return 0;
}
Output:
Value of x is 300
Value of x is 20
Value of x is 20
Q 11. Write short note on return statement.
➢ return statement will return a value to the calling function and control is transfers from called to calling
function.
Syntax:
return <value>;
Example:
return 0;
76

Q 12. Define storage class. What are the storage classes in C. Explain with example?
➢ Storage classes are used to define storage location (whether RAM or Register), scope, lifetime and the default
value of a variable.
➢ In C language, there are FOUR storage classes and they are as follows:
1. auto storage class
2. static storage class
3. register storage class
4. extern storage class
1. auto storage class:
➔ The default storage class of all local variables (variables declared inside block or function) is auto storage
class.
➔ Variable of auto storage class has the following properties:
77

2. static storage class:

➔ The static storage class is used to create variables that hold value beyond its scope until the end of the
program.
➔ The static variable allows to initialize only once and can be modified any number of times.
➔ Variable of static storage class has the following properties:
78

3. register storage class:

➔ The register storage class is used to specify the memory of the variable that has to be allocated in CPU
Registers.
➔ The register variables enable faster accessibility compared to other storage class variables.
➔ As the number of registers inside the CPU is very less we can use very less number of register variables.
➔ Variable of register storage class has the following properties:
79

4. extern storage class:

➔ The default storage class of all global varibles (variables declared outside function) is external storage class.
➔ Variable of external storage class has the following properties:
80

Q 13 . Describe file handling in C language?

➔ File handing in C is the process in which we create, open, read, write, and close operations on a file.
➔ C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform
input, output, and many different C file operations in our program.

Q 14. Define Why do we need File Handling in C?

➔ The operations using the C program are done on a prompt/terminal which is not stored anywhere.
➔ The output is deleted when the program is closed. But in the software industry, most programs are written to
store the information fetched from the program.
➔ The use of file handling is exactly what the situation calls for.
➔ In order to understand why file handling is important, a few features of using files:

Reusability: The data stored in the file can be accessed, updated, and deleted anywhere and anytime providing high
reusability.

Portability: Without losing any data, files can be transferred to another in the computer system. The risk of flawed
coding is minimized with this feature.

Efficient: A large amount of input may be required for some programs. File handling allows you to easily access a part
of a file using few instructions which saves a lot of time and reduces the chance of errors.

Storage Capacity: Files allow you to store a large amount of data without having to worry about storing everything
simultaneously in a program.

Q 15. Explain different types of Files in C

A file can be classified into two types based on the way the file stores the data. They are as follows:

1. Text Files
2. Binary Files

1. Text Files

A text file contains data in the form of ASCII characters and is generally used to store a stream of characters.

• Each line in a text file ends with a new line character (‘\n’).
• It can be read or written by any text editor.
• They are generally stored with .txt file extension.
• Text files can also be used to store the source code.
81

2. Binary Files

A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters. They contain data that is stored
in a similar manner to how it is stored in the main memory.

• The binary files can be created only from within a program and their contents can only be read by a program.
• More secure as they are not easily readable.
• They are generally stored with .bin file extension.

Q 16. Explain File Operations in C.

The different possible operations that we can perform on a file in C such as:

➔ Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
➔ Opening an existing file – fopen()
➔ Reading from file – fscanf() or fgets()
➔ Writing to a file – fprintf() or fputs()
➔ Moving to a specific location in a file – fseek(), rewind()
➔ Closing a file – fclose()
82

Q 17. Define a file pointer in C.

A file pointer is a reference to a particular position in the opened file. It is used in file handling to perform all file
operations such as read, write, close, etc. We use the FILE macro to declare the file pointer variable. The FILE macro is
defined inside <stdio.h> header file.

Syntax of File Pointer

FILE* pointer_name;

File Pointer is used in almost all the file operations in C.

Q 18. Explain how to open a file and File opening modes in C language.

The fopen() function is used with the filename or file path along with the required access modes.

Syntax of fopen()

FILE* fopen(const char *file_name, const char *access_mode);

Parameters

file_name: name of the file when present in the same directory as the source file. Otherwise, full path.

Access_mode: Specifies for what operation the file is being opened.

Return Value

If the file is opened successfully, returns a file pointer to it.

If the file is not opened, then returns NULL.

File opening modes

File opening modes or access modes specify the allowed operations on the file to be opened. They are passed as an
argument to the fopen() function. Some of the commonly used file access modes are listed below:

Opening
Modes Description

Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that
r
points to the first character in it. If the file cannot be opened fopen( ) returns NULL.

rb Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL.

Open for writing in text mode. If the file exists, its contents are overwritten. If the file doesn’t exist, a new
w
file is created. Returns NULL, if unable to open the file.

Open for writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it
wb
will be created.
83

Opening
Modes Description

Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that
a points to the last character in it. It opens only in the append mode. If the file doesn’t exist, a new file is
created. Returns NULL, if unable to open the file.

Open for append in binary mode. Data is added to the end of the file. If the file does not exist, it will be
ab
created.

Searches file. It is opened successfully fopen( ) loads it into memory and sets up a pointer that points to
r+
the first character in it. Returns NULL, if unable to open the file.

rb+ Open for both reading and writing in binary mode. If the file does not exist, fopen( ) returns NULL.

Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created.
w+
Returns NULL, if unable to open the file.

Open for both reading and writing in binary mode. If the file exists, its contents are overwritten. If the file
wb+
does not exist, it will be created.

Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that
a+ points to the last character in it. It opens the file in both reading and append mode. If the file doesn’t exist,
a new file is created. Returns NULL, if unable to open the file.

ab+ Open for both reading and appending in binary mode. If the file does not exist, it will be created.

Q 19. Explain briefly about file handling functions in C language .

There are many functions in the C library to open, read, write, search and close the file. A list of file functions are
given

S.No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file


84

7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

You might also like