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

UNIT 1

Problem Solving Using Computers


1.1 Problem Definition
1.2 Problem Analysis
1.3 Algorithm Development & Flowcharting
1.4 Coding
1.5 Compilation, Debugging & Execution
1.6 Testing
1.7 Program Documentation

Problem Solving Using Computer

Computer based problem solving is a systematic process of designing, implementing and using programming tools
during the problem solving stage. This method enables the computer system to be more intuitive with human logic
than machine logic. Final outcome of this process is software tools which is dedicated to solve the problem under
consideration. Software is just a collection of computer programs and programs are a set of instructions which
guides computer’s hardware. These instructions need to be well specified for solving the problem. After its creation,
the software should be error free and well documented. Software development is the process of creating such
software, which satisfies end user’s requirements and needs.

The following six steps must be followed to solve a pr oblem using computer.

Problem Analysis

Program Design - Algorithm, Flowchart and Pseudocode

Coding

Compilation and Execution

Debugging and Testing

Program Documentation

Problem Analysis
Problem: -Problem is defined as the difference between an existing situation and a desired situation.
-If a problem is solved by using machine called computer, then such process is called Problem Solving using
Computer.
-Before solving any problem you must first try to solve it manually. Unless you have a clear understanding of
problem and the steps that should be followed to reach the solution you cannot solve the problem using machine. So,
first try to get clear idea about the problem.

Steps for problem solving:


1.Determine the nature of problem ( type of computation required ex: whether you need to perform addition or
multiplication or both)
2.Apply each steps properly ( do not carry out the steps in wrong order ex: If addition has to be done before
multiplication then do so and do not change their order else incorrect result might appear)
3.To ensure that everything happens in order, plan the program before writing it b) (ex: preparing Algorithm and
flowchart before beginning program execution)

Algorithm development and Flowchart


Algorithm -Sequence of instructions designed in such a way that if the instructions are executed in the specified
sequence, the desired result will be obtained. -In simple words, algorithm is the step that you should follow to solve
a problem.
For ex: Your mother wants you to go to the market and bring a chicken. What will be its steps?
Step1: You will take the money
Step2: You will go to the market
Step3: You will buy the chicken
Step4: You will come back home

Characteristics of Algorithm
1)Each and every instruction should be precise and unambiguous (clear)
2)Each instruction should be such that it can be performed in a finite time
3)One or more instruction should not be repeated infinitely. This ensures that the algorithm will ultimately terminate
4)After performing the instructions, that is after the algorithm terminates, the desired results must be obtained.

Problem : The attendance sheet of your class is given to you. Only those students with attendance of 70% or above
are qualified to att end final examination (for them print ‘Q’ ) else print ‘NQ’. Write an algorithm to check whether
a student is Qualified or not [Assume Total days of class as ‘TotalClass’]
Hint: Assume the total days a student is present as ‘TotalPresent’ Calculate the PresentPercentage of student :
(TotalPresent / TotalClass)*100% If (PresentPercentage >= 70 ) print ‘Q’ else print ‘NQ’
Solution Step1: Start
Step2: Get the attendance of a student as ‘TotalPresent’
Step3: Calculate the ‘PresentPercentage’ as (TotalPresent/TotalClass) * 100%
Step4: If (PresentPercentage >= 70% ) print ‘Q’ Else print ‘NQ’
Step5: Stop

Problem: Write an algorithm to check whether a number entered by user is odd or even [075 Ashwin]
[Hint: If the number is divisible by 2 then its even else it is odd]

Importance of Algorithm:
a)Gives the idea about problem and solution
b)Easy to implement an algorithm rather than starting from scratch
c)Proper Utilization of resources
d)Writing algorithm improves thinking and reasoning abilities.

Flowchart
-A flowchart is a pictorial representation of an algorithm that uses boxes of different shapes to denote different
types of instructions.
-The actual instructions are written within these boxes using clear and concise statements.
-These boxes are connected by solid lines having arrow marks to indicate the flow of operation.
Normally, an algorithm is first represented in the form of a flowchart and the flowchart is then expressed in some
programming language to prepare a computer program.
Since a flowchart shows the flow of operations in pictorial form, any error in the logic of the procedure can be
detected more easily.

Guidelines to draw Flowchart


1)Each flowchart must have one and only one Start object.
2)The flow of control must always enter an object from the top.
3)The flow of control must always leave an object from the bottom (except for Decision objects, which allow the
flow of control to leave from the side).
4)The flow of control must not split.
Advantages of Flowchart
1)Improved Communication: Flowchart empowers entire teams to collaborate as they create, edit, and analyze
flowcharts
2)Visual Clarity: People often can’t spend the necessary time reading complicated documents. Flowcharts can
bring clarity to concepts that are otherwise difficult to understand.
3)Effective Analysis: The flowcharts can help you visually identify problems.
4)Problem Solving: After identifying a potential problem, programmers can know in which places they need to
modify their code.
5)Documentation: Flowcharts may prove useful for simplifying otherwise difficult procedures.
Flowchart Symbols

Terminal: The terminal symbol is used to indicate the beginning (START) and ending (STOP). It is the first symbol
and last symbol in the program logic.

Input/Output: If there is a program instruction to input data from a disk, cardreader, or any other type of input
device, that step will be indicated in the flowchart with an input/output symbol. Similarly, all output instructions
whether it is output on a printer, magnetic tape, terminal screen or any output device, are indicated in the flowchart
with an input/output symbol.

Processing: A processing symbol is used in a flowchart to represent arithmetic and data movement instructions.
Adding, subtracting, multiplying and dividing are shown by a processing symbol.

Flowlines: Flow lines with arrowheads are used to indicate the flow of operations. The normal flow of flowchart is
from top to bottom and left to right. Flow lines should not cross each other.

Decision: The decision symbol is used in a flowchart to indicate a point at which a decision has to be made and a
branch to one of two or more alternative points is possible. The criteria for making the decision should be indicated
clearly within the decision box.

Connector: Whenever a flowchart becomes complex enough that the direction of flowlines is confusing or it
spreads over more than one page, it is useful to utilize the connector symbol

Problem: A student appeared in semester examination. There were total 5 subjects and the total marks of each
subject was 100. Take the input data(marks of each subject), calculate the percentage and display output using
Flowchart.
[Hint: To calculate the percentage : First calculate total marks obtained ‘TotalMarksObtained’ (TMO) Then
calculate the total full marks ‘TotalFullMarks’ (TFM) Now calculate percentage as : Percentage = (TMO / TFM) *
100% ]
Problem: Draw a flowchart to check whether a number entered by user is even or odd. (assignment no .1)

Compilation and Execution


Compilation: The compilation is a process of converting the source code into object code. It is done with the help
of the compiler. The compiler checks the source code for the syntactical errors, and if the source code is error-free,
then it generates the object code.

The compilation process can be divided into four steps, i.e., Pre-processing, Compiling, Assembling, and Linking.
Pre-processing: This source code is first passed to the preprocessor, and then the preprocessor expands this code.
After expanding the code, the expanded code is passed to the compiler.

Compiling: The compiler converts the pre-processed code into assembly code.

Assembling: The assembly code is converted into object code by using an assembler.If the name of the source file is
'hello.c', then the name of the object file would be 'hello.obj'.

Linking: Mainly, all the programs written in C use library functions.The main working of the linker is to combine
the object code of library files with the object.

Execution: After the creation of an object code, the linker creates the executable file. The loader will then load the
executable file for the execution.

Testing and Debugging


Debugging The process of finding and removing errors (also sometimes called buggs) from a program is known as
debugging
One simple method of debugging is to place print statements throughout the program to display the values of
variables. It displays the dynamics of a program and allows us to examine and compare the information at various
points. Once the location of an error is identified and the error is corrected, the debugging statements may be
removed.
Generally programmers commit three types of errors.They are
1.Syntax errors: -A syntax error is an error in the syntax. -Each function has its own rules, for ex: printf function
requires text written inside ” ” which is present inside ( ). If any character is missed then it is called syntax error
2.Logic errors: -A logic error (or logical error) is a mistake in a program's source code that results in incorrect or
unexpected behavior. -Ex: To calculate avg of 3 numbers we need to add three numbers and then divide the result by
3. But, if a programmer divides the result by 2 instead of 3 then it is logical error
3.Run-time errors: -A runtime error is a program error that occurs while the program is running -Ex:Divide by zero
Null pointer assignment Data over flow.

Testing
-Testing is the process of reviewing and executing a program with the intent of detecting errors.
-Testing can be done manually and computer based testing.
-Manual testing includes code inspection by the programmer, code inspection by a test group and a review by a peer
group.
-Computer based testing is done by computer with the help of compiler.

Programming Documentation
Any written text, illustrations or video that describe a software or program to its users is called programming
documentation. User can be anyone from a programmer, system analyst and administrator to end user.
These are some guidelines for creating the documents −
1)Documentation should be from the point of view of the reader
2)Document should be unambiguous
3)There should be no repetition
4)Industry standards should be used
5)Documents should always be updated
Advantages of Documentation These are some of the advantages of providing program documentation –
1)Keeps track of all parts of a software or program
2)Maintenance is easier
3)Programmers other than the developer can understand all aspects of software
4)Improves overall quality of the software.
Unit -2
2.1 Historical Development of C
2.2 Importance of C
2.3 Basic Structure of C Programs
2.4 Executing a C Program

History of C language
The base or father of programming languages is ‘ALGOL.’ It was first introduced in 1960. ‘ALGOL’ was used on a
large basis in European countries. ‘ALGOL’ introduced the concept of structured programming to the developer
community. In 1967, a new computer programming language was announced called as ‘BCPL’ which stands for
Basic Combined Programming Language. BCPL was designed and developed by Martin Richards, especially for
writing system software. This was the era of programming languages. Just after three years, in 1970 a new
programming language called ‘B’ was introduced by Ken Thompson that contained multiple features of ‘BCPL.’
This programming language was created using UNIX operating system at AT&T and Bell Laboratories. Both the
‘BCPL’ and ‘B’ were system programming languages.

In 1972, a great computer scientist Dennis Ritchie created a new programming language called ‘C’ at the Bell
Laboratories. It was created from ‘ALGOL’, ‘BCPL’ and ‘B’ programming languages. ‘C’ programming language
contains all the features of these languages and many more additional concepts that make it unique from other
languages.

‘C’ is a powerful programming language which is strongly associated with the UNIX operating system. Even most
of the UNIX operating system is coded in ‘C’. Initially ‘C’ programming was limited to the UNIX operating system,
but as it started spreading around the world, it became commercial, and many compilers were released for cross-
platform systems. Today ‘C’ runs under a variety of operating systems and hardware platforms. As it started
evolving many different versions of the language were released. At times it became difficult for the developers to
keep up with the latest version as the systems were running under the older versions. To assure that ‘C’ language
will remain standard, American National Standards Institute (ANSI) defined a commercial standard for ‘C’ language
in 1989. Later, it was approved by the International Standards Organization (ISO) in 1990. ‘C’ programming
language is also called as ‘ANSI C’.
Languages such as C++/Java are developed from ‘C’. These languages are widely used in various technologies.
Thus, ‘C’ forms a base for many other languages that are currently in use.
Why is C so popular

 One of the early programming languages.


 Still, the best programming language to learn quickly.
 C language is reliable, simple, and easy to use.
 C language is a structured language.
 Modern programming concepts are based on C.
 It can be compiled on a variety of computer p latforms.
 Universities preferred to add C programming to their courseware.

Features of C Programming Language

 C is a robust language with a rich set of built-in functions and operators.


 Programs written in C are efficient and fast.
 C is highly portable; programs once written in C, can be run on other machines with minor or no
modification.
 C is a collection of C library functions; we can also create our function and add it to the C library.
 C is easily extensible.

Advantages of C

 C is the building block for many other programming languages.


 Programs written in C are highly portable.
 Several standard functions are there (like in-built) that can be used to develop C programs.
 C programs are collections of C library functions, and it's also easy to add functions to the C library.
 The modular structure makes code debugging, maintenance, and testing easier.

Disadvantages of C

 C does not provide Object Oriented Programming (OOP) concepts.


 There are no concepts of Namespace in C.
 C does not provide binding or wrapping up of data in a single unit.
 C does not provide Constructor and Destructor.

The limitations of C programming languages are as follows:

 Difficult to debug.
 C allows a lot of freedom in writing code, and that is why you can put an empty line or white space
anywhere in the program. And because there is no fixed place to start or end the line, so it isn't easy to read
and understand the program.
 C compilers can only identify errors and are incapable of handling exceptions (run-time errors).
 C provides no data protection.
 It also doesn't feature the reusability of source code extensively.
 It does not provide strict data type checking (for example, an integer value can be passed for floating
datatype).

Where is C used? Key Applications

1. ‘C’ language is widely used in embedded systems.


2. It is used for developing system applications.
3. It is widely used for developing desktop applications.
4. Most of the applications by Adobe are developed using ‘C’ programming language.
5. It is used for developing browsers and their extensions. Google’s Chromium is built using ‘C’
programming language.
6. It is used to develop databases. MySQL is the most popular database software which is built using ‘C’.
7. It is used in developing an operating system. Operating systems such as Apple’s OS X, Microsoft’s
Windows, and Symbian are developed using ‘C’ language. It is used for developing desktop as well as
mobile phone’s operating system.
8. It is used for compiler production.
9. It is widely used in IOT applications.

Why to learn C Language?


As we studied earlier, ‘C’ is a base language for many programming languages. So, learning ‘C’ as the main
language will play an important role while studying other programming languages. It shares the same concepts such
as data types, operators, control statements and many more. ‘C’ can be used widely in various applications. It is a
simple language and provides faster execution. There are many jobs av ailable for a ‘C’ developer in the current
market.

‘C’ is a structured programming language in which program is divided into various modules. Each module can be
written separately and together it forms a single ‘C’ program. This structure makes it easy for testing, maintaining
and debugging processes.

‘C’ contains 32 keywords, various data types and a set of powerful built-in functions that make programming very
efficient.

Another feature of ‘C’ programming is that it can extend itself. A ‘C’ program contains various functions which are
part of a library. We can add our features and functions to the library. We can access and use these functions
anytime we want in our program. This feature makes it simple while working with complex programming.

Various compilers are available in the market that can be used for executing programs written in this language.

It is a highly portable language which means programs written in ‘C’ language can run on other machines. This
feature is essential if we wish to use or execute the code on another computer.

How C Programming Language Works?


C is a compiled language. A compiler is a special tool that compiles the program and converts it into the object file
which is machine readable. After the compilation process, the linker will combine different object files and creates a
single executable file to run the program. The following diagram shows the execution of a ‘C’ program
Nowadays, various compilers are available online, and you can use any of those compilers. The functionality will
never differ and most of the compilers will provide the features required to execute both ‘C’ and ‘C++’ programs.

Following is the list of popular compilers available online:

 Clang compiler
 MinGW compiler (Minimalist GNU for Windows)
 Portable ‘C’ compiler
 Turbo C

C Basic Commands
Following are the basic commands in C programming language:

C Basic commands Explanation


#include <stdio.h> This command includes standard input output header file(stdio.h) from the C library before
compiling a C program
int main() It is the main function from where C program execution begins.
{ Indicates the beginning of the main function.
/*_some_comments_*/ Whatever written inside this command “/* */” inside a C program, it will not be considered for
compilation and execution.
printf(“Hello_World!
This command prints the output on the screen.
“);
getch(); This command is used for any character input from keyboard.
return 0; This command is used to terminate a C program (main function) and it returns 0.
} It is used to indicate the end of the main function.

Beginning with C programming:

Writing the First Program in C

The following code is one of the simplest C programs that will help us the basic syntax structure of a C program.

Example:

#include <stdio.h>

int main() {

int a = 10;
printf("%d", a);

return 0;

Output:

10

Structure of the C program

Structure of a C program

After the above example, we can formally assess the structure of a C program. By structure, it is meant that any
program can be written in this structure only. Writing a C program in any other structure will hence lead to a
Compilation Error. The structure of a C program is as follows:

Components of a C Program:

The first and foremost component is the inclusion of the Header files in a C program.

1. Header Files Inclusion – Line 1 [#include <stdio.h>]


A header file is a file with extension .h which contains C function declarations and macro definitions to be shared
between several source files.

All lines that start with ## are processed by a preprocessor which is a program invoked by the compiler.

In the above example, the preprocessor copies the preprocessed code of stdio.h to our file. The .h files are called
header files in C.
Some of the C Header files:

stddef.h – Defines several useful types and macros.

stdint.h – Defines exact width integer types.

stdio.h – Defines core input and output functions

stdlib.h – Defines numeric conversion functions, pseudo-random network generator, and memory allocation

string.h – Defines string handling functions

math.h – Defines common mathematical functions.

2.Main Method Declaration – Line 2 [int main()]


. Main Method Declaration – Li

The next part of a C program is to declare the main() function.

It is the entry point of a C program and the execution typically begins with the first line of the main().

The empty brackets indicate that the main doesn’t take any parameter.

The int that was written before the main indicates the return type of main().

The value returned by the main indicates the status of program termination. 3. Bo

3. Body of Main Method – Line 3 to Line 6 [enclosed in {}]


Main Method – Line 3 to Line 6 [enclosed in {}]

The body of a function in the C program refers to statements that are a part of that function.

It can be anything like manipulations, searching, sorting, printing, etc.

A pair of curly brackets define the body of a function. All functions must start and end with curly brackets.

4. Statement –

4. Statement – Line 4 [printf(“Hello World”);]


lo World”);]

Statements are the instructions given to the compiler. In C, a statement is always terminated by a semicolon (;).

In this particular case, we use printf() function to instruct the compiler to display “Hello World” text on the screen.

5. Return Statement – Line 5 [return 0;]


– Line 5 [return 0;]
The last part of any C function is the return statement. The return statement refers to the return values from a
function. This return statement and return value depend upon the return type of the function. The return statement in
our program returns the value from main(). The returned value may be used by an operating system to know the
termination status of your program. The value 0 typically means successful termination.

How to Execute the Above Program?


?

In order to execute the above program, we need to first compile it using a compiler and then we can run the
generated executable. There are online IDEs available for free, that can be used to start development in C without
installing a compiler.

1. Windows : There are many free IDEs available for developing programs in C like Code Blocks and Dev-CPP.
IDEs provide us with an environment to develop code, compile it and finally execute it. We strongly recommend
Code Blocks.

2. Linux: GCC compiler comes bundled with Linux which compiles C programs and generates executables for us to
run. Code Blocks can also be used with Linux.

3. macOS : macOS already has a built-in text editor where you can just simply write the code and save it with a
“.c” extension.

Application of C

 Operating systems: C is widely used for developing operating systems such as Unix, Linux, and Windows.
 Embedded systems: C is a popular language for developing embedded systems such as microcontrollers,
microprocessors, and other electronic devices.
 System software: C is used for developing system software such as device drivers, compilers, and
assemblers.
 Networking: C is widely used for developing networking applications such as web servers, network
protocols, and network drivers.
 Database systems: C is used for developing database systems such as Oracle, MySQL, and PostgreSQL.
 Gaming: C is often used for developing computer games due to its ability to handle low-level hardware
interactions.
 Artificial Intelligence: C is used for developin g artificial intelligence and machine learning applications
such as neural networks and deep learning algorithms.
 Scientific applications: C is used for developing scientific applications such as simulation software and
numerical analysis tools.
 Financial applications: C is used for developing financial applications such as stock market analysis and
trading systems.

Structure
Unit -3
3.1 Character Set
3.2 Identifiers & Keywords
3.3 Data Types and modifier
3.4 Constants, Variables
3.5 Declarations and initialization of variables
3.6 Escape Sequences
3.7 Preprocessors Directives
3.8 typedef statement
3.9 Symbolic Constants

Character Set Character Set:


 Like every other language, ‘C’ also has its own character set.
 A program is a set of instructions that, when executed, generate an output.
 The data that is processed by a program consists of various characters and
symbols.
 The output generated is also a combination of characters and symbols.

A compiler always ignores the use of characters, but it is widely used for
formatting the data. Following is the character set in ‘C’ programming. A
character set in is divided into the following types:

A compiler always ignores the use of characters, but it is widely used for
formatting the data. Following is the character set in ‘C’ programming:
 All the lowercase and uppercase characters from A to Z.
 All the digits from 0 to 9.
 Such as Blank space, Newline, Carriage return, and Horizontal tab.
 Special Characters
Keywords and Identifiers:
In ‘C’ every word can be either a keyword or an identifier.
Keywords have fixed meanings, and the meaning cannot be changed. They act as
a building block of a ‘C’ program. There are a total of 32 keywords in ‘C’.
Keywords are written in lowercase letters.
An identifier is nothing but a name assigned to an element in a program.
Example: name of a variable, function, etc.
Identifiers are the user-defined names consisting of the ‘C’ standard character set.
As the name says, identifiers are used to identify a particular element in a
program.
Each identifier must have a unique name.
Following rules must be followed for identifiers:
 The first character must always be an alphabet or an underscore.
 It should be formed using only letters, numbers, or underscore.
 A keyword cannot be used as an identifier.
 It should not contain any white space character.
 The name must be meaningful.

Summary:
 A token is the smallest unit in a program.
 A keyword is reserved words by language.
 There is a total of 32 keywords.
 An identifier is used to identify elements of a program.

Tokens in C
A token in C can be defined as the smallest individual element of the C
programming language that is meaningful to the compiler. It is the basic
component of a C program.

Types of Tokens in C
The tokens of C language can be classified into six types based on the functions
they are used to perform. The types of C tokens are as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators

1. C Token – Keywords
The keywords are pre-defined or reserved words in a programming language.
Each keyword is meant to perform a specific function in a program. Since
keywords are referred names for a compiler, they can’t be used as variable names
because by doing so, we are trying to assign a new meaning to the keyword which
is not allowed. You cannot redefine keywords. However, you can specify the text
to be substituted for keywords before compilation by using C preprocessor
directives. C language supports 32 keywords which are given below:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

2. C Token – Identifiers
Identifiers are used as the general terminology for the naming of variables,
functions, and arrays. These are user-defined names consisting of an arbitrarily
long sequence of letters and digits with either a letter or the underscore(_) as a
first character. Identifier names must differ in spelling and case from any
keywords. You cannot use keywords as identifiers; they are reserved for special
use. Once declared, you can use the identifier in later program statements to
refer to the associated value. A special kind of identifier called a statement label
can be used in goto statements.

Rules for Naming Identifiers


Certain rules should be followed while naming c identifiers which are as follows:
They must begin with a letter or underscore(_).
They must consist of only letters, digits, or underscore. No other special character
is allowed.
It should not be a keyword.
It must not contain white space.
It should be up to 31 characters long as only the first 31 characters are significant.
For example,
main: method name.
a: variable name.

3. C Token – Constants
The constants refer to the variables with fixed values. They are like normal
variables but with the difference that their values cannot be modified in the
program once they are defined. Constants in C refer to fixed values that program
cannot change during the time of execution. Constants are also known as literals. A
constant can be of any data type like character constant, integer constant, string
constant etc.
For Example : 'A', 1234, 123.5, "TechCrashCourse"

C Constants are like normal variables, the only difference is, their values cannot be
changed by the program once they are defined.

Types of Constants in C
 Integer constants
 Character Constants
 Backslash Character Constants
 Integer Constants
 Floating Point Constants
 String Constants

Constants may belong to any of the data types.


Examples of Constants in C
const int c_var = 20;
const int* const ptr = &c_var;

4. C Token – Strings
Strings are nothing but an array of characters ended with a null character (‘\0’).
This null character indicates the end of the string. Strings are always enclosed in
double quotes. Whereas, a character is enclosed in single quotes in C and C++.
Examples of String
char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
char string[20] = “geeksforgeeks”;
char string [] = “geeksforgeeks”;

5. C Token – Special Symbols


The following special symbols are used in C having some special meaning and
thus, cannot be used for some other purpose. Some of these are listed below:
Brackets[]: Opening and closing brackets are used as array element references.
These indicate single and multidimensional subscripts.
Parentheses(): These special symbols are used to indicate function calls and
function parameters.
Braces{}: These opening and ending curly braces mark the start and end of a block
of code containing more than one executable statement.
Comma (, ): It is used to separate more than one statement like for separating
parameters in function calls.
Colon(:): It is an operator that essentially invokes something called an
initialization list.
Semicolon(;): It is known as a statement terminator. It indicates the end of one
logical entity. That’s why each individual statement must be ended with a
semicolon.
Asterisk (*): It is used to create a pointer variable and for the multiplication of
variables.
Assignment operator(=): It is used to assign values and for logical operation
validation.
Pre-processor (#): The preprocessor is a macro processor that is used
automatically by the compiler to transform your program before actual
compilation.
Period (.): Used to access members of a structure or union.
Tilde(~): Used as a destructor to free some space from memory.

6. C Token – Operators
Operators are symbols that trigger an action when applied to C variables and
other objects. The data items on which operators act are called operands.
Depending on the number of operands that an operator can act upon, operators
can be classified as follows:
Unary Operators: Those operators that require only a single operand to act upon
are known as unary operators. For Example increment and decrement operators
Binary Operators: Those operators that require two operands to act upon are
called binary operators. Binary operators can further are classified into:
Arithmetic operators
Relational Operators
Logical Operators
Assignment Operators
Bitwise Operator
Ternary Operator: The operator that requires three operands to act upon is called
the ternary operator. Conditional Operator(?) is also called the ternary operator.

Variables:
 A variable is an identifier that is used to store some value.
 Constants can never change at the time of execution.
 Variables can change during the execution of a program and update the
value stored inside it.
 A single variable can be used at multiple locations in a program.
 A variable name must be meaningful.
 It should represent the purpose of the variable.
Example: Height, age, are the meaningful variables that represent the
purpose it is being used for.
Height variable can be used to store a height value.
The age variable can be used to store the age of a person.
 A variable must be declared first before it is used somewhere inside the
program.
 A variable name is formed using characters, digits, and an underscore.

Local variable in C
 A local variable is declared inside a function.
 A local variable is visible only inside their function, only statements inside
function can access that local variable.
 Local variables are declared when control enters a function and local
variables gets destroyed, when control exits from function.

Global variable in C
 Global variables are declared outside of any function.
 A global variable is visible to any every function and can be used by any
piece of code.
 Unlike local variable, global variables retain their values between function
calls and throughout the program execution.

Following are the rules that must be followed while creating a variable:
 A variable name should consist of only characters, digits, and an
underscore.
 A variable name should not begin with a number.
 A variable name should not consist of white space.
 A variable name should not consist of a keyword.
 ‘C’ is a case-sensitive language that means a variable named ‘age’ and
‘AGE’ are different.

Data types: ‘C’ provides various data types to make it easy for a programmer to
select a suitable data type as per the requirements of an application. Following
are the three data types:
 Primitive data types
 Derived data types
 User-defined data types

The following are five primary fundamental data types:


 int for integer data
 char for character data
 float for floating-point numbers
 double for double-precision floating-point numbers
 void
Derived Data types:
 Array, functions, pointers, structures are derived data types.
 C language provides more extended versions of the above-mentioned
primary data types.
 Each data type differs from one another in size and range.
 The following table displays the size and range of each data type:
Datatypes Size Range

char or signed char 1 -128 to 127

unsigned char 1 0 to 255

int or signed int 2 -32768 to 32767

unsigned int 2 0 to 65535

short int or Unsigned short int 2 0 to 255

signed short int 2 -128 to 127

long int or Signed long int 4 -2147483648 to 2147483647

unsigned long int 4 0 to 4294967295

float 4 3.4E-38 to 3.4E+38

Modifier
Modifiers are keywords in c which changes the meaning of basic data type in c. It
specifies the amount of memory space to be allocated for a variable. Modifiers are
prefixed with basic data types to modify the memory allocated for a variable.
There are five data type modifiers in C Programming Language:
 long
 short
 signed
 unsigned

Declarations and initialization of variables


Declaration of a variable in a computer programming language is a statement used
to specify the variable name and its data type. Declaration tells the compiler about
the existence of an entity in the program and its location. When you declare a
variable, you should also initialize it.

Initialization is the process of assigning a value to the Variable. Every


programming language has its own method of initializing the variable. If the value
is not assigned to the Variable, then the process is only called a Declaration.

Basic Syntax

The basic form of declaring a variable is:

type identifier [= value] [, identifier [= value]]…];

OR

data_type variable_name = value;

where,

type = Data type of the variable

identifier = Variable name

value = Data to be stored in the variable (Optional field)

Note 1: The Data type and the Value used to store in the Variable must match.

Note 2: All declaration statements must end with a semi-colon (;)

int a, b, c; // declare 3 variables.

int z = 35; // declare and initialize variable z with value 35.

double pi = 3.14159; // declare an approximation of pi.

char x, y = ‘y’, z; // declare 3 variables, initialize char y with value ‘y’.


char str[30]; // declare an array named ‘str’ which holds 30 characters.

Rules to Declare and Initialize Variables

There are few conventions needed to be followed while declaring and assigning
values to the Variables –

1. Variable names must begin with a letter, underscore, non-number character.


Each language has its own conventions.
2. Few programming languages like PHP, Python, Perl, etc. do not require to
specify data type at the start.
3. Always use the ‘=’ sign to initialize a value to the Variable.
4. Do not use a comma with numbers.
5. Once a data type is defined for the variable, then only that type of data can be
stored in it. For example, if a variable is declared as Int, then it can only store
integer values.
6. A variable name once defined can only be used once in the program. You cannot
define it again to store another type of value.
7. If another value is assigned to the variable which already has a value assigned to
it before, then the previous value will be overwritten by the new value.

Types of Initialization

1. Static Initialization –

In this method, the variable is assigned a value in advance. Here, the values are
assigned in the declaration statement. Static Initialization is also known as Explicit
Initialization.

Example –

int a;
a = 5;

int b = 10;

int x = 4, y = 5;

2. Dynamic Initialization –

In this method, the variable is assigned a value at the run-time. The value is either
assigned by the function in the program or by the user at the time of running the
program. The value of these variables can be altered every time the program runs.
Dynamic Initialization is also known as Implicit Initialization.

Example –

int speed;

printf("Enter the value of speed");

scanf("%d", &speed);

Escape Sequence in C
An escape sequence in C language is a sequence of characters that doesn't
represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n


represents new line.

List of Escape Sequences in C

Escape Sequence Meaning

\a Alarm or Beep
\b Backspace

\f Form Feed

\n New Line

\r Carriage Return

\t Tab (Horizontal)

\v Vertical Tab

\\ Backslash

\' Single Quote

\" Double Quote

\? Question Mark

\nnn octal number

\xhh hexadecimal number

\0 Null

Escape Sequence Example

#include<stdio.h>
int main(){
int number=50;
printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");
return 0; }

Output:

You
are
learning
'c' language
"Do you know C language"

Preprocessors Directives
The C Preprocessor is not a part of the compiler, but is a separate step in the
compilation process. In simple terms, a C Preprocessor is just a text substitution
tool and it instructs the compiler to do required pre-processing before the actual
compilation. We'll refer to the C Preprocessor as CPP.
The C preprocessor is a macro preprocessor (allows you to define macros) that
transforms your program before it is compiled. These transformations can be the
inclusion of header files, macro expansions, etc.
All preprocessor commands begin with a hash symbol (#). It must be the first
nonblank character, and for readability, a preprocessor directive should begin in
the first column. The following section lists down all the important preprocessor
directives −

Sr.No. Directive & Description


1 #define
Substitutes a preprocessor macro.

2 #include
Inserts a particular header from another file.

3 #undef
Undefines a preprocessor macro.

4 #ifdef
Returns true if this macro is defined.

5 #ifndef
Returns true if this macro is not defined.
6 #if
Tests if a compile time condition is true.

7 #else
The alternative for #if.

8 #elif
#else and #if in one statement.

9 #endif
Ends preprocessor conditional.

10 #error
Prints error message on stderr.

11 #pragma
Issues special commands to the compiler, using a standardized
method.

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is


defined by #define directive. There are two types of macros:

1. Object-like Macros
2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to


represent numeric constants. For example:

#define PI 3.14
Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

#define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No. Macro Description

1 _DATE_ represents current date in "MMM DD YYYY" format.

2 _TIME_ represents current time in "HH:MM:SS" format.

3 _FILE_ represents current file name.

4 _LINE_ represents current line number.

5 _STDC_ It is defined as 1 when compiler complies with the ANSI standard.

typedef statement
The typedef is a keyword that is used to provide existing data types with a new name. The C typedef
keyword is used to redefine the name of already existing data types.

When names of datatypes become difficult to use in programs, typedef is used with user-defined
datatypes, which behave similarly to defining an alias for commands.

C typedef Syntax
typedef existing_name alias_name;

After this declaration, we can use the alias_name as if it were the real existing_name in out C program.

Example of typedef in C
typedef long long ll;

Below is the C program to illustrate how to use typedef.

// C program to implement typedef

#include <stdio.h>

// defining an alias using typedef

typedef long long ll;

// Driver code

int main()

// using typedef name to declare variable

ll var = 20;

printf("%ld", var);

return 0;

Output

20

Use of typedef in C
Following are some common uses of the typedef in C programming:

The typedef keyword gives a meaningful name to the existing data type which helps other users to
understand the program more easily.

It can be used with structures to increase code readability and we don’t have to type struct repeatedly.

The typedef keyword can also be used with pointers to declare multiple pointers in a single statement.

It can be used with arrays to declare any number of variables.

1. typedef struct
typedef can also be used with structures in the C programming language. A new data type can be
created and used to define the structure variable.

Example 1: Using typedef to define a name for a structure

// C program to implement

// typedef with structures

#include <stdio.h>

#include <string.h>

// using typedef to define an alias for structure

typedef struct students {

char name[50];

char branch[50];

int ID_no;

} stu;

// Driver code

int main()

{
stu st;

strcpy(st.name, "Kamlesh Joshi");

strcpy(st.branch, "Computer Science And Engineering");

st.ID_no = 108;

printf("Name: %s\n", st.name);

printf("Branch: %s\n", st.branch);

printf("ID_no: %d\n", st.ID_no);

return 0;

Output

Name: Kamlesh Joshi

Branch: Computer Science And Engineering

ID_no: 108

2. typedef with Pointers


typedef can also be used with pointers as it gives an alias name to the pointers. Typedef is very efficient
while declaring multiple pointers in a single statement because pointers bind to the right on the simple
declaration.

Example:

typedef int* Int_ptr;

Int_ptr var, var1, var2;

In the above statement var, var1, and var2 are declared as pointers of type int which helps us to declare
multiple numbers of pointers in a single statement.

Example 2: Using typedef to define a name for pointer type.

C
// C program to implement

// typedef with pointers

#include <stdio.h>

typedef int* ptr;

// Driver code

int main()

ptr var;

*var = 20;

printf("Value of var is %d", *var);

return 0;

Output

Value of var is 20

3. typedef with Array


typedef can also be used with an array to increase their count.

Example:

typedef int arr[20]

Here, arr is an alias for an array of 20 integer elements.

// it's same as Arr[20], two-Arr[20][23];

arr Arr, two-Arr[23];

Example 3: Using typedef to define an alias for Array.


C

// C program to implement typedef with array

#include <stdio.h>

typedef int Arr[4];

// Driver code

int main()

Arr temp = { 10, 20, 30, 40 };

printf("typedef using an array\n");

for (int i = 0; i < 4; i++) {

printf("%d ", temp[i]);

return 0;

Output

typedef using an array

10 20 30 40

C typedef vs #define

The following are the major difference between the typedef and #define in C:

#define is capable of defining aliases for values as well, for instance, you can
define 1 as ONE, 3.14 as PI, etc. Typedef is limited to giving symbolic names to
types only.
Preprocessors interpret #define statements, while the compiler interprets typedef
statements.

There should be no semicolon at the end of #define, but a semicolon at the end of
typedef.

In contrast with #define, typedef will actually define a new type by copying and
pasting the definition values.

Below is the C program to implement #define:

// C program to implement #define

#include <stdio.h>

// macro definition

#define LIMIT 3

// Driver code

int main()

for (int i = 0; i < LIMIT; i++) {

printf("%d \n", i);

return 0;

Output

2
Symbolic Constants
A symbolic constant is a name given to some numeric constant, or a character
constant or string constant, or any other constants.

Symbolic constant names are also known as constant identifiers. Pre-processor


directive #define is used for defining symbolic constants.

Syntax for Creating Symbolic Constants

#define symbolic_constant_name value_of_the_constant

Symbolic Constants Examples

#define PI 3.141592

#define GOLDENRATIO 1.6

#define MAX 500

Here PI, GOLDENRATIO, SIZE are symbolic constants.

Note: symbolic constants names are written in uppercase by convention, but it is


not required.
UNIT- 4

Operators & Expression

Operators
Operators are the symbols which tell the computer to execute certain
mathematical or logical operations. A mathematical or logical expression is
generally formed with the help of an operator. C programming offers a number of
operators which are classified into 8 categories viz.

1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and Decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
1. Arithmetic Operators

C programming language provides all basic arithmetic operators: +, -, *, / and %.

Note: ‘/’ is integer division which only gives integer part as result after division. ‘%’
is modulo division which gives the remainder of integer division as result.
Some examples of arithmetic operators are:

 a+b

 a–b

 a*b

 a /b

 a%b

In these examples, a and b are variables and are called operands.

Note: ‘%’ cannot be used on floating data type.

2. Relational Operators

Relational operators are used when we have to make comparisons. C programming


offers 6 relational operators.

Relational expression is an expression which contains the relational operator.


Relational operators are most commonly used in decision statements like if, while,
etc. Some simple relational expressions are:

 1<5
 9 != 8

 2 > 1+3

Note: Arithmetic operators have higher priority than relational operators meaning
that if arithmetic expressions are present on two sides of a relational operator
then arithmetic expressions will be calculated first and then the result will be
compared.

3. Logical Operators

Logical operators are used when more than one conditions are to be tested and
based on that result, decisions have to be made. C programming offers three
logical operators. They are:

For example:

a < 18 || a> 60

An expression which combines two or more relational expressions is known as


logical expression.

Note: Relative precedence of relational and logical operators are as follows

Highest precedence !

> >= < <=


== !=

&&

Lowest precedence ||

4. Assignment Operators
Assignment operators are used to assign result of an expression to a variable. ‘=’ is
the assignment operator in C. Furthermore, C also allows the use of shorthand
assignment operators. Shorthand operators take the form:

var op = exp;

where var is a variable, op is arithmetic operator, exp is an expression. In this case,


‘op=’ is known as shorthand assignment operator.

The above assignment

var op = exp;

is the same as the assignment

var = var op exp;

Consider an example:

x += y;

Here, the above statement means the same as

x = x + y;

Note: Shorthand assignment can be used with all arithmetic operators.

5. Increment and Decrement Operators


C programming allows the use of ++ and – operators which are increment and
decrement operators respectively. Both the increment and decrement operators
are unary operators. The increment operator ++ adds 1 to the operand and the
decrement operator – subtracts 1 from the operand. The general syntax of these
operators are:

Increment Operator: m++ or ++m;

Decrement Operator: m–-or –-m;

In the example above, m++ simply means m=m+1; and m– simply means m=m-1;

Increment and decrement operators are mostly used in for and while loops.

++m and m++ performs the same operation when they form statements
independently but they function differently when they are used in right hand side
of an expression.

++m is known as prefix operator and m++ is known as postfix operator. A prefix
operator firstly adds 1 to the operand and then the result is assigned to the
variable on the left whereas a postfix operator firstly assigns value to the variable
on the left and then increases the operand by 1. Same is in the case of decrement
operator.

For example,

X=10;
Y=++X;

In this case, the value of X and Y will be 6.

And,

X=10;

Y=X++;

In this case, the value of Y will be 10 and the value of X will be 11.
6. Conditional Operator
The operator pair “?” and “:” is known as conditional operator. These pair of
operators are ternary operators. The general syntax of conditional operator is:

expression1 ? expression2 : expression3 ;

This syntax can be understood as a substitute of if else statement.

For example,

a=3;

b=5;

Consider an if else statement as:

if (a > b)

x=a;

else

x=b;

Now, this if else statement can be written by using conditional operator as:

x = (a > b) ? a : b ;

7. Bitwise Operator
In C programming, bitwise operators are used for testing the bits or shifting them
left or right. The bitwise operators available in C are:
8. Special Operators
C programming supports special operators like comma operator, sizeof operator,
pointer operators (& and *) and member selection operators (. and ->). The
comma operator and sizeof operator are discussed in this section whereas the
pointer and member selection operators are discussed in later sections.

1. Comma Operator
The comma operator can be used to link the related expressions together. A
comma linked expression is evaluated from left to right and the value of the right
most expression is the value of the combined expression.

For example:

x = (a = 2, b = 4, a+b)

In this example, the expression is evaluated from left to right. So at first, variable a
is assigned value 2, then variable b is assigned value 4 and then value 6 is assigned
to the variable x. Comma operators are commonly used in for loops, while loops,
while exchanging values, etc.

2 .Sizeof() operator
The sizeof operator is usually used with an operand which may be variable,
constant or a data t ype qualifier. This operator returns the number of bytes the
operand occupies. Sizeof operator is a compile time operator. Some examples of
use of sizeof operator are:

x = sizeof (a);

y = sizeof(float);

The sizeof operator is usually used to determine the length of arrays and structures
when their sizes are not known. It is also used in dynamic memory allocation.

Expressions

Arithmetic expression in C is a combination of variables, constants and operators


written in a proper syntax. C can easily handle any complex mathematical
expressions but these mathematical expressions have to be written in a proper
syntax. Some examples of mathematical expressions written in proper syntax of C
are:

Note: C does not have any operator for exponentiation.

C Operator Precedence
At first, the expressions within parenthesis are evaluated. If no parenthesis is
present, then the arithmetic expression is evaluated from left to right. There are
two priority levels of operators in C.

High priority: * / %
Low priority: + –

The evaluation procedure of an arithmetic expression includes two left to right


passes through the entire expression. In the first pass, the high priority operators
are applied as they are encountered and in the second pass, low priority
operations are applied as they are encountered.

Suppose, we have an arithmetic expression as:


x = 9 – 12 / 3 + 3 *2 - 1

This expression is evaluated in two left to right passes as:

First Pass

Step 1: x = 9-4 + 3 * 2 – 1

Step 2: x = 9 – 4 + 6 – 1

Second Pass

Step 1: x = 5 + 6 – 1

Step 2: x = 11 – 1

Step 3: x = 10

But when parenthesis is used in the same expression, the order of evaluation gets
changed.

For example,

x = 9 – 12 / (3 + 3) * (2 – 1)

When parentheses are present then the expression inside the parenthesis are
evaluated first from left to right. The expression is now evaluated in three passes
as:

First Pass

Step 1: x = 9 – 12 / 6 * (2 – 1)

Step 2: x= 9 – 12 / 6 * 1
Second Pass

Step 1: x= 9 – 2 * 1

Step 2: x = 9 – 2

Third Pass

Step 3: x= 7

There may even arise a case where nested parentheses are present (i.e.
parenthesis inside parenthesis). In such case, the expression inside the innermost
set of parentheses is evaluated first and then the outer parentheses are evaluated.

For example, we have an expression as:

x = 9 – ((12 / 3) + 3 * 2) – 1

The expression is now evaluated as:

First Pass:

Step 1: x = 9 – (4 + 3 * 2) – 1

Step 2: x= 9 – (4 + 6) – 1

Step 3: x= 9 – 10 -1

Second Pass

Step 1: x= - 1 – 1

Step 2: x = -2

Note: The number of evaluation steps is equal to the number of operators in the
arithmetic expression.
Example 1: Arithmetic Operators
// Working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;

c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);

return 0;
}
Run Code

Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
The operators +, - and * computes addition, subtraction, and multiplication
respectively as you might have expected.
In normal calculation, 9/4 = 2.25. However, the output is 2 in the program.
It is because both the variables a and b are integers. Hence, the output is also an
integer. The compiler neglects the term after the decimal point and shows
answer 2 instead of 2.25.
The modulo operator % computes the remainder. When a=9 is divided by b=4, the
remainder is 1. The % operator can only be used with integers.
Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming,
// Either one of the operands is a floating-point number
a/b = 2.5
a/d = 2.5
c/b = 2.5

// Both operands are integers


c/d = 2

Example 2: Increment and Decrement Operators


// Working of increment and decrement operators
#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;

printf("++a = %d \n", ++a);


printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);

return 0;
}
Run Code

Output
++a = 11
--b = 99
++c = 11.500000
--d = 99.500000
Here, the operators ++ and -- are used as prefixes. These two operators can also
be used as postfixes like a++ and a--. Visit this page to learn more about
how increment and decrement operators work when used as postfix.

Example 3: Assignment Operators


// Working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c;

c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);

return 0;
}
Run Code

Output
c = 5
c = 10
c = 5
c = 25
c = 5
c = 0

Example 4: Relational Operators


// Working of relational operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;

printf("%d == %d is %d \n", a, b, a == b);


printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);

return 0;
}
Run Code

Output
5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1

Example 5: Logical Operators


// Working of logical operators

#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;

result = (a == b) && (c > b);


printf("(a == b) && (c > b) is %d \n", result);

result = (a == b) && (c < b);


printf("(a == b) && (c < b) is %d \n", result);

result = (a == b) || (c < b);


printf("(a == b) || (c < b) is %d \n", result);

result = (a != b) || (c < b);


printf("(a != b) || (c < b) is %d \n", result);

result = !(a != b);


printf("!(a != b) is %d \n", result);

result = !(a == b);


printf("!(a == b) is %d \n", result);

return 0;
}
Run Code

Output
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
Explanation of logical operator program
 (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b) is 1
(true).
 (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
 (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
 (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0
(false).
 !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1
(true).
 !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).

Example 6: sizeof Operator


#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));

return 0;
}
Run Code

Output
Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte

Operator Precedence
Operator precedence helps us determine which of the operators in an expression
must be evaluated first in case the expression consists of more than a single
operator.
Example,
50 – 2 * 15 is going to yield 20. It is because it gets evaluated as 50 – (2 * 15), and
not as (50 – 2) * 15. The reason here is that subtraction (-) has lower precedence
as compared to multiplication (*).

Precedence rules describe how an under parenthesized expression should be


parenthesized when the expression mixes different kinds of operators. For example,
multiplication is of higher precedence than addition, so 2 + 3 x 4 is equivalent to 2
+ (3 x 4), not (2 + 3) x 4.

Operator Associativity
We use associativity when two or more than two operators with the same
precedence are present in the same expression.
Example,
The precedence of Division and Multiplication arithmetic operators is the same. So,
let’s say we have an expression with us which is 6 * 3 / 20. The evaluation of this
expression would be (6 * 3) / 20 because the associativity will be left to right for
both the operators – multiplication and division. In a similar case, the calculation of
40 / 4 * 5 would be (40 / 4) * 5 because the associativity would be from right to left
here as well.
Associativity rules describe how an under parenthesized expression should be
parenthesized when the expression has a bunch of the same kind of operator. For
example, addition is associative from left to right, so a + b + c is equivalent
to (a + b) + c, not a + (b + c). In ordinary arithmetic, these two
expressions always give the same result; in computer arithmetic, they do not
necessarily. (As an exercise can you find values for a, b, c such that (a + b) +
c is unequal to a + (b + c) in C#?)

Summary of Operator Precedence and Associativity in C


Here is how the operator precedence and associativity work in the C language:

Operator Description of Operator Associativity

. Direct member selection Left to right

-> Indirect member selection Left to right

[] Array element reference Left to right

() Functional call Left to right

~ Bitwise(1’s) complement Right to left

! Logical negation Right to left

– Unary minus Right to left

+ Unary plus Right to left

— Decrement Right to left


++ Increment Right to left

* Pointer reference Right to left

& Dereference (Address) Right to left

(type) Typecast (conversion) Right to left

sizeof Returns the size of an object Right to left

% Remainder Left to right

/ Divide Left to right

* Multiply Left to right

– Binary minus (subtraction) Left to right

+ Binary plus (Addition) Left to right

>> Right shift Left to right

<< Left shift Left to right

> Greater than Left to right

< Less than Left to right

>= Greater than or equal Left to right


<= Less than or equal Left to right

== Equal to Left to right

!= Not equal to Left to right

^ Bitwise exclusive OR Left to right

& Bitwise AND Left to right

|| Logical OR Left to right

| Bitwise OR Left to right

?: Conditional Operator Right to left

&& Logical AND Left to right

, Separator of expressions Left to right

= Simple assignment Right to left

/= Assign quotient Right to left

*= Assign product Right to left

%= Assign remainder Right to left

-= Assign difference Right to left


+= Assign sum Right to left

|= Assign bitwise OR Right to left

^= Assign bitwise XOR Right to left

&= Assign bitwise AND Right to left

>>= Assign right shift Right to left

<<= Assign left shift Right to left

Order of evaluation :
OE refers to the operator precedence and associativity rules according to which
mathematical expressions are evaluated.

Table of the order of evaluation

The order of evaluation in C is illustrated in the following figure:


Order of evaluation rules describe the order in which each operand in an
expression is evaluated. The parentheses just describe how the results are grouped
together; “do the parentheses first” is not a rule of C#. Rather, the rule in C# is
“evaluate each subexpression strictly left to right”.
The expression F() + G() * H() is equivalent to F() + (G() * H()), but C# does NOT
evaluate G() * H() before F(). Rather, this is equivalent to:
temp1 = F();

temp2 = G();

temp3 = H();

temp4 = temp2 * temp3;

result = temp1 + temp4;


Another way to look at it is that the rule in C# is not “do the parentheses first”, but
rather to parenthesize everything then recursively apply the rule “evaluate the left
side, then evaluate the right side, then perform the operation”.

Practice Problems on Operator Precedence and Associativity in C


1. What would be the output/result obtained from this program?
int main()
{
int x = 5, y = 10;
int z;
z = x * 2 + y;
printf(“\n output = %d”, z);
return 0;
}
A. 0
B. 5
C. 20
D. 12
Answer – C. 20
We can calculate the output of this code using the precedence table. According to
this table, the precedence of the assignment operator ( – ) and the addition
operator ( + ) is lower than that of the multiplication operator ( * ). Thus,
multiplication will get evaluated first here.
Thus, z = x * 2 + y
z = 5 * 2 + 10
z = 10 + 10
z = 20
2. What would be the output/result obtained from this program?
int main()
{
int x = 50, y = 5;
int z;
z = x / 2 + y;
printf(“\n output = %d”, z);
return 0;
}
A. 80
B. 30
C. 0
D. 5
Answer – B. 30
We can calculate the output of this code using the precedence table. According to
this table, the precedence of the assignment operator ( – ) and the addition
operator ( + ) is lower than that of the division operator ( / ). Thus, multiplication
will get evaluated first here.
Thus, z = x / 2 + y
z = 50 / 2 + 5
z = 25 + 5
z = 30
3. What would be the output/result obtained from this program?
int main()
{
int x = 30, y = 12;
int z;
z = x * 2 / y;
printf(“\n output = %d”, z);
return 0;
}
A. 5
B. 10
C. 15
D. 60
Answer – A. 5
The evaluation of this expression would be (30 * 2) / 12 because the associativity
will be left to right for both the operators – multiplication and division.
Thus, z = x * 2 / y
z = (30 * 2) / 12
z = 60 / 12
z=5
4. What would be the output/result obtained from this program?
int main()
{
int x = 80, y = 3;
int z;
z = x / 2 * y;
printf(“\n output = %d”, z);
return 0;
}
A. 10
B. 30
C. 55
D. 120
Answer – D. 120
The evaluation of this expression would be (80 / 2) * 3 because the associativity
will be left to right for both the operators – multiplication and division.
Thus, z = x / 2 * y
z = (80 / 2) * 3
z = 40 * 3
z = 120
UNIT-5
Input and Output

C Input Output Statements

In C Language input and output function are available as C compiler functions or C


libraries provided with each C compiler implementation. These all functions are
collectively known as Standard I/O Library function. Here I/O stands for Input and
Output used for different inputting and outputting statements. These I/O functions
are categorized into three processing functions. Console input/output function
(deals with keyboard and monitor), disk input/output function (deals with floppy or
hard disk), and port input/output function (deals with a serial or parallel port). As
all the input/output statements deals with the console, so these are also Console
Input/Output functions. Console Input/Output function access the three major files
before the execution of a C Program. These are as follows:

 stdin: This file is used to receive the input (usually is keyborad file, but can also
take input from the disk file).
 stdout: This file is used to send or direct the output (usually is a monitor file,
but can also send the output to a disk file or any other device).
 stderr: This file is used to display or store error messages.

Input Ouput Statement


Input and Output statement are used to read and write the data in C
programming. These are embedded in stdio.h (standard Input/Output header file).

Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a
file.C programming language provides many built-in functions to read any given
input and to display data on screen when there is a need to output the result.

There are mainly two of Input/Output functions are used for this purpose. These
are discussed as:

 Unformatted I/O functions


 Formatted I/O functions

Unformatted I/O functions

There are mainly six unformatted I/O functions discussed as follows:

 getchar()
 putchar()
 gets()
 puts()
 getch()
 getche()

getchar()

This function is an Input function. It is used for reading a single character from the
keyboard. It is a buffered function n. Buffered functions get the input from the
keyboard and store it in the memory buffer temporally until you press the Enter
key.

The general syntax is as:

v = getchar();
where v is the variable of character type. For example:
char n;
n = getchar();
A simple C-program to read a single character from the keyboard is as:

/*To read a single character from the keyboard using the getchar() function*/
#include <stdio.h>
main()
{
char n;
n = getchar();
}
putchar()

This function is an output function. It is used to display a single character on the


screen. The general syntax is as:

putchar(v);
where v is the variable of character type. For example:

char n;
putchar(n);
A simple program is written as below, which will read a single character using
getchar() function and display inputted data using putchar() function:

/*Program illustrate the use of getchar() and putchar() functions*/


#include <stdio.h>
main()
{
char n;
n = getchar();
putchar(n);
}

gets()
This function is an input function. It is used to read a string from the keyboard. It is
also a buffered function. It will read a string when you type the string from the
keyboard and press the Enter key from the keyboard. It will mark null character
(‘\0’) in the memory at the end of the string when you press the enter key. The
general syntax is as:

gets(v);
where v is the variable of character type. For example:

char n[20];
gets(n);
A simple C program to illustrate the use of gets() function:

/*Program to explain the use of gets() function*/


#include <stdio.h>
main()
{
char n[20];
gets(n);
}
puts()

This is an output function. It is used to display a string inputted by gets() function.


It is also used to display a text (message) on the screen for program simplicity. This
function appends a newline (“\n”) character to the output.

The general syntax is as:

puts(v);
or

puts("text line");
where v is the variable of character type.
A simple C program to illustrate the use of puts() function:

/*Program to illustrate the concept of puts() with gets() functions*/


#include <stdio.h>
main()
{
char name[20];
puts("Enter the Name");
gets(name);
puts("Name is :");
puts(name);
}
The Output is as follows:

Enter the Name


Geek
Name is:
Geek
getch()

This is also an input function. This is used to read a single character from the
keyboard like getchar() function. But getchar() function is a buffered is function,
getchar() function is a non-buffered function. The character data read by this
function is directly assigned to a variable rather it goes to the memory buffer, the
character data is directly assigned to a variable without the need to press the Enter
key.

Another use of this function is to maintain the output on the screen till you have
not press the Enter Key. The general syntax is as:

v = getch();
where v is the variable of character type.

A simple C program to illustrate the use of getch() function:

/*Program to explain the use of getch() function*/


#include <stdio.h>
main()
{
char n;
puts("Enter the Char");
n = getch();
puts("Char is :");
putchar(n);
getch();
}
The output is as follows:

Enter the Char


Char is L
getche()

All are same as getch(0 function execpt it is an echoed function. It means when
you type the character data from the keyboard it will visible on the screen. The
general syntax is as:

v = getche();
where v is the variable of character type.

A simple C program to illustrate the use of getch() function:

/*Program to explain the use of getch() function*/


#include <stdio.h>
main()
{
char n;
puts("Enter the Char");
n = getche();
puts("Char is :");
putchar(n);
getche();
}
The output is as follows:

Enter the Char L


Char is L
Formatted I/O functions

Formatted I/O functions which refers to an Input or Ouput data that has been
arranged in a particular format. There are mainly two formatted I/O functions
discussed as follows:

 scanf()
 printf()

scanf()

The scanf() function is an input function. It used to read the mixed type of data
from keyboard. You can read integer, float and character data by using its control
codes or format codes. The general syntax is as:

scanf("control strings",arg1,arg2,..............argn);
or

scanf("control strings",&v1,&v2,&v3,................&vn);
Where arg1,arg2,……….argn are the arguments for reading and v1,v2,v3,……..vn all
are the variables.

The scanf() format code (spedifier) is as shown in the below table:

Format Code Meaning

%c To read a single character


%d To read a signed decimal integer (short)

%ld To read a signed long decimal integer

%e To read a float value exponential

%f To read a float (short0 or a single precision value

%lf To read a double precision float value

%g To read double float value

%h To read short integer

%i To read an integer (decimal, octal, hexadecimal)

%o To read an octal integer only

%x To read a hexadecimal integer only

%u To read unsigned decimal integer (used in pointer)

%s To read a string
%[..] To read a string of words from the defined range

%[^] To read string of words which are not from the defined range

Example Program:

/*Program to illustrate the use of formatted code by using the formatted scanf()
function */
#include <stdio.h>
main()
{
char n,name[20];
int abc;
float xyz;
printf("Enter the single character, name, integer data and real value");
scanf("\n%c%s%d%f", &n,name,&abc,&xyz);
getch();
}
printf()

This ia an output function. It is used to display a text message and to display the
mixed type (int, float, char) of data on screen. The general syntax is as:

printf("control strings",&v1,&v2,&v3,................&vn);
or

printf("Message line or text line");


Where v1,v2,v3,……..vn all are the variables.

The control strings use some printf() format codes or format specifiers or
conversion characters. These all are discussed in the below table as:
Format Code Meaning

%c To read a single character

%s To read a string

%d To read a signed decimal integer (short)

%ld To read a signed long decimal integer

%f To read a float (short0 or a single precision value

%lf To read a double precision float value

%e To read a float value exponential

%g To read double float value

%o To read an octal integer only

%x To read a hexadecimal integer only

%u To read unsigned decimal integer (used in pointer)

Example Program:
/*Below the program which show the use of printf() function*/
#include <stdio.h>
main()
{
int a;
float b;
char c;
printf("Enter the mixed type of data");
scanf("%d",%f,%c",&a,&b,&c);
getch();
}

Format Specifiers
 To print values of different data types using the printf() statement and while taking input
using the scanf() function, it is mandatory to use format specifiers.
 It is a way to tell the compiler what type of data is in a variable.
 Some examples are %c, %d, %f, etc.
Here is a list of all the format specifiers.

Datatype Format Specifier

int %d, %i

char %c

float %f

double %lf
Datatype Format Specifier

short int %hd

unsigned int %u

long int %li

long long int %lli

unsigned long int %lu

unsigned long long int %llu

signed char %c

unsigned char %c

long double %Lf

Reading & Writing data:

I/O operations that reads or writes data as a stream of bytes without regard to any format.
Unformatted I/O in C is carried out with the aid of functions like fread() and fwrite(). Without
formatting, these operations are used to read and write data directly to and from files.

Syntax:

Syntax for using the fwrite() function to print unformatted data:

1. fwrite(data, size, count, file pointer);


Here, count is the number of elements to be written, size is the size of each element to be
written, and the file pointer is a pointer to the file where the data will be written.

Syntax for using the fread() method with unformatted input:

1. fread(data, size, count, file pointer);

In this syntax, a pointer to the buffer where the data will be read, the size of each element to be
read, the number of elements to be read, and a pointer to the file from which the data will be
read.

Example

Let's examine an illustration of unformatted I/O in C:

AD
#include <stdio.h>
int main() {
char data[100];
FILE *fp;

fp = fopen("file.txt", "w+");

fputs("This is an example of unformatted output.", fp);


fseek(fp, 0, SEEK_SET);

fread(data, sizeof (
char), 100, fp);

printf("%s\n", data);
fclose(fp);

return 0;
}

Output:

This is an example of unformatted output.

Explanation:
In the example, we first declare a file pointer (fp) and a character array (data). After that, the file
pointer is assigned to 'fp' after using the 'fopen()' method to open the 'file.txt' file in write mode.
The string "This is an example of unformatted output." is written to the file using
the 'fputs()' function. The file pointer is then moved to the file's beginning using
the 'fseek()' function. After that, the data is shown using the 'printf()' function after being read
from the file into the 'data' buffer using the 'fread()' function.
UNIT-6

Control Statements

6.1 Repetitive control statements: for, while, do-while


6.2 Conditional control statements: if, if else, Nested if, else if ladder, switch
6.3 Unconditional control statements: break, continue, goto
6.4 exit( ) function

STATEMENTS
A statement causes the computer to carry out some definite action. There are three different classes
of statements in C:
Expression statements, Compound statements, and Control statements.

Null statement
A null statement consisting of only a semicolon and performs no operations . It can appear wherever
a statement is expected. Nothing happens when a null statement is executed.

Syntax: -

Statements such as do, for, if, and while require that an executable statement appear as the statement
body. The null statement satisfies the syntax requirement in cases that do not need a substantive
statement body.
The Null statement is nothing but, there is no body within loop or any other statements in C.
Example illustrates the null statement:
for ( i = 0; i < 10; i++) ;

or

for (i=0;i<10;i++)
{

//empty body
}
Expression
Most of the statements in a C program are expression statements. An expression statement is simply
an expression followed by a semicolon. The lines
i = 0;
i = i + 1;
and printf("Hello, world!\n");
are all expression statements. In C, however, the semicolon is a statement terminator. Expression
statements do all of the real work in a C program. Whenever you need to compute new values for
variables, you'll typically use expression statements (and they'll typically contain assignment
operators). Whenever you want your program to do something visible, in the real world, you'll
typically call a function (as part of an expression statement). We've already seen the most basic
example: calling the function printf to print text to the screen.
Note -If no expression is present, the statement is often called the null statement.

Return
The return statement terminates execution of a function and returns control to the calling function,
with or without a return value. A function may contain any number of return statements. The return
statement has
syntax: return expression(opt);
If present, the expression is evaluated and its value is returned to the calling function. If necessary, its
value is converted to the declared type of the containing function's return value.
A return statement with an expression cannot appear in a function whose return type is void . If
there is no expression and the function is not defined as void , the return value is undefined. For
example, the following main function returns an unpredictable value to the operating system:

main ( )
{

return;
}

Compound statements
A compound statement (also called a "block") typically appears as the body of another statement,
such as the if statement, for statement, while statement, etc
A Compound statement consists of several individual statements enclosed within a pair of braces {
}. The individual statements may themselves be expression statements, compound statements or
control statements. Unlike expression statements, a compound statement does not end with a
semicolon. A typical Compound statement is given below.
{
pi=3.14;
area=pi*radius*radius;
}
The particular compound statement consists of two assignment-type expression statements.
Example:

Selection Statement/Conditional Statements/Decision Making Statements


A selection statement selects among a set of statements depending on the value of a controlling
expression. Or
Moving execution control from one place/line to another line based on condition
Or
Conditional statements control the sequence of statement execution, depending on the value of a
integer expression
C‟ language supports two conditional statements.
1: if
2: switch.

1: if Statement: The if Statement may be implemented in different forms.


1: simple if statement.
2: if –else statement
3: nested if-else statement.
4: else if ladder.

if statement.
The if statement controls conditional branching. The body of an if statement is executed if the value
of the expression is nonzero. Or if statement is used to execute the code if condition is true. If the
expression/condition is evaluated to false (0), statements inside the body of if is skipped from
execution.
Syntax : if(condition/expression)
{
true statement;

}
statement-x;
If the condition/expression is true, then the true statement will be executed otherwise the true
statement block will be skipped and the execution will jump to the statement-x. The „true statement‟
may be a single statement or group of statement.
If there is only one statement in the if block, then the braces are optional. But if there is more than
one statement the braces are compulsory

Flowchart

Example:
#include<stdio.h>
main()
{
int a=15,b=20;

if(b>a)
{
printf("b is greater");
}
}
Output
b is greater
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// Test expression is true if number is less than 0
if (number < 0)
{
printf("You entered %d.\n", number);
}
printf("The if statement is easy.");
return 0;
}
Output 1
Enter an integer: -2
You entered -2.
The if statement is easy.
Output 2
Enter an integer: 5
The if statement in C programming is easy.

If-else statement : The if-else statement is an extension of the simple if statement. The general
form is. The if...else statement executes some code if the test expression is true (nonzero) and
some other code if the test expression is false (0).

Syntax : if (condition)
{
true statement;
}
else
{
false statement;
}
statement-x;
If the condition is true , then the true statement and statement-x will be executed and if the condition
is false, then the false statement and statement-x is executed.
Or
If test expression is true, codes inside the body of if statement is executed and, codes inside the body
of else statement is skipped.
If test expression is false, codes inside the body of else statement is executed and, codes inside the
body of if statement is skipped.
Flowchart

Example:
// Program to check whether an integer entered by the user is odd or even
#include <stdio.h>
int main()
{

int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
Output
Enter an integer: 7
7 is an odd integer.

Nested if-else statement


When a series of decisions are involved, we may have to use more than on if-else statement in nested
form. If –else statements can also be nested inside another if block or else block or both.
Syntax : if(condition-1)
{{
if (condition-2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;

}
statement-x;
If the condition-1 is false, the statement-3 and statement-x will be executed. Otherwise it continues
to perform the second test. If the condition-2 is true, the true statement-1 will be executed
otherwise the statement-2 will be executed and then the control is transferred to the statement-x

Flowchart

Example
#include<stdio.h>
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 !=var2)
{
printf("var1 is not equal to var2");
//Below – if-else is nested inside another if block
if (var1 >var2)
{
printf("var1 is greater than var2");
}
else
{
printf("var2 is greater than var1");
}
}
Else

{
printf("var1 is equal to var2");
}

Else if ladder.
The if else-if statement is used to execute one code from multiple conditions.
Syntax : if( condition-1)
{
statement-1;
}
else if(condition-2)
{
statement-2;
}
else if(condition-3)
{
statement-3;
}
else if(condition-n)
{
statement-n;
}
else
{
default-statement;
}
statement-x;
Flowchart

Example
#include<stdio.h>
#include<conio.h>
void main(){
int number=0;
clrscr();
printf("enter a number:");
scanf("%d",&number);
if(number==10){
printf("number is equals to 10");
}
else if(number==50){
printf("number is equal to 50");
}
else if(number==100){
printf("number is equal to 100");
}
else{
printf("number is not equal to 10, 50 or 100");
}
getch();
}

Switch statement : when there are several options and we have to choose only one option from
the available ones, we can use switch statement. Depending on the selected option, a particular task
can be performed. A task represents one or more statements.
Syntax:
switch(expression)
{
case value-1:
statement/block-1;
break;
case value-2:
statement/block t-2;
break;
case value-3:
statement/block -3;
break;
case value-4:
statement/block -4;
break;
default:
default- statement/block t;
break;

}
The expression following the keyword switch in any „C‟ expression that must yield an integer value.
It must be ab integer constants like 1,2,3 .
The keyword case is followed by an integer or a character constant, each constant in each must be
different from all the other.
First the integer expression following the keyword switch is evaluated. The value it gives is searched
against the constant values that follw the case statements. When a match is found, the program
executes the statements following the case. If no match is found with any of the case statements, then
the statements follwing the default are executed.
Rules for writing switch() statement.
1 : The expression in switch statement must be an integer value or a character constant.
2 : No real numbers are used in an expression.
3 : The default is optional and can be placed anywhere, but usually placed at end.
4 : The case keyword must terminate with colon ( : ).
5 : No two case constants are identical.
6:The case labels must be constants.
Valid Switch Invalid Switch Valid Case Invalid Case
switch(x) switch(f) case 3; case 2.5;
switch(x>y) switch(x+2.5) case 'a'; case x;
switch(a+b-2) case 1+2; case x+2;
switch(func(x,y)) case 'x'>'y'; case 1,2,3;

Example
#include<stdio.h>
main()
{
int a;
printf("Please enter a no between 1 and 5: ");
scanf("%d",&a);
switch(a)
{
case 1:
printf("You chose One");
break;
case 2:

printf("You chose Two");


break;
case 3:
printf("You chose Three");
break;
case 4:
printf("You chose Four");
break;
case 5: printf("You chose Five.");
break;
default :
printf("Invalid Choice. Enter a no between 1 and 5"); break;
}
}
Flowchart

Iteration Statements/ Loop Control Statements


How it Works
A sequence of statements are executed until a specified condition is true. This sequence of statements
to be executed is kept inside the curly braces { } known as the Loop body. After every execution of
loop body, condition is verified, and if it is found to be true the loop body is executed again. When
the condition check returns false, the loop body is not executed.
The loops in C language are used to execute a block of code or a part of the program several times.
In other words, it iterates/repeat a code or group of code many times.
Or Looping means a group of statements are executed repeatedly, until some logical condition is
satisfied.

Why use loops in C language?


Suppose that you have to print table of 2, then you need to write 10 lines of code.By using the loop
statement, you can do it by 2 or 3 lines of code only.
A looping process would include the following four steps.
1 : Initialization of a condition variable.
2 : Test the condition.
3 : Executing the body of the loop depending on the condition.
4 : Updating the condition variable.

C language provides three iterative/repetitive loops.


1 : while loop
2 : do-while loop
3 : for loop
While Loop: Syntax :
variable initialization ;
while (condition)
{
statements ;
variable increment or decrement ;
}
while loop can be addressed as an entry control loop. It is completed in 3 steps.
 Variable initialization.( e.g int x=0; )

 condition( e.g while( x<=10) )

 Variable increment or decrement ( x++ or x-- or x=x+2 )

The while loop is an entry controlled loop statement, i.e means the condition is evaluated first
and it is true, then the body of the loop is executed. After executing the body of the loop, the
condition is once again evaluated and if it is true, the body is executed once again, the process of
repeated execution of the loop continues until the condition finally becomes false and the control is
transferred out of the loop.
Example : Program to print first 10 natural numbers
#include<stdio.h>
#include<conio.h>
void main( )
{

int x;
x=1;
while(x<=10)
{
printf("%d\t", x);
x++;
}
getch();
}
Output
1 2 3 4 5 6 7 8 9 10
C Program to reverse number
#include<stdio.h>
#include<conio.h>
main()
{
int n, reverse=0, rem;
clrscr();
printf("Enter a number: ");
scanf("%d", &n);

while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n/=10;
}
printf("Reversed Number: %d",reverse);
getch();
}

Flowchart

do-while loop
Syntax : variable initialization ;
do{
statements ;
variable increment or decrement ;
}while (condition);
The do-while loop is an exit controlled loop statement The body of the loop are executed first and
then the condition is evaluated. If it is true, then the body of the loop is executed once again. The
process of execution of body of the loop is continued until the condition finally becomes false and
the control is transferred to the statement immediately after the loop. The statements are always
executed at least once.

Flowchart
Example : Program to print first ten multiple of 5
#include<stdio.h>
#include<conio.h>
void main()
{
int a,i;
a=5;
i=1;
do
{
printf("%d\t",a*i);
i++;
}while(i <= 10);
getch();
}

Output
5 10 15 20 25 30 35 40 45 50
Example
main()
{
int i=0
do
{
printf("while vs do-while\n");
}while(i= =1);
printf("Out of loop");
}
Output:
while vs do-while
Out of loop
For Loop:
 This is an entry controlled looping statement.

 In this loop structure, more than one variable can be initialized.

 One of the most important features of this loop is that the three actions can be taken at a time like
variable initialization, condition checking and increment/decrement.

 The for loop can be more concise and flexible than that of while and do-while loops.

Syntax : for(initialization; condition; increment/decrement)


{
Statements;
}

Example:
#include<stdio.h>
#include<conio.h>
void main( )
{
int x;
for(x=1; x<=10; x++)
{
printf("%d\t",x);
}
getch();
}
Output
1 2 3 4 5 6 7 8 9 10
Various forms of FOR LOOP
I am using variable num in all the below examples –
1) Here instead of num++, I‟m using num=num+1 which is nothing but same as num++.
for (num=10; num<20; num=num+1)
2) Initialization part can be skipped from loop as shown below, the counter variable is declared
before the loop itself.
int num=10;
for (;num<20;num++)
Must Note: Although we can skip init part but semicolon (;) before condition is must, without which
you will get compilation error.

3) Like initialization, you can also skip the increment part as we did below. In this case semicolon (;)
is must, after condition logic. The increment part is being done in for loop body itself.
for (num=10; num<20; )
{
//Code
num++;
}
4) Below case is also possible, increment in body and init during declaration of counter variable.
int num=10;
for (;num<20;)
{
//Statements
num++;
}
5) Counter can be decremented also, In the below example the variable gets decremented each time
the loop runs until the condition num>10 becomes false.
for(num=20; num>10; num--)
Program to calculate the sum of first n natural numbers
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when n is less than count

for(count = 1; count <= num; ++count)


{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}
Output
Enter a positive integer: 10
Sum = 55
Factorial Program using loop
#include<stdio.h>
#include<conio.h>
void main(){
int i,fact=1,number;
clrscr();
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++){
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
getch();
}

Output:
Enter a number: 5
Factorial of 5 is: 120
Flow Chart of for Loop :

Infinitive for loop in C


If you don't initialize any variable, check condition and increment or decrement variable in for loop,
it is known as infinitive for loop. In other words, if you place 2 semicolons in for loop, it is known as
infinitive for loop.
for(; ;){

printf("infinitive for loop example by javatpoint");


}

Nested for loop


We can also have nested for loops, i.e one for loop inside another for loop. nesting is often used for
handling multidimensional arrays.
Syntax:
for(initialization; condition; increment/decrement)
{
for(initialization; condition; increment/decrement)

statement ;
}
}
Example:
main()
{
for (int i=0; i<=5; i++)
{
for (int j=0; j<=5; j++)
{
printf("%d, %d",i ,j);
}
}
}
Example : Program to print half Pyramid of numbers
#include<stdio.h>
#include<conio.h>
void main( )
{
int i,j;
for(i=1;i<5;i++)
{
printf("\n");

for(j=i;j>0;j--)
{
printf("%d",j);
}
}
getch();
}
Output
1
21
321
4321
54321
Jump Statements
Jumping statements are used to transfer the program‟s control from one location to another, these are
set of keywords which are responsible to transfer program‟s control within the same block or from
one function to another.
There are four jumping statements in C language:
 goto statement

 return statement

 break statement

 continue statement

goto statement : goto statement doesnot require any condition. This statement passes control
anywhere in the program i.e, control is transferred to another part of the program without testing
any condition.

Syntax : goto label;


.....
.....
label:
statements;
Inthissyntax, label isan identifier. When, the control of program reaches to goto statement, the
control of the program will jump to the label: and executes the code below it.
Or
The goto statement requires a label to identify the place to move the execution. A label is a valid
variable/identifier name and must be ended with colon ( : )
Flowchart

Example
int main()
{
int age;
Vote:
printf("you are eligible for voting");
NoVote:
printf("you are not eligible to vote");
printf("Enter you age:");
scanf("%d", &age);
if(age>=18)
goto Vote;
else
goto NoVote;
return 0;

}
Output
Enter you age:19
you are eligible for voting
Enter you age:15
you are not eligible to vote
Break Statement
Break is a keyword. The break statement terminates the loop (for, while and do...while loop)
immediately when it is encountered. The break statement is used/ associated with decision making
statement such as if ,if-else.
Syntax of break statement
break;
Flowchart

How break statement works?


Example
#include <stdio.h>
#include <conio.h>
void main(){
int i=1;//initializing a local variable
clrscr();
//starting a loop from 1 to 10
for(i=1;i<=10;i++){

printf("%d \n",i);
if(i==5){//if value of i is equal to 5, it will break the loop
break;
}
}//end of for loop
getch();
}
Output
12345

Continue Statement
Continue is keyword exactly opposite to break. The continue statement is used for continuing next
iteration of loop statements. When it occurs in the loop it does not terminate, but it skips some
statements inside the loop / the statements after this statement. . The continue statement is used/
associated with decision making statement such as if ,if-else.
Syntax of continue Statement
continue;
Flowchart of continue Statement

How continue statement works?


Example

1. #include <stdio.h>
2. #include <conio.h>
3. void main(){
4. int i=1;//initializing a local variable
5. clrscr();
6. //starting a loop from 1 to 10
7. for(i=1;i<=10;i++){
8. if(i==5){//if value of i is equal to 5, it will continue the loop
9. continue;
10. }
11. printf("%d \n",i);
12. }//end of for loop
13. getch();
14. }
Output
1234678910

Comparision between break and continue statements

Break
Continue
1 : break statement takes the control to the 1 :continue statement takes the control to
ouside of the loop the beginning of the loop..
2 : it is also used in switch statement. 2 : This can be used only in loop
statements.
3 : Always associated with if condition in 3 : This is also associated with if
loops. condition.
UNIT -7
Functions
7.1 Advantages of using Function
7.2 User Defined & Library Functions
7.3 Function Prototypes, definition & return statement
7.4 Call by Value & Call by reference
7.5 Concept of Local, Global & Static variables
7.6 Recursive Function
7.7 Storage Classes and Visibility, Automatic or local variables, Global variables, Static variables,
External variables

Functions
Functions are building blocks of a C program. Understanding functions is one of the most
important steps in C language.
Definition
A function is a self-contained program segment that carries out a specific, well-defined
task. A function is a collection of instructions that performs a specific task. Every function
is given a name. The name of the function is used to invoke (call) the function. A
function may also take parameters (arguments). If a function takes parameters, parameters
are to be passed within parentheses at the time of invoking function.
A function theoretically also returns a value, but you can ignore the return value of the
function in C language. Function name must follow the same rules of formation as other
variables in C. The argument list contains valid variable names separated by commas.
C is a function-oriented language. Many operations in C language are done through
functions. For example, we have used printf() function to display values, scanf() function
to read values from keyboard, strlen() function to get the length of the string etc.

Classification of Functions
C functions can be classified into two categories namely
1. Library functions
2. User defined functions.
The main difference between these 2 categories is that
 library functions are not required to be written by the user, printf, scanf, strlen, sqrt
and pow, etc belong to the category of library functions.
 user defined function has to be developed by the user at the time of writing a
program. main() function is an example of user-defined function. Every program
must have a main function to indicate where the program has to begin its
execution.
Standard/Library functions
A function which is made available to programmer by compiler is called as
standard or pre-defined function. Every C compiler provides good number offunctions. All that a
programmer has to do is use them straight away. For example, if you have to find length of a
string , use strlen() without having to write the required code.
The code for all standard functions is available in library files, like cs.lib, and
graphics.lib. These library files are supplied by the vendor of compiler. Where
these libraries are stored in the system depends on the compiler. For example, if
you are using Turbo C, you find libraries in LIB directory under directory where
Turbo C is installed.
Declarations about standard functions are available in header files such as stdio.h,
and string.h. Turbo C provides around 400 functions covering various areas like
Screen IO, graphics, disk IO etc.
User-defined functions
User-defined function is a function that is defined by user. That means, the code
for the function is written by user (programmer). User-defined functions are
similar to standard functions in the way you call. The only difference is instead of
C language providing the function, programmer creates the function.
If a program is divided into functional parts than each part may be independently coded
and later combined into single unit.
Advantages of Functions:
1. The length of the source program can be reduced by using functions at appropriate
places.
2. It becomes easier to locate a faculty functions.
3. Many other programs may use a function.
User-defined functions are used mainly for two purposes:
(1) To avoid repetition of code
In programming you often come across the need to execute the same code in
different places in the program. For exam ple, if you have to print an array at the
beginning of the program and at the end of the program. Then you need to write
the code to display the array twice.
If you create a function to display the array, then you have to call the function
once at the beginning of the program. That means, the source code need not be
written for multiple times. It is written only for once and called for multiple times.
(2) To break large program into smaller units
It is never a good idea to have a single large code block. If you write entire C
program as one block, the entire blocks ends up in main() function. It becomes
very difficult to understand and manage.

If you can break a large code block into multiple smaller blocks, called functions,
then it is much easier to manage the program. In the following example, instead
of taking input, processing and displaying output in main() function, if you can
divide it into three separate functions, it will be much easier to understand and
manage.

Creating user-defined function


A user-defined function is identical to main() function in creation. However, there are
two differences between main function and a user-defined function.
 Name of main() function is standard, whereas a user-defined function can have
any name.
 main() function is automatically called when you run the program, whereas a user-
defined function is to be explicitly called.

Terminology of Functions
Function Declaration:
A function may contain declaration and definition. Function declaration specifies
function name, return type, and type of parameters. This is normally given at the
beginning of the program. Though it is not mandatory in all cases, it is better to declare
each function. In fact header files (*.h) contain declarations of all standard functions.
following is the syntax for function declaration.
return-type functionname ( parameters );
Function declaration is called as Prototype declaration. Though it is not necessary in
majority of cases, it is needed in cases where the following conditions apply:
 Call to function comes before definition of the function
 Function returns non-integer value.

Function Definition:
Function definition is where the statements to be executed are given. When the function
is called the statements given here are executed.
return-type function nname ( parameters )
{
statements;
return value;
}
Where,
Return type: specifies the type of value function returns. If function doesn’t return any
value then it must be void.
Parameters are :formal parameters of the function.
Statements :are the statements to be executed when function is called.
Return: statement is used to return a value from function.

Caller and Callee


The function which calls another function is called caller. The function which is called by
the caller is called callee.

Passing Parameters:
A parameter or argument is a value passed to function so that function can use that value
while performing task. A function may take none, one or more parameters depending
upon the need.
Example: line(); /*function that pass no parameters*/
line(20); /*function that pass one parameter*/
getaverage(10,20); /*function that pass more than one parameter*/

Actual Parameter: It is the value that is passed to function while calling the function. For
example; 10 and 20 values that we passed to line() and getaverage() function in the
above are actual parameters.
Formal Parameter: Variable that is used to receive actual parameter is called formal
parameter.
Example: getaverage(int a, int b); Here a and b are formal parameters.

Returning Value:
Normally after performing the task functions return a value. The return value may be of
any type. But a function can return only one value. To return a value from the function,
we have to first specify what type of value the function returns and then we have to use
return statement in the code of the function to return the value.
When return type is not explicitly mentioned it defaults to int. If a function doesn't
return any value then specify return type as void.
A function returns the value to the location from where it has been called.

Storage Classes
Properties of a variable:
A variable in C language is associated with the following properties:

Blocks:
C is a block structured language. Blocks are delimited by { and }. Every block can have its
own local variables. Blocks can be defined wherever a C statement could be used. No
semi-colon is required after the closing brace of a block.

Scope
The area of the program from where a variable can be accessed is called as scope of the
variable. The scope of a variable determines over what parts of the program a variable is
actually available for use (active). Scope of the variable depends on where the variable is
declared. The following code illustrate the scope of a variable:
int g; /* scope of g is from this point to end of program */
main()
{
int x; /* scope of x is throughout main function */
. . . .
}
void sum()
{
int y; /* scope of y is throughout function sum */
. . . .
}
The scope of a variable may be either global or local.

Global Scope: It means the variable is available throughout the program. It is available to
all functions that are defined after the declaration of the variable. This is the scope of the
variables, which are declared outside of all functions. Variables that have global scope are
called as Global Variables.
In the above example, variable g has global scope; that means the variable is accessible to
all the functions of the program (main, sum) that are defined after the variable is defined.

Local Scope: Variables declared at the beginning of the block are available only to that
block in which they are declared. When the scope of the variable is confined to block it is
called as Local Scope. Variables with local scope are called as Local Variables.
In the above example, variables x and y have local scope; that means the variables are
accessible only to the functions at which they are declared.
C allows you to create variables not only at the beginning of a function, you can also
declare variables at the beginning of the block.
main()
{
int x; /* scope of x is throughout main function */
. . . .
if( ...) {
int p; /* scope of p is accessible only within if block */
. . . .
}
else {
int q; /*scope of q is accessible only within else block*/
. . . .
}
}
You cannot change the scope of a variable, it is completely dependent on the place of
declaration in the program.

Visibility:
Normally visibility and scope of variables are same. In other words, a variable is visible
throughout its scope.
Visibility means the region of the program in which a variable is visible. A variable can
never be visible outside the scope. But it may be invisible inside the scope.
int g; /* scope of g is from this point to end of program */
main()
{
int x; /* scope of x is throughout main function */
. . . .
}
void sum()
{
int y; /* scope of y is throughout function sum */
int g;
g=20; /* local variable g is used not global variable g */
}
In the above code, variable g has global scope. But it becomes invisible throughout the
function sum as a variable with the same name is declared in that function.
When a global variable is re-declared in a function then the local variable takes
precedence i.e., g in function sum will reference g in function but not g declared as global
variable. So, in this case though g has scope throughout program, it is not visible
throughout function sum.
For global variable to get its visibility in a function, when a local variable with same
variable name is declared and use we use scope resolution operator(::). This helps in
accessing global variable even though another variable with same name is existing.
int g; /* scope of g is from this point to end of program */
main()
{
int x; /* scope of x is throughout main function */
. . . .
}
void sum()
{
int y; /* scope of y is throughout function sum */
int g;
g=20; /* local variable g is used not global variable g */
::g=g+10; /*global variable g is used now with the operator*/
/*'::' called scope resolution operator*/
}

Extent/Lifetime
Also called as Longevity. This refers to the period of time during which a variable resides
in the memory and retains a given value during the execution of a program. Longevity
has a direct effect on the utility of a given variable.
A variable declared inside a block has local extent. Because it exists in the memory as
long as the block is in execution. It is created when block is invoked and removed when
the execution of the block is completed.
On the other hand, variable declared outside all functions has static extent as they remain
in memory throughout the execution of program.
Though variable is available in memory, we can access it only from the region of the
program to which the variable is visible. That means, just because the variable is there in
the memory we cannot access it.
STORAGE CLASS SPECIFIERS
'Storage' refers to the scope of a variable and memory allocated by compiler to store that
variable. Scope of a variable is the boundary within which a variable can be used.
Storage class defines the scope and lifetime of a variable.
From the point view of C compiler, a variable name identifies physical location from a
computer where variable is stored. There are two memory locations in a computer
system where variables are stored as: Memory and CPU Registers.
Functions of storage class:
 To determine the location of a variable where it is stored?
 Set initial value of a variable or if not specified then setting it to default value.
 Defining scope of a variable.
 To determine the life of a variable.
Syntax:
[storage-class] data type variable [= value] ;

Types of Storage Classes


 auto
 register
 static
 extern

auto or Automatic Storage class


This is normally not used as it is always implicitly associated with all local variables. The
keyword used for this storage class is auto. An auto variable is automatically created and
initialized when control enters into a block and removed when control comes out of
block.
auto int i=30; /*an auto variable with local scope and extent*/
Storage Location: Main Memory
Default Value: Garbage
Scope: Local to the block in which variable is declared
Lifetime: till the control remains within the block.
Example: Program to illustrate how auto variables work.
main() {
auto int i=10;
clrscr();
{
auto int i=20;
printf("%d",i);
}
printf("\t%d",i);
}

register or Register Storage class


We can tell the compiler that a variable should be kept in registers (which are memory
locations on microprocessors used for internal operations), instead of keeping in the
memory (where normal variables are stored).
Since a register access is much faster than a memory access, keeping the frequently
accessed variables (e.g. loop control variables) in the registers will lead to faster
execution of program. Most of the compilers allow only int or char variables to be
placed in the register.
register int i;
The above is a request to the compiler to allocate a register to variable i instead of
allocating memory. If the register is available then i is placed in register, otherwise it is as
usual given memory location.
The programmer doesn't know whether register is allocated or memory is allocated to a
variable that is used with register storage class. So, it is not possible to use address
operator (&) with variables that contain register storage specifier. This is of the fact that
registers do not contain address.
It is not applicable for arrays, structures or pointers. It cannot not used with static or
external storage class.
Storage Location: CPU registers
Default Value: Garbage
Scope: Local to the block in which variable is declared
Lifetime: till the control remains within the block.
Since, there are limited number of register in processor and if it couldn't store the variable
in register, it will automatically store it in memory.
Example:
main()
{
register int i;
for(i=0;i<10000;i++)
. . . .
}

static or Static Storage Class


static is the default storage class for global variables. This is used to promote local extent
of a local variable to static extent.
The value of static variables persists until the end of the program. A variable can be
declared static using the keyword static like
static int x;
static float y;
When you use static storage class while declaring local variable, instead of creating the
variable and initializing it whenever control enters the block, the variable is created and
initialized only for once - when variable's declaration is encountered for first time. So a
variable with static extent will remain in the memory across function calls.
Storage Location: Main Memory
Default Value: Zero
Scope: Local to the block in which variable is declared
Lifetime: till the value of the variable persists between different function calls.
Example: Program to illustrate the properties of a static variable.
main() {
int i;
for (i=0; i<3; i++)
incre();
}
incre() {
int avar=1;
static int svar=1;
avar++; svar++;
printf("\n Automatic variable value : %d",avar);
printf("\t Static variable value : %d",svar);
}
Output:
Automatic variable value: 2 Static variable value: 2
Automatic variable value: 2 Static variable value: 3
Automatic variable value: 2 Static variable value: 4

extern or External Storage class:


extern is used to give a reference of a global variable that is visible to ALL the program
files. When you use 'extern' the variable cannot be initialized as all it does is point the
variable name at a storage location that has been previously defined.
External variable can be accessed by any function. They are also known as global
variables. Variables declared outside every function are external variables.
When you have multiple files and you define a global variable or function which will be
used in other files also, then extern will be used in another file to give reference of
defined variable or function.
In case of large program, containing more than one file, if the global variable is declared
in file 1 and that variable is used in file 2 then, compiler will show error. To solve this
problem, keyword extern is used in file 2 to indicate that, the variable specified is global
variable and declared in another file.
/* File1.c */
extern int count; /* refers to an external variable count */
inccount() {
count++;
}
/* File2.c */
#include"File1.c"
int count; /* creates variable count with static extent */
main() {
. . .
}
In this case program File1.c has to access the variable defined in program File2.c.
Storage Location: Main Memory
Default Value: Zero
Scope: Global/File Scope
Lifetime: as long as the program execution doesn't come to an end.
Example: Program to illustrate extern storage class
write.c
void write_extern();
extern int count;
void write_extern()
{
count = count + 2;
printf("Count is %d\n",count);
}
mmain.c
#include"write.c"
int count=5;
main() {
write_extern();
write_extern();
}

Category of Functions:
A function depending on whether arguments are present or not and whether a value is
returned or not may belong to one of the following categories:
1. Functions with no arguments and no return value.
2. Functions with arguments and no return value.
3. Functions with arguments and return value.
4. Functions with no arguments and return value.

Functions with no arguments and no return value


When a function has no argument, it does not receive any data from calling function.
When it does not return a value, the calling function does not receive any data from
called function. In effect, there is no data transfer between calling function & called
function.
Program 1:
#include<stdio.h>
main()
{
printf("Text in main Function\n");
print();
}
print()
{
printf("\nText in print function");
}
Program 2:
#include<stdio.h>
main()
{
printf("Addition of 2 numbers:\n");
sum();
}
sum()
{
int a,b;
printf("Enter 2 numbers: ");
scanf("%d %d",&a,&b);
printf("\nSum of %d and %d is %d",a,b,a+b);
}
Functions with no arguments and return value
When a function has no argument, it does not receive any data from calling function.
When it does return a value, the calling function receives data from called function. In
effect, there is data transfer between called function & calling function.
Program:
#include<stdio.h>
float average();
main()
{
float avg;

printf("Average of 3 numbers:\n");
avg = average();
printf("Average: %f",avg);
}
float average()
{
int a,b,c,s;
printf("Enter 3 numbers: ");
scanf("%d %d %d",&a,&b,&c);
s=a+b+c;
return s/3.0;
}
Functions with arguments and no return value
When a function has argument(s), it does receive data from calling function. When it
does not return a value, the calling function receives does not data from called function.
In effect, there is data transfer between calling function & called function.
Program 1:
#include<stdio.h>
main()
{
dline(15);
printf("\nFunctions...");
dline(15);
getch();
}
dline(int n)
{
int l;
for(l=0;l<n;l++)
putch('-');
}
Program 2:
#include<stdio.h>
void interest(float,int,float);
main()
{
int t;
float p,r;
printf("Enter principal amount: ");
scanf("%f",&p);
printf("Enter time period: ");
scanf("%d",&t);
printf("Enter rate: ");
scanf("%d",&r);
interest(p,t,r);
}
void interest(float pr,int tp,float rate)
{
float si;

si = (pr*tp*rate)/100;
printf("Simple Interest for Rs %0.2f is %0.2f",pr,si);
}
Functions with arguments and return value
When a function has an argument, it receives back any data from calling function. When
it returns a value, the calling function receives any data from called function. In effect,
there is a data transfer between the calling function & called function.
Program:
int getsum(int n);
main()
{
int v,sum;
printf("Enter n value: ");
scanf("%d",&v);
sum = getsum(v);
printf("Sum=%d",sum);
}
int getsum(int n)
{
int s=0;
for(;n>0;n--)
s+=n;
return s;
}

Parameter Passing Techniques: Call by Value & Call by Reference


Call by Value:
If data is passed by value, the data is copied from the variable used in main() to a
variable used by the function. So if the data passed (that is stored in the function
variable) is modified inside the function, the value is only changed in the variable used
inside the function.
When we call a function then we will just pass the variables or the arguments and we
doesn’t pass the address of variables , so that the function will never effects on the values
or on the variables.
So Call by value is that the values those are passed to the functions will never effect the
actual values those are Stored into the variables.
Example: Program to illustrate the concept of call by value
#include <stdio.h>
swap (int, int);
main()
{
int a, b;
printf("\nEnter value of a & b: ");
scanf("%d %d", &a, &b);
printf("\nBefore Swapping:\n");
printf("\na = %d\n\nb = %d\n", a, b);
swap(a, b);
printf("\nAfter Swapping:\n");
printf("\na = %d\n\nb = %d", a, b);
getch();
}
swap (int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
Output:
Enter value of a & b: 2 3
Before swapping: 2 3
After swapping: 2 3

Call by Reference:
If data is passed by reference, a pointer to the data is copied instead of the actual
variable as it is done in a call by value. Because a pointer is copied, if the value at that
pointers address is changed in the function, the value is also changed in main().
In the call by reference we pass the address of the variables whose arguments are also
send. So that when we use the reference then, we pass the address the variables.
When we pass the address of variables to the arguments then a function may effect on
the variables. So, when a function will change the values then the values of variables gets
automatically changed and when a function performs some operation on the passed
values, then this will also effect on the actual values.
Example: Program to illustrate the concept of call by reference
#include <stdio.h>
swap (int *, int *);
main()
{
int a, b;
printf("\nEnter value of a & b: ");
scanf("%d %d", &a, &b);
printf("\nBefore Swapping:\n");
printf("\na = %d\n\nb = %d\n", a, b);
swap(&a, &b);
printf("\nAfter Swapping:\n");
printf("\na = %d\n\nb = %d", a, b);
getch();
}
swap (int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
Output:
Enter value of a & b: 2 3
Before swapping: 2 3
After swapping: 3 2

Passing an array as argument to function:


An array is actually held as an address to an area of memory. This means that when you
come to pass it into a function, it can only be passed in as a reference.
Also, when you define the parameter to read in the data in the function prototype, you
declare it as though you were reading in a single-item variable instead of an array. When
an array is passed as parameter, only the name of the array is given at the time of calling
function the formal parameter is to be declared as an array.

It is then up to the function to read the first item from the array, move the pointer along
to the next item, and then carry on until it finds the end of the array - thus, it has to
somehow know how long the array is.
function_name(int x[5])
function_name(int x[])
The parameter x in the above declarations are also internally taken as an integer pointer
by C to access the elements of the array from the first element.
Passing a 1-dimensional array as argument to function:
Example 1: Program to print the given array
printarray(int []);
main()
{
int a[5],i;
for(i=0;i<5;i++)
scanf("%d",&a[i]);
printarray(a);
}
printarray(int ar[5])
{
int i;
for(i=0;i<5;i++)
printf("%d\n",i[ar]);
}
Example 2: Program to find largest from the given array
#define SIZE 50
int big(int [], int);
main()
{
int a[SIZE], n, i, b;
printf("\nEnter size of array: ");
scanf("%d", &n);
printf("\nEnter elements:\n");
for (i=0; i<n; i++)
scanf("%d", &a[i]);
b = big(a, n);
printf("\nLargest number: %d", b);
}
int big(int a[], int n)
{
int b, i;
b = a[0];
for(i=0; i<n; i++)
if (a[i] > b) b = a[i];
return b;
}

2-dimensional array as argument to function:


Example: Program to find Diagonal elements of given matrix
#define ROW 10
#define COL 10
int trace(int [][], int, int);
main()
{
int a[ROW][COL], row, col, i, j, sum;
printf("\nEnter no. of rows and columns of a matrix: ");
scanf("%d %d", &row, &col);
printf("\nEnter elements:\n");
for (i=0; i<row; i++)
for (j=0; j<col; j++)
scanf("%d", &a[i][j]);
printf("\nMatrix is:\n\n");
for (i=0; i<row; i++)
{
for (j=0; j<col; j++)
printf("\t%d", a[i][j]);
printf("\n");
}
sum = trace(a, row, col);
printf("\nSum: %d", sum);
}
int trace(int x[ROW][COL], int r, int c)
{
int i, j, s=0;
for (i=0; i<r; i++)
for (j=0; j<c; j++)
if (i == j) s = s + x[i][j];
return s;
}
Passing String as Parameter to function
This is similar to the concept of passing an array to a function as argument. With strings
(i.e. character arrays) - we have one advantage: we know that the end of the array is
marked by a zero character, so as long as we know where the beginning of the array is,
we can find the end of the string of characters by moving from the beginning of the array
to the end one-character at a time.
Example: Program to modify a string and display.
main()
{
char st[20];
printf("Enter Name: ");
gets(st);
modifystring(st);
printf("\n%s",st);
}
modifystring(char st[20]) {
strcat(st," Welcome");

}
Passing structure as argument to function
A structure can be passed to a function. To pass a structure to a function you have to
pass it just like how you would pass standard data types like int and float.
Example: Program to illustrate the concept of passing structure to function.
struct point
{
int x,y;
};
void display(struct point t);
main()
{
struct point p;
printf("Read Coordinates of a point: ");
scanf("%d %d",&p.x,&p.y);
display(p);
}
void display(struct point t)
{
printf("Coordinates of a point: x=%d, y=%d",t.x,t.y);
}
When you are sending a structure to a function, make sure that both calling function and
called function have access to structure. This can be done if you declare the structure at
the beginning of the program.
Just like how we send a structure variable to a function you can also send an array of
structures to a function.
Return a Structure
A function can also return a structure as return type. All that you have to do is specify
return type as structure and return a structure variable.
Example: Program to call a function that returns a variable of structure.
struct point {
int x,y;
};
struct point getpoint();
main()
{
struct point p;
p = getpoint();
printf("Coordinates of a point: x=%d, y=%d",p.x,p.y);
}
struct point getpoint()
{
struct point t;
printf("Enter point coordinates: ");
scanf("%d %d",&t.x,&t.y);
return t;
}

Passing array to function and accessing array with pointer


Whenever you send an array to function as parameter, you send the address of the array
and not the complete array. That means, whenever an array is passed it is passed by
reference. The formal parameter in called function is nothing but a pointer pointing to
first element of array.
function_name(int *x): This declaration declares x as an integer pointer. All that C needs
here is a pointer to integer.
Example: Program to display the given array of elements.
main()
{
int arr[10],i;
printf("Enter 10 elements: ");
for(i=0;i<10;i++)
scanf("%d",&arr[i]);
displayarray(arr);
}
displayarray(int *a)
{
int i;
printf("Elements in reverse order: ");
for(i=10-1;i>=0;i--)
printf("%d ",*(a+i));
}
Passing string to function and accessing string with pointer
Strings which are made up of characters, we'll be using pointers to characters. However,
pointers only hold an address; they cannot hold all the characters in a character array.
This means that when we use a char * to keep track of a string, the character array
containing the string must already exist.
Example: Program to accept string and display vowels
vowels(char *p);
main()
{
char str[10];
printf("\nEnter the string: ");
gets(str);
vowels(str);
}
vowels(char *p)
{
int i,l;
l=strlen(p);
printf("\n\nThe vowels in the string are: ");
for(i=0;i<l;i++)
{
if(p[i]=='a' || p[i]== 'e' || p[i]=='i' || p[i]=='o' ||
p[i]=='u'|| p[i]=='A' || p[i]=='E' || p[i]=='I' ||
p[i]=='O' || p[i]=='U')
{

printf("%c",p[i]);
}
else
continue;
}
}
Calling Function within Function
One of the main reasons of using various functions in your program is to isolate
assignments; this allows you to divide the jobs among different entities so that if
something is going wrong, you might easily know where the problem is.
Functions trust each other, so much that one function does not have to know HOW the
other function performs its assignment. One function simply needs to know what the
other function does, and what that other function needs.
Once a function has been defined, other functions can use the result of its assignment.
Imagine you define two functions A and B.

If Function A needs to use the result of Function B, function A has to use the name of
function B. This means that Function A has to “call” Function B:

When calling one function from another function, provide neither the return value nor
the body, simply type the name of the function and its list of arguments, if any.

Example: Program to call function inside a function.


main()
{
processinput();
getch();
}
processinput()
{
int a,b,sum;
printf("Enter 2 numbers: ");
scanf("%d %d",&a,&b);
sum = process(a,b);
displayresult(a,b,sum);
}
process(int a,int b)
{
return a+b;
}
displayresult(int x,int y,int s)

{
printf("Sum of 2 numbers %d and %d is %d",x,y,s);
}
Pointer to Function
It is also possible to have a pointer pointing to a function. A pointer to a function
contains the address of the location to which control is transferred when you use the
pointer.
The following example shows how to declare a pointer to a function and use it to
invoke the function.
/*pointer pointing to function that returns void*/
void (*fp)();
void print();
main()
{
/*make fp pointing to print function*/
fp = print;
/*call print function through pointer to function*/
(*fp)();
}
void print()
{
printf("Hello! From Function Print...");
}
Recursion
Recursion is a process of defining something in terms of itself and is sometimes called
circular definition. When a function calls itself it is called as recursion. Recursion is natural
way of writing certain functions.
Recursive Function: A function is said to be recursive if a statement in the body of the
function calls itself. Each recursive function must specify an exit condition for it to
terminate, otherwise it will go on indefinitely.
A simple example of recursion is presented below:
main()
{
printf("\nThis is an example of recursion");
main();
}
When executed, this program will produce an output like:
This is an example of recursion
This is an example of recursion



This is an example of recursion

Execution must be terminated abruptly (suddenly or unexpected) or forcibly, otherwise


the execution will continue infinitely.
Recursive functions can be effectively used to solve problems where the solution is
expressed in terms of successively applying the same solution of the subset of the
problem.
When we write recursive functions we must have an if statement somewhere to force the
function to return without recursive calls being executed. Otherwise function will never
return back and will be terminated with an error saying “out of stack space”.
Example: Program to find sum of n below numbers using recursion.
#include <stdio.h>
main()
{
int n,sum;
printf("\nEnter n value: ");
scanf("%d", &n);
sum = sum_num(n);
printf("\nSum of %d below numbers is %d",n,sum);
getch();
}
sum_num(int n)
{
if (n == 1)
return n;
else
return n+sum_num(n-1);
}
sum_num(5) returns (5 + sum_num(4),
which returns (4 + sum_num(3),
which returns (3 + sum_num(2),
which returns (2 + sum_num(1),
which returns (1)))))
Example: Program to find factorial of given number using recursion.
#include <stdio.h>
long fact(int);
main()
{
int n;
long f;
printf("\nEnter number to find factorial: ");
scanf("%d", &n);
f = fact(n);
printf("\nFactorial: %ld", f);
getch();
}

long fact(int n)
{
int m;
if (n == 1)
return n;
else
return n * fact(n-1);
}
Example: Program to find the GCD of two given integers using Recursion
#include<stdio.h>
#include<conio.h>
int gcd (int, int); //func. declaration.
void main( )
{
int a, b, res;
clrscr( );
printf("Enter the two integer values:");
scanf("%d%d", &a, &b);
res= gcd(a, b); // calling function.
printf("\nGCD of %d and %d is: %d", a, b, res);
getch( );
}
int gcd( int x, int y) //called function.
{
int z;
z=x%y;
if(z==0)
return y;
gcd(y,z); //recursive function
}
Example: Program to generate the Fibonocci series using Recursion.
#include<stdio.h>
#include<conio.h>
int fibno(int); // function declaration.
void main()
{
int ct, n, disp;
clrscr( );
printf("Enter the no. of terms:");
scanf("%d", &n);
printf("\n The Fibonocci series:\n");
for( ct=0; ct<=n-1; ct++)
{
disp= fibno(ct); //calling function.
printf("%5d", disp);
}
getch( );
}
int fibno( int n)

{
int x, y;
if(n==0)
return 0;
else if(n==1)
return 1;
else
{
x= fibno( n-1);
y= fibno( n-2);
return (x+y);
}
}
UNIT – 8
Arrays and Strings
8.1 Introduction
8.2 Single and Multi-dimension arrays
8.3 Processing an array
8.4 Passing arrays to Functions
8.5 Arrays of Strings
8.6 String Handling Function

ARRAYS

An array is a collection of similar datatype that are used to allocate memory in a


sequential manner.

Array is a collection or group of elements (data). All the elements of array are
homogeneous (similar). It has contiguous memory location.

Array of character is a string. Each data item of an array is called an element. And
each element is unique and located in separated memory location. Each of
elements of an array share a variable but each element having different index no.
known as subscript.
An array can be a single dimensional or multi-dimensional and number of
subscripts determines its dimension. And number of subscript is always starts
with zero. One dimensional array is known as vector and two dimensional arrays
are known as matrix.

Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Easy to traverse data: By using the for loop, we can retrieve the elements of an
array easily.
3) Easy to sort data: To sort the elements of array, we need a few lines of code
only.
4) Random Access: We can access any element randomly using the array.

Disadvantage of Array
Fixed Size: Whatever size, we define at the time of declaration of array, we can't
exceed the limit. So, it doesn't grow the size dynamically like LinkedList.
Types of Array
1. Static Array
2. 2. Dynamic Array.
Static Array An array with fixed size is said to be a static array.
Types of static array:
1. One Dimensional Array
2. Two Dimensional Array.
3. Multi Dimensional Array.

1. One Dimensional Array An Array of elements is called 1 dimensional, which


stores data in column or row form. Example: int ar[5]; This above array is called
one dimensional array because it will store all the elements in column or in row
form .

2. Two Dimensional Array. An array of an array is said to be 2 dimensional array ,


which stores data in column androw form Example: int ar[4][5]; This above array
is called two dimensional array because it will store all the elements in column
and in row form .
NOTE: In above example of two dimensional array, we have 4 rows and 5
columns.
NOTE: In above example of two dimensional array, we have total of 20 elements.

3. Multi Dimensional Array. This array does not exist in c and c++.

Dynamic Array. This type of array also does not exist in c and c++.

Example: Program based upon array:


WAP to store marks in 5 subjects for a student. Display marks in 2nd and
5thsubject.
#include<stdio.h>
#include<conio.h>
void main()
{
int ar[5];
int i;
for(i=0;i<5;i++)
{
printf("\n Enter marks in ",i, "subject");
scanf("%d",&ar[i]);
}
printf("Marks in 2nd subject is: ",ar[1]);
printf("Marks in 5th subject is: ",ar[4]); }

Declaring an array
An array is declared just like an ordinary variable but with the addition of number
of elements that the array should contain.
A particular value is indicated by writing a number called 'index or subscript'
number in brackets for after the array name.
Syntax:
type variablename[size];
The type specifies data type of element that will be contained in an array such as
int, float, char, and double.
The size indicates the maximum number of elements that can be stored inside the
array.
E.g. The following declaration declares n array of 20 elements where each
element is of int type.
int marks[20];
Now, marks is the name of the array of 20 integers. Marks occupies 40 bytes, if int
occupies 2 bytes (20*2).

Array can be of any variable type. The ability to use a single name to represent a
collection to refer to an item by specifying the item number enables us to develop
efficient programs.
TYPES:
Arrays in C Programming are of 3 types:
(1) One [or] Single Dimensional Array
(2) Two [or] Double Dimensional Array
(3) Multi Dimensional Array
ONE-DIMENSIONAL ARRAY
A list of items can be given one variable name using only one subscript and such a
variable is called a single subscripted variable or one dimensional array.
For Example: If we want to represent a set of 5 numbers 35, 40, 20, 57, 19 by an array
variable 'number' then we may declare the variable number as follows:
int number[5]; and computer reverses 5 storage locations are shown below:
The elements can be used in programs just like as any other 'C' variable.
It is not possible to either add new elements or delete existing elements after the array is
created. In other words the size of the array is static and it cannot be changed at runtime.

Initializing an array
It is possible to store values into an array during time of declaration.
int a[5] = {10, 20, 30, 40, 50};
Values given in { } are placed in corresponding element of an array. If number of values
given is more than the size, C displays an error "Too many Initializers in Function...". If
number of values given is less than the size, then the number of elements then only the
corresponding elements are filled.
In certain case, you can ignore the size of the array if you are initializing the array. C
determines the size of the array from the number of values given in the initialization.
int a[] = {20,30,40}; /*is an array of 3 elements*/
Sample C Programs
Example: Program to insert elements into an array and print the array elements.
#include<stdio.h>
#include<conio.h>
main()
{
int a[5],i;
clrscr();
printf("Enter 5 elements into an array:\n");
for(i=0;i<=4;i++) {
scanf("%d",&a[i]);
}
printf("The 5 elements are:\n");
for(i=0;i<=4;i++)
printf("%d\n",a[i]);
getch();
}
Output:
Enter 5 elements into an array:
35
23
45
67
11
The 5 elements are:
35
23
45
67
11

Example: Take an array of 10 integers and accept values into it. Sort the array in
descending order.
#include<stdio.h>
#include<conio.h>
main()
{
int ar[10];
int i, j, temp;
clrscr();
for (i = 0 ; i < 10 ; i++)
{
printf("Enter number for [%d] element: ",i);
scanf("%d", &ar[i]);
}
/* sort array in descending order */
for ( i = 0 ; i < 9 ; i++)
{
for ( j = i+1; j < 10 ; j ++)
{
if ( ar[i] > ar[j])
{
/* interchange */
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
} /* end of j loop */
} /* end of i loop */
/* display sorted array */
printf("\nSorted Numbers \n");
for ( i = 0 ; i < 10 ; i++)
{
printf("%d\n", ar[i]);
}
getch();
}
Output:
Enter number for [0] element: 35
Enter number for [1] element: 67
Enter number for [2] element: 98
Enter number for [3] element: 12
Enter number for [4] element: 6
Enter number for [5] element: 58
Enter number for [6] element: 49
Enter number for [7] element: 23
Enter number for [8] element: 71
Enter number for [9] element: 85
Sorted Numbers
6
12
23
35
49
58
67
71
85
98

Example: Program to search an element in an array using Linear search (Sequential


Search)
Linear search or sequential search is a method for finding a particular value in a list that
checks each element in sequence until the desired element is found or the list is
exhausted.
#include<stdio.h>
int main(){
int a[10],i,n,m,c=0;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i=0;i<=n-1;i++){
scanf("%d",&a[i]);
}
printf("Enter the number to be search: ");
scanf("%d",&m);
for(i=0;i<=n-1;i++){
if(a[i]==m){
c=1;
break;
}
}
if(c==0)
printf("The number is not in the list");
else
printf("The number is found");
return 0;
}
Sample output:
Enter the size of an array: 5
Enter the elements of the array: 4 6 8 0 3
Enter the number to be search: 0
The number is found

Example: Program to search an element in an array using Binary search


The binary search begins by comparing the target value to value of the middle element
of the sorted array.
If the target value is equal to the middle element's value, the position is returned.
If the target value is smaller, the search continues on the lower half of the array,
or if the target value is larger, the search continues on the upper half of the array.
This process continues until the element is found and its position is returned, or
there are no more elements left to search for in the array and a "not found"
indicator is returned.
#include<stdio.h>
int main(){
int a[10],i,n,m,c=0,l,u,mid;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements in ascending order: ");
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
printf("Enter the number to be search: ");
scanf("%d",&m);
l=0,u=n-1;
while(l<=u){
mid=(l+u)/2;
if(m==a[mid]){
c=1;
break;
}
else if(m<a[mid]){
u=mid-1;
}
else
l=mid+1;
}
if(c==0)
printf("The number is not found.");
else
printf("The number is found.");
return 0;
}
Sample output:
Enter the size of an array: 5
Enter the elements in ascending order: 4 7 8 11 21
Enter the number to be search: 11
The number is found.

TWO-DIMENSIONAL ARRAY
A list of items can be given one variable name using two subscripts and such a variable is
called a double subscripted variable or two-dimensional array. So to access
twodimension array you have to have one row index and one column index.

Declaration of Two-dimensional array


The general form of Two-dimensional arrays is
Syntax:
type array_name[row_size][column_size];
For example, to access 3rd row and 2nd column of marks array you would give:
marks[2][1] = 70;
Initialization of 2D Array
There are many ways to initialize two Dimensional arrays –
int disp[2][4] = {
{10, 11, 12, 13},
{14, 15, 16, 17}
};
OR
int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};

Things which you must consider while initializing 2D array – You must remember that
when we give values during one dimensional array declaration, we don’t need to
mention dimension. But that’s not the case with 2D array; you must specify the second
dimension even if you are giving values during the declaration. Let’s understand this with
the help of few examples –
/* Valid declaration*/
int abc[2][2] = {1, 2, 3 ,4 }
/* Valid declaration*/
int abc[][2] = {1, 2, 3 ,4 }
/* Invalid declaration – you must specify second dimension*/
int abc[][] = {1, 2, 3 ,4 }
/* Invalid because of the same reason mentioned above*/
int abc[2][] = {1, 2, 3 ,4 }
Sample C Programs
Example: Program to insert elements into array and display the array
#include<stdio.h>
#include<conio.h>
main()
{
int a[2][2],i,j;
clrscr();
printf("Enter 4 elements into array: ");
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++) {
scanf("%d",&a[i][j]);
}
}
printf("The 4 elements are:\n\t");
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++) {
printf("%d\t",a[i][j]);
}
printf("\n\t");
}
getch();
}
Output:
Enter 4 elements into array:
6
3
2
1
The 4 elements are:
6 3
2 1
Example: Program to print Multiplication Table
#include<stdio.h>
#include<conio.h>
#define ROWS 5
#define COLUMNS 5
main()
{
int row,column,product[ROWS][COLUMNS];
int i,j;
clrscr();
printf(" MULTIPLICATION TABLE \n\n");
printf(" ");
for(j=1;j<=COLUMNS;j++)
printf("%4d",j);
printf("\n");
printf("-----------------------\n");
for(i=0;i<ROWS;i++)
{
printf(" ");
row=i+1;
printf("%2d",row);
for(j=1;j<COLUMNS;j++)
{
column=j+1;
product[i][j] = row*column;
printf("%4d",product[i][j]);
}
printf("\n");
}
getch();
}
Output:
MULTIPLICATION TABLE
1 2 3 4 5
-----------------------
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Example: Program to solve multiplication of 2 matrices
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q,k;
clrscr();
printf("Enter order of matrix A for m & n\n");
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("Enter a[%d][%d] element: ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("Enter order of matrix B for p & q\n");
scanf("%d%d",&p,&q);
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf("Enter b[%d][%d] element: ",i,j);
scanf("%d",&b[i][j]);
}
}
if(n==p) {
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<m;k++)
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
}
}
printf("A MATRIX\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%5d",a[i][j]);
}
printf("\n");
}
printf("B MATRIX\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf("%5d",b[i][j]);
}
printf("\n");
}
printf("Elements after multiplication\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%5d",c[i][j]);
}
printf("\n");
}
}
else
printf("Mutliplication Not Possible for given matrices!");
getch();
}
Output:
Enter order of matrix A for m & n
2 2
Enter a[0][0] element: 1
Enter a[0][1] element: 2
Enter a[1][0] element: 3
Enter a[1][1] element: 4
Enter order of matrix B for p & q
2 2
Enter b[0][0] element: 2
Enter b[0][1] element: 3
Enter b[1][0] element: 4
Enter b[1][1] element: 5
A MATRIX
1 2
3 4
B MATRIX
2 3
4 5
Elements after multiplication
10 13
22 29
Strings Handling
A collection of characters is called as string. In the absence of string data type to store
strings in C we have to simulate string using an array of characters. Any group of
characters (except double quote sign) defined between double quotation marks is a
constant string.
Character strings are often used to build meaningful and readable programs. The
common operations performed on character strings are:
 Reading and writing strings
 Combining strings together
 Copying one string to another
 Comparing strings for equality
 Extracting a portion of a string

Declaring a String
An array of characters is also a collection of characters. So an array of characters is used
to represent a string in C. For example, to store a name, which may be up to 50
characters, you would declare a string as follows:
/* name can contain up to 50 characters */
char name[50];
/* to store 10 names where each name can contain 20 characters */
char names[10][20];

How String is stored?


A string is stored as an array in the memory. However, when you declare a string of 20
characters, it doesn’t always contain 20 characters. It may contain only 15 characters. So
to identify the end of the actual characters in a string C is storing a null character (with
ASCII code 0) at the end of the string.
Null character is written as ‘\0’. It is the character for ASCII code 0. As no other character
contains ASCII code 0, when we encounter a null character in a string we can stop taking
characters after that character.

Initializing String Variables:


Character arrays may be initialized when they are declared. C permits a character array
to be initialized in either of the following two forms:
char text[9] = "WELCOME"; / char city[9] = "NEW YORK";
char text[9] = {'W', 'E', 'L', 'C', 'O', 'M', 'E'};
char text[9] = {'W', 'E', 'L', 'C', 'O', 'M', 'E', '\0'};
Input/output of Strings
You can read a string from keyboard. C has provided a conversion character %s for
inputting and outputting string. You can read a string using scanf() & print using printf().
The following code snippet is to read name of the user and display the same.
char name[30];
printf("What’s your name: ");
scanf("%s",name);
printf("Welcome %s",name);
There are few important points that you have to understand about reading strings using scanf()
 You must not precede string variable with & (ampersand). The reason will be evident to
you once you understand pointers. Giving & before the string variable is a logical error.
Compiler may not complain about it but program will not work.
 You can read the data from keyboard only up to first whitespace character (space or tab).
That means if I want to enter my name, I can enter only Johson and not complete name
“Johnson P D”. This is because of the fact that scanf() function assumes the end of the
input for a field once it encounters a whitespace character.
Note: While using %s to read a string with scanf(), do not precede variable with & symbol.
Another important point about strings is, all standard functions such as scanf() and
printf() take care of null character at the end of the string.
For instance, when you enter a string using scanf(), the function will automatically put a
null at the end of the string. And in the same way while you are printing, printf() will
take characters until null character is encountered.
String I/O
In order to read and write string of characters the functions gets() and puts() are used
gets() function reads the string and puts() function takes the string as argument and writes
on the screen.
(1) gets()
This function reads a sequence of characters entered through the keyword and is
useful for interactive programming. Since a string has no predetermined length
gets() needs a way to know to stop. It reads character until it reaches a new line
character. To terminate input at the keyword, press the ‘Enter’ key.
Syntax: gets(variable);

(2) puts()
The function puts() writes a string argument onto the screen. The puts() can only
output a string of characters. It takes less space and runs faster than printf().
Syntax: puts(variable);

Example: Program to print the accepted string.


/*Program to print accepted string*/
#include<stdio.h>
#include<conio.h>
main()
{
char ch[30];
clrscr();
printf("Enter String: ");
gets(ch);
printf("\nEntered String: ");
puts(ch);
}
Output:
Enter String: C is a good language.
Entered String: C is a good language.
The gets() and puts() functions offer simple alternatives with regard to the use of scanf()
and printf() which are of reading and displaying strings respectively. These executes faster
than printf() and scanf() due to the non-use of format specifies and occupies less space.

fflush(stdin):
The fflush(stdin) is a standard library function, which is used to clear the buffer, which it
receives as a parameter.
Syntax: fflush(<std.buf.ref.>);

Program to read integer and character


/*Program to read integer and character*/
#include<stdio.h>
main(){
char ch;
int a;
clrscr();
printf("Enter Integer value: ");
scanf("%d",&a);
fflush(stdin);
printf("Enter character value: ");
ch=getchar();
printf("\nEntered integer = %d \tEntered character = %c",a,ch);
}
Output:
Enter Integer value: 22
Enter character value: k
Entered integer = 22 Entered character = k

String “string.h” Library


C provides a set of functions that performs operations on strings. These functions take a
string and take actions such as reversing content of string, converting the string to upper
case and return length of the string. The following are functions from string library. All
functions are declared in string.h header file.

strlen() function
This function counts and returns the number of characters in a string. The length does not
include a null character.
Syntax: len = strlen(string);
where len is integer variable which receives the value of length
of the string.
Example: Program to find length of the string using strlen() function.
#include<stdio.h>
#include<string.h>
main()
{
char name[100];
int length;
printf("Enter a string: ");
gets(name);
length = strlen(name);
printf("\nNumber of characters in the string is %d",length);
getch();
}
Output:
Enter a string: peter
Number of characters in the string is 5
strlwr() function
This function converts all characters in a string from uppercase to lowercase.
Syntax: strlwr(string);
For Example: strlwr("EXFORSYS");
converts to exforsys.
strupr() function
This function converts all characters in a string from lowercase to uppercase.
Syntax: strupr(string);
For Example: strupr("exforsys");
converts to EXFORSYS.
Example: Program to convert lowercase to uppercase and uppercase to lowercase.
#include<stdio.h>
#include<string.h>
main()
{
char name[100];
clrscr();
printf("Enter a string: ");
gets(name);
printf("\nUppercase String: ");
puts(strupr(name));
strlwr(name);
printf("\nLowercase String: ");
puts(name);
getch();
}
Output:
Enter a string: peter
Uppercase String: PETER
Lowercase String: peter
strrev() function
This function reverses the characters in a string.
Syntax: strrev(string);
For Example: strrev("exforsys");
reverses the characters to sysrofxe.

strcpy() function
C does not allow to assign the characters to a string directly as in the statement
name="exforsys"; instead use the strcpy() function found in most compilers.
Syntax: strcpy(string1,string2);
For Example: strcpy(name,"exforsys");
String exforsys is assigned to the string called name.

strcmp() function
In C we cannot directly compare the value of 2 strings in a condition like
if(string1==string2)
Most libraries however contain the strcmp() function, which returns a zero if 2 strings are
equal, or a non zero number (>0 or <0) if the strings are not same.
Syntax: strcmp(string1,string2);
string1 and string2 may be variables or constants. Some computers
return a negative value if string1 is alphabetically less than the
second and a positive if the string1 is greater than the second.
For Example:
strcmp("their","there");
will return -9 which is the numeric difference between
ASCII 'i' and ASCII 'r'.
strcmp("the","The");
will return 32 which is the numeric difference between
ASCII 't' and ASCII 'T'.
strcmp("hello","hello");
will return 0 as two strings are equal.

strcmpi() function
This function is same as strcmp() which compares 2 strings but not case sensitive.
Syntax: strcmpi(string1,string2);
For Example:
strcmpi("the","THE");
will return 0 as it ignores case of the string.
Example: Program to check whether given string is palindrome or not.
#include<stdio.h>
#include<string.h>
main()
{
char name1[20],name2[20];
clrscr();
printf("Enter a string: ");
gets(name1);
strcpy(name2,name1); strrev(name2);
printf("Reversed String is ",name2);
if(strcmp(name1,name2) == 0)
printf("String is Palindrome");
else
printf("String is Not Palindrome");
getch();
}
Output:
Enter a string: peter
Reversed String: retep
String is not Palindrome

strcat() function
When you combine two strings, you add the characters of one string to the end of other
string. This process is called concatenation. The strcat() function joins 2 strings together. It
takes the following form:
Syntax: strcat(string1,string2);
When the function strcat is executed string2 is appended to string1, the string at string 2
remains unchanged.
For Example:
strcat(st1,"hello ");
strcat(st2,"world");
printf("%s",strcat(st1,st2));
From the above program segment of value of st1 becomes "hello world".
The string at st2 remains unchanged as "world".
Example: Program to sort an array of 10 strings
#include<stdio.h>
#include<string.h>
main()
{
char names[10][20];
int i,j;
char temp[20];
clrscr();
printf("Enter array of strings:\n");
for(i=0;i<10;i++)
gets(names[i]);
for(i=0;i<9;i++)
for(j=i+1;j<10;j++)
if(strcmp(names[i],names[j])>0)
{ strcpy(temp,names[i]);
strcpy(names[i],names[j]);
strcpy(names[j],temp);
}
printf("Sorted array of strings: \n");
for(i=0;i<10;i++)
puts(names[i]);
}
Output:
Enter array of strings:
santosh
anand
praneeth
manohar
naidu
hari
rajesh
aditya
julie
pavan
Sorted array of strings:
aditya
anand
hari
julie
manohar
naidu
pavan
praneeth
rajesh
santosh

strstr() function
This function returns the address (pointer) in string1 where string2 is starting in string1.
Syntax: strstr(string1,string2);

strchr() function
This function returns the address (pointer) of first occurrence of character ch in string.
Syntax: strchr(string,ch);
Sample C Programs for String Operations without using String Functions
Example: Program to read a line of text
#include<stdio.h>
main()
{
char line[81],character;
int c=0;
clrscr();
printf("Enter text. Press Enter at end\n");
do {
character = getchar();
line[c] = character;
c++;
}
while(character!='\n');
c=c-1;
line[c] = '\0';
printf("\n%s\n",line);
getch();
}
Output:
Enter text. Press Enter at end
This program reads a string and prints.
This program reads a string and prints.
Example: Program to Accept a string and display string in uppercase.
#include<stdio.h>
main()
{
char st[20];
int i;
clrscr();
/* accept a string */
printf("Enter a string: ");
gets(st);
/* display it in upper case */
for ( i = 0 ; st[i] != '\0'; i++)
if ( st[i] >= 'a' && st[i] <= 'z' )
putch( st[i] - 32);
else
putch( st[i]);
getch();
} Output:
Enter a string: c programming
C PROGRAMMING
Example: Program to write string using %s format.
#include<stdio.h>
main()
{
char country[15]="United Kingdom";
clrscr();
printf("\n\n");
printf("-------------------\n");
printf("|%15s|\n",country);
printf("|%5s|\n",country);
printf("|%15.6s|\n",country);
printf("|%.6s|\n",country);
printf("|%15.0s|\n",country);
printf("|%.3s|\n",country);
printf("|%s|\n",country);
printf("------------------\n");
getch();
}
Output:
------------------
| United Kingdom|
|United Kingdom|
| United|
|United|
| |
|Uni|
|United Kingdom|
------------------
Example: Program to find length of the string.
#include<stdio.h>
main()
{
char str[20];
int i = 0;
clrscr();
printf("\nEnter any string: ");
gets(str);
while (str[i] != '\0') i++;
printf("\nLength of string: %d", i);
getch();
}
Output:
Enter any string: ANIL NEERUKONDA
Length of string: 15
Example: Program to accept a string and display it in reverse.
#include<stdio.h>
main()
{
char st[20];
int i;
clrscr();
printf("Enter a string: "); /* accept a string */
gets(st);
/* get length of the string */
for ( i = 0 ; st[i] != '\0'; i++);
/* display it in reverse order */
for ( i -- ; i >= 0 ; i --)
putch(st[i]);
getch();
}
Output:
Enter a string: HELLO WORLD
DLROW OLLEH
Example: Program to Concatenate of 2 Strings
#include<stdio.h>
#include<conio.h>
main()
{
char string1[30], string2[20];
int i, length=0, temp;
printf("Enter the Value of String1: \n");
gets(string1);
printf("\nEnter the Value of String2: \n");
gets(string2);
for(i=0; string1[i]!='\0'; i++)
length++;
temp = length;
for(i=0; string2[i]!='\0'; i++)
{
string1[temp] = string2[i]; temp++;
}
string1[temp] = '\0';
printf("\nThe concatenated string is:\n");
puts(string1);
getch();
}
Output:
Enter the Value of String1:
C Language
Enter the Value of String2:
is good
The concatenated string is:
C Language is good
Example: Program to Copy one string to another string.
#include <stdio.h>
#include <conio.h>
main()
{
char string1[20], string2[20];
int i;
clrscr();
printf("Enter the value of STRING1: \n");
gets(string1);
for(i=0; string1[i]!='\0'; i++)
string2[i]=string1[i];
string2[i]='\0';
printf("\nThe value of STRING2 is:\n");
puts(string2);
getch();
}
Output:
Enter the value of STRING1:
c programs are cool
The value of STRING2 is:
c programs are cool
Example: Program to Compare two given strings.
#include<stdio.h>
main()
{ char string1[15],string2[15];
int i,temp = 0;
clrscr();
printf("Enter the string1 value:\n");
gets(string1);
printf("\nEnter the String2 value:\n");
gets(string2);
for(i=0;string1[i] != ‘\0’;i++) {
if(s1[i] == s2[i])
temp = 1;
else
temp = 0;
}
if(temp==1)
printf("Both strings are same.");
else
printf("Both strings not same.");
getch();
}
Output1:
Enter the string1 value:
c programs
Enter the String2 value:
cprograms
Both strings not same.
Output2:
Enter the string1 value:
c programs
Enter the String2 value:
c programs
Both strings are same.
Example: Program to print alphabet set in decimal and character form.
#include<stdio.h>
main()
{
char c;
clrscr();
printf("\n\n"); for(c=65;c<=122;c=c+1)
{
if(c>90 && c<97)
continue;
printf("%5d - %c",c,c);
}
printf("\n");
getch();
}
Output:
65 - A 66 - B 67 - C 68 - D 69 - E 70 - F 71 - G 72 - H
73 -I 74 - J 75 - K 76 - L 77 - M 78 - N 79 - O 80 - P
81 - Q 82 - R 83 - S 84 - T 85 - U 86 - V 87 - W 88 - X
89 - Y 90 - Z 97- a 98 - b 99 - c 100 - d 101 - e 102 - f
103 - g 104 - h 105 - i 106 - j 107 - k 108 - l 109 - m 110 - n
111 - o 112 - p 113 - q 114 - r 115 - s 116 - t 117 - u 118 - v
119 - w 120 - x 121 - y 122 - z
UNIT – 9
Pointers

9.1 Fundamentals
9.2 Pointer Declarations and initialization
9.3 Accessing value through a pointer
9.4 Pointer to a pointer
9.5 Similarities between Pointers and one dimensional arrays
9.6 Pointer with one dimensional and two dimensional arrays
9.7 Passing Pointers to Functions
9.8 Dynamic Memory Allocation

Fundamentals
Pointer is a variable that stores/hold address of another variable of same data type/ t is also known
as locator or indicator that points to an address of a value. A pointer is a derived data type in C.

Benefit of using pointers


 Pointers are more efficient in handling Array and Structure.

 Pointer allows references to function and thereby helps in passing of function as arguments to other
function.

 It reduces length and the program execution time.

 It allows C to support dynamic memory management.

Declaration of Pointer
data_type* pointer_variable_name;
int* p;
Note: void type pointer works with all data types, but isn't used often.
Initialization of Pointer variable
Pointer Initialization is the process of assigning address of a variable to pointer variable. Pointer
variable contains address of variable of same data type
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
or,

int *ptr = &a ; //initialization and declaration together


Note:Pointer variable always points to same type of data.
float a;
int *ptr;
ptr = &a; //ERROR, type mismatch
Above statement defines, p as pointer variable of type int. Pointer example

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4.
The value of number variable is 50. But the address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p.

Reference operator (&) and Dereference operator (*)


& is called reference operator. It gives you the address of a variable. There is another operator that
gets you the value from the address, it is called a dereference operator (*).
Symbols used in pointer

Dereferencing of Pointer
Once a pointer has been assigned the address of a variable. To access the value of variable, pointer is
dereferenced, using the indirection operator *.
int a,*p;
a = 10;
p = &a;
printf("%d",*p); //this will print the value of a.
printf("%d",*&a); //this will also print the value of a.
printf("%u",&a); //this will print the address of a.
printf("%u",p); //this will also print the address of a.
printf("%u",&p); //this will also print the address of p.
KEY POINTS TO REMEMBER ABOUT POINTERS IN C:
 Normal variable stores the value whereas pointer variable stores the address of the variable.

 The content of the C pointer always be a whole number i.e. address.


 Always C pointer is initialized to null, i.e. int *p = null.

 The value of null pointer is 0.

 & symbol is used to get the address of the variable.

 * symbol is used to get the value of the variable that the pointer is pointing to.

 If a pointer in C is assigned to NULL, it means it is pointing to nothing.

 Two pointers can be subtracted to know how many elements are available between these two
pointers.

 But, Pointer addition, multiplication, division are not allowed.

 The size of any pointer is 2 byte (for 16 bit compiler).


Example: Program to illustrate the concept of pointers.
/*Program to Illustrate the Concept of Pointers*/
#include <stdio.h>
main()
{
int a = 10;
int *p;
p = &a;
clrscr();
printf("\nAddress of a: %u", &a);
printf("\nAddress of a: %u", p);
printf("\nAddress of p: %u", &p);
printf("\nValue of p: %d", p);
printf("\nValue of a: %d", a);
printf("\nValue of a: %d", *(&a));
printf("\nValue of a: %d", *p);
getch();
}
Output:
Address of a: 65494
Address of a: 65494
Address of p: 65496
Value of p: 65494
Value of a: 10
Value of a: 10
Value of a: 10
Example: Program to illustrate the use of indirection operator.
/*Program to Illustrate the use of Indirection operator*/
#include <stdio.h>
main()
{
int x,y;
int *p;
clrscr();
x = 10;
p = &x;
y = *p;
printf("\nValue of x: %d", x);
printf("\n%d is stored at address %u", x,&x);
printf("\n%d is stored at address %u", *p,p);
printf("\n%d is stored at address %u", y,&*p);
printf("\n%u is stored at address %u", p,&p);
printf("\n%d is stored at address %u", y,&y);
*p = 25;
printf("\nValue of x: %d", x);
getch();
}
Output:
Value of x: 10
10 is stored at address 65492
10 is stored at address 65492
10 is stored at address 65492
65492 is stored at address 65496
10 is stored at address 65494
Value of x: 25

Example:
#include <stdio.h>
#include <conio.h>
void main(){
int number=50;
int *p;
clrscr();
p=&number;//stores the address of number variable
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p);
printf("Value of p variable is %d \n",*p);
getch();
}
Output
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

Example:
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;

/* address of q is assigned to ptr */


ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}
Output
50
Example:
#include <stdio.h>
int main()
{
int var =10;
int *p;
p= &var;
printf ( "\n Address of var is: %u", &var);
printf ( "\n Address of var is: %u", p);
printf ( "\n Address of pointer p is: %u", &p);
/* Note I have used %u for p's value as it should be an address*/
printf( "\n Value of pointer p is: %u", p);
printf ( "\n Value of var is: %d", var);
printf ( "\n Value of var is: %d", *p);
printf ( "\n Value of var is: %d", *( &var));
}

Output:
Address of var is: 00XBBA77
Address of var is: 00XBBA77
Address of pointer p is: 77221111
Value of pointer p is: 00XBBA77
Value of var is: 10
Value of var is: 10
Value of var is: 10
NULL Pointer
A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any
address to be specified in the pointer at the time of declaration, you can assign NULL value.
Or
It is always a good practice to assign a NULL value to a pointer variable in case you do not have an
exact address to be assigned. This is done at the time of variable declaration. A pointer that is
assigned NULL is called a null pointer.int *p=NULL;
Note: The NULL pointer is a constant with a value of zero defined in several standard libraries/ in
most the libraries, the value of pointer is 0 (zero)
Example:
The value of ptr is 0

Pointers for Inter‐Function Communication


Pointers to Pointers
Pointers can point to other pointers /pointer refers to the address of another pointer.
pointer can point to the address of another pointer which points to the address of a value.
Example:
#include <stdio.h>
#include <conio.h>
void main(){
int number=50;
int *p;//pointer to int
int **p2;//pointer to pointer
clrscr();
p=&number;//stores the address of number variable
p2=&p;
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p);

printf("Value of *p variable is %d \n",*p);


printf("Address of p2 variable is %x \n",p2);
printf("Value of **p2 variable is %d \n",**p);
getch();
}
Output
Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50
Arrays and Pointers
When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address which gives location of the first element is also allocated by the
compiler.
Suppose we declare an array arr,
int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two byte, the five element
will be stored as follows:

Here variable arr will give the base address, which is a constant pointer pointing to the element,
arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.
arr is equal to &arr[0] // by default
We can declare a pointer of type int to point to the array arr.
int arr[5]={ 1, 2, 3, 4, 5 };
int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element to another.
NOTE : You cannot decrement a pointer once incremented. p-- won't work.
Pointer to Array
we can use a pointer to point to an Array, and then we can use that pointer to access the array. Lets
have an example,
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}

In the above program, the pointer *p will print all the values stored in the array one by one. We can
also use the Base address (a in above case) to act as pointer and print all the values.
Relation between Arrays and Pointers
Consider an array:
int arr[4];

In C programming, name of the array always points to address of the first element of an array.
In the above example, arr and &arr[0] points to the address of the first element.
&arr[0] is equivalent to arr
Since, the addresses of both are the same, the values of arr and &arr[0] are also the same.
arr[0] is equivalent to *arr (value of an address of the pointer)

Similarly,
&arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1).
&arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2).
&arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3).
.
.
&arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i).
Example: Program to find the sum of six numbers with arrays and pointers
#include <stdio.h>
int main()
{
int i, classes[6],sum = 0;
printf("Enter 6 numbers:\n");
for(i = 0; i < 6; ++i)
{
// (classes + i) is equivalent to &classes[i]
scanf("%d",(classes + i));
// *(classes + i) is equivalent to classes[i]
sum += *(classes + i);
}
printf("Sum = %d", sum);
return 0;
}
Output

Enter 6 numbers:
2
3
4
5
3
4
Sum = 21
Pointer Arithmetic and Arrays
pointer holds address of a value, so there can be arithmetic operations on the pointer variable.
There are four arithmetic operators that can be used on pointers:
o Increment(++)

o Decrement(--)

o Addition(+)

o Subtraction(-)

Increment pointer:
1. Incrementing Pointer is generally used in array because we have contiguous memory in array and
we know the contents of next memory location.
2. Incrementing Pointer Variable Depends Upon data type of the Pointer variable.

The formula of incrementing pointer is given below:


new_address= current_address + i * size_of(data type)
Three rules should be used to increment pointer
Address + 1 = Address
Address++ = Address

++Address = Address
Pictorial Representation :
Note :
32 bit
For 32 bit int variable, it will increment to 2 byte.
64 bit
For 64 bit int variable, it will increment to 4 byte.
Example:
#include <stdio.h>
void main(){
int number=50;

int *p;//pointer to int


p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+1;
printf("After increment: Address of p variable is %u \n",p);
}
Output
Address of p variable is 3214864300
After increment: Address of p variable is 3214864304
Decrement(--)
Like increment, we can decrement a pointer variable.
formula of decrementing pointer
new_address= current_address - i * size_of(data type)
Example:
#include <stdio.h>
void main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-1;

printf("After decrement: Address of p variable is %u \n",p);


}
Output
Address of p variable is 3214864300
After decrement: Address of p variable is 3214864296
Addition(+)
We can add a value to the pointer variable.
formula of adding value to pointer
new_address= current_address + (number * size_of(data type))
Note:
32 bit
For 32 bit int variable, it will add 2 * number.
64 bit
For 64 bit int variable, it will add 4 * number.
Example:
#include <stdio.h>
void main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);

p=p+3; //adding 3 to pointer variable


printf("After adding 3: Address of p variable is %u \n",p);
}
Output
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312
Subtraction (-)
Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting
value from pointer variable.
new_address= current_address - (number * size_of(data type))
Example:
#include <stdio.h>
void main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \n",p);
}
Output

Address of p variable is 3214864300


After subtracting 3: Address of p variable is 3214864288
Passing an Array to a Function
If you want to pass a single-dimension array as an argument in a function, you would have to declare
a formal parameter in one of following three ways and all three declaration methods produce similar
results because each tells the compiler that an integer pointer is going to be received. Similarly, you
can pass multi-dimensional arrays as formal parameters.
1) Formal parameters as a pointer –

void myFunction(int *param) {


.
.
.
}
2) Formal parameters as a sized array –

void myFunction(int param[10]) {


.
.
.
}
3) Formal parameters as an unsized array −

void myFunction(int param[10]) {


.
.
.
}
Example1: pass an entire array to a function argument
#include <stdio.h>
/* function declaration */
double getAverage(int arr[], int size);
int main () {
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};

double avg;
/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;
/* output the returned value */
printf( "Average value is: %f ", avg );
return 0;
}
double getAverage(int arr[], int size) {
int i;
double avg;
double sum = 0;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
avg = sum / size;
return avg;
}
Output
Average value is: 214.400000
Example2: pass an entire array to a function argument
#include <stdio.h>
myfuncn( int *var1, int var2)
{
for(int x=0; x<var2; x++)
{
printf("Value of var_arr[%d] is: %d \n", x, *var1);
/*increment pointer for next element fetch*/
var1++;
}
}

int main()
{
int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
myfuncn(&var_arr, 7);
return 0;
}
Output
Value of var_arr[0] is: 11
Value of var_arr[1] is: 22
Value of var_arr[2] is: 33
Value of var_arr[3] is: 44
Value of var_arr[4] is: 55
Value of var_arr[5] is: 66
Value of var_arr[6] is: 77
Example: Call by value method –
#include <stdio.h>
disp( char ch)
{
printf("%c ", ch);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'I', 'j'};
for (int x=0; x<=10; x++)
{
/* I‟m passing each element one by one using subscript*/
disp (arr[x]);
}
return 0;
}
Output:
abcdefghij

In this method of calling a function, the actual arguments gets copied into formal arguments. In this
example actual argument(or parameter) is arr[x] and formal parameter is ch.
Example: Call by reference method: Using pointers
#include <stdio.h>
disp( int *num)
{
printf("%d ", *num);
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<=10; i++)
{
/* I‟m passing element‟s address*/
disp (&arr[i]);
}
return 0;
}
Output:
1234567890

Array of Pointers
An array of pointers would be an array that holds memory locations. An array of pointers is an
indexed set of variables in which the variables are pointers (a reference to a location in memory).
Syntax:
data_type_name * variable name
Example
int *ptr[MAX];
Array alpha[] Pointer a
alpha[0] *a
alpha[1] *(a+1)
alpha[2] *(a+2)
alpha[3] *(a+3)
alpha[n] *(a+n)

ptr[i] = &var[i]; /* assign the address of integer. */


}
for ( i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}
Output
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
Example2:
#include <stdio.h>

#include <conio.h>

main()

{ clrscr();

int *array[3];

int x = 10, y = 20, z = 30;

int i;

array[0] = &x;

array[1] = &y;

array[2] = &z;

for (i=0; i< 3; i++) {

printf("The value of %d= %d ,address is %u\t \n", i, *(array[i]), array[i]);

getch();

return 0; }
Output

Example3:
#include <stdio.h>
const int MAX = 4;
int main () {
char *names[] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali"
};
int i = 0;
for ( i = 0; i < MAX; i++) {
printf("Value of names[%d] = %s\n", i, names[i] );
}
return 0;
}

Output:
Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali

Example4:
#include <stdio.h>
int main()
{
char *fruit[] = {
"watermelon",
"banana",
"pear",
"apple",
"coconut",
"grape",
"blueberry"
};
int x;
for(x=0;x<7;x++)
puts(fruit[x]);

return(0);
}
Pointers to Void and to Functions
Pointers to Void
Note:
1. Suppose we have to declare integer pointer, character pointer and float pointer then we need to
declare 3 pointer variables.
2. Instead of declaring different types of pointer variable it is feasible to declare single pointer
variable which can act as integer pointer,character pointer.

A pointer variable declared using a particular data type can not hold the location address of variables
of other data types. It is invalid and will result in a compilation error.
Ex:- char *ptr;
int var1;
ptr=&var1; // This is invalid because „ptr‟ is a character pointer variable.

Here comes the importance of a “void pointer”. A void pointer is nothing but a pointer variable
declared using the reserved word in C „void‟.
Void Pointer Basics :
3. In C General Purpose Pointer is called as void Pointer.

4. It does not have any data type associated with it

5. It can store address of any type of variable

6. A void pointer is a C convention for a raw address.

7. The compiler has no idea what type of object a void Pointer really points to ?
Void pointer: A void pointer is a pointer that has no associated data type with it. A void pointer can
hold address of any type and can be typcasted to any type. Special type of pointer called void
pointer or general purpose pointer.
Declaration of void pointer
void * pointer_name;
Void pointer example
void *ptr; // ptr is declared as Void pointer
char cnum;
int inum;
float fnum;
ptr = &cnum; // ptr has address of character data
ptr = &inum; // ptr has address of integer data
ptr = &fnum; // ptr has address of float data
Advantages of void pointers:
1) malloc() and calloc() return void * type and this allows these functions to be used to allocate
memory of any data type (just because of void *)
int main(void)
{
// Note that malloc() returns void * which can be
// typecasted to any type like int *, char *, ..
int *x = malloc(sizeof(int) * n);
}
2) void pointers in C are used to implement generic functions in C.

#include<stdio.h>
int main()
{
int a = 10;
void *ptr = &a;
printf("%d", *ptr);
return 0;
}
Pointers to functions/ Function Pointers
A pointer to a function points to the address of the executable code of the function.

We can use pointers to call functions and to pass functions as arguments to other
functions.

We cannot perform pointer arithmetic on pointers to functions.

The type of a pointer to a function is based on both the return type and parameter types of
the function.

A declaration of a pointer to a function must have the pointer name in parentheses.

The function call operator () has a higher precedence than the dereference operator *.
Without them, the compiler interprets the statement as a function that returns a pointer to a
specified return type.

declare Pointer to function?


<function return type>(*<Pointer_name>)(function argument list)
For example –
For example:
1) int *f(int a); /* function f returning an int * */
In this declaration, f is interpreted as a function that takes an int as argument, and returns a
pointer to an int.
2) double (*p2f)(double, char)

Here double is a return type of function, p2f is pointer name & (double, char) is an argument
list for the function. Which means the first argument for this function should be double and
the second one would be of char type.
Example:
#include<stdio.h>
int sum (int num1, int num2)
{
return sum1+sum2;
}
int main()
{
int (*f2p) (int, int);
f2p = sum;
int op1 = f2p (10, 13);
int op2 = sum (10, 13);
printf("Output 1 – for function call via Pointer: %d",op1);
printf("Output2 – for direct function call: %d", op2);
return 0;
}
Output:
Output 1 – for function call via Pointer: 23
Output2 – for direct function call: 23
You would have noticed that the output of both the statements is same – f2p(10, 13) ==
sum(10, 13)
which means in generic sense you can write it out as:
pointer_name(argument list) == function(same argument list)
wherein pointer_name is declared as:
return_type(*pointer_name)(argument list);
pointer_name = function_name(argument list);
Memory Allocation Functions
The concept of dynamic memory allocation in c language enables the C programmer to
allocate memory at runtime.
Or
The process of allocating memory at runtime is known as dynamic memory allocation.
Library routines known as "memory management functions" are used for allocating and
freeing memory during execution of a program. These functions are defined in stdlib.h.
Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.
1. malloc()

2. calloc()

3. realloc()

4. free()

Difference between static memory allocation and dynamic memory allocation.

static memory allocation dynamic memory allocation


memory is allocated at compile time. memory is allocated at run time.
memory can't be increased while executing memory can be increased while executing
program. program.
used in array. used in linked list

Methods used for dynamic memory allocation.

malloc() allocates single block of requested


memory.
calloc() allocates multiple block of requested
memory.
realloc() reallocates the memory occupied by
malloc() or calloc() functions.
free() frees the dynamically allocated memory.
Note: Dynamic memory allocation related function can be applied for any data type that's why
dynamic memory allocation related functions return void*.
Memory Allocation Process
Global variables, static variables and program instructions get their memory in permanent storage
area whereas local variables are stored in area called Stack. The memory space between these two
region is known as Heap area. This region is used for dynamic memory allocation during execution
of the program. The size of heap keep changing.
malloc()
malloc stands for "memory allocation".
The malloc() function allocates single block of requested memory at runtime. This function reserves
a block of memory of given size and returns a pointer of type void. This means that we can assign it
to any type of pointer using typecasting. It doesn't initialize memory at execution time, so it has
garbage value initially. If it fails to locate enough space (memory) it returns a NULL pointer.
syntax
ptr=(cast-type*)malloc(byte-size)
Example
int *x;
x = (int*)malloc(100 * sizeof(int)); //memory space allocated to variable x
free(x); //releases the memory allocated to variable x

This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and
the pointer points to the address of first byte of memory.
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}

calloc()
calloc stands for "contiguous allocation".
Calloc() is another memory allocation function that is used for allocating memory at runtime. calloc
function is normally used for allocating memory to derived data types such as arrays and structures.
The calloc() function allocates multiple block of requested memory.
It initially initialize (sets) all bytes to zero.If it fails to locate enough space( memory) it returns a
NULL pointer. The only difference between malloc() and calloc() is that, malloc() allocates single
block of memory whereas calloc() allocates multiple blocks of memory each of same size.
Syntax
ptr = (cast-type*)calloc(n/number, element-size);
calloc() required 2 arguments of type count, size-type.
Count will provide number of elements; size-type is data type size
Example
int*arr;
arr=(int*)calloc(10, sizeof(int)); // 20 byte
cahr*str;
str=(char*)calloc(50, siceof(char)); // 50 byte
Example
struct employee
{
char *name;
int salary;
};
typedef struct employee emp;
emp *e1;
e1 = (emp*)calloc(30,sizeof(emp));

Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) calloc(num, sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}

Diffrence between malloc() and calloc()

calloc() malloc()
calloc() initializes the allocated memory with 0 malloc() initializes the allocated memory with
value. garbage values.
Number of arguments is 2 Number of argument is 1
Syntax : Syntax :
(cast_type *)calloc(blocks , size_of_block); (cast_type *)malloc(Size_in_bytes);

realloc(): changes memory size that is already allocated to a variable.


Or
If the previously allocated memory is insufficient or more than required, you can change the
previously allocated memory size using realloc().
 If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc()
function. In short, it changes the memory size. By using realloc() we can create the memory
dynamically at middle stage. Generally by using realloc() we can reallocation the memory. Realloc()
required 2 arguments of type void*, size_type. Void* will indicates previous block base address,
size-type is data type size. Realloc() will creates the memory in bytes format and initial value is
garbage.

syntax
ptr=realloc(ptr, new-size)
Example
int *x;
x=(int*)malloc(50 * sizeof(int));
x=(int*)realloc(x,100); //allocated a new memory to variable x

Example
void*realloc(void*, size-type);
int *arr;
arr=(int*)calloc(5, sizeof(int));
.....
........
....
arr=(int*)realloc(arr,sizeof(int)*10);
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Address of previously allocated memory: ");
for(i = 0; i < n1; ++i)
printf("%u\t",ptr + i);
printf("\nEnter new size of array: ");
scanf("%d", &n2);
ptr = realloc(ptr, n2);
for(i = 0; i < n2; ++i)
printf("%u\t", ptr + i);
return 0;
}

free()
When your program comes out, operating system automatically release all the memory allocated by
your program but as a good practice when you are not in need of memory anymore then you should
release that memory by calling the function free().
The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.
Or
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its own.
You must explicitly use free() to release the space.
Syntax:
free(ptr);
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);

sum += *(ptr + i);


}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
Command‐Line Arguments:
It is possible to pass some values from the command line to your C programs when they are
executed. These values are called command line arguments and many times they are important for
your program especially when you want to control your program from outside instead of hard coding
those values inside the code.
The arguments passed from command line are called command line arguments. These arguments are
handled by main() function.
To support command line argument, you need to change the structure of main() function
Syntax:
int main(int argc, char *argv[] )
Here, argc counts the number of arguments. It counts the file name as the first argument.
The argv[] contains the total number of arguments. The first argument is the file name always.
Example1
#include <stdio.h>
int main( int argc, char *argv[] ) {
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}

}
Output
Example2
#include <stdio.h>
void main(int argc, char *argv[] ) {
printf("Program name is: %s\n", argv[0]);
if(argc < 2){
printf("No argument passed through command line.\n");
}
else{
printf("First argument is: %s\n", argv[1]);
}
}
Output
program.exe hello
Program name is: program
First argument is: hello
Note
But if you pass many arguments within double quote, all arguments will be treated as a single
argument only.
Example
./program "hello c how r u"
Program name is: program
First argument is: hello c how r u
You can write your program to print all the arguments. In this program, we are printing only
argv[1], that is why it is printing only one argument.

Example3
#include<stdio.h>
#include<conio.h>
void main(int argc, char* argv[])
{
int i;
clrscr();
printf("Total number of arguments: %d",argc);
for(i=0;i< argc;i++)
{
printf("\n %d argument: %s",i,argv[i]);
getch();
}
}
Output
C:/TC/BIN>TCC mycmd.c
C:/TC/BIN>mycmd 10 20
Number of Arguments: 3
0 arguments c:/tc/bin/mycmd.exe
1 arguments: 10
2 arguments: 20
Note: In above output we passed two arguments but is show "Number of Arguments: 3" because
argc take Number of arguments in the command line including program name. So here two
arguments and one program name (mycmd.exe) total 3 arguments.

Example4:
#include<stdio.h>
#include<conio.h>
void main(int argc, char* argv[])
{
clrscr();
printf("\n Program name : %s \n", argv[0]);
printf("1st arg : %s \n", argv[1]);
printf("2nd arg : %s \n", argv[2]);
printf("3rd arg : %s \n", argv[3]);
printf("4th arg : %s \n", argv[4]);
printf("5th arg : %s \n", argv[5]);
getch();
}
Output
C:/TC/BIN>TCC mycmd.c
C:/TC/BIN>mycmd this is a program

Program name : c:/tc/bin/mycmd.c


1st arg : this
2nd arg : is
3rd arg : a
4th arg : program
5th arg : (null)
Explanation: In the above example.
argc = 5
argv[0] = "mycmd"
argv[1] = "this"
argv[2] = "is"
argv[3] = "a"
argv[4] = "program"
argv[5] = NULL
Why command line arguments program not directly run form TC IDE
Command line arguments related programs are not execute directly from TC IDE because arguments
can not be passed.
Edit Command Line Argument Program
To Edit the Command Line Argument Program use edit Command.
Syntax
C:/cprogram>edit mycmd.c
UNIT -10
Structures and Unions 6 Hours
10.1 Defining a Structure
10.2 Arrays of Structures
10.3 Structures within Structures
10.4 Processing a Structure
10.5 Structures & Pointers
10.6 Passing Structures to Functions
10.7 Union & its importance

Structure
During programming, there is a need to store multiple logically related elements
under one roof. For instance, an employee’s details like name, employee number,
and designation need to be stored together. In such cases, the C language provides
structures to do the job for us.

Structure is a user defined data type which hold or store heterogeneous/different types data item
or element in a single variable. It is a Combination of primitive and derived data type.
A structure is a collection of one or more data items of different data types, grouped together under a
single name.
Variables inside the structure are called members of structure.
Each element of a structure is called a member.
struct keyword is used to define/create a structure. struct define a new data type which is a
collection of different type of data.
Syntax to Define a Structure in C

struct structName
{
// structure definition
Data_type1 member_name1;
Data_type2 member_name2;
Data_type2 member_name2;
};
Below is the description of Structure in C programming
Description of the Syntax
Keyword struct: The keyword struct is used at the beginning while defining a
structure in C. Similar to a union, a structure also starts with a keyword.
structName: This is the name of the structure which is specified after the keyword
struct.
data_Type: The data type indicates the type of the data members of the structure.
A structure can have data members of different data types.
member_name: This is the name of the data member of the structure. Any
number of data members can be defined inside a structure. Each data member is
allocated a separate space in the memory.

Declare Structure Variables:


Variables of the structure type can be created in C. These variables are allocated a
separate copy of data members of the structure. There are two ways to create a
structure variable in C.
Declaration of Structure Variables with Structure Definition
This way of declaring a structure variable is suitable when there are few variables
to be declared.
Syntax
struct structName
{
// structure definition
Data_type1 member_name1;
Data_type2 member_name2;
Data_type2 member_name2;
} struct_var1, struct_var2;
Example
struct bookStore
{
// structure definition
char storeName
int totalBooks;
char storeLicense[20];
} storeA, storeB; // structure variables
The structure variables are declared at the end of the structure definition, right
before terminating the structure. In the above example, storeA and storeB are the
variables of the structure bookStore. These variables will be allocated separate
copies of the structure’s data members that are- storeName, totalBooks, and
storeLicense.

Declaration of Structure Variables Separately


This way of creating structure variables is preferred when multiple variables are
required to be declared. The structure variables are declared outside the
structure.
Syntax
struct structName
{
// structure definition
Data_type1 member_name1;
Data_type2 member_name2;
Data_type2 member_name2;
};
struct structName struct_var1, struct_var2;
Example
struct bookStore
{
// structure definition
char storeName
int totalBooks;
char storeLicense[20];
};
int main()
{
struct bookStore storeA, storeB; // structure variables;
}
When the structure variables are declared in the main() function, the keyword
struct followed by the structure name has to be specified before declaring the
variables. In the above example, storeA and storeB are the variables of the
structure bookStore.
Initialize Structure Members
Structure members cannot be initialized like other variables inside the structure
definition. This is because when a structure is defined, no memory is allocated to
the structure’s data members at this point. Memory is only allocated when a
structure variable is declared. Consider the following code snippet.
struct rectangle
{
// structure definition
int length = 10; // COMPILER ERROR: cannot initialize members here.
int breadth = 6; // COMPILER ERROR: cannot initialize members here.
};
A compilation error will be thrown when the data members of the structure are
initialized inside the structure.
To initialize a structure’s data member, create a structure variable. This variable
can access all the members of the structure and modify their values. Consider the
following example which initializes a structure’s members using the structure
variables.
struct rectangle
{
// structure definition
int length;
int breadth;
};
int main()
{
struct rectangle my_rect; // structure variables;
my_rect.length = 10;
my_rect.breadth = 6;
}
In the above example, the structure variable my_rect is modifying the data
members of the structure. The data members are separately available to my_rect
as a copy. Any other structure variable will get its own copy, and it will be able to
modify its version of the length and breadth.

Access Structure Elements


The members of a structure are accessed outside the structure by the structure
variables using the dot operator (.). The following syntax is used to access any
member of a structure by its variable:
Syntax
structVariable.structMember
Example
The following example illustrates how to access the members of a structure and
modify them in C.
#include <stdio.h>
#include <string.h>
struct cube
{
// data members
char P_name[10];
int P_age;
char P_gender;
};
int main()
{
// structure variables
struct cube p1, p2;
// structure variables accessing the data members.
strcpy(p1.P_name, "XYZ");
p1.P_age = 25;
p1.P_gender = 'M';
strcpy(p2.P_name, "ABC");
p2.P_age = 50;
p2.P_gender = 'F';
// print the patient records.
// patient 1
printf("The name of the 1st patient is: %s\n", p1.P_name);
printf("The age of the 1st patient is: %d\n", p1.P_age);
if (p1.P_gender == 'M')
{
printf("The gender of the 1st patient is: Male\n");
}
else
{
printf("The gender of the 1st patient is: Female\n");
}
printf("\n");
// patient 2
printf("The name of the 2nd patient is: %s\n", p2.P_name);
printf("The age of the 2nd patient is: %d\n", p2.P_age);
if (p2.P_gender == 'M')
{
printf("The gender of the 2nd patient is: Male\n");
}
else
{
printf("The gender of the 2nd patient is: Female\n");
}
return 0;
}

In the above program, a structure named Patient is defined. It has three data
members- P_name, P_age, and P_gender. These data members have not been
allocated any space in the memory yet. The variables p1 and p2 are the structure
variables declared in the main function.
As soon as these variables are created, they get a separate copy of the structure’s
members with space allocated to them in the memory. Both p1 and p2 are
accessing their copies of the structure’s members to modify them using the dot
operator.

Pass Structures to Functions in C


As all the members of a structure are public in C, therefore they are accessible
anywhere and by any function outside the structure. Functions accept structures
as their arguments in a similar way as they accept any other variable or pointer. To
pass a structure to a function, a structure variable is passed to the function as an
argument.
A structure variable can be passed to a function as an argument in the following
three ways:
Passing Structure to a Function by Value
When a structure variable is passed by its value, a copy of the members is passed
to the function. If the function modifies any member, then the changes do not
affect the structure variable’s copy of members. The following example illustrates
how to pass a structure variable to a function by value in C.
#include <stdio.h>
#include <string.h>
struct patient
{
int ID;
char name[10];
char gender;
};
// function that accepts a structure variable as arguments.
void passByValue(struct patient p)
{
p.ID = 102; // this modification does not affect P1's id.
// print the details.
printf(" The patient's ID is: %d \n", p.ID);
printf(" The patient's name is: %s \n", p.name);
printf(" The patient's gender is: %c \n", p.gender);
}
int main()
{
struct patient P1;
P1.ID = 101;
strcpy(P1.name, "ABC");
P1.gender = 'M';
passByValue(P1); // pass structure variable by value.
// P1's ID remains unaffected by the function's modification.
printf("\n The original value of ID is: %d\n\n", P1.ID);
return 0;
}

In the above program, the function passByValue() accepts the structure’s variable
P1 as an argument. This argument is passed by value. When the function makes a
modification in the member ID, this modification does not affect the P1’s version
of ID. The reason is that in the case of pass-by-value, only a copy of the members is
passed to the function. So, any changes made by the function do not reflect in the
original copy.

Passing Structure to a Function by Reference


When a structure variable is passed by its reference, the address of the structure
variable is passed to the function. This means the function does not get any copy,
instead, it gets the reference or address of the structure variable’s members.
If the function modifies any member, then the changes get reflected in the
structure variable’s copy of members. Note that in pass-by-reference, the
structure members can be accessed using the arrow operator (->).
The following example illustrates how to pass a structure variable to a function by
reference in C.
#include <stdio.h>
#include <string.h>
struct patient
{
int ID;
char name[10];
char gender;
};
// function that accepts a structure variable as arguments.
void passByReference(struct patient *p)
{
p->ID = 102; // this modification reflects P1's id.
// print the details.
printf(" The patient's ID is: %d \n", p->ID);
printf(" The patient's name is: %s \n", p->name);
printf(" The patient's gender is: %c \n", p->gender);
}
int main()
{
struct patient P1;
P1.ID = 101;
strcpy(P1.name, "ABC");
P1.gender = 'M';
passByReference(&P1); // pass structure variable by reference.
// P1's ID gets affected by the function's modification.
printf("\n The original value of ID is: %d\n\n", P1.ID);
return 0;
}
In the above example, the function passByReference() accepts the structure’s
variable P1 as an argument. This argument is passed by reference. So, the function
gets access to the location of the structure variable. When the function makes a
modification in the member ID, this modification affects the P1’s version of ID.

Declaring Structure Variables as Global


When a structure variable is declared as global, it can be accessed by any function
in the program. There will be no need to pass the structure variable to the
function. However, this is not advised as all the functions can modify the values of
the structure variable’s copy of members. This also affects the data security in the
program.
The following example illustrates how to declare a global structure variable in C
and access it in functions.
#include <stdio.h>
#include <string.h>
struct patient
{
int ID;
char name[10];
char gender;
};
// structure variable declared globally.
struct patient P1;
void my_function()
{
// print the details.
printf(" The patient's ID is: %d \n", P1.ID);
printf(" The patient's name is: %s \n", P1.name);
printf(" The patient's gender is: %c \n\n", P1.gender);
}
int main()
{
P1.ID = 101;
strcpy(P1.name, "ABC");
P1.gender = 'M';
// no need to pass the structure variable
// to the function as an argument.
my_function(); // function call
return 0;
}

In the above example, the structure variable P1 is declared as a global variable.


Being a global variable, P1 is accessed by any function in the program. The function
my_function() does not require P1 to be passed to it as an argument. It can directly
access P1 and modify any structure member using P1.

Designated Initialization
In the C99 standard, there is a unique feature that is not available in other
standards like C90 or GNU C++. Designated initialization is supported
for array, union, and structure in C. To understand the working of designated
initialization, consider the following example of array initialization at the time of
declaration.
int my_arr[5] = {10, 20, 30, 40, 50};
// my_arr[0] = 10, my_arr[1] = 20, ..., my_arr[5] = 50.
In the above array initialization, all array elements are initialized in the fixed order.
This means that the element at index 0 is initialized first, then the index 1 element
is initialized, and so on.
These array elements can also be initialized in any random order, and this method
is called designated initialization. Consider the following example which initializes
the array elements in random order.
int a[5] = {[3] = 30, [2] = 20 };
// OR
int a[5] = {[3]30 , [2]20 };
The following program illustrates the designated initialization of a structure in C.
#include <stdio.h>
struct rectangle
{
int length, breadth, height;
};
int main()
{
// Examples of initialization using designated initialization
struct rectangle r1 = {.breadth = 10, .height = 5, .length = 6};
struct rectangle r2 = {.breadth = 20};
printf("The values of r1 are: \n");
printf("length = %d, breadth = %d, height = %d\n", r1.length, r1.breadth,
r1.height);
printf("The values of r2 are: \n");
printf("length = %d, breadth = %d, height = %d\n\n", r2.length, r2.breadth,
r2.height);
return 0;
}
In the above example, the structure members- length, breadth, and height are
initialized in a random order using the designated initialization. This type of
initialization would throw an error in the compiler of other standards and even C++
does not support this functionality.

Array of Structures
Array of structures to store much information of different data types. Each
element of the array representing a structure variable. The array of structures is
also known as collection of structures.
Ex : if you want to handle more records within one structure, we need not specify
the number of structure variable. Simply we can use array of structure variable to
store them in one structure variable.

Suppose you need to store the details of students like name, class, and roll number
in your database. Now, the first thing that comes to your mind would be to create
a structure variable and access the student details. This method is practical for a
few students only, but what if the total number of students is 100 or something. It
is not convenient to create 100 separate structure variables for 100 students. In
such cases, we use an array of structures.
Just like other data types (mostly primitive), we can also declare an array of
structures. An array of structures acts similar to a normal array. However, there is
one thing to be kept in mind and that is the name of the structure followed by the
dot operator(.) and the name of the array has to be mentioned to access an array
element.
The following example illustrates the working of the array of structures in C.
#include <stdio.h>
// structure definition
struct Student
{
// data members
char name[10];
int marks;
};
// declare an array of the structure Student.
struct Student stu[3];
int i, j;
// function to read the values
// from the user and print them.
void print()
{
// read input from the user.
for (i = 0; i < 3; i++)
{
printf("\nEnter the record of Student %d\n", i + 1);
printf("\nStudent name: ");
scanf("%s", stu[i].name);
printf("Enter Marks: ");
scanf("%d", &stu[i].marks);
}
// print the details of each student.
printf("\nDisplaying Student record\n");
for (i = 0; i < 3; i++)
{
printf("\nStudent name is %s", stu[i].name);
printf("\nMarks is %d", stu[i].marks);
}
}
int main()
{
// function call
print();
return 0;
}

In the above example, we have created a structure Student that holds student
names and marks. We have initialized an array stu of size 3 to get the names and
marks of 3 students. Note that unlike the usual array in C, the array of structures in
C is initialized by using the names of the structure as a prefix.

Structure Pointer
A pointer structure is a variable that holds the address of the memory block of the
structure. It is similar to other pointer variables like a pointer to an int or a pointer
to a float.
Consider the following code snippet.
struct point
{
// data member
int num;
};
int main()
{
// struct1 variable var
struct struct1 var;
// pointer variable
struct point *ptr = &var;
return 0;
}
Here, var is the structure variable of struct1 and ptr is the pointer variable. The ptr
is storing the address of the var. In the case of a pointer to a structure, the
members can be accessed using the arrow (->) operator.
The following example illustrates the pointer to a structure in C.
#include<stdio.h>
struct myStruct
{
int x, y;
};
int main()
{
struct myStruct var1 = {1, 2};
// var2 is a pointer to structure var1.
struct myStruct *var2 = &var1;
// Accessing data members of myStruct using a structure pointer.
printf("%d %d", var2->x, var2->y);
return 0;
}

In the above example, the structure myStruct has a variable var1. The var2 is the
pointer variable that stores the address of this structure variable.

Nested Structures
The C programming language allows the nesting of the structure. This can be done
by using one structure into the body of another structure. Nesting of multiple
separate structures enables the creation of complex data types.
For instance, you need to store the information of multiple students. Now the data
members of the structure may be student name, student class, and student roll
number. Now class can have multiple subparts like standard, section, and stream.
Such types of cases can use nested structures to a great extent.
A structure in C can be nested in two ways:
By Creating a Separate Structure
We can create two separate, let's say struct1 and struct2 structures, and then nest
them. If you want to nest struct2 in struct1, then it is necessary to create struct2
variable inside the primary structure i.e., struct1. The nested structure would be
used as a data member of the primary structure.
Consider the following code snippet.
// structure 2
struct struct2
{
// data members of struct2
};
// structure 1
struct struct1
{
// data members of struct1
// struct2 variable
struct struct2 obj2;
}obj1; // struct1 variable
Here, struct1 is the primary structure and struct2 is the secondary one. It is clearly
observable that the variable of struct2 is created inside struct1.
Example
The following example illustrates the nesting of a structure in C by creating a
separate structure.
#include <stdio.h>
// structure 2
struct class_details
{
int standard;
char section;
char stream[20];
};
// structure 1
struct Student
{
char name[20];
int roll_num;
// nested structure 2 in structure 1
// class_details variable Class
struct class_details Class;
};
int main()
{
// Student variable stu
struct Student stu;
// read the input from user
printf("Enter details of the student: \n");
scanf("%s %d %d %c %c",
&stu.name,
&stu.roll_num,
&stu.Class.standard,
&stu.Class.section,
&stu.Class.stream);
// display the input info
printf("The Student's details are: \n");
printf("Name: %s\nRoll_num: %d\nStandard: %d\nSection: %c\nStream %s: ",
stu.name,
stu.roll_num,
stu.Class.standard,
stu.Class.section,
stu.Class.stream);
return 0;
}
In the above example, we created two structures, Student and class_details. The
structure Student contains the basic information about the student while the
structure class_details contains the information about the class of the student
specifically. The class_details structure is nested inside the Student structure by
creating the object inside it so that all the data members of the class_details can
be accessed by the Student structure too.

By Creating Embedded Structure


In this method, instead of creating independent structures, if create a structure
within a structure. This takes the independence of a structure and makes it
inaccessible as well as useless for other structures. However, in this way, you have
to write less code and the program will be cleaner.
Consider the following code snippet.
// structure 1
struct struct1
{
// data members of struct1
// structure 2
struct struct2
{
// data members of struct2
} obj2; // struct2 variable
} obj1; // struct1 variable
Here, struct2 is created inside struct1 just like a data member, and the struct2
variable is also defined inside the primary structure.
Example
The following example illustrates the nesting of a structure in C by creating an
embedded structure.
#include <stdio.h>
// structure 1
struct Student
{
char name[20];
int roll_num;
// nested structure 2 in structure 1
// structure 2
struct class_details
{
int standard;
char section;
char stream[20];
};
// class_details variable Class
struct class_details Class;
};
int main()
{
// Student variable stu
struct Student stu;
// read the input from user
printf("Enter details of the student: \n");
scanf("%s %d %d %c %c",
&stu.name,
&stu.roll_num,
&stu.Class.standard,
&stu.Class.section,
&stu.Class.stream);
// display the input info
printf("The Student's details are: \n");
printf("Name: %s\nRoll_num: %d\nStandard: %d\nSection: %c\nStream %s: ",
stu.name,
stu.roll_num,
stu.Class.standard,
stu.Class.section,
stu.Class.stream);
return 0;
}

Here, the logic and the data members are exactly the same as in the previous
example. The major difference here is that instead of creating a separate structure
of details of the class, we created an embedded structure. You can observe that
even though the methods are different, the outputs of both methods are exactly
the same.

Limitations of Structure in C Programming


 The struct data type can not be used as a built-in data type. If you try to use
it as a built-in data type, the compiler will throw an error.
 Arithmetic operators can not be implemented on structure variables.
Consider the following code as an example.
#include <stdio.h>
struct number
{
float x;
};
int main()
{
struct number n1, n2, n3;
n1.x = 4;
n2.x = 3;
n3 = n1 + n2;
return 0;
}

Data hiding is not possible in structures. Structure in C does not permit any data
members to be hidden and allows every function to access them.
You can not define member functions inside a structure in C. Structure in C only
allows the definition of data members inside it and prohibits functions.
The concept of access modifiers is absent in the C language. So data members in a
structure are always public to all the functions outside that structure.
Structure in C does not permit the creation of static members and constructors
inside its body.
Difference between Structure and Union
Unions
A union is a special data type available in C that allows to store different data types
in the same memory location.
Unions are conceptually similar to structures. The syntax of union is also similar to
that of structure. The only difference is in terms of storage. In structure each
member has its own storage location, whereas all members of union use a single
shared memory location which is equal to the size of its largest data member.
We can access only one member of union at a time. We can‟t access all member
values at the same time in union. But, structure can access all member values at
the same time. This is because, Union allocates one common storage space for all
its members. Where as Structure allocates storage space for all its members
separately.
syntax
union union_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Example
union employee
{ int id;
char name[50];
float salary;
};
Example
#include <stdio.h>
#include <string.h>
union employee
{ int id;
char name[50];
}e1; //declaring e1 variable for union
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
//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 : 1869508435
employee 1 name : Sonoo Jaiswal
As you can see, id gets garbage value because name has large memory size. So only
name will have actual value.
Example
#include <stdio.h>
#include <conio.h>
union item
{
int a;
float b;
char ch;
};
int main( )
{
union item it;
it.a = 12;
it.b = 20.2;
it.ch='z';
clrscr();
printf("%d\n",it.a);
printf("%f\n",it.b);
printf("%c\n",it.ch);
getch();
return 0;
}
Output
-26426
20.1999
z
As you can see here, the values of a and b get corrupted and only variable c prints
the expected result. Because in union, the only member whose value is currently
stored will have the memory.

Difference between Structure and Union


Structure Union
For defining structure use struct For defining union we use union
keyword. keyword
Structure occupies more memory Union occupies less memory space
space than union. than Structure.
In Structure we can access all In union we can access only one
members of structure at a time. member of union at a time.
Structure allocates separate storage Union allocates one common storage
space for its every members. space for its all members. Union find
which member need more memory
than other member, then

Bit-Fields
Syntax
struct {
type [member_name] : width ;
};
The following table describes the variable elements of a bit field –

Elements Description
type An integer type that determines how
a bit-field's value is interpreted. The
type may be int, signed int, or
unsigned int.
member_name The name of the bit-field.
width The number of bits in the bit-field.
The width must be less than or equal
to the bit width of the specified type
The variables defined with a predefined width are called bit fields. A bit field can
hold more than a single bit; for example, if you need a variable to store a value
from 0 to 7, then you can define a bit field with a width of 3 bits as follows −
struct {
unsigned int age : 3;
} Age;
The above structure definition instructs the C compiler that the age variable is
going to use only 3 bits to store the value. If you try to use more than 3 bits, then it
will not allow you to do so. Let us try the following example –
#include <stdio.h>
#include <string.h>
struct {
unsigned int age : 3;
} Age;
int main( ) {
Age.age = 4;
printf( "Sizeof( Age ) : %d\n", sizeof(Age) );
printf( "Age.age : %d\n", Age.age );
Age.age = 7;
printf( "Age.age : %d\n", Age.age );
Age.age = 8;
printf( "Age.age : %d\n", Age.age );
return 0;
}
Output
Sizeof( Age ) : 4
Age.age : 4
Age.age : 7
Age.age : 0
typedef
The typedef is a keyword that allows the programmer to create a new data type
name for an existing data type. So, the purpose of typedef is to redefine the name
of an existing variable type.
Syntax
typedef datatype alias_name;
Example of typedef
#include<stdio.h>
#include<conio.h>
typedef int Intdata; // Intdata is alias name of int
void main()
{
int a=10;
Integerdata b=20;
typedef Intdata Integerdata; // Integerdata is again alias name of Intdata
Integerdata s;
clrscr();
s=a+b;
printf("\n Sum:= %d",s);
getch();
}
Output
Sum: 20

Advantages of typedef :
1 : Provides a meaningful way of declaring the variable.
2 : Increase the readability of the program.
#include<stdio.h>
#include<conio.h>
void main()
{
typedef int digits;
digits a,b,sum;
clrscr();
printf("Enter a and b values:");
scanf("%d%d",&a,&b);
sum=a+b;
printf("The sum is:%d",sum);
getch();
}
Note: By using typedef only we can create the alias name and it is under control of
compiler.
Application of typedef
typedef can be used to give a name to user defined data type as well. Lets see its
use with structures.
typedef struct
{
type member1;
type member2;
type member3;
} type_name ;
Here type_name represents the stucture definition associated with it. Now this
type_name can be used to declare a variable of this stucture type.
type_name t1, t2 ;
Example of structure definition using typedef
#include<stdio.h>
#include<conio.h>
#include<string.h>
typedef struct employee
{
char name[50];
int salary;
} emp ;
void main( )
{
emp e1;
printf("\nEnter Employee record\n");
printf("\nEmployee name\t");
scanf("%s",e1.name);
printf("\nEnter Employee salary \t");
scanf("%d",&e1.salary);
printf("\nstudent name is %s",e1.name);
printf("\nroll is %d",e1.salary);
getch();
}
typedef and Pointers
typedef can be used to give an alias name to pointers also. Here we have a case in
which use of typedef is beneficial during pointer declaration.
In Pointers * binds to the right and not the left.
int* x, y ;
By this declaration statement, we are actually declaring x as a pointer of type int,
whereas y will be declared as a plain integer.
typedef int* IntPtr ;
IntPtr x, y, z;
But if we use typedef like in above example, we can declare any number of
pointers in a single statement.
NOTE : If you do not have any prior knowledge of pointers, do study Pointers first.
Enumerations
An enum is a keyword, it is an user defined data type. All properties of integer are
applied on Enumeration data type so size of the enumerator data type is 2 byte. It
work like the Integer.
It is used for creating an user defined data type of integer. Using enum we can
create sequence of integer constant value.
Syntax
enum tagname {value1, value2, value3,....};
In above syntax enum is a keyword. It is a user defiend data type.

In above syntax tagname is our own variable. tagname is any variable name.

value1, value2, value3,.... are create set of enum values.


It is start with 0 (zero) by default and value is incremented by 1 for the sequential
identifiers in the list. If constant one value is not initialized then by default
sequence will be start from zero and next to generated value should be previous
constant value one.
Example of Enumeration in C
#include<stdio.h>
#include<conio.h>
enum ABC {x,y,z};
void main()
{
int a;
clrscr();
a=x+y+z; //0+1+2
printf("Sum: %d",a);
getch();
}
Output
Sum: 3
Example of Enumeration in C
#include<stdio.h>
#include<conio.h>
enum week {sun, mon, tue, wed, thu, fri, sat};
void main()
{
enum week today;
today=tue;
printf("%d day",today+1);
getch();
}
Output
3 day
Example of Enumeration in C
#include<stdio.h>
#include<conio.h>
enum week {sun, mon, tue, wed, thu, fri, sat};
void main()
{
for(i=sun; i<=sat; i++)
{
printf("%d ",i);
}
getch();
}
Output
In above code replace sun, mon, tue,.... with Equivalent numeric value 0, 1, 2,...
UNIT - 11
Data Files

11.1 Opening & Closing a Data File


11.2 Creating a Data File
11.3 Error Handling during I/O Operations
11.4 Processing a Data File

There are two main types of files in C programming: text files and binary files. Text files contain data that
is human-readable and can be opened and edited using a text editor. Binary files, on the other hand,
contain non-textual data that is encoded in binary format and is typically processed by computer
programs.
1. What is ASCII Text file?
In C programming, an ASCII text file is a type of text file that uses the ASCII (American Standard Code for
Information Interchange) character set to represent text. ASCII is a standard character encoding that assigns
a unique numerical value to each character, including letters, digits, punctuation marks, and other
symbols. ASCII text files are human-readable and can be opened and edited using a text editor.
In an ASCII text file, each character is represented using a single byte (8 bits) of information, allowing for
a maximum of 256 possible characters. This includes the standard ASCII characters as well as extended
ASCII characters that are specific to certain languages or regions.
2. What is a Binary file?
A binary file is a type of file that contains non-textual data encoded in binary format, meaning that the
data is represented using a sequence of 1s and 0s. Binary files are typically used to store executable code,
images, audio, video, or other types of data that cannot be easily represented as text.
Binary files can be either processed sequentially or can be processed using random access techniques. In C,
processing a file using random access techniques involves moving the current file position to an
appropriate place in the file before reading or writing data.
Importance of File Handling in C Programming
File handling is an important aspect of programming because it allows programs to read data from and
write data to files, which are external storage devices. This is essential for many programs that need to
store data beyond the lifetime of a program’s execution.
Here are some specific reasons why file handling is important in programming:
Persistent Data Storage: Files allow data to be stored outside of the program’s memory, so it can be
accessed even after the program has terminated. This is important for programs that need to save data
between runs, or for programs that need to share data with other programs.
Data Processing: Many programs process large amounts of data, and files provide an efficient means of
storing and processing this data. This is particularly true for programs that work with text or binary files.
Configuration Files: Many programs use configuration files to store settings that are used each time the
program is run. This allows users to customize the behavior of the program without changing the
program’s source code.
Interprocess Communication: Programs running on the same computer can use files to communicate with
each other. This allows programs to share data or coordinate tasks.

DEFINITION:
A file can be defined as a collection of bytes stored on the disk under a name. A file may
contain anything, in the sense the contents of files may be interpreted as a collection of
records or a collection of lines or a collection of instructions etc.
A file is a collection of records. Each record provides information to the user. These files
are arranged on the disk.

Basic operations on files include:


 Open a file
 Read data from file/Write data to file
 Close a file
To access the data in a file using C we use a predefined structure FILE present in stdio.h
header file, that maintains all the information about files we create (such as pointer to
char in a file, end of file, mode of file etc).

FILE is a data type which is a means to identify and specify which file you want to
operate on because you may open several files simultaneously.
When a request is made for a file to be opened, what is returned is a pointer to the
structure FILE. To store that pointer, a pointer variable is declared as follows:
FILE *file_pointer;
where file_pointer points to first character of the opened file.

Opening of a file:
A file needs to be opened when it is to be used for read/write operation. A file is opened
by the fopen() function with two parameters in that function. These two parameters are
file name and file open mode.
Syntax: fopen(filename, file_open_mode);

The fopen function is defined in the “stdio.h” header file. The filename parameter refers
to any name of the file with an extension such as “data.txt” or “program.c” or
"student.dat" and so on.
File open mode refers to the mode of opening the file. It can be opened in ‘read mode’
or ‘write mode’ or ‘append mode’.
The function fopen() returns the starting address of file when the file we are trying to
open is existing (i.e. success) else it returns NULL which states the file is not existing or
filename given is incorrect.
E.g.: FILE *fp;
fp=fopen("data.txt","r");
/*If file exists fp points to the starting address in memory
Otherwise fp becomes NULL*/
if(fp==NULL) printf("No File exists in Directory");
NULL is a symbolic constant declared in stdio.h as 0.

Modes of Operation:
1. "r" (read) mode: open file for reading only.
2. "w" (write) mode: open file for writing only.
3. "a" (append) mode: open file for adding data to it.
4. "r+" open for reading and writing, start at beginning
5. "w+" open for reading and writing (overwrite file)
6. "a+" open for reading and writing (append if file exists)
When trying to open a file, one of the following things may happen:
 When the mode is ‘writing’ a file with the specified name is created if the file does
not exist. The contents are deleted, if the file is already exists.
 When the purpose is ‘appending’, the file is opened with the current contents safe.
A file with the specified name is created if the file does not exist.
 When the purpose is ‘reading’, and if it exists, then the file is opened with the
current contents safe; otherwise an error occurs.
With these additional modes of operation (mode+), we can open and use a number of
files at a time. This number however depends on the system we use.

Closing a file:
A file must be closed as soon as all operations on it have been completed. This ensures
that all outstanding information associated with the file is flushed out from the buffers
and all the links to the file are broken. It also prevents any accidental misuse of file.

Closing of unwanted files might help open the required files. The I/O library supports a
function to do this for us.
Syntax: fclose(file_pointer);
/*This would close the file associated with the FILE pointer file_pointer*/
fcloseall();
/*This would close all the opened files. It returns the number of files it closed. */

Example: Program to check whether given file is existing or not.


#include<stdio.h>
main()
{
FILE *fp;
fp=fopen("data.txt","r");
if(fp==NULL) {
printf("No File exists in Directory");
exit(0);
}
else
printf("File Opened");
fclose(fp);
getch();
}
Reading and Writing Character on Files
To write a character to a file, the input function used is putc or fputc. Assume that a file is
opened with mode 'w' with file pointer fp. Then the statement,
putc(character_variable,file_pointer);
fputc(character_variable,file_pointer);
writes the character contained in the 'character_variable' to the file associated with FILE
pointer 'file_pointer'.
E.g.: putc(c,fp);
fputc(c,fp1);
To read a character from a file, the output function used is getc or fgetc. Assume that a
file is opened with mode 'r' with file pointer fp. Then the statement,
character_variable = getc(file_pointer);
character_variable = fgetc(file_pointer);
read the character contained in file whose FILE pointer 'file_pointer' and stores in
'character_variable'.
E.g.: getc(fp);

fgetc(fp);
The file pointer moves by one character position for every operation of getc and putc.
The getc will return an end-of-file marker EOF, when end of the file has been reached.
Therefore, the reading should be terminated when EOF is encountered.
Example: Program for Writing to and reading from a file
#include<stdio.h>
main()
{
FILE *f1;
char c;
clrscr();
printf("Write data to file: \n");
f1 = fopen("test.txt","w");
while((c=getchar())!='@')
putc(c,f1);
/*characters are stored into file until '@' is encountered*/
fclose(f1);
printf("\nRead data from file: \n");
f1 = fopen("test.txt","r"); /*reads characters from file*/
while((c=getc(f1))!=EOF)
printf("%c",c);
fclose(f1);
getch();
}

Example: Program to write characters A to Z into a file and read the file and print the
characters in lowercase.
#include<stdio.h>
main()
{
FILE *f1;
char c;
clrscr();
printf("Writing characters to file... \n");
f1 = fopen("alpha.txt","w");
for(ch=65;ch<=90;ch++)
fputc(ch,f1);
fclose(f1);
printf("\nRead data from file: \n");
f1 = fopen("alpha.txt","r");
/*reads character by character in a file*/
while((c=getc(f1))!=EOF)
printf("%c",c+32); /*prints characters in lower case*/
fclose(f1);

getch();
}
Example: Program to illustrate the append mode of operation for given file.
#include<stdio.h>
main()
{
FILE *f1;
char c,fname[20];
clrscr();
printf("Enter filename to be appended: ");
gets(fname);
printf("Read data from file: \n");
f1 = fopen(fname,"r");
if(f1==NULL)
{
printf("File not found!");
exit(1);
}
else
{
while((c=getc(f1))!=EOF)
printf("%c",c);
}
fclose(f1);
f1 = fopen(fname,"a");
while((c=getchar())!='@')
putc(c,f1);
/*characters are appended into file with existing data until
'@' is encountered*/
fclose(f1);
getch();
}
Reading and Writing Integers getw and putw functions:
These are integer-oriented functions. They are similar to getc and putc functions and are
used to read and write integer values. These functions would be useful when we deal
with only integer data.
The general forms of getw and putw are:
putw: Writes an integer to a file.
putw(integer,fp);
getw: Reads an integer from a file.
getw(fp);

Example: Program to illustrate getw and putw functions.


#include<stdio.h>
main()
{
int n,num,i,sum=0;
FILE *fp;
clrscr();
printf("Enter the number of integers to be written to file: ");
scanf("%d",&n);
fp = fopen("numbers.txt","w");
for(i=0;i<n;i++)
{
scanf("%d",&num);
putw(num,fp);
}
fclose(f1);
fp = fopen("numbers.txt","r");
while((num=getw(fp))!=EOF)
{
sum=sum+num;
}
fclose(fp);
printf("Sum of %d numbers is %d\n\n",n,sum);
printf("Average of %d numbers is %d",sum/n);
getch();
}
End of File: feof()
The feof() function can be used to test for the end of the file condition. It takes a FILE
pointer as its only argument and returns a non-zero integer value if all the data from
specified file has been read and returns zero otherwise.
This function returns true if you reached end of file in given file, otherwise returns false.
while(!feof(fp))
{
....
....
....
}
/*executes set of statements in the loop until EOF is encountered*/
fgets and fputs functions:
fputs writes string followed by new line into file associated with FILE pointer fp.
fputs(char *st, FILE *fp);
E.g.: fputs(str,fp);

fgets reads characters from current position until new line character is encountered or
len-1 bytes are read from file associated with FILE pointer fp. Places the characters read
from the file in the form of a string into str.
fgets(char *st,int len,FILE *fp);
E.g.: fgets(str,50,fp);
Example: Program to illustrate fgets and fputs function.
#include<stdio.h>
main()
{
FILE *fp;
char s[80];
clrscr();
fp=fopen("strfile.txt","w");
printf("\nEnter a few lines of text:\n");
while(strlen(gets(s))>0)
{
fputs(s,fp);
fputs("\n",fp);
}
fclose(fp);
printf("Content in file:\n");
fp=fopen("strfile.txt","r");
while(!feof(fp))
{
puts(s);
fgets(s,80,fp);
}
fclose(fp);
getch();
}
fprintf and fscanf functions
The functions fprintf and fscanf perform I/O operations that are identical to the familiar
printf and scanf functions, except of course that they work on files. The first argument of
these functions is a file pointer, where specifies the file to be used.
fprintf(): Writes given values into file according to the given format. This is similar to
printf but writes the output to a file instead of console.
fscanf(): Reads values from file and places values into list of arguments. Like scanf it
returns the number of items that are successfully read. When the end of file is reached, it
returns the value EOF.

The general form of fprintf and fscanf isfprintf(file_pointer/stream, “control string”, list);
fscanf(file_pointer/stream, “control string”, list);
where file_pointer is a pointer associated with a file that has been opened for writing.
The stream refers to a stream or sequence of bytes that can be associated with a device or
a file. The following are the available standard file pointers/streams:
 stdin refers to standard input device, which is by default keyboard.
 stdout refers to standard output device, which is by default screen.
 stdprn refers to printer device.
 stderr refers to standard error device, which is by default screen.
The control string (format specifier) contains output specifications for the items in the list.
The list may include variables, constants and strings.
E.g.:
fprintf(fp, “%s %d %f”, name, age, 7.5); /*writes to file*/
fprintf(stdout, “%s %d %f”, name, age, 7.5); /*prints data on console*/
fscanf(fp, “%s %d %f”, name, &age, &per); /*reads from file*/
fscanf(stdin, “%s %d %f”, name, &age, &per); /*reads data from console*/
Example: Program to illustrate fprintf and fscanf function.
#include<stdio.h>
main()
{
FILE *fp;
int number,quantity,i;
float price,value;
char item[20],filename[10];
clrscr();
printf("Enter filename: ");
gets(filename);
fp=fopen(filename,"w");
printf("Enter Inventory data: \n");
printf("Enter Item Name, Number, Price and Quantity
(3 records):\n");
for(i=1;i<=3;i++) {
fscanf(stdin,"%s %d %f %d",item,&number,&price,&quantity);
fprintf(fp,"%s %d %0.2f %d",item,number,price,quantity);
}
fclose(fp);
fprintf(stdout,"\n\n");
fp=fopen(filename,"r");
printf("Item Name\tNumber\tPrice\tQuantity\tValue\n");
for(i=1;i<=3;i++)

{
fscanf(fp,"%s %d %f %d",item,&number,&price,&quantity);
value=price*quantity;
fprintf(stdout,"%s\t%10d\t%8.2f\t%d\t%11.2f\n",item,number,price,
quantity,value);
}
fclose(fp);
getch();
}

C File management
A File can be used to store a large volume of persistent data. Like many other languages ‘C’ provides following file
management functions,

1. Creation of a file
2. Opening a file
3. Reading a file
4. Writing to a file
5. Closing a file

Following are the most important file management functions available in ‘C,’

function purpose
fopen () Creating a file or opening an existing file
fclose () Closing a file
function purpose
fprintf () Writing a block of data to a file
fscanf () Reading a block data from a file
getc () Reads a single character from a file
putc () Writes a single character to a file
getw () Reads an integer from a file
putw () Writing an integer to a file
fseek () Sets the position of a file pointer to a specified location
ftell () Returns the current position of a file pointer
rewind () Sets the file pointer at the beginning of a file

Create a data File


A data file must be created before it can be processed. A streamoriented data file can be created in two
ways. The first one is to create the file directly using a text editor or word processor. The second one is
to write a program that generates information in a computer and then writes it out to the data file. We
create unformatted data file with the second method. To create a file in a ‘C’ program following syntax is
used,

FILE *fp;
fp = fopen ("file_name", "mode");
In the above syntax, the file is a data structure which is defined in the standard library.

fopen is a standard function which is used to open a file.

 If the file is not present on the system, then it is created and then opened.
 If a file is already present on the system, then it is directly opened using this function.

fp is a file pointer which points to the type file.

Whenever you open or create a file, you have to specify what you are going to do with the file. A file in ‘C’
programming can be created or opened for reading/writing purposes. A mode is used to specify whether you want
to open a file for any of the below-given purposes. Following are the different types of modes in ‘C’ programming
which can be used while working with a file.

File
Description
Mode
Open a file for reading. If a file is in reading mode, then no data
r
is deleted if a file is already present on a system.
Open a file for writing. If a file is in writing mode, then a new file
is created if a file doesn’t exist at all. If a file is already present
w
on a system, then all the data inside the file is truncated, and it
is opened for writing purposes.
Open a file in
a append mode. If a file is in append mode, then the file is
opened. The content within the file doesn’t change.
r+ open for reading and writing from beginning
w+ open for reading and writing, overwriting a file
a+ open for reading and writing, appending to file
In the given syntax, the filename and the mode are specified as strings hence they must always be enclosed within
double quotes.

Example:

#include <stdio.h>
int main() {
FILE *fp;
fp = fopen ("data.txt", "w");
}

Close a data file


One should always close a file whenever the operations on file are over. It means the contents and links to the file
are terminated. This prevents accidental damage to the file.

‘C’ provides the fclose function to perform file closing operation. The syntax of fclose is as follows,

fclose (file_pointer);
Example:

FILE *fp;
fp = fopen ("data.txt", "r");
fclose (fp);

Processing a Data File

To execute any program we are required to first enter the program, compile it, and then execute it.
Instead of the program prompting for entering the source and target filenames it can be through
command prompt in the form: C> filecopy sample1.c sample2.c where sample1.c is the source filename
and sample2.c is target filename. The second option is possible by passing the source filename and
target filename to the function main(). Let us first consider an example:

#include “stdio.h>

main( int argc,char * argv [])

{ FILE *fs , *ft;

Error Handling during I/O Operations:


The functional methods perror(), strerror(), ferror(), feof(), clearerr() , and Exit status are used to
handle errors while executing file operations even though the C language lacks direct support for error
handling.
When we attempt to use a file that has not yet been opened or read a file that doesn’t even exist, issues
frequently occur. We can consult errno to determine the type of error. When we call a function in C
language, a variable is automatically initialized with a numeric value and we can use that to identify the
type of error if encountered while writing the code. This variable is called errno value. It is a global
variable that is defined in errno.h header file.
There are really only two categories of errno-related functions. They are perror() and strerror() ,
respectively. These routines allow us to show the text message related to errno .
related to errno.
1. The textual representation of the current errno value is displayed after the colon, space, and the
string you supply to the function perror(), which is then responsible for displaying the string you
passed it.
2. In order to retrieve the textual representation of the current errno value, use the strerror()
method.

Implement Error Handling with Errno in C


Here is a easy system that will show you how to use errno to handle exceptions and errors in C.
This application demonstrates what occurs when a file that does not exist in the computer system is
attempted to be opened.

errno value Error

1 Operation not permitted

2 No such file or directory

3 No such process

4 Interrupted system call

5 I/O error
errno value Error

6 No such device or address

7 Argument list too long

8 Exec format error

9 Bad file number

10 No child processes

11 Try again

12 Out of memory

13 Permission denied

1. Operation not permitted: Sometimes while performing operations of file handling in C, we try to read
from a file or change permissions of a file by accessing it. If we don't have ownership rights or system
rights to access a file, then we get this particular error message.
2. No such file or directory: This error message occurs whenever we try to access a file or directory that
doesn't exists. It also occurs when we specify wrong file destination path.
3. No such process: When we perform some operations that are not supported during file handling in C,
it gives no such process error.
4. Interrupted System call: If we try to read user's input and if there is no input present, then the system
calling process will not return any value and will be blocked forever. This results in interrupted system
calls.
5. I/O error: I/O stands for input/output errors that occur when system is not able to perform basic
operations like reading from a file or copying data from one file to another.
6. No such device or address: When we specify incorrect device path or address while opening or
accessing them, this error occurs.
For example: If we are trying to access a device driver using its path but in actual, it has been removed
from the system.
7. Argument list too long: This error generally occurs when we work with large number of files.
For example: If we need to get count of no. of files in a directory (consisting of large number of files)
that starts with string - "Scaler", then due to limited buffer space it will show an error message -
"Argument list too long" as no. of files in that directory will be equal to the arguments list.
8. Exec format error: This error occurs when we try to execute a file that is not executable or has an
invalid executable-file format.
9. Bad file number: This error occurs generally when we try to write to a file which is opened for read-
only purpose.
10. No child process: If a process has no further sub-process or child process, then the code returns -
1 value and we get no child process error message.
11. Try again: An attempt to create a process fails, when there are no more process slots or not enough
memory available. We then get try again error.
12. Out of memory: This error occurs when there is not enough memory available to execute a process.
13. Permission denied: This error occurs when we try to read from a file that is not opened. It suggests
that an attempt was made to access a file in a way that is incompatible with the file's attributes.

Methods of Error Handling in C


Functional methods of error handling in C Library that is helpful while performing file operations:
1. perror()
perror() function stands for print error and when called by the user, it displays a message describing
about the most recent error that occurred in the code.
perror() function is contained in stdio.h header file.
Syntax:
void perror(const char *str1)
Here, str1 is a string containing a custom message that is to be printed before the error message itself.
User-defined message is printed firstly, followed by a colon and then the error message is printed.
We can call perror() function even if no error has encountered and in that case, it will display 'No
Error' message.
C Program to illustrate the use of perror() function: In this program with the help of perror() function, we
are displaying an error message when there is no file available naming "test.txt".
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

int main(){
FILE* fp;
fp = fopen("test.txt","r");

if(fp==NULL){ //Error handling in case if the file doesn't exists


perror("Message from perror ");
//User-Defined message passed as an argument string in perror() function
return -1;
}
fclose(fp);
return 0;
}
We have declared a file pointer 'fp' and using it, we are trying to open "test.txt" file in read only mode. If
file doesn't exists i.e. fp is NULL, we call perror() function to print the error message.
Output:
Assuming "test.txt" file doesn't exists: (Output):
Message from perror : No such file or directory
Here, string - "Message from perror" is user-defined parameter passed in the function that is printed
before the actual error message.
2. strerror()
strerror() function is contained in string.h header file.
It takes 'errno' as an argument and returns the string error message of currently passed errno.
Syntax:
char *strerror(int errnum)
Here, errnum is the error number (errno value) using which, respective error message will be displayed
accordingly.
C Program to illustrate the use of strerror() function: In this program with the help of strerror() function, we
are displaying an error message using errno value when there is no file available naming "test.txt".
#include <errno.h>
#include <stdio.h>
#include <string.h>

int main(){
FILE* fp;
fp = fopen("test.txt","r");

if(fp==NULL){ //Error handling in case if the file doesn't exists


printf("Error: %s\n",strerror(errno));
//errno passed as an argument to display respective order error message
}
fclose(fp);
return 0;
}
After opening the file in read only mode using file pointer fp, we check that if fp is NULL i.e. the file
doesn't exists and then we pass errno as parameter in strerror() function that will print respective error
message.
Output:
Assuming "test.txt" file doesn't exists: (Output):
Error: No such file or directory
As the file doesn't exists, we have printed errno-2 error message i.e. No such file or directory.

3. ferror()
ferror() function is contained in stdio.h header file.
This function basically checks for error in the file stream. It returns zero value if there is no error or else,
it returns a positive non-zero value in case of error.
File pointer stream is passed as an argument to the function. It will check for the error until the file is
closed or we call clearerr() function.
To identify the type of error, we can further use perror() function.
Syntax:
int ferror(FILE *stream);
C Program to illustrate the use of ferror() function: In this program, we are trying to read data from the file
but has opened the file in the wrong access mode i.e, writing mode. Now, ferror() function will detect
this error in the file stream and using perror() function, we will display the error message.
#include <stdio.h>

int main(){
FILE *fp;
fp = fopen("test.txt","w");
char ch = fgetc(fp); //Trying to read data, despite of writing mode opened
if(ferror(fp)){ //Error detected in the file stream pointer
printf("File is opened in writing mode!");
printf("\nError in reading from the file!");
perror("Error Message from perror");
//Identifying the type of error using perror() function
}
fclose(fp);
return(0);
}
Output:
File is opened in writing mode!
Error Message from perror: Bad file descriptor
Error in reading from the file!
Here, we are printing error messages both user-defined and from perror() function as well.

4. feof()
feof() function is contained in stdio.h header file.
This function tests for end-of-file (eof indicator) for the file pointer stream passed as an argument to the
function.
On detecting that the end-of-file indicator associated with the file stream is set, it returns a non-zero
positive value or else, zero is returned.
Syntax:
int feof(FILE *stream);
Here, file pointer stream is passed as an argument and on detecting the end-of-file, this function will
return a non-zero positive value.
C Program to illustrate the use of feof() function: In this program, we are trying to read data from the file
and to avoid printing the garbage value characters, we are using feof() function. On detecting the end-of-
file, it will return a non-zero value and hence, breaks the loop.
#include <stdio.h>
#include <stdbool.h>

int main(){
FILE *fp;
fp = fopen("test.txt","r");
if(fp==NULL){
perror("Message from perror");
return -1;
}
while(true){
char ch = fgetc(fp); //Reading data from the file
if(feof(fp)){
//On detecting the end-of-file, feof() function will return non-zero value
//hence, it will break the loop
break;
}
printf("%c",ch);
}
fclose(fp);
return 0;
}
Output: Assuming there's some data present in the "test.txt" file, it will read and print:
Scaler Topic: Error Handling in C during File Operations
In absence of feof() function, it will further print the garbage value characters.

5. clearerr()
clearerr() function is contained in stdio.h header file.
This function clears the end-of-file and the error indicators from the file stream.
Error indicators are not automatically cleared and they continue to return the errors until clearerr()
function is called.
Syntax:
void clearerr(FILE *stream)
C Program to illustrate the use of clearerr() function: In this program, we are trying to read data from the
file but has opened the file in the wrong access mode i.e, writing mode. Now, we will clear the error
indicators using clearerr() function from the file stream and hence, ferror() couldn't then detect that
error again.
#include <stdio.h>

int main(){
FILE *fp;
fp = fopen("test.txt","w");
char ch = fgetc(fp); //Trying to read data but the file is opened in writing mode
if(ferror(fp)) { //ferror() will detect error in file pointer stream
printf("Error in reading from file!");
}
clearerr(fp); //clearerr() will clear error-indicators from the file stream
if(ferror(fp)){ //No error will be detected now
printf("Error again in reading from file!");
}
fclose(fp);
return 0;
}
After opening the file in writing mode, we are trying to read data from it using fgetc() and therefore,
using ferror() function we can detect the error. After using clearerr() function, it will remove the error in
the file pointer stream and further, we won't get any error on checking through ferror() function.
Output:
Error in reading from file!
In absence of clearerr() function, output will be:
Error in reading from file!
Error again in reading from file!

6. Exit Status
The macros of exit status() functional method are defined in stdlib.h header file. They are used to inform
calling function about the error.
There are two constant exit status values available for the exit() function: EXIT_STATUS and
EXIT_FAILURE.
When program code comes out after a successful operation, then EXIT_SUCCESS is used to show
successful exit. Its value is defined as 0.
We use EXIT_FAILURE in case of failures or abrupt termination of the program. Its value is defined as -1.
Syntax:
exit(EXIT_SUCCESS); //successful termination
exit(EXIT_FAILURE); //unsuccessful termination
C Program to illustrate the use of Exit Status function: In this program, we are illustrating the use of two exit
function constant values: EXIT_SUCCESS and EXIT_FAILURE depending upon how the program code is
terminated.
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

int main(){
FILE *fp;
fp = fopen ("test.txt","r");
if(fp==NULL){
printf("Value of errno: %d",errno);
perror("Error printed by perror");
exit(EXIT_FAILURE); //Good practice to exit the program using exit status
printf("This message will not be printed!");
//This won't be printed due to exit above
}
else{
fclose (fp);
exit(EXIT_SUCCESS); //Successful exit from the program
printf("This message will not be printed!");
//This won't be printed due to exit above
}
return 0;
}
After opening a file using file pointer fp, if it doesn't exists then we will print the error messages and exit
from the function (EXIT_FAILURE). If file exists, then we will exit from the program by executing else
condition here (EXIT_SUCCESS). Output: In case, if "test.txt" file doesn't exists: exit(EXIT_FAILURE)
Error printed by perror: No such file or directory
Value of errno: 2
7. Division by zero
If we divide a number by zero, C programming language will give warnings and also give runtime error.
To avoid such an undefined behaviour, there is no construct or method in C.
To avoid such situations, we can check the value of divisor before using it for division purposes. This can
be done using if-else conditions and whenever we encounter such a situation, we can simply print error
message.
C Program to illustrate the error of Division by zero: In this program, we are keeping a check if in case we
get zero number value for division that can produce errors and can also abruptly terminate the program.
#include <stdio.h>
#include <stdlib.h>

void division(int x){


if(x==0){ //Checking if divisor is zero, to avoid errors
printf("Division by Zero is not allowed!");
exit(EXIT_FAILURE); //unsuccessful termination
}
else{
float fx = 10/x;
printf("f(x) is: %.5f",fx);
}
}

int main(){
int x = 0;
division(x); //Calling function to perform division
return 0;
}
Here, we have passed the value x in division function. Using if condition we check if it is 0, then we can't
perform division using it. Using else condition, we divide 10 by x and then print the resultant
value. Output:
Division by Zero is not allowed!
UNIT 12.
Graphics
Graphics programming in C used to drawing various geometrical shapes(rectangle, circle eclipse etc), use
of mathematical function in drawing curves, coloring an object with different colors and patterns and
simple animation programs like jumping ball and moving cars.

Graphics options are used in c-programming to draw different graphical shapes. First of all we have to
call the initgraph() function that will initialize the graphics mode on the computer.

Call to function initgraph() is done as


initgraph(&gdriver, &gmode, “path_to_driver”);

initgraph() initializes the graphics system by loading a graphics driver from disk (or validating a
registered driver) then putting the system into graphics mode. initgraph() also resets all graphics settings
(color, palette, current position, viewport, etc.) to their defaults, then resets graph result to 0.
gdriver:
It is declared as integer variable that specifies the graphics driver to be used.
gmode:
It is also declared as integer variable which specifies the initial graphics mode (unless gdriver = DETECT).
If gdriver = DETECT, initgraph sets gmode to the highest resolution available for the detected driver.
path_to_driver:
Specifies the directory path where initgraph() looks for graphics drivers (e.g. egavga.bgi in turbo c++)
1. If the driver is not there, initgraph() looks in the current directory.
2. If path_to_driver is null, the driver files must be in the current directory.
After a call to initgraph, gdriver is set to the current graphics driver, and gmode is set to the
current graphics mode.

Gdriver =DETECT auto-detects the attached video adapter at run time and pick the corresponding driver.
If we tell initgraph to auto-detect, it calls detectgraph to select a graphics driver and mode.

Normally, initgraph() loads a graphics driver by allocating memory for the driver, then loading the
appropriate .BGI file from disk

Next

Initializing Graphics Mode


Function initgraph()

This function is used to load the graphics drivers and initialize the graphics system. For every function, that uses

graphics mode, graphics mode must be initialized before using that function.
void initgraph(int far *driver, int far *mode, char far *path)

Path determines that path to the specified graphics driver.


Function detectgraph()

Detectgraph function determines the graphics hardware in the system, if the function finds a graphics adapter

then it returns the highest graphics mode that the adapter supports.
void detectgraph(int far *driver, int far *mode)
Function cleardevice()

This function clears the graphics screen contents and return the control to the location (0,0).
void cleardevice(void)
Function closegraph()

This function shutdown the graphics mode and returns to the position it was before the initgraph() function was

called. The closegraph() function releases all the resources occupied by the graphics system like memry, fonts,

drivers etc…
void closegraph(void)

Sample Program

Error Handling
• graphresult() function is used to check if
certain graphics operation succeeded or not.
• It return 0 for no error.
Some Functions in Graphics
• putpixel() and getpixel()
• setcolor() and setbcolor()
• line()
• circle()
• ellipse
• rectangle()
• settextstyle() and outtext()
• getmaxx() and getmaxy()
1)putpixel() and getpixel()
getpixel returns the color of pixel present at point(x, y).
putpixel plots a pixel at a point(x, y) of specified color.
Syntax:
int getpixel(int x, int y);
void putpixel(int x, int y, int color);
2)setbcolor()
setbkcolor function changes current background color e.g. setbkcolor(YELLLOW) changes the current background
color to YELLOW.
Remember that default drawing color is WHITE and background color is BLACK.
Syntax :-
void setbkcolor(int color);
3)setcolor()
setcolor function changes current drawing color e.g. setcolor(YELLLOW) changes the
current drawing color to YELLOW.
Syntax :-
void setcolor(int color);
4)line()
line function is used to draw a line from a point(x1,y1) to point(x2,y2)
Syntax :-
void line(int x1, int y1, int x2, int y2);
5)circle()
Circle function is used to draw a circle with center (x,y) and third parameter specifies the
radius of the circle.

Syntax :-
void circle(int x, int y, int radius);
6.ellipse()
Ellipse is used to draw an ellipse (x,y) are coordinates of center of the ellipse, stangle is
the starting angle, end angle is the ending angle, and fifth and sixth parameters specifies
the X and Y radius of the ellipse.
Syntax :-
void ellipse(int x, int y, int stangle, int endangle, int xradius, int yradius);

7.rectangle()
Coordinates of left top and right bottom corner are required to draw the rectangle.
Syntax:-
void rectangle(int left, int top, int right, int bottom);
8.settextstyle()
font argument specifies the font of text, Direction can be HORIZ_DIR (Left to right) or
VERT_DIR (Bottom to top).
Syntax :-
– void settextstyle( int font, int direction, int charsize);
9.outtext()
outtext function displays text at current position.
Syntax :-
void outtext(char *string);
10.getmaxx() and getmaxy()
getmaxx function returns the maximum X coordinate for current graphics mode and driver.
Declaration :- int getmaxx();
getmaxy function returns the maximum Y coordinate for current graphics mode and driver.
Declaration :- int getmaxy();
The line function which is most important function in creating any graphics.

Function line()

This function draws a line in the graphics mode.

void line(int startx, int starty, int endx, int endy)


Function arc()

This function draws an arc from start to the end point. It uses the radius and the angle inputted in the function

parametsr. Function prototye is

void arc (int x, int y, int start, int end, int radius)

Function bar()

The bar() functions draws a rectangular bar on the screen. It takes four parameters of type int which are infact the

points on the graphics screen, and fills the bar with the defined fill-pattern. Function prototye is

void bar(int left, int top, int right, int bottom)

Here left & top are the starting point for the rectangular bar from x and y coordinates respectively and right &

bottom are the ending point.

Function bar3d()

As the name suggests that this function will draw the 3 Dimensional rectangular bar on the screen. Bar3d function

takes six parameters of which four are the points , fifth one is the depth of the bar and sixth is the flag to indicate

the 3D view. Here is the prototype of the bar3d function.


void bar3d(int left, int top, int right, int bottom, int depth, int topflag)
Function circle()

Draws the circle on the screen using a point(x,y) and the radius for the circle.

void circle(int x, int y, int radius)


Function drawpoly()

This function draws an outline of a polygon.

void drawpoly(int numpoints, int far *points)

Here numpoints is the number of end points in the polygon. And points is the integer array which contains the x

and y coordinates of the points.

Function ellipse()

Draws an ellipse using the current drawing color.

void ellipse(int x, int y, int start, int end, int xradius, int yradius)
Function floodfill()

This function fills an object drawn on the graphics screen with the defined color and fill pattern. Now if the x,y

coordinates lie within the boundries of the object then it will fill the interior of the object otherwise out side the

object.

void floodfill(int x, int y, int border)


Function outtext()

Displays a text string on the screen in graphics mode.

void outtext(char far *str)


Function outtextxy()

Displays the text at a specified position in graphics mode.

void outtext(int x, int y, char *str)


Function putpixel()

Prints a pixel at the specified point on the screen.

void putpixel(int x, int y, int color)


Function rectangle()
Draws a rectangular box on the screen using the points given in the parameters.

void rectangle(int left, int top, int right, int bottom)

program to draw a line #


/*program to draw a line*/

#include <graphics.h>

#include <stdlib.h>

#include <stdio.h>

#include <conio.h>

int main()

/* request auto detection */

int gdriver = DETECT, gmode, errorcode;

/* initialize graphics mode */

initgraph(&gdriver, &gmode, "");

/* read result of initialization */

errorcode = graphresult();

if (errorcode != grOk) /* an error occurred */

printf("Graphics error: %s\n", grapherrormsg(errorcode));

printf("Press any key to halt:");

getch();

exit(1); /* return with error code */

/* draw a line */

line(0, 0, getmaxx(), getmaxy());

/* clean up */

getch();

closegraph();

return 0;

Program to draw a circle #


/*Program to draw a circle*/
#include <graphics.h>

#include <stdlib.h>

#include <stdio.h>

#include <conio.h>

int main()

/* request auto detection */

Int x,y;

int gdriver = DETECT, gmode, errorcode;

/* initialize graphics mode */

initgraph(&gdriver, &gmode, "");

/* read result of initialization */

errorcode = graphresult();

if (errorcode != grOk) /* an error occurred */

printf("Graphics error: %s\n", grapherrormsg(errorcode));

printf("Press any key to halt:");

getch();

exit(1); /* return with error code */

/* draw a line */

circle(x,y,100);

/* clean up */

getch();

closegraph();

return 0;

A program to draw concentric circles #


#include <graphics.h>

int main()

int gd = DETECT, gm;

int x = 320, y = 240, radius;

initgraph(&gd, &gm, "");


for ( radius = 25; radius <= 125 ; radius = radius + 20)

circle(x, y, radius);

getch();

closegraph();

return 0;

Program to draw an arc #


#include<graphics.h>

#include<conio.h>

int main()

int gd = DETECT, gm;

initgraph(&gd, &gm, "");

arc(100, 100, 0, 135, 50);

getch();

closegraph();

return 0;

Program to move a car #


#include <graphics.h>

#include <dos.h>

int main()

int i, j = 0, gd = DETECT, gm;

initgraph(&gd,&gm,"C:\\TC\\BGI");

settextstyle(DEFAULT_FONT,HORIZ_DIR,2);

outtextxy(25,240,"Press any key to view the moving car");

getch();
for( i = 0 ; i <= 420 ; i = i + 10, j++ )

rectangle(50+i,275,150+i,400);

rectangle(150+i,350,200+i,400);

circle(75+i,410,10);

circle(175+i,410,10);

setcolor(j);

delay(100);

if( i == 420 )

break;

if ( j == 15 )

j = 2;

cleardevice(); // clear screen

getch();

closegraph();

return 0;

You might also like