0% found this document useful (0 votes)
10 views

Programming in C (28!02!2017)

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

Programming in C (28!02!2017)

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

V.S.M College (Autonomous) Dept.

of Computer Science

UNIT-I
Introduction to Algorithms and Flowcharts
Algorithm: “A step-by-step description of how to arrive at a solution is called an algorithm”.
Algorithms are mainly used to achieve software re-use. An algorithm, a sequence of instructions
must possess the following characteristics:
 Be precise
 Be unambiguous
 Not even a single instruction must be repeated infinitely
 After the algorithm gets terminated, the desired result must be obtained.

Control structures used in algorithms:


An algorithm has a finite number of steps and some steps involve decision-making and
repetition.
1. Sequence: Sequence means that each step of the algorithm is executed in the specified order.

Example:
An algorithm to add two numbers is written in sequential order.
Step 1: Input the first number as A
Step 2: Input the second number as B
Step 3: Set sum= A + B
Step 4: Print sum
Step 5: End

2. Decision: Decision statements are used when the execution of a process depends on the
outcome of some condition. For example, if x = y, then print “EQUAL”. Hence, the general form
of the if construct can be given as:
if condition then process
A decision statement can also be stated in the following manner:
If condition
then process1
Else process2
An algorithm to check the equality of two numbers:
Step 1: Input the first number as A
Step 2: Input the second number as B
Step 3: if A = B
then print “Equal”
else
print “Not equal”
Step 4: End

1
V.S.M College (Autonomous) Dept. of Computer Science

3. Repetition: Repetition, which involves executing one or more steps for a number of times, can
be implemented using constructs such as the while, do while, and for loops. These loops execute
one or more steps until some condition is true.

An algorithm to print the first 10 natural numbers:


Step 1: [initialize] set I =1, N = 10
Step 2: Repeat steps 3 and 4 while I <= N
Step 3: Print I
Step 4: Set I = I + 1
Step 5: End

SOME MORE ALGORITHMS:

Example 1: Write an algorithm for interchanging/ swapping two values.

Solution:

Step 1: Input first number as A


Step 2: Input second number as B
Step 3: Set temp = A
Step 4: Set A = B
Step 5: Set B = temp
Step 6: Print A, B
Step 7: End
Example 2: Write an algorithm to find the larger of two numbers.
Solution:

Step 1: Input first number as A


Step 2: Input second number as B
Step 3: if A > B
then print A
else if A < B
then print B
else
print “The numbers are equal”
Step 4: End

2
V.S.M College (Autonomous) Dept. of Computer Science

Example 3: Write an algorithm to find whether a number is even or odd.


Solution:

Step 1: Input the number as A


Step 2: if A % 2 = 0
then print “Even”
else
print “Odd”
Step 3: End
Example 4: Write an algorithm to find the sum of first N natural numbers.
Solution:

Step 1: Input N
Step 2: set I =1, sum = 0
Step 3: Repeat step 4 while I <= N
Step 4: Set sum = sum + I
Set I = I + 1
Step 5: Print sum
Step 6: End

Example 5: Write an algorithm to print the grade obtained by a student using the following
rules:
Marks Grade
Above 75 O
60 - 75 A
50 - 60 B
40 - 50 C
Less than 40 D
Solution:
Step 1: Enter the marks obtained as M
Step 2: if M> 75
then print “0”

Step 3: if M >= 60 and M < 75


then print “A”
step 4: if M >= 50 and M < 60

3
V.S.M College (Autonomous) Dept. of Computer Science

then print “B”


step 5: if M >= 40 and M <50
then print “C”
else
print “D”
Step 6: End

4. Flowcharts: “A flow chart is a graphical or symbolic representation of a process”. When


designing a flowchart, each step in the process is depicted by a different symbol and is
associated with a short description.

Symbols of Flowchart:

 Start and end symbols are also known as the terminal symbols and are
represented as circles, ovals, or rounded rectangles. Terminal symbols are always
the first and the last symbols in a flow chart.
 Arrows depict the flow of control of the program. They illustrate the exact
sequence in which the instructions are executed.
 Generic processing step, also called as activity, is represented using a rectangle.
 Input / Output symbols are represented using a parallelogram and are used to
get inputs from the users or display the results to them.
 A conditional or decision symbol is represented using a diamond. It is basically
used to depict a Yes/No question or a True/False test.
 Labelled connectors are represented by an identifying label inside a circle and are
used in complex or multi sheet diagrams to substitute for arrows.

4.1 Significance of Flowcharts:

A flowchart is a diagrammatic representation that illustrates the sequence of steps that must be
performed to solve a problem. Once a flowchart is drawn, programmers can make users
understand the solution easily and clearly. A flow chart follows the top-down approach in solving
problems.

Advantages:
 Flowcharts are very good communication tools to explain the logic of a system to all
concerned. They help to analyze the problem in a more effective manner.
 They are also used for program documentation. They are even more helpful in the case of
complex programs. They can be used to debug programs that have error. They help the
programmers to easily detect, locate, and remove mistakes in the program in a
systematic manner.

Limitations:
 Drawing flowcharts is a laborious and time-consuming activity. Just imagine the effort
required to draw a flowchart of a program having 50,000 statements in it.
 Often, the flowchart of a complex program becomes complex and clumsy.
 There are no well-defined standards that limit the details that must be incorporated into
a flowchart.

5. Pseudo code:
4
V.S.M College (Autonomous) Dept. of Computer Science

Pseudo code is a form of structured English that describes algorithms. An ideal pseudo code
must be complete, describing the entire logic of the algorithm, so that it can be translated
straightway into a programming language.

5.1 Keywords used while writing Pseudo codes:

For looping and selection, the designer must include the keywords Do While … EndDo; Do Until
… EndDo; Case … EndCase; If … EndIf; Call … with (parameters); Call; Return …; Return; When,
and so on.
Parts of Pseudo codes:
 Consider the following part of a pseudo code:
IF condition THEN
Sequence 1
ELSE
Sequence 2
ENDIF

Here, the ELSE keyword and sequence 2 are optional. If the condition is true, sequence 1
performed, otherwise sequence 2 is performed.

Example:
IF age >= 18 THEN
Display Eligible to vote
ELSE
Display Not Eligible
ENDIF
 The WHILE construct specifies a loop that tests a condition at the top. The loop is entered
only if the condition is true. After each iteration, the condition will be tested, and the
loop will continue as long as the condition is true. The beginning and end of the loop are
indicated by the keywords WHILE and ENDWHILE.

The general form is:


WHILE condition
Sequence
ENDWHILE
Example:
WHILE i < 10
Print i
Increment i
ENDWHILE

5
V.S.M College (Autonomous) Dept. of Computer Science

 A CASE construct indicates a multi-way branch based on conditions that are mutually
exclusive. The Pseudo code must include keywords such as CASE, Of, OTHERS, and
ENDCASE.
The general form is:
CASE expression OF
Condition 1: sequence 1
Condition 2: sequence 1
...
Condition n: sequence 1
OTHERS:
default sequence
ENDCASE
Here, the keyword OTHERS is optional and specifies the default sequence.
Example:
CASE day OF
0: print Sunday
1: print Monday
2: print Tuesday
3: print Wednesday
4: print Thursday
5: print Friday
6: print Saturday
ENDCASE
The REPEAT construct is similar to the WHILE loop, except that the test is performed at the end
of the loop. The keywords used are REPEAT and UNTIL.
The general form is:
REPEAT
Sequence
UNTIL condition
Here, sequence will be performed at least once as the test is performed after it is
executed. After each iteration, the condition is evaluated, and the loop repeats if the
condition is false.
 The FOR loop is used for iterating a sequence for a specific number of times. The
keywords used are FOR and ENDFOR.
The general form is:
FOR iteration bounds
Sequence
ENDFOR

6
V.S.M College (Autonomous) Dept. of Computer Science

Example:
FOR each student in the class
Add 10 as bonus marks
ENDFOR
1. Write a pseudo code for calculating the price of a product after adding sales tax to its original
price.
Solution:
1. Read the price of the product
2. Read the sales tax rate
3. Calculate sales tax = price of the item x sales tax rate
4. Calculate total price = price of the product + sales tax
5. Print total price
6. End
Variables: price of the product, sales tax rate, sales tax, total price.
2. Write a pseudo code to calculate the weekly wages of an employee. The pay depends on
wages per hour and the number of hours worked. Moreover, if the employee has worked for
more than 30 hours, then he or she gets twice the wages per hour, for every extra hour that he or
she has worked.
Solution:
1. Read hours worked
2. Read wages per hour
3. Set overtime charges to 0
4. Set overtime hrs to 0
5. IF hours worked > 30 then
a. Calculate overtime hrs = hours worked – 30
b. Calculate overtime charges = overtime hrs x (2 x wages per hour)
c. Set hours worked = hours worked – overtime hrs
ENDIF
6. Calculate salary = (hours worked x wages per hour) + overtime charges
7. Display salary
8. End
Variables: hours worked, wages per hour, overtime charges, overtime hrs, salary

*****

7
V.S.M College (Autonomous) Dept. of Computer Science

Programming Languages
Programming Languages:
A programming language is a language specifically designed to express computations that can be
performed by a computer. Programming languages are used to create programs that control the
behavior of a system, to express algorithms, or as mode of human communication.

Programming languages have a vocabulary of syntax and semantics for instructing a


computer to perform specific tasks. The term programming language refers to high level languages
such as BASIC (Beginners All-purpose Symbolic Instruction Code), C, C++, COBOL (Common Business
Oriented Language), FORTRAN (FORmula TRANslator), Ada, and Pascal and so on.
Generations of Programming Languages:
There are five generations of programming languages include machine language, assembly
language, high-level language, very high-level language and fifth generation language that include
artificial intelligence.
First Generation: Machine Language
Machine Language was used to program the first stored program computer systems. This is the
lowest level of programming language and is the only language that a computer understands. All
the commands and data values are expressed using 0’s and 1’s, corresponding to the off and on
electrical states in a computer.

In the 1950s, each computer had its own native language, and programmers had primitive
systems for combining numbers to represent instructions such as add and subtract. In machine
language, all instructions, memory locations, numbers and characters are represented in strings of
0s and 1s.

Advantages and disadvantages of Machine language:

Advantages disadvantages

 Code can be directly executed by the  Code is difficult to write.


computer.  Code is difficult to understand by other
 Execution is fast and efficient. people.
 Programs can be written to efficiently  Code is difficult to maintain.
utilize memory.  There is more possibility for errors to
creep in.
 It is difficult to detect and correct
errors.
 Code is machine dependent and thus
non-portable.

8
V.S.M College (Autonomous) Dept. of Computer Science

Second Generation: Assembly Language

Second-generation programming languages comprise the assembly languages. Assembly languages


are symbolic programming languages that use symbolic notations to represent machine language
instructions. Assembly language developed in the mid-1950s, it is used symbolic codes, also known
as mnemonic codes.

Example of these codes include ADD for add, CMP for compare, and MUL for multiply.
Assembly language programs consist of a series of individual statements or instructions to instruct
the computer what to do. Basically, an assembly language statement consists of label, an operation
code, and one or more operands.

Assembler: Computers can execute only codes written in machine language, a special program,
called the assembler, is required to convert the code written in assembly language into an
equivalent code in machine language, which contains only 0s and 1s.

Advantages and disadvantages of Assembly language:

Advantages disadvantages

 It is easy to understand.  Code is machine dependent and thus


 It is easier to write programs in non-portable.
assembly language than in machine  Programmers must have a good
language. knowledge of the hardware and
 It is easy to detect and correct errors. internal architecture of the CPU.
 It is easy to modify.  The code cannot be directly executed
 It is less prone to errors. by the computer.

Third Generation: High-level Language

The Third-generation was introduced to make the languages more programmers friendly. The
Third-generation languages spurred the great increase in data processing that occurred in the
1960s and 1970s. In general, a statement written in a high-level programming language will expand
into several machine language instructions.

Some high-level languages were specifically designed to serve a specific purpose, whereas
other languages were flexible and considered to be general purpose. Most programmers to use
general-purpose high-level languages such as BASIC, FORTRAN, PASCAL, COBOL, C++ or Java to
write the code for their applications . Again, a translator is needed to translate the instructions
written in a high-level language into the computer-executable machine language. Such translators
are commonly known as compilers and interpreters.

Compiler: A Compiler is a special type of program that transforms the source code written in a
programming language into machine language, which uses only digits-0 and 1. The resultant code in
0s and 1s is known as the object code. It is used to create an executable code.

9
V.S.M College (Autonomous) Dept. of Computer Science

If the source code contains errors, then the compiler will not be able to do its intended task.
Errors that limit the compiler in understanding a program are called syntax errors. The work of a
compiler is only to translate the human readable source code into a computer-executable machine
code.

Interpreter: The interpreter executes instructions written in a high-level language. Basically, a


program written in a high-level language can be executed in any of the ways-by compiling the
program or by passing the program through an interpreter.

Linker: A program is divided into various modules as it is to code, edit, debug, test, document, and
maintain them. Once the modules are coded and tested, the object files of all the modules are
combined together to form the final executable file. A linker, also called a link editor or binder, is a
program that combines the object modules to form an executable program.

Loader: A loader is a special type of program that copies programs from a storage device to the
main memory, where they can be executed.

Advantages and disadvantages of Third Generation

Advantages disadvantages

 The code is machine independent.  Code may not be optimized.


 It is easy to learn and use the language.  The code is less efficient.
 There are few errors.  It is difficult to write a code that
 It is easy to document and understand controls the CPU, memory, and
the code. registers.
 It is easy to maintain the code.
 It is easy to detect and correct errors.

Fourth Generation: Very High-level Languages

A Fourth Generation language is the query language, which allows a user to request information
from a database with precisely worded English-like sentences. A query language is used as a
database user interface and hides the specific details of the database from the user. For example,
when working with Structured Query Language (SQL), the programmer follow some rules of syntax
and logic.
Fifth-generation Programming language

Fifth-generation Programming languages (5GLs) are centered on solving problems using the
constraints given to a program rather than using an algorithm written by a programmer. These
languages are widely used in artificial intelligence research. A Fifth generation language is contains
visual tools to help develop a program. Typical examples of 5GLs include Prolog, OPS5, Mercury,
and Visual Basic.

10
V.S.M College (Autonomous) Dept. of Computer Science

Fifth Generation Programming languages are designed to make the computer solve a given
problem without the programmer. While working with a 4GL, programmers have to write a specific
code to do a work, but with a 5GL, they only have to worry about what problems need to be solved
and what conditions need to be met. 5GLs were generally built upon LISP, many originating on the
LISP machine, such as ICAD.

Some Popular High-Level Languages


BASIC: BASIC (Beginner’s All-purpose Symbolic Instruction Code) is a general-purpose, high-level
programming language developed by John G. Kemeny and Thomas E. Kurtz in 1964.

FORTRAN: FORTRAN (Formulas Translation) is one of the oldest general purpose programming
languages. It was developed in 1957 at IBM by a team of programmers led by John Backus.
FORTRAN is especially suited to high-performance numeric, scientific, statistical, and engineering
computing and is extensively used in areas such as weather prediction, finite element analysis,
computational physics, computational chemistry and fluid dynamic. It is also used in programming
video games, air traffic control systems, payroll calculations, military applications, factory
automation.

PASCAL: Pascal, which was named after the mathematician Blaise Pascal, is a procedural
programming language developed in the late 1960s by Niklaus Wirth. It is a small and efficient
language specifically designed to encourage good programming practices using structured
programming and data structuring.

C: C is a high-level general-purpose programming language that was developed in the 1970’s by


Dennis Ritche at Bell Labs. It was designed for system programming, C is a powerful and flexible
language that can be used for a wide range of applications varying from business programs to
engineering.

Features of C-Language

 It is easy to understand.
 Codes written in C are easy to maintain.
 Programs written in C are easily portable.
 It supports procedures and modularization of programs.

C++: C++ is an object oriented programming language developed by Bjarne Stroustrup starting in
1979 at Bell Labs. C++ is a superset of the C language. C++ is a superset of the C language. C++
supports all features of C and also includes other new features such as classes, objects,
polymorphism, inheritance, data abstraction, encapsulation, single-line comments using two
forward slashes, and strong type checking.

Java: Java is a general-purpose, object-oriented programming language released by sun


Microsystems in 1995. Though the syntax and semantics of Java is similar to C++ . Programs written
in Java are robust, secure, and reliable. Java was the first language to bring animation and

11
V.S.M College (Autonomous) Dept. of Computer Science

interactivity to Internet-based applications. Java programs follow the write once, run anywhere
concept. Programmers have to write a code only once and the same code can be executed on any
platform without any modification. Java source code files having a .java extension are compiled into
a byte code file having a .class extension, which can then be executed by a java interpreter.

LISP: LISP, an acronym for list processing, is one of the oldest programming languages used by
programmers all over the world. It was developed by John McCarthy in 1959. LISP is a functional
programming language in which all computations are accomplished by applying functions to
arguments. The main advantage of using LISP is that even complex functions can be easily written
and understood by others.

Structured Programming (Modular programming): Structured programming (sometimes


known as modular programming) is a subset of procedural programming that enforces a logical
structure on the program being written to make it more efficient and easier to understand and
modify. Certain languages such as Ada, Pascal, and dBASE are designed with features that
encourage or enforce a logical program structure.

Structured programming frequently employs a top-down design model, in which developers


map out the overall program structure into separate subsections. A defined function or set of
similar functions is coded in a separate module or sub module, which means that code can be
loaded into memory more efficiently and that modules can be reused in other programs. After a
module has been tested individually, it is then integrated with other modules into the overall
program structure. Program flow follows a simple hierarchical model that employs looping
constructs such as "for," "repeat," and "while." Use of the "Go To" statement is discouraged.

Almost any language can use structured programming techniques to avoid common pitfalls of
unstructured languages. Unstructured programming must rely upon the discipline of the developer
to avoid structural problems, and as a consequence may result in poorly organized programs. Most
modern procedural languages include features that encourage structured programming. Object-
oriented programming (OOP) can be thought of as a type of structured programming, uses
structured programming techniques for program flow, and adds more structure for data to the
model.
Modular programming
Modular programming (also called "top-down design" and "stepwise refinement") is a
software design technique that emphasizes separating the functionality of a program into
independent, interchangeable modules, such that each contains everything necessary to execute
only one aspect of the desired functionality. Conceptually, modules represent a separation of
concerns, and improve maintainability by enforcing logical boundaries between components.
Modules are typically incorporated into the program through interfaces. A module interface
expresses the elements that are provided and required by the module. The elements defined in the
interface are detectable by other modules. The implementation contains the working code that
corresponds to the elements declared in the interface.

*****
12
V.S.M College (Autonomous) Dept. of Computer Science

Introduction to C
THE STRUCTURE OF C PROGRAM WITH AN EXAMPLE PROGRAM .
Basic structure of C program:
Structure of C program is defined by set of rules called protocols (syntax), to be followed by
programmer while writing C program. All C programs are having sections/parts which are mentioned
below.
1. Documentation section
2. Link/Include Section and Macro Definition Section
3. Global declaration section
4. Function prototype declaration / function Definition section
5. Main function
5.1. Local Declaration part
5.2. Executable statements part
6. User defined function definition section
Description for each section of a C program:
S.No Sections Description
In this section, It describes the purpose of the program, comments
about the program, creation or modified date, author name etc.,In this
Documentation section section, the characters or words or anything which are given between
1
(Optional) “/*” and “*/”, won’t be considered by C compiler for compilation
process. These will be ignored by C compiler during compilation.
Example : /* comment line1 comment line2 comment 3 */
This is a preprocessor directive section Pre-defined and user-defined
header files are included in this section. Header files are required to
execute a C program
2 Link or Include Section
Example: #include<stdio.h> .
The symbol # indicates preprocessor directive. The preprocessor
directive is a program, which gives the directions to the compiler
Macro Definition In this section, Macro identifiers are defined and values are set to
Section (Optional) these Macro identifiers.
Global memory locations for variables, constants, etc., are declared in
Global declaration
3 this section. These memory locations can be used by all functions
section (Optional)
within a program.
Function prototype Function prototype gives many information to the compiler about a
declaration/ Function function like return type, parameter names used inside the function.
4
definition section User can also define their own functions in this section which perform
(Optional) particular task as per the user requirement.
5 main( ) function section Every C program is started from main( ) function. the main( ) tells
that, the execution of any C program should begins from this function.
It contains two major sections(parts)
1. Local declaration part and
Lacal memory locations for variables, constants, etc., are declared
13
V.S.M College (Autonomous) Dept. of Computer Science

in this part. These memory locations can be used by the main( )


funtion only.
2. Executable statements part.
In this part of main() section, Input , Process and Output
statements are specified.
If funtion prototypes are specified before main(), Then the user can
User defined function
6 define their own functions after the main(). User-defined functin
section (Optional)
performs particular task as per the user requirement.

C LANGUAGE CHARACTER SET:


Every programming language has its own set of characters which are used to write the statements of
the program (source code). In C language also, a program is written by using a set of characters.
These characters are known as character set of C. The character set of C language is given below

1. Lowercase letters: a, b, c, …, z
2. Uppercase letters: A, B, C, ..., Z
3. Digits: 0, 1, 2, ..., 9
4. Special characters: +, -, /, =, (, ), [, ], {, }, <, >, ', ", !, @, #, $, %, \, /, ;
5. White Spaces: blank space, back space, new line, tab etc.

Special Characters:

Symbol Meaning Symbol Meaning


~ Tilde = Equal to sign
! Exclamation mark { Left brace
# Number sign(Hash) } Right brace
$ Dollar sign [ Left bracket
% Percent sign ] Right bracket
^ Caret : Colon
& Ampersand " Quotation mark
* Asterisk ; Semicolon
( Lest parenthesis < Opening angle bracket
) Right parenthesis > Closing angle bracket
_ Underscore ? Question mark
+ Plus sign , Comma
| Vertical bar . Period
\ Backslash / Slash
` Apostrophe
- Minus sign

14
V.S.M College (Autonomous) Dept. of Computer Science

EXPLAIN TOKENS IN C LANGUAGE.

C TOKENS: . C tokens are the basic buildings blocks in C language which are constructed together
to write a C program. Each and every smallest individual unit in a C program is known as C tokens.
C tokens are of six types. They are,
1. Keywords (eg: int, while, float ),
2. Identifiers Variables (eg: main, total, avg PI),
3. Constants (eg: 10, 20),
4. Strings (eg: “total”, “hello”),
5. Special symbols (eg: ( ), {}),
6. Operators (eg: +, /,-,*)

1. Keywords (Reserved words) in C language:


Keywords are pre-defined words in a C language. Each keyword is meant to perform a specific
function or task in a C program. Since keywords are referred names for compiler, they can’t be used
as identifier name.
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. Identifiers in C language:
Definition: An Identifier is a name , which identifies a memory location, function, file, pointer etc.,.
Variables, functions and arrays are examples for identifiers. Example: int totalmarks; here,
totalmarks is an identifier(name) given to integer variable.

Rules for constructing identifier name in C:


1. First character should be an alphabet or underscore( _ ).
2. Except First character, Succeeding characters might be alphabet ,or digits (or both).
3. Punctuation, special characters and white(blank) space are not allowed except
underscore( _ ).
4. Identifiers should not be keywords.
5. The length of identifiers is up to 31 characters in ANSI C compiler.

15
V.S.M College (Autonomous) Dept. of Computer Science

Variables in C language:
Definition: A variable is an identifier and it is a named memory location. A variable contains a
value. The value can be changed during execution of the program. A variable name should satisfy
the rules of identifiers. Variable names must be given in lower-case letters for readability feature.
Declaring & initializing C variable:
 Variables should be declared in the C program before to use.
 Variable initialization means assigning a value to the variable at the time of declaration.
Type Syntax Example
int x, y, z ;
Variable declaration data_type variable_name ;
char flat, ch ;
int x = 50 , y = 30 ;
Variable initialization data_type variable_name = value;
char flag = ‘x’, ch=’l’;
Example: int totalmarks ; where, totalmarks is a variable name given to integer variable.

3. Constants in C language:
Definition: A constant is an identifier and it is a named memory location. A constant contains a
fixed value. The value cannot be changed during execution of the program. A constant name should
satisfy the rules of identifiers. Constant names must be given in upper-case letters for readability
feature.
Syntax: const datatype constant_identifier_name = value;
Example: const float PI = 3.142;
1. Numeric Constants
i. Integer Constants
ii. Real Constants
2. Character Constants
i. Single Character Constants
ii. String Constants
3. Backslash Character Constants
1. Integer Constants:
An integers constant refers to a sequence of digits. There are three types of integers namely
decimal integers(Base 10), octal integer(Base 8) and hexadecimal integer(Base 16).
Example values : 125, -562 , 0 , 9635 , +776
Example : const int MAX_MARKS = 1000;
Embedded space, commas, and non-digit characters are not permitted between digits. Below
examples are illegal numbers.
Illegal Examples : 15 750 (space) 20,000(comma) $6325(dollar).
2. Real Constants :
A real constant must have at least one digit including fraction part or exponent. It must have a
decimal point. It could be either positive or negative. If no sign precedes an real constant, it is
assumed to be positive. No commas or blanks are allowed within a real constant. Example
values : 10.25 , -20.25
Example : const float PI = 3.142;

16
V.S.M College (Autonomous) Dept. of Computer Science

3. Single Character Constants:


A single character constant is a single alphabet, or a single digit or a single special symbol
and enclosed within single quotes (‘ ’). A character may be an alphabet, digit, any one white
space symbol ,or any one special symbol. The maximum length of a character constant is one
character.
Example : const char GRADE = ‘A’;
4. String Constants:
String constant contains one or more characters and they are enclosed within double quotes
(“ ”). A characters may be an alphabet, digits, white space symbols , or/and special symbols.
Example : const char *MESSAGE = “ Welcome to 2015 ” ;
5. Backslash Character Constants(Escape Sequence Characters):
There are some characters which have special meaning in C language. They should be
preceded by backslash( \ ) symbol to make use of special function of them.
Given below is the list of special characters and their purpose.
Backslash Backslash Meaning
Meaning
_character _character
\b Backspace \’ Single quote
\f Form feed (used in printing only) \\ Backslash
\n New line ( cursor go to next line) \v Vertical tab
\r Carriage return \a Alert or bell (audible bell)
\t Horizontal tab \? Question mark
NULL character
\” Double quote \0 (Zero)
( end of the string)

Example program using const keyword in C:


#include <stdio.h>
#include <conio.h>
main( )
{
clrscr( );
const int MAX_MARKS = 1000; /*integer constant*/
const float PI = 3.142; /*Real constant*/
const char GRADE = 'A'; /*character constant*/
const char *MESSAGE = "Welcome"; /*string constant*/
const char BACKSLASH = '\?'; /* Backslash character Constant */
printf("value of MAX_MARKS : %d \n", MAX_MARKS);
printf("value of PI : %.3f \n", PI );
printf("value of GRADE : %c \n", GRADE );
printf("value of MESSAGE : %s \n", MESSAGE);
printf("value of BACKSLASH: %c \n", BACKSLASH);
getch( );
}

17
V.S.M College (Autonomous) Dept. of Computer Science

Output: value of MAX_MARKS : 1000


value of PI : 3.142
value of GRADE : A
value of MESSAGE : Welcome
value of BACKSLASH : ?

How to use constants in a C program?


We can define constants in a C program in the following ways.
1. By using const keyword
2. By using #define preprocessor directive
Example program using #define pre-processor directive in C:
#include <stdio.h>
#include <conio.h>
#define MAX_MARKS 1000 /*integer constant*/
#define PI 3.142 /*Real constant*/
#define GRADE 'A' /*character constant*/
#define MESSAGE "Welcome" /*string constant*/
#define BACKSLASH '\?' /* Backslash character Constant */
main( )
{
clrscr( );
printf("value of MAX_MARKS : %d \n", MAX_MARKS);
printf("value of PI : %.3f \n", PI );
printf("value of GRADE : %c \n", GRADE );
printf("value of MESSAGE : %s \n", MESSAGE);
printf("value of BACKSLASH: %c \n", BACKSLASH);
}

Output:
value of MAX_MARKS : 1000
value of PI : 3.142
value of GRADE : A
value of MESSAGE : Welcome
value of BACKSLASH : ?

EXPLAIN DATA TYPES IN C LANGUAGE


C has a concept of 'data types' which are used to define a variable before its use. The
definition of a variable will assign storage for the variable and define the type of data that will be
held in the location. The value of a variable can be changed any time.

There are four Basic data types in C language. They are,


18
V.S.M College (Autonomous) Dept. of Computer Science

S.no Types Data Types


1 Basic / intrinsic/ built-in/ predefined/ primitive data types char, int, float, double
2 Derived data type enum, pointer, array, function
3 User defined data types structure, union
4 Void data type void

C has the following basic built-in data types.


 int
 float
 double
 char

int - data type: The keyword int is used to define integer variables.
For Example:
int Count;
Count = 5;

float - data type : The keyword float is used to define floating point variables.
For Example:
float Miles;
Miles = 5.6;

double - data type


The keyword double is used to define BIG floating point variables. It reserves twice the storage for
the number. On Personal Computers, this is likely to be 8 bytes.
For Example:
double Atoms;
Atoms = 2500000;

char - data type


The keyword char defines character data type variable.
For Example:
char Letter;
Letter = 'x';
MODIFIERS IN DATA TYPES
The data types explained above have the following modifiers.
 short
 long
 signed
 unsigned
Data Type Bytes Range
------------------------------------------------------------------------------------------------
19
V.S.M College (Autonomous) Dept. of Computer Science

short int 2 -32,768 to +32,767 (32kb)


unsigned short int 2 0 to +65,535 (64Kb)
int 2 -32,768 to +32,767 (32kb)
unsigned int 2 0 to +65,535 (64Kb)
long int 4 -2,147,483,648 to +2,147,483,647 ( 2Gb)
signed char 1 -128 to +127
unsigned char 1 0 to +255

Floating- point Datatypes

Type Storage size Value range Precision

float 4 bytes 3.4 E-38 to 3.4E+38 6 decimal places

double 8 bytes 1.7E-308 to 1.7E+308 15 decimal places

long double 10 bytes 3.4E-4932 to 1.1E+4932 19 decimal places

Here is an example to check size of memory taken by various data types.


main()
{
printf("sizeof(char) == %d\n", sizeof(char));
printf("sizeof(short) == %d\n", sizeof(short));
printf("sizeof(int) == %d\n", sizeof(int));
printf("sizeof(long) == %d\n", sizeof(long));
printf("sizeof(float) == %d\n", sizeof(float));
printf("sizeof(double) == %d\n", sizeof(double));
printf("sizeof(long double) == %d\n", sizeof(long double));
printf("sizeof(long long) == %d\n", sizeof(long long));
}
Unsigned advantage: When you declare a variable as unsinged it cann´t contain negative values.
The advantage with declaring a variable as unsigned is that it can store larger values than signed
values.

Control Strings or Format strings:


Control
String Description
Character

int as a signed decimal number. ' %d ' and ' %i ' are synonymous for output, but
%d ,% i they are different, when used with scanf() for input (where using %i will interpret
a number as hexadecimal if it's preceded by 0x , and octal if it's preceded by 0.)

%u It prints decimal unsigned int .

20
V.S.M College (Autonomous) Dept. of Computer Science

double value in normal (fixed-point) notation. ' f ' and ' F ' only differs in how the
%f , % F strings for an infinite number or NaN are printed (' inf ', ' infinity ' and ' nan ' for ' f ',
' INF ', ' INFINITY ' and ' NAN ' for ' F ').

%e , % E double value in standard form ([ - ]d.ddd e [ + / - ]ddd). An E conversion uses the


letter E (rather than e ) to introduce the exponent. The exponent always contains at
least two digits; if the value is zero, the exponent is 00 . In Windows, the exponent
contains three digits by default, e.g. 1.5e002 , but this can be altered by Microsoft-
specific _set_output_format function.

Double value in either normal or exponential notation, whichever is more


%g ,% G appropriate for its magnitude. ' g ' uses lower-case letters, ' G ' uses upper-case
letters.
unsigned int as a hexadecimal number(Base 16). ' x ' uses lower-case letters and
%x , % X
' X ' uses upper-case.

%o unsigned int in octal(Base 8).


%s It specifies null-terminated string. NULL means ‘\0’
%c It represents char (character).
.

21
V.S.M College (Autonomous) Dept. of Computer Science

22
V.S.M College (Autonomous) Dept. of Computer Science

Input / Output (I/O) Statements(Functions) in C language


C has number of Input and Output Functions to read the data from input devices and display
the results on the screen. The Input and Output functions can be classified into two types.

1. Formatted Functions

2. Unformatted Functions.

Various functions of these categories are shown as follows.

Input and Output Functions

Formatted Functions Unformatted Functions

Input Output Input Output

scanf() printf() getch() putch()


sscanf() sprinf() getche() putchar()

getchar() puts()

gets()

1. Formatted Functions

The formatted Input/Output Functions read and write all types of data values. They require
format/control string (conversion symbol such as %d,%c) to identify the data type. Control strings
can be used for both reading and writing of all data values.

Formatted Input Function: scanf()

The scanf() statement reads all types of data values from input device such as keyboard. It is used for
runtime assignment of values to variables through keyboard by using address of variables. Syntax of
scanf() function:

scanf( “control or format string” , &variable1, &variable2,…& variableN);

Example: scanf(“%c%d%f”,&a, &b, &c);

In the above statement, character type data, integer type data and float type data are stored into the
variables a,b,and c respectively.

The scanf() statement requires &(ampersand) operator to specify address of a variable. This operator
is called address operator. & operator specifies address of a variable, in which the input data value
can be stored.
23
V.S.M College (Autonomous) Dept. of Computer Science

Example: Write a program to read character type data, integer type data and float type data
from keyboard and display them.

/* read character type data, integer type data and float type data from keyboard and display them.*/

#include<stdio.h>

#include<conio.h>

void main()

char a; int b; float c;

clrscr();

printf( “Enter character type data, integer type data and float type data from keyboard \n”);

scanf(“%c%d%f”, &a,&b,&c);

printf( “ The Input values are \n” );

printf(“ Character Data =%c\n” , a);

printf(“ Integer Data =%d\n” , b);

printf(“ Float(Real) Data =%f\n” , c);

getch();

Output:

Enter character type data, integer type data and float type data from keyboard

A 50 10.55

The Input values are

Character Data = A

Integer Data = 50

Float(real)Data= 10.550000

The above program reads character type data, integer type data and float type data from keyboard
and displayed them

24
V.S.M College (Autonomous) Dept. of Computer Science

Formatted Output Function : printf()

The printf() statement displays all types of data values along with messages on output device such as
screen of the monitor. It requires control string and variables to display data.

Syntax of printf() function:

printf( “[messagewith] control or format string” , variable1, variable2,… variableN);

Example:

printf(“ The values are %c %d %f” , a, b, c);

In the above statement, character type data, integer type data and float type data of three variables
a,b,and c are displayed respectively.

Example: Write a program to display “Welcome” message.

/* Display Welcome Message*/

#include<stdio.h>

#include<conio.h>

void main()

clrscr();

printf(“Welcome”);

getch();

Output:

Welcome

The above program displayed “Welcome” message.

Unformatted I/O Functions:

The Unformatted input and output functions only work with the character data type. They do
not require control string or conversion symbol to identify data type because they work with
character data type.

C language has two types Unformatted I/O functions.

1. Character I/O functions

2. String I/O functions


25
V.S.M College (Autonomous) Dept. of Computer Science

1. Character I/O Functions:

a) getch() function:

The getch() function reads (accept) only one character from standard input device such as
keyboard . But, the input character, which is given, is not displayed on screen.

Syntax: char getch(); Here, the return data type is optional.

b) getche() function: (here ‘e’ indicates echo ):

The getche() function reads (accept) only one character from standard input device such as
keyboard and the input character, which is given, is displayed on screen.

Syntax: char getche(); Here, the return data type is optional.

Example: Write a program to show the effect of getche() and getch()

/* To show the effect of getche() and getch() */

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“Enter any two characters: ”);
getche();
getch();
}
Output: Enter any two characters: A
Explanation: In the above program, even though two characters are entered, The user can see only
one character on screen. The second character is accepted from keyboard but displayed on the
console(screen). i.e., The getche() function reads (accept) only one character from standard input
device such as keyboard and the input character, which is given, is displayed on screen. The
getch() function reads (accept) only one character from standard input device such as keyboard .
But, the input character, which is given, is not displayed on screen.

c) getchar() function:

The getchar() function reads character type data from standard input device, But, It accepts one

character at a time till the user presses the Enter Key.

Syntax: char getchar(); It returns one character at a time.

Example:

char ch;
ch= getchar();

26
V.S.M College (Autonomous) Dept. of Computer Science

In the above statement, the getchar() function accepts one character along with Enter Key . But,

The character is only stored into character type variable ch and Enter Key is not stored.

d) putchar() function:

The putchar() function displays(prints) one character at a time on screen , which is taken from the

standard input device.

Syntax: putchar(char); Here, char indicates character type variable(argument ) to be displayed.

e) putch() function:

The putch() function displays(prints) one character , which is taken from the standard input device.
Syntax: putch(char); Here, char indicates character type variable(argument ) to be displayed.

Example: Write a program to read and display the character using getch() and putch().

/* to read and display the character using getch() and putch()*/

#include<stdio.h>
#include<conio.h>
main()
{
char ch;
clrscr();
printf(“Enter any character or any Key: ”);
ch=getch( );
putch( ch );
}
Output:
Enter any character or any Key: A
In the above program, The character ‘A’ is accepted by getch() function and displayed by putch()
function.

2. String I/O functions:

a) gets() function

The gets() function is used to accept (read) any string including white spaces from standard input
device until Enter Key is pressed.

Syntax :

gets( char* st ); here, the variable st is a string(array of characters ) type variable.

27
V.S.M College (Autonomous) Dept. of Computer Science

Example: Write a program to read and display a student name.

/* read and display student name*/


#include<stdio.h>
#include<conio.h>
void main()
{
char * sname;
clrscr();
printf(“Enter name of a student:\n”);
gets(sname);
printf(“ The student name is -- %s”, sname);
getch();
}
Output:
Enter name of a student:
Sri Guru [Press Enter Key]
The student name is --Sri Guru
In the above program, gets() function reads a string with white spaces from standard input device
and stores that string into a character type pointer variable sname. The variable sname contained
“Sri Guru” words including white space.

b) puts() function:

The puts() function prints the string or character type array. It includes a new line(\n) character at the
end of the line automatically. These is no need to specify new line (\n) character at the end of the
string.

Syntax: puts(char * st); here, the variable st is a string(array of characters ) type variable.

Write a program to read and display a student name.

/* read and display student name*/


#include<stdio.h>
#include<conio.h>
void main()
{
char * sname ;
clrscr( ) ;
puts(“Enter name of a student:”);
gets(sname) ;
puts(“ The student name is” );
puts(sname);
getch();
}

28
V.S.M College (Autonomous) Dept. of Computer Science

Output:
Enter name of a student:
Sri Guru [Press Enter Key]
The student name is
Sri Guru
In the above program, The puts() function displayed messages and the data of variable sname.

======================================================================

EXPLAIN OPERATORS IN C LANGUAGE.

 The symbols which are used to perform logical, relational and mathematical operations in a C
program are called C operators.
 These C operators join individual constants values (Literals) and operands to form
expressions.

TYPES OF ‘C‘OPERATORS:

C language offers many types of operators. They are,


1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment/decrement operators
6. Conditional operators (ternary operators)
7. Bit wise operators
8. Special operators

1. Arithmetic Operators in C:
Arithmetic operators form (create) Arithmetic expressions. Arithmetic operators are used to perform
mathematical calculations like addition, subtraction, multiplication, division and modulo-division in
C programs.
S.no Arithmetic Operators Operation Example A=10 B =3
1 + Addition A+B 10+3 = 13
2 - Subtraction A-B 10-3 = 7
3 * multiplication A*B 10*3 = 30
4 / Division A/B 10/3 = 3 (quotient)
5 % Modulo-division A%B 10%3 = 1 (remainder)

Example program for C arithmetic operators:


In this example program, two values “40″ and “20″ are used to perform arithmetic operations
such as addition, subtraction, multiplication, division, modulus and output is displayed for each
operation.

29
V.S.M College (Autonomous) Dept. of Computer Science

main()
{
int a=10,b=3, add , sub , mul, div , mod;
clrscr();
add = a+b;
sub = a-b; OUTPUT:
mul = a*b;
div = a/b; Addition of a, b is : 13
mod = a%b; Subtraction of a, b is : 7
printf("Addition of a, b is : %d\n", add); Multiplication of a, b is : 30
printf("Subtraction of a, b is : %d\n", sub); Division of a, b is : 3
printf("Multiplication of a, b is : %d\n", mul); Modulo-division of a, b is:1
printf("Division of a, b is : %d\n", div);
printf("Modulo-division of a,b is:%d\n", mod);
}
2. Relational operators in C:
Relational operators form(create) relational expressions. Relational operators are used to find the
relation between two operands. i.e. to compare the values of two operands in a C program.
S.no Operators Description Example x=10, y=5
1 > x is greater than y x > y yes
2 < x is less than y x < y no
3 >= x is greater than or equal to y x >= y yes
4 <= x is less than or equal to y x <= y no
5 == x is equal to y x == y no
6 != x is not equal to y x != y yes

Example program for relational operators in C:


In this program, relational operator (==) is used to compare 2 values whether they are equal are not.
If both values are equal, output is displayed as ” values are equal”. Else, output is displayed as
“values are not equal”. Note: double equal sign (==)should be used to compare 2 values. We should
not single equal sign (=).

#include <stdio.h>
main()
{
int m=40,n=20;
if (m == n)
printf("m and n are equal");
else
30
V.S.M College (Autonomous) Dept. of Computer Science

printf("m and n are not equal");


}
} Output : m and n are not equal

3. Logical operators in C:
Logical operators construct logical expressions. These operators are used to perform logical
operations on the given expressions. There are 3 logical operators in C language. They are, logical
AND (&&), logical OR (||) and logical NOT (!).

S.no Operators Name Example Description


logical
1 && (x>5)&&(y<5) It returns true when both conditions are true
AND
2 || logical OR (x>=10)||(y>=10) It returns true when at-least one of the condition is true
It reverses the state of the operand “((x>5) && (y<5))”
logical
3 ! !((x>5)&&(y<5)) If “((x>5) && (y<5))” is true, logical NOT operator
NOT
makes it false

Example program for logical operators in C:


#include <stdio.h>
main()
{
int m=40 , n=20;
int o=20 , p=30;
if (m>n && m !=0)
{
printf("&& Operator : Both conditions are true\n");
}

if (o>p || p!=20)
{
printf("|| Operator : Only one condition is true\n");
}
if (!(m>n && m !=0))
{
printf("! Operator : Both conditions are true\n");
}
else
{
printf("! Operator : Both conditions are true.But, status is inverted as false\n");
}
}
Output:
&& Operator: Both conditions are true
|| Operator: Only one condition is true
! Operator: Both conditions are true. But, status is inverted as false
31
V.S.M College (Autonomous) Dept. of Computer Science

 In this program, operators (&&, || and !) are used to perform logical operations on the given
expressions.
 && operator – “if clause” becomes true only when both conditions (m>n and m! =0) is true.
Else, it becomes false.
 || Operator – “if clause” becomes true when any one of the condition (o>p || p!=20) is true. It
becomes false when none of the condition is true.
 ! Operator – It is used to reverses the state of the operand.
 If the conditions (m>n && m!=0) is true, true (1) is returned. This value is inverted by “!”
operator.
 So, “! (m>n and m! =0)” returns false (0).
4. Assignment operators in C:
In C programs, values for the variables are assigned using assignment operators. For
example, if the value “10″ is to be assigned for the variable “sum”, it can be assigned as “sum = 10;”
Other assignment operators in C language are given below.

Operators Example Explanation


Simple assignment operator = sum=10 10 is assigned to variable sum
+= sum+=10 This_is_same_as_ sum=sum+10…
-= sum -=10 This is same as sum = sum-10
Compound assignment operators *= sum*=10 This is same as sum = sum*10
(short-hand Assignment /+ sum/=10 This is same as sum = sum/10
operators) %= sum%=10 This is same as sum = sum%10
&= sum&=10 This is same as sum = sum&10
^= sum^=10 This is same as sum = sum^10

Example program for C assignment operators:

o In this program, values from 0 – 9 are summed up and total “45″ is displayed as
output.
o Assignment operators such as “=” and “+=” are used in this program to assign the
values and to sum up the values.

# include <stdio.h>
main()
{
int total=0 ,i;
for(i=0 ; i<10 ; i++) Output:
{ Total = 45
total += i;
}
printf("Total = %d", total);
}
32
V.S.M College (Autonomous) Dept. of Computer Science

5. Increment/decrement Operators
Increment operators are used to increase the value of the variable by one and decrement operators are
used to decrease the value of the variable by one in C programs. Syntax:

Increment operator : ++var_name; (or) var_name++;


Decrement operator : - - var_name; (or) var_name - -;

Example:
Increment operator : ++ i ; i ++ ;
Decrement operator: --i; i--;
Example program for increment operators in C:
In this program, value of “i” is incremented one by one from 1 up to 9 using “i++” operator and
output is displayed as “1 2 3 4 5 6 7 8 9”.
//Example for increment operators
main()
{
int i=1;
while(i<10)
{ Output: 123456789
printf("%d ",i);
i++;
}
}
Example program for decrement operators in C:
In this program, value of “i” is decremented one by one from 20 up to 11 using “i–” operator and
output is displayed as “20 19 18 17 16 15 14 13 12 11”.

//Example for decrement operators


#include <stdio.h>
int main()
{
int i=20;
while(i>10)
{
printf("%d ",i);
i--;
}

33
V.S.M College (Autonomous) Dept. of Computer Science

Output: 20 19 18 17 16 15 14 13 12 11

Difference between pre/post increment & decrement operators in C:


Below table will explain the difference between pre/post increment and decrement operators in C.
S.no Operator type Operator Description
j=++i Value of i is incremented by a value one(1) before assigning it to
1 Pre increment
variable j.
j=++ Value of i is incremented by a value one(1) after assigning it to
2 Post-increment
variable j.
j=– –i Value of i is decremented by a value one(1) before assigning it to
3 Pre decrement
variable j.
j=i– – Value of i is decremented by a value one(1) after assigning it to
4 Post_decrement
variable j.
Example program for pre – increment operators in C:
//Example for increment operators
#include <stdio.h>
main()
{
int i=0;
while(++i < 5 )
{
printf("%d ",i);
}
}
Output: 1234

 Step 1: In above program, value of “i” is incremented from 0 to 1 using pre-increment


operator.
 Step 2: This incremented value “1″ is compared with 5 in while expression.
 Step 3: Then, this incremented value “1″ is assigned to the variable “i”.
 Above 3 steps are continued until while expression becomes false and output is “1 2 3
4″.
Example program for post – increment operators in C:
#include <stdio.h>
main()
{
int i=0;
while(i++ < 5 )
{
printf("%d ",i); Output: 1 2 3 4 5
}

34
V.S.M College (Autonomous) Dept. of Computer Science

 Step 1: In this program, value of i ”0″ is compared with 5 in while expression.


 Step 2: Then, value of “i” is incremented from 0 to 1 using post-increment operator.
 Step 3: Then, this incremented value “1″ is assigned to the variable “i”.
 Above 3 steps are continued until while expression becomes false and output is “1 2 3
4 5″.

Example program for pre - decrement operators in C:


#include <stdio.h>
main()
{
int i=10;
while(--i > 5 )
{
printf("%d ",i);
}
}
9876
Output:
 Step 1: In above program, value of “i” is decremented from 10 to 9 using pre-
decrement operator.
 Step 2: This decremented value “9″ is compared with 5 in while expression.
 Step 3: Then, this decremented value “9″ is assigned to the variable “i”.
 Above 3 steps are continued until while expression becomes false and output is “9 8 7
6″.
Example program for post - decrement operators in C:
#include <stdio.h>
int main()
{
int i=10;
while(i-- > 5 )
{
printf("%d ",i); Output: 9 8 7 6 5
}
}
 Step 1: In this program, value of i ”10″ is compared with 5 in while expression.
 Step 2: Then, value of “i” is decremented from 10 to 9 using post-decrement operator.
 Step 3: Then, this decremented value “9″ is assigned to the variable “i”.
 Above 3 steps are continued until while expression becomes false and output is “9 8
7 6 5″.

6. Conditional or Ternary operators in C:

Conditional operators return one value if condition is true and returns another value is condition is
false. This operator is also called as ternary operator.
35
V.S.M College (Autonomous) Dept. of Computer Science

Syntax : (Condition ? true_value : false_value);


Example: (A > 100 ? 0 : 1);
In above example, if A is greater than 100, 0 is returned otherwise, 1 is returned. This is equal to if
else conditional statements.
Example program for conditional/ternary operators in C:
#include <stdio.h>
main()
{
int a , b , big;
printf(“ Enter two numbers :”);
scanf(“%d%d” , &a , &b);
big = a>b ? a : b ;
printf("The Biggest number is %d” , big);

Output:
Enter two numbers : 10 5
The Biggest number is 10.
7. Bit wise operators in C:
In C language, These operators are used to perform bit operations. Decimal values are
converted into binary values which are the sequence of bits and bit wise operators work on these bits.
Bit wise operators are & (bitwise AND), | (bitwise OR), ^ (bitwise Exclusive-OR), ~ (bitwise one’s
complement ), << (left shift) and >> (right shift).
Truth table for bit wise operation Bit wise operators
x y x|y x&y x^y Operator_symbol Operator_name
0 0 0 0 0 & Bitwise_AND
0 1 1 0 1 |
Bitwise OR

1 0 1 0 1 ^
Bitwise XOR

1 1 1 1 0 ~ Bitwise_NOT
(one’s complement)
<<
Left Shift

>>
Right Shift

Consider x=40 and y=80. Binary form of these values are given below.

x = 00101000
y= 01010000

All bit wise operations for x and y are given below.

36
V.S.M College (Autonomous) Dept. of Computer Science

x & y = 00000000 (binary) = 0 (decimal)


x | y = 01111000 (binary) = 120 (decimal)
x ^ y = 01111000 (binary) = 120 (decimal)

x << 1 = 01010000 (binary) = 80 (decimal)


x >> 1 = 00010100 (binary) = 20 (decimal)
~x =1111111111111111111111111111111111111111111111111111111111010111
.. ..= -41 (decimal)
Note:Bit wise NOT :
Value of 40 in binary is
0000000000000000000000000000000000000000000000000000000000101000.
So, all 0′s are converted into 1′s in bit wise NOT operation.
 Bit wise left shift and right shift : In left shift operation “x << 1 “, 1 means that the bits will
be left shifted by one place. If we use it as “x << 2 “, then, it means that the bits will be left
shifted by 2 places.
Example program for bit wise operators in C:

o In this example program, bit wise operations are performed as shown above and
output is displayed in decimal format.

#include <stdio.h>
main()
{
int m=40 , n=80,AND_opr, OR_opr, XOR_opr, NOT_opr ; Output:
AND_opr = (m & n);
OR_opr = (m | n); AND_opr value = 0
XOR_opr = (m ^ n); OR_opr value = 120
NOT_opr = (~m); XOR_opr value = 120
printf("AND_opr value = %d\n",AND_opr );
NOT_opr value = -41
printf("OR_opr value = %d\n",OR_opr );
left_shift value = 80
printf("XOR_opr value = %d\n",XOR_opr );
right_shift value = 20
printf("NOT_opr value = %d\n",NOT_opr );
printf("left_shift value = %d\n", m << 1);
printf("right_shift value = %d\n", m >> 1);
}

8. Special operators in C: In C –Language has some special operators. They are sizeof() ,comma(,)
& and * ( uses in pointers).
EXPLAIN TYPE CONVERSION AND TYPE CASTING IN C LANGUAGE:
Type Conversions:
Type conversion is a way to convert a variable from one data type to another data type. For
example, if you want to store a long value into a simple integer then you can type cast long to int
There are two kinds of type conversion we need to talk about: automatic or implicit type
conversion and explicit type conversion.

37
V.S.M College (Autonomous) Dept. of Computer Science

Implicit Type Conversion


The operators we have looked at can deal with different types. For example we can apply the
addition operator + to an int as well as a double. It is important to understand how operators deal
with different types that appear in the same expression. There are rules in C that govern how
operators convert different types, to evaluate the results of expressions.
For example, when a floating-point number is assigned to an integer value in C, the decimal
portion of the number gets truncated. On the other hand, when an integer value is assigned to a
floating-point variable, the decimal is assumed as .0.
This sort of implicit or automatic conversion can produce nasty bugs that are difficult to find,
especially for example when performing multiplication or division using mixed types, e.g. integer
and floating-point values. Here is some example code illustrating some of these effects:
#include <stdio.h>
main()
{
int a = 2;
double b = 3.5;
double c = a * b;
double d = a / b;
int e = a * b;
int f = a / b;
printf("a=%d, b=%.3f, c=%.3f, d=%.3f, e=%d, f=%d\n",
a, b, c, d, e, f);
return 0;
}
Explicit Type Conversion (Type Casting):
There is a mechanism in C to perform type casting, that is to force an expression to be
converted to a particular type of our choosing. We surround the desired type in brackets and place
that just before the expression to be forced as follows:
Syntax: (type_name) expression
Look at the following example code:
main()
{
int a = 2;
int b = 3;
printf("a / b = %.3f\n", a/b);
printf("a / b = %.3f\n", (double) a/b);
}

UNIT - II
EXPLAIN CONTROL STATEMENTS IN C LANGUAGE

Control statement: A Control statement is a C language statement, which controls the order of the
execution of the program. The control statements can be classified into two types.

38
V.S.M College (Autonomous) Dept. of Computer Science

1. Branching control statements


2. Looping control statements.
The types of control statements can be shown as follows.
Control statements

Branching Looping

Conditional Unconditional Entry controlled Exit controlled


Branching (Decision) Branching loops loop

1. if statement 1. goto 1. for loop 1. do.. while loop

a) Simple if 2. break 2. while loop

b) if.. else 3. continue

c) else.. if ladder 4. return

d) nested if statement

2. switch.. case statement

Conditional Branching Statements (Decision-Making statements):

Conditional Branching statement contains a decision-making condition to check whether a


particular condition is satisfied or not. C language supports the following Decision-making
statements. 1. if statement

2. switch.. case statement

1. if statement :
The if statement tests a condition and executes its corresponding block of statements. It has
the following sub types:
a) Simple if statement

b) if.. else statement (Two –way statement)

c) else.. if ladder statement (Multi –way statement)

d) nested if statement (Two –way statement)

a) Simple if statement: C language uses the keyword if to test a condition. In simple if statement, if
the condition is true , then one or more statements of true block can be executed and the control of
execution can be transferred to next statement of if statement. If the condition is false, then the
control of execution is directly transferred to next statement of if statement without execution of true
block.
Syntax of simple if statement:
39
V.S.M College (Autonomous) Dept. of Computer Science

The syntax of simple if statement is as follows:


if ( test-condition)
{
statement block;
}
Statement-x;
Flow-chart of simple if statement
Entry

True
test
condition

Statement-block
False

Statement-x

Next Statement
Example: Write a program to display a given number, if the input number is less than 10 only.
/* Display a given number, if the input number is less than 10 only.*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n; clrscr();
printf(“Enter a Number: ”);
scanf(“%d”, &n);
if(n<10)
{
printf( “The input number is %d\n”,n);
}
printf(“End of the Program”) ;
getch();
}
Output:
Enter a Number: 5[Press Enter Key]
The input number is 5
End of the Program
b) if..else statement(Two –way statement): In if..else statement, if the condition is true , then one or
more statements of true block can be executed and the control of execution can be transferred to

40
V.S.M College (Autonomous) Dept. of Computer Science

next statement of if statement. If the condition is false, then one or more statements of false block
can be executed and then the control of execution is directly transferred to next statement of if
statement.

Syntax of if..else statement: The syntax of if..else statement is as follows:


if( test condition)
{
True- block statements;
}
else
{
False- block statements;
}
Statement-x;

Flow-chart of if else statement


Entry

True False
test
condition

True-block statements False-block statements

Statement-x

Next Statement
Example: Write a program to find biggest number of two input numbers.
/* Display biggest number of two input numbers.*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(“Enter Two Numbers: ”);
scanf(“%d%d”, &a,&b);
if(a>b)
{
printf( “The Biggest number is %d\n”,a);
}
41
V.S.M College (Autonomous) Dept. of Computer Science

else
{
printf( “The Biggest number is %d\n”,b);
}
printf(“End of the Program”) ;
getch();
}
Output:1
Enter Two Numbers: 10 5 [Press Enter Key]
The Biggest number is 10
End of the Program
c) else..if ladder statement(Multi –way statement):
In else..if ladder statement, two or more conditions and corresponding blocks can be
presented. At First, condition_1 can be tested. if condition_1 is true , then one or more statements of
true block_1 can be executed and the control of execution is directly transferred to next statement of
if statement. If condition_1 is false, then condition_2 can be tested. If condition_2 is true, then one or
more statements of true block_2 can be executed and then the control of execution is directly
transferred to next statement of if statement, and so on. If all conditions are false, then the final else
block can be executed and then the control of execution is transferred to next statement of if
statement.
Syntax of else..if ladder statement:
The syntax of else..if ladder statement is as follows:
if( condition 1)
{
statement-1;
}
else if (condition 2)
{
Statement-2;
}
………………………
………………………
else if (condition N)
{
Statement- N;
}
else
{
Default-statement;
}
statement-x;
Flow-chart of else..if ladder statement

Entry

True False

Condition 1

42
V.S.M College (Autonomous) Dept. of Computer Science

True False
Condition 2
Statement-1

False
Statement-2 True
Condition N

Statement-N Default
Statement

Statement-x

Example: Write a program to find biggest number of three input numbers.


/* Display biggest number of three input numbers.*/
#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c;
clrscr();
printf(“Enter Three Numbers: ”);
scanf(“%d%d%d”, &a,&b,&c);
if( (a>b) &&(a>c) )
{
printf( “The Biggest number is %d \n”,a);
}
else if ( b>c)
{
printf( “The Biggest number is %d \n”,b);
}
else
{
printf( “The Biggest number is %d \n”,c);
}
printf(“End of the Program”) ;
getch(); }
Output: 1
Enter Three Numbers: 100 50 10[Press Enter Key]
The Biggest number is 100
End of the Program
d) Nested if statement (Two –way statement): The if statement with in if statement is called
nested if statement .In nested if statement, At First, condition_1 can be tested. if condition_1 is
true , then condition_2 will be tested. If condition_2 is true, then the statement-1 will be executed
43
V.S.M College (Autonomous) Dept. of Computer Science

and the control of execution is directly transferred to next statement of if statement. Otherwise else
block statements i.e., statement-2 will be executed. If condition_1 is false, then one or more
statements of statement-3 can be executed and then the control of execution is directly transferred to
next statement, and so on. The syntax of nested if statement is as follows:
if( test-condition1)
{
if(test-condition2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
}
Statement-x;
Flow-chart of nested if statement

Entry

False True
test condition1

True
False test condition2

Statement-3 Statement-2 Statement-1

Statement-x

Example: Write a program toNext


findstatement
biggest number of three input numbers using nested if
statement
/* Display biggest number out of three input numbers.*/
#include<stdio.h>
#include<conio.h>
void main()
44
V.S.M College (Autonomous) Dept. of Computer Science

{
int a, b, c, big; clrscr( );
printf(“Enter Three Numbers: ”);
scanf(“%d%d%d”, &a,&b,&c);
if (a>b)
if(a>c)
big=a;
else
big=c;
else
if ( b>c)
big=b;
else
big=c;
printf( “The Biggest number is %d\n”,big);
getch();
}
Output: 1
Enter Three Numbers: 100 50 10[Press Enter Key]
The Biggest number is 100
End of the Program
In the above output of a Program, The input values are 100 , 50 and 10. The value 100 is
greater than the value 50 and the value 100 is greater than the value 10 . So, the condition_1 and
condition_2 are true. Therefore, the true block_2 is executed and the output is displayed as:
The Biggest number is 100
2. switch..case statement(Multi –way statement): The switch..case statement is a multi-way
branching statement. In the program, if there is a possibility to make a choice from a number of
options , then this switch..case selection structure is useful. The switch statement requires only one
argument of any ordinal data type, which is checked with a number of case options.
The switch statement evaluate expression and looks for its value among the case constants. If
the value matches with case constant , then the corresponding case option is executed. If not, the
default option is executed. Here, switch,case, and default are keywords. Every case statement
terminates with : symbol. The break statement is used to exit execution from the current case option
and control of execution can be transferred to next statement of switch ..case statement.The
switch..case statement is used to write menu driven program.

The Syntax of switch..case statement is as follows:


switch( variable or expression)
{
case constant1 : statement Block-1;
break;

case constant2 : statement Block-2;


break;
45
V.S.M College (Autonomous) Dept. of Computer Science

………………………………………
………………………………………
case constantN : statement Block-N;
break;
default : Default-statements;
}
next statement;
Note: the default option can be specified anywhere within the switch case statement with break
statement. Switch..case statement is used to write menu driven programs. It is an alternative
statement for else..if ladder.
Flow chart of the switch.. case statement
Entry

Switch
expression

Expression=
value 1
Statement Block-1

Expression=
value 2
Statement Block-2

Expression=
value N
Statement Block-N

(No match) default


Default statements

Statement-X

Example: Write a program to display week day name by giving day number.
/* Display week day name by giving day number.*/
#include<stdio.h>
#include<conio.h>
main()
{
int dayno;

46
V.S.M College (Autonomous) Dept. of Computer Science

clrscr();
printf(“ Enter Week day Number between 1 and 7: ”);
scanf(“%d”, & dayno);
switch(dayno)
{
case 1 : printf(“SUN DAY”);
break;
case 2 : printf(“MON DAY”);
break;
.
case 7 : printf(“SATUR DAY”);
break;
default : printf(“ Invalid Input . Please enter 1 to 7 values only”);
}
printf(“ End of the program”);
getch();
}
Output: 1
Enter Week day Number between 1 and 7: 2 [Press Enter Key]
MON DAY
In the above output, case 2 options is selected
Output: 2
Enter Week day Number between 1 and 7: 12 [Press Enter Key]
Invalid Input . Please enter 1 to 7 values only
EXPLAIN UNCONDITIONAL CONTROL STATEMENTS
C language provides the following unconditional control statements.
1. goto statement
2. continue statement
3. break statement
1. goto statement:
The goto statement does not require any condition. This statement passes execution control to
any statement in the program. The user can define goto statement either forward goto or backward
goto as follows:
goto label;
Statement;
Statement;
label: statement;
where, the label name must start with any character. The label indicates a position where the
execution control is to be transferred.
Example: Write a program to detect the number is even or odd.
/* Detect the number is even or odd.*/
#include<stdio.h>
#include<conio.h>
main()
47
V.S.M College (Autonomous) Dept. of Computer Science

{
int n;
clrscr();
printf(“Enter a number: ”);
scanf(“%d” , &n);
if(n%2==0)
goto evenlabel;
else
goto oddlabel;
evenlabel :
printf(“%d is Even Number”,n);
return;
oddlabel :
printf(“%d is Odd Number”,n);
getch();
}
Output:
Enter a number: 10 [Press Enter Key]
10 is Even Number
In the above program, the input value is 10. the value 10 is even number. Therefore, the goto with
evenlabel is executed.

2. continue statement:
The continue statement is used for continuing the next iteration of loop. When it occurs in the
loop, it does not terminate the loop, but it skips the statements after this statement in a loop and
execution control goto next iteration.
Syntax of continue statement is as follows:
continue;
In while and do..while loops, continue causes the execution control to go directly to the test-
condition and then to execute the next iteration process. In case of for loop, the increment/decrement
section of the loop is executed before going to next iteration.

Example: /* Write a program to display 1 to 10 numbers, if the number is 5 then do not display
the number 5. */
#include<stdio.h>
#include<conio.h>

main()
{
int i;
clrscr();
printf(“ The Numbers from 1 to 10 except 5\n”);
for(i=1; i<=10; i++)
{
if (i==5)
48
V.S.M College (Autonomous) Dept. of Computer Science

continue;
printf(“ %4d”,i);
}
printf(“\nEnd of program”);
getch();
}
Output:
The Numbers from 1 to 10 except 5
1 2 3 4 6 7 8 9 10
End of program
In the above program, if the value of i variable is 5 then continue statement is executed and the value
of i variable is incremented. The statements after the continue statement in the loop are skipped.
3. break statement:
The break statement is used to terminate case option in switch case statement and to
terminate the loop prematurely, and execution control goto next statement of the loop.
Syntax of break statement is as follows:
break;
Example:/* Write a program to display 1 to 10 numbers, if the number is 5 then do not display
remaining numbers including 5. */
#include<stdio.h>
#include<conio.h>
main()
{
int i; clrscr();
printf(“ The Numbers from 1 to 10 \n”);
for(i=1; i<=10; i++)
{
if (i==5)
break;
printf(“ %4d” , i);
}
printf(“\nEnd of program”); getch();
}
Output:
The Numbers from 1 to 10 except 5 to 10
1 2 3 4
End of program
Explain Looping Control Statements.
Control structures are the statements which controls the overall execution of any program. Iterative
Statements repeated execution of a particular set of instructions for a desired number of times.
These statements are generally called loops for their execution in nature.
A loop basically consists of a loop variable which is used for the completion of any iterative
process. A loop consists of three main statements:-

49
V.S.M College (Autonomous) Dept. of Computer Science

(1) Initialization (2) Condition (3) Increment/Decrement


Initialization is used to start any loop i.e. it gives some initial value to the loop variable. Which
defines that, from which value, the loop has to get start. Condition is provided to give the final value
to the loop variable so that how many times the loop has to get executed. For reaching the loop
variable from initial value to the final value, there should be some sort of incrementation or
decrementation. It is provided by the third component statement of loop. The value of the loop
variable can be incremented or decremented in each iteration of the loop.
In any loop, if the incrementation/decrementation or the final value is not provided, then the loop
becomes infinite. If the initialization is not done, then the garbage value of the loop variable becomes
its initial value.Basically, the type of looping statements depends on the condition checking mode.
Condition checking can be made in two ways as: Before loop and after loop. So, there are two types of
looping statements.
 Entry controlled loop
 Exit controlled loop
1. Entry controlled loop:
In such type of loop, the test condition is checked first before the loop is executed.
Some common examples of these looping statements are:
 for loop
 while loop
2. Exit controlled loop:
In such type of loop, the loop is executed first and then condition is checked after block of statements
are executed. The loop is executed at least one time compulsorily.
Some common example of this looping statement is:
 do-while loop
In C language, the iterative statements (loops) can be implemented in the three loops and they are as
follows:
1. while loop :
In while loop, initialization, condition and incrementation/decrementation is done in the three
different statements within a loop. This loop is count as well as event loop. In case of while loop, the
body of the loop will consist of more than one statements because each time one statement will be of
incrementation/decrementation. The loop statements will be executed till the condition is true. First,
the test-condition is evaluated. If the test-condition is true, then the body of the loop is executed.
When the condition is false, then the execution control will be transferred to next-statement after the
loop. In while loop, the condition can be tested for n+1 times and the iterations are ‘n’ times.

Syntax of while loop is as follows:


initialization;
while(test-condition)
{
Body of loop;

50
V.S.M College (Autonomous) Dept. of Computer Science

incrementation/decrementation;
}
next-statement after loop;
Flow chart of the while loop

Initialization
Initialization

False
False
test
test
condition
condition
Exit
Exit

True
True

Body
Bodyofof
loop
loop

Increment/decrement
Increment/decrement

Example: Write a program to display numbers from 1 to 10


/* Display Numbers from 1 to 10 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i; /* the variable i is a loop variable*/
clrscr();
printf(“ The numbers from 1 to 10 are:”);
i=1; /* initialization*/
while(i<=10) /* condition */
{
printf(“%5d”, i);
i++; /* incrementation */
}
printf(“ \nEnd of the Program”);
getch();
}
The first part initializes the loop variable. The loop variable controls and counts the number of times
a loop runs. In the example the loop variable is called i and is initialized to 1.
The second part of the while loop is the condition. A loop must satisfy the condition to keep running.
In the example the loop will run while i is less than or equal to 10 or in other words it will run 10
times. The third part is the loop variable incrementation/decrementation. In the example, i++ has
been used which is the same as saying i = i + 1. This is called as incrementation. Each time the loop
51
V.S.M College (Autonomous) Dept. of Computer Science

runs, the value of variable i is incremented by one(1). It is also possible to use i-- to subtract 1 from a
loop variable. In which case, it is called as decrementation.
2. do..while loop:
In do..while loop, initialization, condition and incrementation/decrementation is done in the
three different statements within a loop. This loop is count as well as event loop. In case of do..while
loop, the body of the loop will consist of more than one statements because each time one statement
will be of incrementation/decrementation. Hence the open and closed curly brackets are required.
The loop statements will be executed at least once without testing the condition and then the
test-condition can be evaluated at the bottom of the loop. If the test-condition is true, then the body
of the loop is executed as next iteration. When the condition is false, then the execution control will
be transferred to next-statement after the loop. In do..while loop, the condition can be tested for n
times and the iterations are also n times.
Syntax of do..while loop is as follows:
initialization;
do
{
Body of loop;
incrementation/decrementation;
}
while (test-condition);
Next-statement after loop;
Flow chart of the do..while loop

Initialization

Body of loop

Increment/decrement

False
test condition
Exit

True

In this loop the condition is checked at the end, and for this reason this loop will execute at least once
whether the condition may be satisfying and unsatisfying.
Example: Write a program to display numbers from 1 to 10
/* Display Numbers from 1 to 10 */
#include<stdio.h>
#include<conio.h>
main()

52
V.S.M College (Autonomous) Dept. of Computer Science

{
int i; /* the variable i is a loop variable*/
clrscr();
printf(“ The numbers from 1 to 10 are:”);
i=1; /* initialization*/
do
{
printf(“%5d”, i);
i++; /* incrementation */
}
while(i<=10); /* condition */
printf(“ \nEnd of the Program”);
getch();
}
The first part initializes the loop variable. The loop variable controls and counts the number of times
a loop runs. In the example, the loop variable is called i and is initialized to 1. The second part is the
loop variable incrementation/decrementation. In the example, i++ has been used which is the same as
saying i = i + 1. This is called as incrementation. Each time the loop runs, the value of variable i is
incremented by one(1). It is also possible to use i-- to subtract 1 from a loop variable.In which case,
it is called as decrementation. The third part of the do..while loop is the condition. A loop must
satisfy the condition to keep running. In the example the loop will run while i is less than or equal to
10 or in other words it will run 10 times.
3. for loop:
The for loop will perform its execution until the condition remains satisfied. If the body of
the loop consists of more than one statement then these statements are made compound by placing
the open and closed curly brackets { } around the body of the loop. For loop is a count loop. The
initialization condition and incrementation/decrementation may be done in the same statement. If the
condition is false at the first time itself, then for loop will not be executed at least once. When the
condition is false , then the execution control will be transferred to next-statement after the loop.
Syntax of for loop:
for (initialization; test-condition; incrementation/decrementation)
{
Body of loop;
}
next-statement after loop;

Flow chart of the for loop

53
V.S.M College (Autonomous) Dept. of Computer Science

Initialization

False
test condition
Exit

True

Body of loop

Increment/decrement

Example: Write a program to display numbers from 1 to 10


/* Display Numbers from 1 to 10 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i; /* the variable i is a loop variable*/
clrscr();
printf(“ The numbers from 1 to 10 are :”);
for(i=1;i<=10; i++)
{
printf(“%5d”, i);
}
printf(“ \nEnd of the Program”);
getch();
}
Output:
The numbers from 1 to 10 are: 1 2 3 4 5 6 7 8 9 10
End of the Program
 In loops, if there is more than one statement, then we have to put statements between curly
brackets { and }. A for loop is made up of three parts inside its brackets which are separated
by semi-colons. The first part initializes the loop variable. The loop variable controls and
counts the number of times a loop runs. In the example the loop variable is called i and is
initialized to 1.
 The second part of the for loop is the condition. A loop must satisfy the condition to keep
running. In the example the loop will run while i is less than or equal to 10 or in other words
it will run 10 times.

54
V.S.M College (Autonomous) Dept. of Computer Science

 The third part is the loop variable incrementation/decrementation. In the example, i++ has
been used which is the same as saying i = i + 1. This is called as incrementation. Each time
the loop runs, the value of variable i is incremented by one(1). It is also possible to use i-- to
subtract 1 from a loop variable.In which case, it is called as decrementation.
Additional features of for loop:
1. More than one variable can be initialized at a time in the for statement.
Example:
for( i=1 , p=1 ; i<=5 ; i++)
In the above statement, the initialization section has two parts: i=1 and p=1 separated by comma(,).
2. The increment/decrement section may also have more than one part.
Example:
for(i=1, j=1; i<=5; i++ , j++)
In the above statement, the increment/decrement section has two parts: i++ and j++ separated by
comma(,).
3. Both the initialization and increment/decrement sections are omitted in the for statement. If the
test-condition is not present, then the for statement setup an infinite loop. Such loops cab be broken
by using break and goto statements in the loop.
Example:
i=1;
for(; i<=5;)
{
printf( “%5d”,i);
i++;
}
--------------------------------------------------------------------------------------------------------
EXPLAIN NESTED FOR LOOPS:
A loop statement within a loop statement is called Nested loop. Nesting of loops are allowed in C
language. The combination of any loop can be nested. The nesting may continue up to any desired
level. Two loops can be nested as follows:
for(i=1; i<=5;i++) /* begin of Outer Loop */ Output:
{ 1 2 3 4 5
for(j=1;j<=5;j++) /* begin of Inner Loop */ 1 2 3 4 5
{ 1 2 3 4 5
printf(“ %5d”,j); 1 2 3 4 5
} /* end of Inner Loop */ 1 2 3 4 5
printf(“\n”);
} /* end of Outer Loop */

Explain Differences between break and continue statements:


 The break statement terminates the current loop and goto next statement of the loop
 The continue statement skip the current iteration of the loop and the next iteration of the loop
can be continued.

55
V.S.M College (Autonomous) Dept. of Computer Science

FUNCTIONS
Definition: A function is a self contained block of code that performs a particular task, when it is
called(invoked). The C language supports two types of functions.
1. Standard Library functions 2. User-Defined Functions
1. Standard Library functions: The Library functions are pre-defined set of functions. The
user can only the use the library functions but cannot change or modify them. Example:
printf(), scanf(), getch(), sqrt(), pow(), sin(), cos() etc.,
2. User-defined Functions: The functions, which are defined by the user / programmer
according to his/her requirements are called User-defined functions.
The user/programmer has full scope to implement his/her own logic in the function.

Example: display(), findSum(), findBig(), etc.,

Need of user-defined Functions (Advantages of functions):

There are times when certain type of operations is repeated at many points throughout the
program. Once a function is defined, the function can be called and used for any number of times
to perform the task repetitively.
The modular programming approach provides the following advantages:
1. It facilitates Top-Down modular programming. In top-down approach, the high level logic of
the overall problem is solved first, while the details of each low level function are addressed
later.
2. The length of the source program can be reduced by using functions at appropriate places.
3. It is very easy to locate and isolate a faulty function for further testing.
4. A function may be used by many other programs. i.e., reusability.
5. The productivity of programs can be increased.
In order to make use of user-defined functions, we need to establish three elements that are related to
functions.

1. Function declaration
2. Function definition
3. Function call
1. Function declaration: All functions in a C program must be declared, before they are invoked. A
function declaration is a function prototype, which consists of four parts:
a) Function return data type.
b) Function name
c) Parameter List(Argument List)
d) Terminating semicolon (;)
Syntax of function Declaration:
returndatatype functionname(parameter list);
For Example, int findBiggest(int a, int b); or findBiggest(int , int); The default return datatype
is int data type.

56
V.S.M College (Autonomous) Dept. of Computer Science

When a function does not take any arguments, and does not return any value ,then its prototype is
written as : void display(void);

2. Definition of Function: The function can be defined as follows:

Syntax: returndatatype functionName(arguments/parameters list)

{
Local declaration;
Executable statements;
return (value or variable or expression);
}
The first line: returndatatype functionName(arguments/parameters list) is known as the function
header and the statements within the opening and closing braces constitute the function body, which
is a compound statement.

Example:

int findBiggest( int x, int y)


{
int big;
if(x>y)
big=x;
else
big=y;
return(big);
}
In the above example, the name of the function is findBiggest(),. int a, int b are formal arguments,
the return data type of function is int ,i.e., It returns a value of integer type.

3. Function Call: A Function can be called by simply using the function name followed by a list of
actual arguments (parameters) enclosed in parentheses, if any.

Example:

void main()
{
int a,b,big;
clrscr();
printf(“Enter two numbers”);
scanf(“%d%d”, &a,&b);
big= findBiggest(a,b); /* Function call */
printf(“ The Biggest Number is %d”,big);
getch();
}

57
V.S.M College (Autonomous) Dept. of Computer Science

When the compiler encounters a function call, the execution control is transferred to the
findBiggest() function. This function is then executed line by line and a biggest value is returned,
when a return statement is encountered. This value is assigned to a variable big.

Calling Function: The function, which calls another function, is called as calling function . For
example, the main () function is a calling function.

Called function: The function, which is called by another function, is called as called function. For
example, the findBiggest() function is a called function.

Actual Arguments: The arguments of function call are called actual arguments. The arguments a
and b in function call are called actual arguments.

Formal arguments: The arguments of function definition are called formal arguments. The
arguments x and y in function definition are called formal arguments.

The actual and formal arguments should match in number of arguments, data types, and order of
arguments. The names of actual and formal arguments may not be equal. While the formal
arguments must be valid identifier(variable) names, The actual arguments may be variables, literals,
expressions.

return statement:

A function may or may not send back any value to the calling function. If it does, it is done
through the return statement. The return statement can take one of the following two forms:

1. return; or 2. return(value or expression or address);

The first return statement does not return any value; it acts much as closing brace (}) of the
function or program. When return statement is executed, the execution control is immediately passed
back to the calling function or end of the program. The second return statement with an
expression returns the value of the expression to the calling function.( i.e., from the function
definition to the function call). The return statement terminates the process of the program or It
returns the execution control to the calling function.
Categories of Functions:

A function 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 no arguments and return value.
4. Functions with arguments and return value.
1. Functions with no arguments and no return value: When a function has no arguments, it does
not receive any input data from the calling function. Similarly, when a function does not return a
value, the calling function does not receive any output data from the called function. That is, there is
no data transfer between the calling function and the called function. For Example:

58
V.S.M College (Autonomous) Dept. of Computer Science

/* Find Biggest number of two numbers */

#include<stdio.h>
void findBiggest() /* Function definition with no arguments and no return value */
{
int x,y, big;
printf(“Enter two numbers”);
scanf(“%d%d”, &x,&y);
if(x>y)
big=x;
else
big=y;
printf((“ The Biggest Number is %d”,big);
}
void main()
{
findBiggest(); /* Function call without arguments */
getch();
}
2. Functions with arguments and no return value: When a function has arguments, it does receive
any input data from the calling function. When a function does not return a value, the calling
function does not receive any output data from the called function. That is, the nature of data
communication between the calling function and the called function with arguments but no return
value.
/* Find Biggest number of two numbers */
#include<stdio.h>
#include<conio.h>
void findBiggest(int x , int y) /* Function definition with arguments but no return value */
{
int big;
if(x>y)
big=x;
else
big=y;
printf((“ The Biggest Number is %d”,big);
}
void main()
{
int a,b;
clrscr();
printf(“Enter two numbers”);
scanf(“%d%d”, &a,&b);
findBiggest(a,b); /* Function call with arguments */
getch();
}
59
V.S.M College (Autonomous) Dept. of Computer Science

Here, The actual and formal arguments should match in number of arguments, data types, and order
of arguments. The names of actual and formal arguments may not be equal. While the formal
arguments must be valid identifier (variable) names, The actual arguments may be variables, literals,
expressions. One way data communication from calling function to called function.
3. Functions with no arguments and return value: When a function has no arguments, it does not
receive any input data from the calling function. When a function does return a value, the calling
function does receive one output data from the called function. That is, the nature of data
communication between the calling function and the called function with only one return value. For
Example: /* Find Biggest number of two numbers */
#include<stdio.h>
#include<conio.h>
int findBiggest() /* Function definition with no arguments but one return value */
{
int x,y, big;
printf(“Enter two numbers”);
scanf(“%d%d”, &x,&y);
if(x>y)
big=x;
else
big=y;
return(big);
}
void main()
{
int big;
clrscr();
big =findBiggest(); /* Function call with no arguments and assign a return value */
printf(“ The Biggest Number is %d”, big);
getch();
}
Here one way data communication from called function to calling function by returning a value.
4. Functions with arguments and return value: When a function has arguments, it does receive
any input data from the calling function. When a function does return a value, the calling function
does receive one output data from the called function. That is, the nature of data communication
between the calling function and the called function with arguments and one return value.
For Example: /* Find Biggest number of two numbers */
#include<stdio.h>
#include<conio.h>
int findBiggest(int x, int y) /* Function definition with arguments and one return value */
{
int big;
if(x>y)
big=x;
else
big=y;
60
V.S.M College (Autonomous) Dept. of Computer Science

return(big);
}
void main()
{
int a,b, big;
clrscr();
printf(“Enter two numbers”);
scanf(“%d%d”, &a,&b);
big =findBiggest(a,b); /* Function call with arguments and assign a return value */
printf(“ The Biggest Number is %d”, big);
getch();
}
Here Two way data communication between calling function and called function by sending
arguments and by returning a value.
=========================================================
Explain Call-by-Value and Call-by-Reference.
C language provides two mechanisms to pass arguments (parameters) to a function.
1. Passing arguments by value (Call by Value)
2. Passing arguments by address (Call by Reference)
1. Passing arguments by value (Call by Value):
In C language, by default, Functions pass arguments (parameters) by value. Passing
arguments by Value means that, when a function call is made, only a copy of the values of actual
arguments of function call is passed into the formal arguments of called function. Whatever
modification is occurred on formal arguments inside the called function will have no effect on the
variables used in the actual arguments list in the calling function. The following example shows the
concept of passing arguments by value.
/* swap two numbers without using 3rd variable (temporary variable) */
#include<stdio.h>
#include<conio.h>
void swap( int a, int b)
{
a = a+b;
b = a-b;
a = a-b;
printf(“ In Function, After swap: a=%d, b=%d\n” , a , b);
}
void main()
{
int a , b;
clrscr();
printf(“Enter Two numbers”);
scanf(“%d%d”, &a, &b);
printf(“ In main, Before swap: a=%d, b=%d\n” , a , b);
swap(a,b);
printf(“ In main , After swap: a=%d, b=%d\n” , a , b);
getch();
}

61
V.S.M College (Autonomous) Dept. of Computer Science

Output:
Enter Two numbers 5 10
In main, Before swap: a=5, b=10
In Function, After swap: a=10, b=5
In main, After swap: a=5, b=10
In the above program, The values are swapped (interchanged) in function swap(), but, the
modification is not occurred on actual arguments of function call in the main() function.
2. Passing arguments by address (Call by Reference (address)): (or) Passing Pointers to
functions
In C language, Functions pass arguments by address also.. Passing arguments by address
means that , when a function call is made, only the addresses of actual arguments of function call
are passed into the formal arguments of called function. Whatever modification is occurred on
formal arguments inside the called function will have immediate effect on the variables used in the
actual arguments list in the calling function through their addresses. The mechanism of sending back
information through arguments is achieved by using address operator (&) and indirection operator
(*). The operator * is known as indirection operator because it gives an indirect reference to a
variable through its address. The following example shows the concept of passing arguments by
reference.
/* swap two numbers without using 3rd variable (temporary variable) */
#include<stdio.h>
#include<conio.h>
void swap( int *a, int *b)
{
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
printf(“ In Function, After swap: a=%d, b=%d\n” , *a , *b);
}
void main()
{
int a , b;
clrscr();
printf(“Enter Two numbers”);
scanf(“%d%d”, &a, &b);
printf(“ In main, Before swap: a=%d, b=%d\n” , a , b);
swap(&a , &b);
printf(“ In main , After swap: a=%d, b=%d\n” , a , b);
getch();
}
Output:
Enter Two numbers 5 10
In main, Before swap: a=5, b=10
In Function, After swap: a=10, b=5
In main, After swap: a=10, b=5

62
V.S.M College (Autonomous) Dept. of Computer Science

In the above program, The values are swapped (interchanged) in function swap() means that, , the
values of actual arguments of function call in the main() function are swapped through addresses
directly. The function can return multiple values with the help of call by reference mechanism. In the
above example, the two values are returned from called function to calling function the help of call
by reference mechanism.
Explain Nesting of Functions.
Nesting of Functions: C language permits nesting of functions freely. The main() calls findBiggest()
function. The findBiggest() function calls display() function and so on. The below example shows
nesting of functions:
/* Find Biggest number of two numbers */
#include<stdio.h>
#include<conio.h>
void display( int big)
{
printf(“ The Biggest Number is %d”, big);
}
void findBiggest(int x, int y) /* Function definition with arguments but no return value */
{
int big;
if(x>y)
big=x;
else
big=y;
display(big);
}
.void main()
{
int a , b , big;
clrscr();
printf(“Enter two numbers”);
scanf(“%d%d”, &a,&b);
findBiggest(a , b); /* Function call with arguments */
getch();
}
Note: Nesting does not means defining one function within another function. Nesting means one
function calls another function to perform a particular task.
========================================================================

63
V.S.M College (Autonomous) Dept. of Computer Science

Explain Scope Rules (or) Scope of Variables.

A scope in any programming is a region of the program where a defined variable can have its
existence and beyond that variable cannot be accessed. There are three places where variables can be
declared in C programming language:

1. Inside a function or a block which is called local variables,


2. Outside of all functions which is called global variables.
3. In the definition of function parameters which is called formal parameters.
Let us explain what are local and global variables and formal parameters.

Local Variables:

Variables that are declared inside a function or block are called local variables. They can be used
only by statements that are inside that function or block of code. Local variables are not known to
functions outside their own. Following is the example using local variables. Here all the variables a,
b and c are local to main() function.

#include <stdio.h>
main ()
{
/* local variable declaration */
int a, b;
int c;

/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}

Global Variables:

Global variables are defined outside of a function, usually on top of the program. The global
variables will hold their value throughout the lifetime of your program and they can be accessed
inside any of the functions defined for the program.

A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration. Following is the example using global and local
variables:

64
V.S.M College (Autonomous) Dept. of Computer Science

#include <stdio.h>
/* global variable declaration */
int g;
int main ()
{
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
}

A program can have same name for local and global variables but value of local variable inside a
function will take preference. Following is an example:

#include <stdio.h>
/* global variable declaration */
int g = 20;
void main ()
{
/* local variable declaration */
int g = 10;
printf ("value of g = %d\n", g);
}

When the above code is compiled and executed, it produces the following result:
Value of g = 10
Formal Parameters

Function parameters, formal parameters, are treated as local variables with-in that function and they
will take preference over the global variables. Following is an example:
#include <stdio.h>
/* global variable declaration */
int a = 20;
int main ()
{
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
printf ("value of a in main() = %d\n", a);

65
V.S.M College (Autonomous) Dept. of Computer Science

c = sum( a, b);
printf ("value of c in main() = %d\n", c);
}
/* function to add two integers */
int sum(int a, int b)
{
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}

When the above code is compiled and executed, it produces the following result:

value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30

Initializing Local and Global Variables:

When a local variable is defined, it is not initialized by the system, you must initialize it yourself.
Global variables are initialized automatically by the system when you define them as follows:
Data Type Initial Default Value

int 0

char '\0'

float 0

double 0

pointer NULL

It is a good programming practice to initialize variables properly otherwise, your program may
produce unexpected results because uninitialized variables will take some garbage value already
available at its memory location.

=======================================================================
Explain Storage Classes in C (Or) Explain the Scope, Visibility, And Lifetime of Variables.
Storage Classes in C (or) The Scope , Visibility , And Lifetime of Variables
In C language, all variables have a data type, and also have a storage class. The type of storage area
of a variable is called storage class. The following variable storage classes are most relevant to
functions:
1. automatic variables (auto)
66
V.S.M College (Autonomous) Dept. of Computer Science

2. external variables (extern)


3. static variables( static)
4. register variables (register)
1. automatic variables(auto):
Automatic variables are declared inside a function or inside a block, in which they are to be used.
They are created, when the function is called and they are destroyed when the function is exited,
hence, the name automatic. Automatic variables are local or internal variables. A variable declared
inside a function without storage class is an automatic by default.
For example:

#include<stdio.h>
#include<conio.h>
/* function declarations or prototypes */
void function1( );
void function2( );
main( )
{
int n=10;
clrscr( );
printf(“ In main( ), n= %d\n”, n);
function1( );
getch( );
}
void function1( )
{
int n=100;
printf (“ In function 1 , n= %d \n”,n);
function2( );
}
void function2( )
{
int n=1000;
printf (“ In function 2 , n= %d \n”,n);
}
OUTPUT:
In main( ), n=10
In function 1, n=100
In function 2, n=1000
In the above program, three memory locations are created in three functions.These three memory
locations are different.

67
V.S.M College (Autonomous) Dept. of Computer Science

2. External variables:

The variables that are both alive and active throughout the entire program are known as
external variables. They are also known as global variables. External variables are declared outside a
function. Global variables can be accessed by any function in the program. . An external variable
definition can appear in only one program. The extern variable can be accessed by current program
and other programs also.. For example:

#include<stdio.h>
#include<conio.h>
/* function declarations or prototypes */
void function1( );
void function2( );
int n=10; /* global variable */
main( )
{
clrscr( );
printf(“ In main( ), n= %d\n”, n);
function1( );
getch( );
}
void function1( )
{
printf (“ In function 1 , n= %d \n”,n);
function2( );
}
void function2( )
{
printf (“ In function 2 , n= %d \n”,n);
}
OUTPUT:
In main( ), n=10
In function 1, n=10
In function 2, n=10
In the above program, one global memory location is accessed by all three functions.
If local variables and global variables have the same name, the local variable will have high
precedence over the global one in the function where it is declared.

For example:
#include<stdio.h>
#include<conio.h>
/* function declarations or prototypes */
void function1( );
void function2( );
int n=10; /* global variable */
68
V.S.M College (Autonomous) Dept. of Computer Science

main( )
{
clrscr( );
printf(“ In main( ), output of global variable n= %d\n”, n);
function1( );
getch( );
}
void function1( )
{
int n=20;
printf (“ In function 1 , output of local variable n= %d \n”,n);
function2( );
}
void function2( )
{
printf (“ In function 2 , output of global variable n= %d \n”,n);
}

OUTPUT:
In main( ), output of global variable n=10
In function 1, output of local variable n=20
In function 2, output of global variable n=10
Note: if the variable is declared after a particular function, then the function cannot access that
variable. This problem can be solved by declaring the variable with the storage class extern
keyword. For example:
#include<stdio.h>
#include<conio.h>
/* function declarations or prototypes */
void function1( );
void function2( );
main( )
{
extern int n;
clrscr( );
printf(“ In main( ), output of global variable n= %d\n”, n);
function1( );
getch( );
}
void function1( )
{
extern int n;
printf (“ In function 1 , output of local variable n= %d \n”,n);
function2( );
}
void function2( )
{
extern int n;
printf (“ In function 2 , output of global variable n= %d \n”,n);
}
int n=10;
69
V.S.M College (Autonomous) Dept. of Computer Science

OUTPUT:
In main( ), output of global variable n=10
In function 1, output of global variable n=10
In function 2, output of global variable n=10
Note: The extern declaration does not allocate storage space for variables. The memory
location(storage space) of global variable can be shared by all extern variables in the program.
3. static variables:

The value of static variables persists until end of the program. A static variable is initialized
by zero only once, when the program is compiled. It is never initialized again. A static storage class
retains the value of a variable until end of the program. Static variables can be used to retain
values between function calls. For example, count the number of calls made to a function.
#include<stdio.h>
#include<conio.h>
void counting( )
{
static int count;
count++;
printf(“ Count of function call =%d\n” , count);
}
main( )
{
clrscr( );
counting();
counting();
counting();
getch( );
}
Output:
Count of function call =1
Count of function call =2
Count of function call =3
4. register variables:

We can tell the compiler that a variable should be kept in one the registers of the computer,
instead of keeping variables in the RAM memory. Since a register access is much faster than a
memory access, keeping the frequently accessed variables in the registers will lead to faster
execution of programs. This can be done by using register keyword as follows:

register int count;

Note: C will automatically convert register variables into non-register variables once the limit of
registers is reached. The register of processor should only be used for variables that require quick
access such as counters ( integer counting).

70
V.S.M College (Autonomous) Dept. of Computer Science

Scope: the scope of a variable determines over what region of the program, a variable is actually is
available for use.
Longevity: It refers to the period during which a variable retains a given value during execution of a
program.
Visibility: It refers to the accessibility of a variable from the memory.
Local variables (Internal): Local variables are those, which are declared with in a particular
function or within a block.
Global variables (External): External variables are declared outside of any function.
========================================================================

Explain Recursion with examples.

Definition: A recursive function is a function, which calls itself until a particular condition is
satisfied, or a function call to a second function which eventually calls the first function is known as
recursive function. Two conditions must be satisfied by any recursive function:

1. There must be a base (decision) criterion for stopping the process or computation. (escape
hatch).
2. Each time a function calls itself it must be closer in some sense to a solution (action
criterion)
If base (condition) criterion is not specified, then the recursive function will be executed till the stack
overflows.
Example1: /* Find Factorial of a given number using recursion */
#include<stdio.h>
#include<conio.h>
long int findFact( int n)
{
if( n==1)
return(1);
else
return( n * findFact(n-1));
}
void main()
{
int n; long int fact;
clrscr();
printf(“ Enter a value for n”);
scanf(“%d”, &n);
fact= findFact(n);
printf(“Factorial of %d = %ld”, n , fact);
getch();
}
Output:
Enter a value for n 5
Factorial of 5 =120

71
V.S.M College (Autonomous) Dept. of Computer Science

Example2: Compute Fibonacci sequence using recursion


/*Compute Fibonacci sequence using recursion*/
#include<stdio.h>
#include<conio.h>
int Fibonacci( int n)
{
if( n==0)
return(0);
else if ( n==1)
return(1);
else
return(Fibonacci(n-1) + Fibonacci(n-2));
}
void main()
{
int n, i;
clrscr();
printf(“Enter how many numbers to be generated:”);
scanf(“%d”, &n);
printf(“The Fibonacci sequences are \n”);
for( i=0 ; i<n ; i++)
printf(“%5d”, Fibonacci(i));
getch();
}

Output:
Enter how many numbers to be generated 10
The Fibonacci sequences are
0 1 1 2 3 5 8 13 21 34

Example 3: /*Find GCD of two numbers */


#include<stdio.h>
#include<conio.h>
int Gcd( int m, int n)
{
if( n > m)
return Gcd(n , m);
if ( n==0)
return(m);
else
return (Gcd(n, m%n));
}

72
V.S.M College (Autonomous) Dept. of Computer Science

void main()
{
int m,n, result;
clrscr();
printf(“Enter two numbers to find GCD:”);
scanf(“%d%d”, &m, &n);
result= Gcd(m.n);
printf(“GCD of %d and %d = %d “, m ,n , result);
getch();
}

Output:
Enter two numbers to find GCD: 13 45
GCD of 13 and 45 = 1
Example 4: /* Towers of Hanoi */
#include<stdio.h>
#include<conio.h>
void Towers( int n, char from , char temp, char to)
{
if( n>0)
{
Towers(n-1, from, to, temp);
printf(“ Move disk %2d from %c to %c \n”, n, from , to);
Towers(n-1, temp, from, to);
}
}
void main()
{
int n;
clrscr();
printf(“Enter number of disks:”);
scanf(“%d”, &n);
printf(“Steps for Towers of Hanoi with %d disks \n”,n);
Towers( n , ‘L’ , ‘C’ , ‘R’);
getch();
}
In the above program, L indicates left pole, C indicates center pole, and R indicates right pole.

Output:
Enter number of disks: 3
Steps for Towers of Hanoi with 3 disks
Move disk 1 from L to R
Move disk 2 from L to C
Move disk 1 from R to C
Move disk 3 from L to R
Move disk 1 from C to L
Move disk 2 from C to R
Move disk 1 from L to R

73
V.S.M College (Autonomous) Dept. of Computer Science

Explain difference between Recursion and Iteration.

RECURSION ITERATION

Recursive function – is a function that is Iterative Instructions –are loop based


partially defined by itself repetitions of a process

Recursion Uses selection structure Iteration uses repetition structure


Infinite recursion occurs if the recursion step An infinite loop occurs with iteration if
does not reduce the problem in a manner that the loop-condition test never becomes
converges on some condition.(base case) false

Recursion terminates when a base case is Iteration terminates when the loop-
recognized condition fails

Recursion uses more memory than iteration Iteration consume less memory

Infinite recursion can crash the system infinite looping uses CPU
cycles repeatedly

Recursion makes code smaller Iteration makes code longer

74
V.S.M College (Autonomous) Dept. of Computer Science

UNIT-III
ARRAYS
What is an Array? Explain different types of arrays.
To process large amount of similar type of data, C supports a derived data type known as
array that can be used for processing large amount of similar type of data.
Definition:
An array is a fixed-sized consecutive memory locations, having similar (same or
homogeneous) type of data elements (data items). All memory locations can be referenced by a
common name known as array name. Each memory location can be identified by a unique number
known as index or subscript. In array, the index number is always started from 0(zero). Each
memory location can be referenced by array name and index number known as subscripted variable.
A set of pairs of index and a value is called as an array.
Types of Arrays: Arrays can be classified into three types.
1. One-dimensional Arrays
2. Two-dimensional Arrays
3. Multi-dimensional Arrays.
1. One-dimensional Arrays: An array, which uses one subscript, is called One-dimensional Array.
A list of data elements referenced by one variable name using only one index or subscript and such a
variable is called a single-subscripted variable or a one-dimensional array.
Declaring one-dimensional array: We can declare one dimensional array as follows:
Syntax:
datatype arrayname[size];
Example: int a[10];
The above statement create 10 memory locations of type integer with a common name. The range
of index is from 0 to 9. The array index position is always started from 0 (ZERO).

01 23456789
Initializing one-dimensional array:
An array can be initialized at either of the following stages:
1. At compile time
2. At run time.
1. Compile time initialization: We can initialize an array, when it is declared with size.
Syntax: datatype arrayname [size]={ list of values };
Example:
int numbers[5]={10,20,30,40,50};
The above statement declares the array variable numbers with size 5 and will assign 10,20,30,40,50
values into each memory location of an array as follows:
10 20 30 40 50
0 1 2 3 4
When an array is being declared, we can initialize an array without specifying the size of array as
follows:
Syntax: datatype arrayname[ ]={ list of values };
75
V.S.M College (Autonomous) Dept. of Computer Science

Example: int numbers[ ]={10,20,30,40,50};


The above statement declares the array variable numbers with size 5 and will assign 10, 20, 30 ,40,
50 values into each memory location of an array as follows:
10 20 30 40 50
0 1 2 3 4
2. Run-time initialization: The memory locations of an array can be explicitly initialized at run time
as follows.
Example:
int a[100],i;
for( i=0; i<100;i++)
{
a[i]= 0;
}
In the above loop, the 100 locations of array ‘a’ are initialized with 0 (zero) at run time.
Accessing Array Elements:
Given the declaration above of a 100 element array the compiler reserves space for 100 consecutive
integer values and accesses these values using an index/subscript that takes values from 0 to 99.
The first element in an array in C always has the index 0, and if the array has n elements the last
element will have the index n-1.
An array element is accessed by writing the identifier of the array followed by the subscript in
square brackets.
Example: annual_temp[14] = 1.5;
Note that since the first element is at index 0, then the ith element is at index i-1. Hence in the above
the 15th element has index 14.
2. Two-dimensional Array: An array, which uses two subscripts, is called Two-dimensional Array.
A table of data elements referenced by one variable name using two indices or subscripts and such a
variable is called a two-dimensional array. The first index indicates rows and the second index
indicates columns. Two-dimensional arrays are used to manipulate matrices.
Declaring two-dimensional array: We can declare two dimensional array as follows:
Syntax: datatype arrayname[rowsize][columnsize];
Example: int a[3][4];
A 2-dimensional array a, which contains three rows and four columns can be shown as below:
int a[3][4];

The above statement create 3*4 (12) memory locations of type integer with a common name. The
range of first index is from 0 to 2 and the range of second index is from 0 to 3.
Initializing a two-dimensional array:
An array can be initialized at either of the following stages:
1. At compile time
2. At run time.
1. Compile time initialization: We can initialize an array, when it is declared with size.
Syntax: datatype arrayname[rowsize][columssize]={ list of values };

76
V.S.M College (Autonomous) Dept. of Computer Science

Example: int matrix[3][3]={10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 , 90};


or
int matrix[3][3]={{10 , 20 , 30}, {40 , 50 , 60},{70 , 80 , 90} };
The above statement declares the array variable matrix with size 3*3 and will assign 10, 20, 30, 40,
50, 60, 70, 80, 90 values into each memory location of an array as follows:
0 1 2 - Columns
10 20 30
40 50 60
70 80 90

2. Run-time initialization: The memory locations of an array can be explicitly initialized at run time
as follows.
Example:
int matrix[3][3], i , j;
for( i=0; i<3;i++)
{
for( j=0;j<3;j++)
matrix[i][j]= 0;
}
In the above nested loop, the 3*3 = (9) locations of array matrix are initialized with 0 (zero) at run
time.
3. Multi-dimensional array: An array, which use more than two subscripts , is called Multi-
dimensional array. C language allows arrays of three or more dimensions.
syntax:
datatype arrayname[size_1][size_2]…[size_i]..[size_n];
where size_i is the size of ith dimension .
Example:
int survey[5][4][12]; where, survey is a three-dimensional array declared, it contain 240
integer type elements. The array survey may represent survey data of 12 months rainfall during last 4
years in 5 cities.

========================================================================
Explain advantages and disadvantages of arrays with example.
Advantages:
1. Arrays use static memory allocation process to create memory locations for array, it saves
execution time.
2. Similar type of data elements can be stored only.
3. All elements can be processed in a sequential manner.
Disadvantages:
2. Sometimes , Waste of memory, or shortage of memory
3. Unable to store different types of data elements.
4. There is no random access facility to process individual data element.
Arrays can be used in the following examples:
1. List of student numbers in a college.

77
V.S.M College (Autonomous) Dept. of Computer Science

2. List of employees in an organization


3. List of products and their costs sold by a shop.
4. A Table of daily rainfall data. etc.,
========================================================================

Write a C program to find addition of two matrices


/* To find Addition of two matrices */
#include <stdio.h>
#include<conio.h>
main()
{
int a[10][10], b[10][10], c[10][10], m, n , p, q, i, j;
clrscr();
printf("Enter the number of rows and columns of A Matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the number of rows and columns of B Matrix\n");
scanf("%d%d", &p, &q);
/* checks if matrices can be added */
if((n==p) && (m==q))
{
Printf(“Matrices can be added \n”);
printf("Enter the elements of Matrix A\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("Enter the elements of Matrix B\n");
for (i = 0; i < m; i++)
{
for (j = 0 ; j < n; j++)
{
scanf("%d", &b[i][j]);
}
}
/* Addition of two matrices */
for (i = 0; i < m; i++)
{
for (j = 0 ; j < n; j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
printf("Sum of A and B matrices:\n");
for (i = 0; i < m; i++)
{
for (j = 0 ; j < n; j++)
{
78
V.S.M College (Autonomous) Dept. of Computer Science

printf("%5d", c[i][j]);
}
printf("\n");
}
}
else
printf(“Matrices cannot be added \n”);

getch();
}
Output of program:
Run1:
Enter the number of rows and columns of A Matrix
3 3
Enter the number of rows and columns of B Matrix
1 2
Matrices cannot be added.
Run2:
Enter the number of rows and columns of A Matrix
3 3
Enter the number of rows and columns of B Matrix
3 3
Matrices can be added
Enter the elements of Matrix A
1 2 3
4 5 6
7 8 9
Enter the elements of Matrix B
1 2 3
4 5 6
7 8 9
Sum of A and B matrices:
2 4 6
8 10 12
14 15 16

This c program adds two matrices i.e. compute the sum of two matrices and then print it.
==========================================================================
Write a C program to find Multiplication of two matrices
/*To Find Multiplication of two matrices */
#include <stdio.h>
main()
{
int a[10][10], b[10][10], c[10][10], m , n , p , q , i , j ,k ;
clrscr();

printf("Enter order of Matrix of A\n");


scanf("%d%d", &m, &n);
printf("Enter order of Matrix of B\n");
scanf("%d%d", &p, &q);
79
V.S.M College (Autonomous) Dept. of Computer Science

if(n==p)
{
printf("Matrix Multiplication is possible\n");
printf("Enter the elements of Matrix A \n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("Enter the elements of Matrix B\n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf("%d", &b[i][j]);
}
}
printf("GIVEN MATRIX A:\n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
printf("%5d", a[i][j]);
}
Printf(“\n”);
}
printf("GIVEN MATRIX B: \n");
for(i=0; i<p; i++)
{
for(j=0; j<q; j++)
{
printf("%5d", b[i][j]);
}
Printf(“\n”);
}
printf("THE MATRIX MULTIPLICATION IS\n");
for(i=0; i<m; i++)
{
for(j=0; j<q; j++)
{
c[i][j]=0;
for(k=0; k<n; k++)
c[i][j]=c[i][j] + a[i][k]*b[k][j];
printf("%5d",c[i][j]);
}
printf("\n");
}
}
else
80
V.S.M College (Autonomous) Dept. of Computer Science

{
printf("\nTHE MATRIX MULTIPLICATION IS NOT POSSIBLE\n");
}
getch();
}
Output of program:
Run1:
Enter order of Matrix of A
1 2
Enter order of Matrix of B
3 4
MATRIX MULTIPLICATION IS NOT POSSIBLE
Run2:
Enter order of Matrix of A
3 3
Enter order of Matrix of B
3 3
Enter the elements of Matrix A
1 2 3 4 5 6 7 8 9
Enter the elements of Matrix B
1 2 3 4 5 6 7 8 9
GIVEN MATRIX A:
1 2 3
4 5 6
7 8 9
GIVEN MATRIX B:
1 2 3
4 5 6
7 8 9
THE MATRIX MULTIPLICATION IS
30 36 42
66 81 96
102 126 150
This c program multiplies two matrices and then print it.
============================================================================
Write a C program for transpose of a given Matrix
/* Transpose of a given Matrix */
#include <stdio.h>
#include<conio.h>
main()
{
int a[10][10], b[10][10], m, n, i, j;
clrscr();
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of Matrix A \n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
81
V.S.M College (Autonomous) Dept. of Computer Science

scanf("%d", &a[i][j]);
}
}
printf("GIVEN MATRIX A:\n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
printf("%5d", a[i][j]);
}
printf(“\n”);
}
/* The rows and columns are interchanged: transpose */
for (i = 0; i < m; i++)
for( j = 0 ; j < n ; j++ )
b[i][j] = a[j][i];
printf("TRANSPOSE OF MATRIX A : \n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
printf("%5d", b[i][j]);
}
printf(“\n”);
}
getch();
}
Output of program:
Enter the number of rows and columns of matrix
3 3
Enter the elements of Matrix A
1 2 3 4 5 6 7 8 9
GIVEN MATRIX A
1 2 3
4 5 6
7 8 9
TRANSPOSE OF MATRIX A
1 4 7
2 5 8
3 6 9
=======================================================================
*****

82
V.S.M College (Autonomous) Dept. of Computer Science

STRINGS
EXPLAIN STRINGS IN C LANGUAGE.
In C language, A group of or, One or more characters, digits, symbols, special symbols
enclosed with in double quotation (“ ,”) marks are called as String. In other words, A character
array is called a string. Strings are used to manipulate text such as words and sentences. Every
string is terminated with ‘\0’ (NULL) character. The NULL character is a byte with all bits at logic is
zero.
The common operations performed on character strings include:
1. Reading and Writing Strings
2. Combining Strings together.
3. Copying one string to another.
4. Comparing Strings for equality.
Declaring and Initializing String Variable:
‘C’ does not support string as a data type.It allows us to represent string as character array.
The (Syntax) general form of declaration of a string variable is as follows:
char stringname[size];
Here, stringname is a name of the string .The size determines the number of characters in the
stringname variable.
For Example: char city[20];
When the compiler assigns a character string to a character array, it automatically supplies a NULL
character (‘\0’) at the end of the string. Therefore, The size should be equal to the maximum number
of characters in the string plus one.
Character arrays (strings) may be initialized, when they are declared. C permits a string to be
initialized in either of the following two forms:
1. char city[9]= “NEW YORK”;
2. char city[9]= {‘N’,’E’,’W’,’ ‘, ‘Y’,’O’,’R’,’K’,’\0’};
The reason that, the string variable city had to be 9 elements(characters) long is that the string NEW
YORK contains 8 characters and one element space (location) is provided for the NULL character.
Reading Strings from terminal (Input device):
We can read strings using scanf() function with control string(format string) %s as follows:
For example:
char city[10]; scanf(“%s”, &city);
The scanf() function determines its input on the first white space it finds.(White space includes
blanks, tabs, carriage returns, form feeds, new lines).Therefore, the scanf() function reads first word
as a string input and terminates the remaining words after the white spaces.
For example, NEW YORK typed from keyboard.
The string NEW word is read into the variable city only, since the white space after the NEW will
terminate the remaining words.
In the case of reading strings, The ampersand(&) is not required before the string variable name in
scanf() function.
For example: char city[10]; scanf(“%s”, city);
We can read required number of characters from keyboard using scanf() with field width as follows:
scanf(“%ws”, stringvariable);
83
V.S.M College (Autonomous) Dept. of Computer Science

Example: char city[12]; scanf( “%5s”, city);


The input string “NEW YORK” will be stored as

N E W Y \0 \0 \0 \0 \0 \0 \0

Displaying the Strings:


We can display Strings using printf() and puts() functions.
char city[20]=”New York”;
printf(“%s”, city);
It displays the value of string city and cursor is placed at the same line.
puts(city);
It displays the value of string city and cursor is placed at the next line (\n).
------------------------------------------------------------------------------------------------------
EXPLAIN STRING HANDLING FUNCTIONS.
The string header file string.h provides many string handling functions useful for manipulating
strings (character arrays).
1 strcat(): It Appends the string pointed to by str2 to the end of the string pointed to by str1. The
terminating null character of str1 is overwritten. Copying stops once the terminating null character of
str2 is copied. If overlapping occurs, the result is undefined. The argument str1 is returned.
Syntax: char *strcat(char *str1 , const char *str2);
Exmple:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str_one[60],str_two[30];
clrscr();
printf("Enter String One : ");
scanf("%s",&str_one);
printf("Enter String Two : ");
scanf("%s",&str_two);
strcat(str_one, str_two);
printf("Concatenated String : %s",str_one);
getch();
}
Output :
Enter String One: VSM
Enter String Two: COLLEGE
Concatenated String: VSMCOLLEGE
2. strncat(): It Appends the string pointed to by str2 to the end of the string pointed to by str1 up
to n characters long. The terminating null character of str1 is overwritten. Copying stops once n
characters are copied or the terminating null character of str2 is copied. A terminating null character
is always appended to str1. If overlapping occurs, the result is undefined. The argument str1 is
returned.

84
V.S.M College (Autonomous) Dept. of Computer Science

Syntax: char *strncat(char *str1, const char *str2, size_t n);


3. strcmp() : It Compares the string pointed to by str1 to the string pointed to by str2. If str1 and str2
are equal based on ASCII value, then returns zero. If str1 is less than or greater than str2 then it
returns less than zero or greater than zero respectively.
Syntax: int strcmp(const char *str1, const char *str2);
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str_one[30], str_two[30];
int n;
clrscr();
printf("Enter String One : ");
scanf("%s",&str_one);
printf("Enter String Two : ");
scanf("%s",&str_two);
n=strcmp(str_one,str_two);
if(n==0)
{
printf("Both the Strings are Equal");
}
else
{
printf("Strings are not Equal");
}
getch();
}
Output 1:
Enter String One: welcome
Enter String Two: welcome
Both the Strings are Equal
Output 2:
Enter String One: welcome
Enter String Two: WELCOME
Strings are not Equal
In the second output, the ASCII values of lower case ‘w’ letter and upper case ‘W’ letter are
different. Therefore, the two strings are not equal.
4. strncmp(): It Compares at most the first n bytes of str1 and str2. It stops comparing after the null
character. It returns zero , if the first n bytes (or null terminated length) of str1 and str2 are equal
based on ASCII value, then returns zero. If str1 is less than or greater than str2 then it returns less
than zero or greater than zero respectively.

85
V.S.M College (Autonomous) Dept. of Computer Science

Syntax:
int strncmp(const char *str1, const char *str2, size_t n);
5. strcpy(): It Copies the string pointed to by str2 to str1. It Copies up to and including the null
character of str2. If str1 and str2 overlap the behavior is undefined. The previous content of str1 is
overwritten.
Syntax: char *strcpy(char *str1, const char *str2);
Returns the argument str1. For example:
str_one = "abc";
str_two = "def";
strcpy(str_two , str_one); /* str_two becomes "abc" */
Example: Write a program to copy contents of one string into another string
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str_one[30], str_two[30];
printf("Enter a String : ");
scanf("%s",&str_one);
strcpy(str_two,str_one);
printf("Contents of String One : %s",str_one);
printf("\nContents of String Two : %s",str_two);
getch();
}
Output :
Enter a String : abc
Contents of String One : abc
Contents of String Two : abc
6. strncpy(): It Copies up to n characters from the string pointed to by str2 to str1. It Copying stops
when n characters are copied or the terminating null character in str2 is reached. If the null character
is reached, the null characters are continually copied to str1 until n characters have been copied.
Returns the argument str1.
Syntax: char *strncpy(char *str1, const char *str2, size_t n);
Example:
str_one = "abc";
str_two = "def";
strcpy(str_two , str_one,2); /* str_two becomes "ab" */
Example: Write a program to copy contents of one string into another string
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{

86
V.S.M College (Autonomous) Dept. of Computer Science

char str_one[30], str_two[30];


printf("Enter a String : ");
scanf("%s",&str_one);
strcpy(str_two,str_one,2);
printf("Contents of String One : %s",str_one);
printf("\nContents of String Two : %s",str_two);
getch();
}
Output :
Enter a String : abc
Contents of String One : abc
Contents of String Two : ab
7. strrev(): It is used to reverse the characters in a given string. The contents(data) of a given string
are reversed. The previous data of a string can be overwritten.
Syntax: char *strrev(char *str1);
Example :
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str_one[30];
printf("Enter String : ");
scanf("%s",&str_one);
strrev(str_one);
printf("Reversed String : %s",str_one);
getch();
}
Outout:
Enter String: VSM
Reversed String : MSV
8. strlen(): It Computes the length of the string str up to but not including the terminating null
character. Returns the number of characters in the string.
Syntax: size_t strlen(const char *str);
Example:
#include<stdio.h>
#include<string.h>
main()
{
char str_one[30];
int len;
printf("Enter a String : ");
scanf("%s",&str_one);
len=strlen(str_one);

87
V.S.M College (Autonomous) Dept. of Computer Science

printf("\n Length of the Given String is : %d",len);


getch();
}
Output:
Enter a String:welcome
Length of the Given String is :7
Here, the variable len contains the value 7 , i.e the length of string “welcome”.
9. strlwr(): The given string is converted into lowercase characters.
Syntax: strlwr(string_variable);
Example:
String str[20]=”V.S.M.College”;
Strlwr(str);
The result is v.s.m.college
10. strupr(): The given string is converted into uppercase characters.
Syntax: strupr(string_variable);
Example:
String str[20]=”V.S.M.College”;
Strupr(str);
The result is V.S.M.COLLEGE
Write a C program to check the given string is palindrome or not.
/* Write a C program to check the given string is palindrome or not */
#include <stdio.h>
#include<conio.h>
#include <string.h>
main()
{
char a[100], b[100];
clrscr();
printf("Enter the string to check if it is a palindrome\n");
gets(a);
strcpy(b,a);
strrev(b);
if (strcmp(a,b) == 0)
printf("Entered string is a palindrome.\n");
else
printf("Entered string is not a palindrome.\n");
getch();
}
Output of program:
Run1:
Enter the string to check if it is a palindrome MALAYALAM
Entered string is a palindrome.
Run2:
Enter the string to check if it is a palindrome COLLEGE
Entered string is not a palindrome.
======================================================================

88
V.S.M College (Autonomous) Dept. of Computer Science

Write a C program to check the given number is palindrome number or not


/*Write a C program to check the given number is palindrome number or not */
#include <stdio.h>
#include<conio.h>
main()
{
int n, reverse = 0, temp;
clrscr();
printf("Enter a number to check if it is a palindrome or not\n");
scanf("%d",&n);
temp = n;
while (temp != 0)
{
reverse = reverse * 10;
reverse = reverse + temp%10;
temp = temp/10;
}
if (n == reverse)
printf("%d is a palindrome number.\n", n);
else
printf("%d is not a palindrome number.\n", n);
getch();
}
Output of program:
Run1:
Enter a number to check if it is a palindrome or not
121
121 is a palindrome number.
Run2:
Enter a number to check if it is a palindrome or not
789
789 is not a palindrome number.
=======================================================================
******

89
V.S.M College (Autonomous) Dept. of Computer Science

UNIT-IV
POINTERS
Introduction to pointers
Definition: A pointer is a derived data type in C language. It is built from one of the fundamental data types
available in C or user defined data types. A pointer is a variable, which stores an address of another variable.
Memory locations for pointers are allocated in Heap (RAM) memory.
Declaration of a pointer:
Pointer variables can be declared as follows:
datatype *pointervariable ;
For Example,
int *pv; here, pv is a pointer variable of type int.
The asterisk * tells that the variable pv is a pointer variable the * operator is called as indirection
operator or dereference operator.
Initializing the address of a variable to a pointer:
The process of assigning the address of a variable to a pointer variable is known as initialization.
Once a variable is declared , we can use the assignment operator to initialize the pointer variable as follows:
Example:
int number; 1000 1002
int *p; /* declaration */
1002 25
p= &number; /* initialization */
p number
we can combine initialization with declaration as follows:
int *p= &number;
Here, & operator indicates address of a variable.
Accessing a variable through its pointer:
Once an address of a variable is assigned to a pointer, we can access the value of a variable using
pointer with the help of the * operator, which is called as indirection operator or dereference operator.
Example:
main()
{
int *p; /* pointer declaration */
int number;
clrscr();
printf(“Enter a number ”);
scanf(“%d”, &number);
p= &number; / * Assign address of a variable to a pointer */
printf(“Value of a variable number =%d\n”,number);
printf(“Address of variable number =%u\n”, &number);
printf(“Value of a pointer variable p =%u\n”,p);
printf(“Address of pointer variable p =%u\n”, &p);
printf(“Value a variable number through pointer p =%d\n”,*p);
getch();
}
Output:
Enter a number 25
Value of a variable number =25
Address of variable number =1002 (generation of address depends on system)
Value of a pointer variable p =1002
Address of pointer variable p =1000
Value a variable number through pointer p =25
90
V.S.M College (Autonomous) Dept. of Computer Science

Pointer pointing to a variable:


The pointer points to variable identifier as follows:
int number= 10;
int *p; /* declaration */
p= &number; /* initialization */
Now, *p contains a value 10.
Pointer expressions:
Like other variables , pointer variables can be used in expressions. For example,
int *p1, *p2;
int a, b, y;
a=50; b=10;
p1= &a;
p2=&b;
y= *p1 * *p2;
float z;
z= *p1 / *p2; Here, space is required between / and *
now the output of y = 500 and z= 5
Note: two pointer variables cannot be added.
Note: The value of a pointer variable can be incremented or decremented based on size of its data
type.. For example:
int *p = 1000;
p++;
Now, The pointer variable p contains value 1002 and not 1001, Its value is incremented by the length
of int data type i.e., 2 bytes.
Pointer (Address) Arithmetic:
C pointer is an address, which is a numeric value. Therefore, you can perform arithmetic
operations on a pointer just as you can a numeric value. There are four arithmetic operators that
can be used on pointers: ++, --, +, and -
To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the
address 1000. Assuming 16-bit integers, let us perform the following arithmetic operation on the
pointer:
ptr++
Now, after the above operation, the ptr will point to the location 1004 because each time ptr is
incremented, it will point to the next integer location which is 2 bytes next to the current location.
This operation will move the pointer to next memory location without impacting actual value at the
memory location. If ptr points to a character whose address is 1000, then above operation will
point to the location 1001 because next character will be available at 1001.
Pointer Arithmetic:: Incrementing a Pointer ( ++)
We prefer using a pointer in our program instead of an array because the variable pointer can be
incremented, unlike the array name which cannot be incremented because it is a constant pointer.
The following program increments the variable pointer to access each succeeding element of the
array:
#include <stdio.h>
const int MAX = 3;
main ()
{
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
91
V.S.M College (Autonomous) Dept. of Computer Science

ptr = var;
for ( i = 0; i < MAX; i++)
{
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
/* move to the next location */
ptr++;
}
}
When the above code is compiled and executed, it produces result something as follows:
Address of var[0] = bf882b30
Value of var[0] = 10
Address of var[1] = bf882b32
Value of var[1] = 100
Address of var[2] = bf882b34
Value of var[2] = 200
Pointer Arithmetic: Decrementing a Pointer(- -)
The same considerations apply to decrementing a pointer, which decreases its value by the number
of bytes of its data type as shown below:
#include <stdio.h>
const int MAX = 3;
main ()
{
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--)
{
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
/* move to the previous location */
ptr--;
}
}
When the above code is compiled and executed, it produces result something as follows:
Address of var[3] = bfedbcd4
Value of var[3] = 200
Address of var[2] = bfedbcd2
Value of var[2] = 100
Address of var[1] = bfedbcd0
Value of var[1] = 10
Arrays and Pointer Arithmetic using ( + , -)
In C, arrays have a strong relationship to pointers.
Consider the following declaration. :
float arr[ 10 ] ;
Now, arr[ i ] is defined using pointer arithmetic as
arr[ i ] == * ( arr + i )
92
V.S.M College (Autonomous) Dept. of Computer Science

Where, arr is a pointer to arr[ 0 ]. In fact, it is defined to be & arr[ 0 ].


A pointer is an address in memory. arr contains an address in memory---the address where arr[ 0 ] is
located.
What is arr + i? If arr is a pointer to arr[ 0 ] then arr + i is a pointer to arr[ i ].
Perhaps this is easier shown in a diagram.

We assume that each float takes up 4 bytes of memory. If arr is at address 1000, then arr + 1 is address
1004, arr + 2 is address 1008, and in general, arr + i is address 1000 + (i * 4).
The idea is to have arr + i point to i elements after arr regardless of what type of element the array holds.
Rules of pointer operations:
A pointer variable can be assigned the address of another variable.
A pointer variable can be assigned the values of another pointer variable.
A pointer variable can be initialized with NULL or zero value.
A pointer variable can be pre-fixed or post-fixed with increment or decrement operators.
An integer value may be added or subtracted from a pointer variable.
When two pointers point to the same array, one pointer variable can be subtracted from another.
When two pointer points to the objects of the same data type, they can be compared using relational
operators.
A pointer variable cannot be multiplied by a constant.
Two pointer variables cannot be added.
A value cannot be assigned to an arbitrary address i. e. &x=10 is illegal
NULL Pointer
A NULL pointer is a pointer which is pointing to nothing. NULL pointer points the base address of
segment.
Examples of NULL pointer:
1. int *ptr=(char *)0;
2. float *ptr=(float *)0;
3. char *ptr=(char *)0;
4. double *ptr=(double *)0;
5. char *ptr=’\0’;
6. int *ptr=NULL;
What is meaning of NULL
NULL is macro constant which has been defined in the heard file stdio.h, alloc.h, mem.h, stddef.h and
stdlib.h as
#define NULL 0
Examples:
What will be output of following c program?
#include <stdio.h>
main(){
if(!NULL)
printf("I know preprocessor");
else
93
V.S.M College (Autonomous) Dept. of Computer Science

printf("I don't know preprocessor");


return 0;
}
Output: I know preprocessor
Explanation:
!NULL = !0 = 1
In condition , any non zero number means true and zero means false.
Generic pointer or void pointer:
In C language, void is a keyword. The void pointer in c is known as generic pointer. Generic pointer is a
pointer which can point to any type of data variable.
Syntax: void *ptr; Here ptr is void or generic 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 */
Important points about generic (void) pointer in c:
1. We cannot dereference generic pointer.
2. We can find the size of generic pointer using sizeof operator.
3. Generic pointer can hold any type of pointers like char pointer, struct pointer, array of pointer etc without
any typecasting.
Example:
char c='A';
int i=4;
void *p;
char *q=&c;
int *r=&i;
p=q;
printf("%c\n",*(char *)p);
p=r;
printf("%d",*(int*)p);

Output: A
4
------------------------------------------------------------------------------------------------------------------------------------
Pointers and Functions (or) Call by reference:
In C language, Functions pass arguments by address also. Passing arguments by address means that,
when a function call is made, only the addresses of actual arguments of function call are passed into the
formal arguments of called function. Whatever modification is occurred on formal arguments inside the
called function will have immediate effect on the variables used in the actual arguments list in the calling
function through their addresses.
The mechanism of sending back information through arguments is achieved by using address
operator (&) and indirection operator(*). The operator * is known as indirection operator because it gives an
indirect reference to a variable through its address. This is known as call by reference.The following example
shows the concept of passing arguments by reference.
/* Example of call by reference (or) swap two numbers without using 3rd variable (temporary variable) */
#include<stdio.h>
#include<conio.h>
void swap( int *a, int *b)
94
V.S.M College (Autonomous) Dept. of Computer Science

{
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
printf(“ In Function, After swap: a=%d, b=%d\n” , *a , *b);
}
void main()
{
int a , b;
clrscr();
printf(“Enter Two numbers”);
scanf(“%d%d”, &a, &b);
printf(“ In main, Before swap: a=%d, b=%d\n” , a , b);
swap(&a , &b);
printf(“ In main , After swap: a=%d, b=%d\n” , a , b);
getch();
}
Output:
Enter Two numbers 5 10
In main, Before swap: a=5, b=10
In Function, After swap: a=10, b=5
In main, After swap: a=10, b=5
In the above program, The values are swapped (interchanged) in function swap() means that, , the values of
actual arguments of function call in the main() function are swapped through addresses directly. The
function can return multiple values with the help of call by reference mechanism. In the above example, the
two values are returned from called function to calling function the help of call by reference mechanism.
----------------------------------------------------------------------------------------------------------------------------------
Explain Pointers and Arrays:
When array is declared, The compiler allocates base address and sufficient amount of storage to
contain all the elements of the array in contiguous memory locations. The base address is the first element
of the array. Suppose,
An array int a[10]; is declared. Now, The pointer variable *p contains an address of first location of an
array as follows:
int *p;
p= &a[0]; or p=a;
We can access every value of array a using p++ ; to move a pointer from one element to another element.
An address of an element is calculated using its index and the scale factor(size) of its data type. For example,
Assume that, the base address is 1000.
Effective Address of a[3] = base address + ( 3 * sizeof ( int))
= 1000 + (3 * 2)
= 1000+6 = 1006. Here, 1006 is an address of fourth element of an array a.
/* Example program for pointers and arrays */:
main()
{
int a[10] ,i, n;
int *p;
clrscr();
printf( “ Enter how many numbers “);
scanf(“%d” , & n);
printf(“Enter %d numbers”,n);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
95
V.S.M College (Autonomous) Dept. of Computer Science

p=&a[0];
printf (“Element AddressValue\n”);
for(i=0;i<n;i++)
{
printf( “a[%d] %u %d\n”, i, p, *p);
p++;
}
getch();
}
output:
Enter how many numbers 5
Enter 5 numbers 1 2 3 4 5
Element AddressValue
a[0] 1000 1
a[1] 1002 2
a[2] 1004 3
a[3] 1006 4
a[4] 1008 5

-------------------------------------------------------------------------------------------------------
What are the difference between an Pointer and an Array?
Pointer Array
1. A pointer is a variable, which stores an address of 1. An array is a single, pre allocated chunk of
another memory location contiguous elements (all of the same type), fixed
in size and location.
2. Pointer can be initialized by address at definition. Example: 2. Array can be initialized by values at definition.
int * p = &a; Example : int num[] = { 2, 4, 5};
3. Pointer is dynamic in nature. The memory allocation can be 3. They are static in nature. Once memory is
resized or freed later. allocated , it cannot be resized or freed
dynamically.
4. The assembly code of Pointer is different than Array 4. The assembly code of Array is different than
Pointer
5. Pointers support: 5.Arrays support :
1. sizeof - get its size 1. sizeof - get its size
Like arrays, pointers have a size that can be You can apply sizeof to it. An array x of N
obtained with sizeof. Note that different pointer elements of type T (T x[N]) has the size N
* sizeof (T), which is what you should
types can have different sizes.
expect. For example, if sizeof (int) == 2
2. & - get its address
and int arr[5];, then sizeof arr == 10 == 5 *
Assuming your pointer is an lvalue, you can take 2 == 5 * sizeof (int).
its address with &. The result is a pointer to a 2. & - get its address
pointer. You can take its address with &, which
3. * - dereference it results in a pointer to the entire array.
Assuming the base type of your pointer isn't an 3. any other use - implicit pointer
incomplete type, you can dereference it; i.e., you conversion
can follow the pointer and get the object it refers Any other use of an array results in a
to. Incomplete types include void and pointer to the first array element (the
predeclared struct types that haven't been array "decays" to a pointer).
defined yet.
96
V.S.M College (Autonomous) Dept. of Computer Science

4. +, - - pointer arithmetic
If you have a pointer to an array element, you
can add an integer amount to it. This amount can
be negative, and ptr - n is equivalent to ptr + -n
(and -n + ptr, since + is commutative, even with
pointers). If ptr is a pointer to the i'th element of
an array, then ptr + n is a pointer to the (i + n)'th
array element, unless i + n is negative or greater
than the number of array elements, in which case
the results are undefined. If i + n is equal to the
number of elements, the result is a pointer that
must not be dereferenced.
5. -> - struct dereference
p->m is equivalent to (*p).m, where . is the
struct/union member access operator. This
means p must be a pointer to a struct or union.
6. [] - indexed dereference
a[b] is equivalent to *(a + b). This means a and b
must be a pointer to an array element and an
integer; not necessarily respectively, because
a[b] == *(a + b) == *(b + a) == b[a]. Another
important equivalence is p[0] == 0[p] == *p.

--------------------------------------------------------------------------------------------------------
Explain Pointers and Strings :
C supports a method to create strings using pointer variables of type char. Example:
char *str= “good”;
The above statement creates a string for the literal and stores its address in the pointer variable str.Now,
The pointer variable points to the first character of the string “good”.
/*Example : Display a string using a pointer */
main()
{
char name[20];
char *str;
int length;
clrscr();
printf(“Enter a string”);
scanf(“%s”, &name);
str= name;
printf(“ The given string is: “);
while( *str != ‘\0’)
{
printf(“%c”, *str);
str++;
}
length= str- name;
printf(“ \nThe length( number of characters ) in a string= %d”, length);
getch();
}

97
V.S.M College (Autonomous) Dept. of Computer Science

Output :
Enter a string : VSM
The given string is : VSM
The length(number of characters ) in a string= 3
------------------------------------------------------------------------------------------------------------------------------------

Pointer to a pointer:
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer
contains the address of a variable. When we define a pointer to a pointer, the first pointer contains
the address of the second pointer, which points to the location that contains the actual value as
shown below.

A variable that is a pointer to a pointer must be declared as such. This is done by placing an
additional asterisk(*) in front of its name. For example, following is the declaration to declare a
pointer to a pointer of type int:
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires
that the asterisk operator be applied twice, as is shown below in the example:
#include <stdio.h>
main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;
/* take the address of var */
ptr = &var;
/* take the address of ptr using address of operator & */
pptr = &ptr;
/* take the value using pptr */
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
}
When the above code is compiled and executed, it produces the following result:
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
--------------------------------------------------------------------------------------------------------
Static Memory Allocation and Dynamic Memory Allocation
Static Memory Allocation :
Static-duration variables are allocated in main memory, usually along with the executable code of
the program, and persist for the lifetime of the program. For static-duration variables, the size of the
allocation is required to be compile-time constant. In many situations the programmer requires greater
flexibility in managing the lifetime of allocated memory. Therefore, We are using Dynamic Memory
Allocation Technique.
98
V.S.M College (Autonomous) Dept. of Computer Science

Dynamic Memory Allocation :


Dynamic memory management technique permits us to allocate additional memory space or to release
unwanted space at run time( during execution of the program), thus optimizing the use of storage space.
The process of allocating memory at run time is known as Dynamic Memory Allocation . There are four
library functions in C language. These functions are available in alloc.h header file.:
1.malloc() : It allocates required size of bytes.
2.calloc() : It allocates consecutive memory space for an array of elements and initializes them to zero
3.realloc() : It Modifies the size of previously allocated memory space .
4.free() : It frees(releases) previously allocated memory space.

1. Allocating a block of memory using malloc():


The malloc() functions reserves a block of memory of specified size and returns a pointer of size void.
This means , We can assign it to any type of pointer. It takes one argument.
Syntax:
ptr = (cast_type*) malloc(byte_size);
Where, ptr is a pointer of any type . byte_size indicates required size of space to be allocated.
Example 1:
int *numbers;
numbers= (int*) malloc( 10 * sizeof(int));
Where, numbers is an integer type pointer variable. the size 10 * 2= 20 bytes of memory space is
allocated and address of the first byte of memory is assigned to the pointer variable numbers.
Example 2:
char *name;
name= (char*) malloc(20);
Now, the variable name contains 20 bytes of memory space.
Example 3:
struct student
{
int sno;
char sname[20];
};
struct student *s;
s= (struct student *) malloc(sizeof(struct student));
Now, the structure variable s contains (2 + 20) =22 bytes of memory space.
2. Allocating multiple blocks of memory using calloc():
The calloc() function allocates multiple blocks of memory space with same size for an array of
elements or structures and initializes them to zero. It takes two arguments.
Syntax: ptr = (cast_type*) calloc(n , byte_size);
Where, ptr is a pointer of any type .The variable n indicates the number of blocks, byte_size
indicates required size of space to be allocated.
Example 1:
int *numbers;
numbers= (int*) calloc( 10 , sizeof(int));
Where, numbers is an integer type pointer variable. the size 10 * 2= 20 bytes of memory space is
allocated and address of the first byte of memory is assigned to the pointer variable numbers.
3. Altering the size of a block using realloc():
The realloc() function changes the memory size , which is previously allocated. i.e., It Modifies the
size of previously allocated memory space .
Syntax:
ptr= (cast_type*) malloc(size);
then reallocation of space is done by the statement
ptr =(cast_type*) realloc(ptr, newsize);
99
V.S.M College (Autonomous) Dept. of Computer Science

This function allocates a new memory space of size newsize to the pointer variable ptr and returns
an address of first byte of the new memory block to a pointer ptr.
The newsize may be smaller or larger than the previous size.
Example:
char *buffer;
buffer= (char*)malloc(10); /* Buffer size 10 bytes created */
strcpy(buffer, “HYDERABAD”);
buffer= . (char*) realloc(buffer,15); /* Buffer size is modified to 15 bytes */
strcpy( buffer, “SECUNDERABAD”);
4. Releasing the used memory space using free() function:
We can release the memory when the memory is not required. The free() function releases
previously allocated space.
Syntax:
free(pointervariable);
Example :
char *buffer;
buffer= (char*)malloc(10); /* Buffer size 10 bytes created */
strcpy(buffer, “HYDERABAD”);
printf(“ The string is %s”, buffer);
free(buffer); /* the memory of buffer variable is released */
Advantages of pointers:
The pointers offer a number of benefits/advantages to the programmers. They include:
1. Pointers are more efficient in handling arrays and data tables.
2. Pointers are used to return multiple values from a function via function arguments.
3. The use of pointer arrays to character strings result in saving of data storage space in memory.
4. Pointers allows C language to support dynamic memory management.
5. Pointers provide an efficient tool for manipulating dynamic data structures.
6. Pointers reduce length and complexity of programs.
7. Pointers increase execution speed.
Limitations of pointers/Drawbacks of pointers:
1. It takes additional memory to maintain an address.
2. Sometimes, memory leak , dangling pointers may be exists in the program.
3. Do not use more number of pointers in the program, thus increases space complexity
------------------------------------------------------------------------------------------------------------------------
*****

Structure, Union and Enumerated Data types


100
V.S.M College (Autonomous) Dept. of Computer Science

Structure Definition: A Structure is a user-defined data type, which contains a collection of one or
more variables of different data types or similar data types, grouped together under a single name. By using
structure declaration, we can make a group of structure variables, arrays, pointers.
Declaration of Structures:
Structures can be declared as given below:
Syntax:
struct struct_name or tag_name
{ datatype1 field1 ;
datatype2 field2 ;
:
:
datatypeN fieldN ;
};
The structure name is sometimes called as structure tag name. Structure declaration is always start
with struct keyword. struct_name is known as tag or structure name. The struct declaration is enclosed
with in a pair of curly braces { }. The field1, field2, …. fieldN are members of the structure . After declaring a
structure, We can define structure variables to create memory locations. The structure declaration declares
structures, but, this process does not allocate memory. The memory locations can be allocated, whenever
structure variables are defined.
Syntax:
struct struct_name structvariable1, structvariable2,…. structvariableN ;
Here, structvariable1, structvariable2 ,….structvariableN are variables of struct struct_name.
Accessing structure members:
We can access and assign values to the members of a structure in number of ways. The link between
member and structure variable is established using the member operator . (dot operator)or period
operator. For example:
stu[0].sno=10;
strcpy (stu[0].sname,”raju”) ; Here, stu is a structure variable and sno, sname are members of the
strcture.
Structure members (fields) can also be accessed using the following one of two notations in pointer
representation.
1. ptr-> sno and ptr->sname
The symbol -> is called the arrow operator or member selection operator.
2. (*ptr).sno and (*ptr).sname
Here, The parentheses ( ) around *ptr are required because, member operator . has higher
precedence than * operator.
Initialization of Structures:
A structure variable can be initialized at compile time as follows:
struct student
{
int sno;
char sname[20];
} stu={10 , ”ramu”}; This assigns the value 10 to stu.sno and “ramu” to stu.sname
Coping (Assigning) and comparing structure variables:
Two variables of same structure type can be copied the same way as ordinary variables. If stu1, and
stu2 belong to the same structure, then the following statements are valid :
stu2=stu1; /* the values of stu1 are assigned to stu2 structure. */
stu1=stu2; /* the values of stu2 are assigned to stu1 structure. */

101
V.S.M College (Autonomous) Dept. of Computer Science

Note: C language does not permit logical operations on structure variables. We have to compare members
individually.
------------------------------------------------------------------------------------------------------------------------------------------------
Arrays of structures:
We use structures to define the format of a number of related variables. For Example, to maintain three
student’s details, we may declare array of structures, each element of array representing a structure
variable. For example,
struct student stu 2 20 2 20 2 20 = 66 Bytes
{
int sno;
char sname[20]; sno sname sno sname sno sname
}; 0 1 2
struct student stu[3];
Here, the variable stu is an array of struct student type.
/* Example : Read and Display 3 students data using Array of structures*/
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20];
};
struct student stu[3] ;
main()
{
int i;
printf(“Enter 3 students data\n”);
for( i=0;i<3; i++)
{
printf(“ Enter student number and name:”);
scanf(“%d%s”, & stu[i].sno, &stu[i].sname);
}
printf(“ \nStudent details are \n”);
for( i=0;i<3; i++)
{
printf(“ student number = %d and name:= %s\n”, stu[i].sno , stu[i].sname);
}
getch();
}

Output:
Enter 3 students data
Enter student number and name: 10 raju
Enter student number and name: 20 ravi
Enter student number and name: 30 rama

Student details are


Student number =10 and name= raju
Student number =20 and name= ravi
Student number =30 and name= rama

102
V.S.M College (Autonomous) Dept. of Computer Science

Arrays with in structures:


C language permits the use of arrays as structure members. We can declare single, or multi-
dimensional arrays with in structures. For example,
struct student
{
int sno;
char sname[20];
int marks[3];
};
struct student stu[3];
Here, the variable stu is an array of struct student type, the member sname is an array of type char and the
member marks is an array of type int.
/* Example : Read and Display 3 students data using Arrays with in structures*/
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20]; /* char type Array with in structure */
int marks[3]; /* int type Array with in structure */
};
struct student stu[3] ;
main()
{
int i,j, tmarks;
printf(“Enter 3 students data\n”);
for( i=0;i<3; i++)
{
printf(“ Enter student number and name:”);
scanf(“%d%s”, & stu[i].sno, &stu[i].sname);
printf(“Enter marks of 3 subjects”);
for(j=0;j<3;j++)
scanf(“%d”, &stu[i].marks[j]);
}
printf(“ \nStudent details are \n”);
for( i=0;i<3; i++)
{
printf(“ student number = %d and name:= %s\n”, stu[i].sno , stu[i].sname);
tmarks=0;
for (j=0; j<3;j++)
tmarks= tmarks + stu[i].marks[j];
printf(“ Total Marks = %d\n”, tmarks);
}

getch();
}
Output:
Enter 3 students data
Enter student number and name: 10 raju
Enter marks of 3 subjects 50 60 70
Enter student number and name: 20 ravi
Enter marks of 3 subjects 70 80 90
103
V.S.M College (Autonomous) Dept. of Computer Science

Enter student number and name: 30 rama


Enter marks of 3 subjects 40 50 60
Student details are
Student number =10 and name= raju
Total Marks = 180
Student number =20 and name= ravi
Total Marks = 240
Student number =30 and name= rama
Total Marks = 150
------------------------------------------------------------------------------------------------------------------------------------------------
Nested structures (or) Structure declarations with in structures:
We can declare structures with in structures in C language. Structures with in structures are known as
nesting of structures. For example, We can declare dateofjoin structure with in student structure as follows:
struct student
{
int sno;
char sname[20];

struct
{
int day;
int month;
int year;
}dateofjoin;
};
struct student stu;
Here, the student structure contains sno, sname, and a member dateofjoin which itself is a structure with
three members i.e., day, month, year are members of the inner structure. These can referred to as :
stu.dateofjoin.day
stu.dateofjoin.month
stu.dateofjoin.year

/* Example : Read and Display one student data using structure declaration with in structures or nesting
of structures */
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20];
struct
{
int day;
int month;
int year;
}dateofjoin;
};
struct student stu;
main()
{

104
V.S.M College (Autonomous) Dept. of Computer Science

printf(“Enter One student data\n”);


printf(“ Enter student number and name:”);
scanf(“%d%s”, &stu.sno, &stu.sname);
printf(“ Enter Date of Joining:”);
scanf(“%d%d%d”, &stu.dateofjoin.day, &stu.dateofjoin.month, &stu.dateofjoin.year);
printf(“ \nGiven Student details are \n”);
printf(“ student number = %d and name:= %s\n”, stu.sno , stu.sname);
printf(“ Date of Join is =”);
printf(“%2d-%2d-%4d”,stu.dateofjoin.day, stu.dateofjoin.month, stu.dateofjoin.year);
getch();
}
Output:
Enter One student data
Enter student number and name: 10 raju
Enter Date of Joining: 12 5 2010
Enter student number and name: 20 ravi
Enter Date of Joining: 13 5 2010
Enter student number and name: 30 rama
Enter Date of Joining: 14 5 2010
Given Student details are
Student number =10 and name= raju
Date of Join is = 12- 5-2010
Student number =20 and name= ravi
Date of Join is = 13- 5-2010
Student number =30 and name= rama
Date of Join is = 14- 5-2010
Structure Variables with in structures:
We can declare structure variables with in structures in C language.. For example, We can declare
dateofjoin structure variable of date structure with in a student structure as follows:
struct date
{
int day;
int month;
int year;
};
struct student
{
int sno;
char sname[20];
struct date dateofjoin;
};
struct student stu;
Here, the student structure contains sno, sname, and a member dateofjoin which is a member of structure
date with three members i.e., day, month, year are members of the structure date. These can referred to
as :
stu.dateofjoin.day
stu.dateofjoin.month
stu.dateofjoin.year
/* Example : Read and Display one student data using structure variables with in structures */
#include<stdio.h>
#include<conio.h>
struct date
105
V.S.M College (Autonomous) Dept. of Computer Science

{
int day;
int month;
int year;
};
struct student
{
int sno;
char sname[20];
struct date dateofjoin;
};
struct student stu;
main()
{
printf(“Enter One student data\n”);
printf(“ Enter student number and name:”);
scanf(“%d%s”, &stu.sno, &stu.sname);
printf(“ Enter Date of Joining:”);
scanf(“%d%d%d”, &stu.dateofjoin.day, &stu.dateofjoin.month, &stu.dateofjoin.year);
printf(“ \nGiven Student details are \n”);
printf(“ student number = %d and name:= %s\n”, stu.sno , stu.sname);
printf(“ Date of Join is =”);
printf(“%2d-%2d-%4d”,stu.dateofjoin.day, stu.dateofjoin.month, stu.dateofjoin.year);
getch();
}
Output:
Enter One student data
Enter student number and name: 10 raju
Enter Date of Joining: 12 5 2010
Enter student number and name: 20 ravi
Enter Date of Joining: 13 5 2010
Enter student number and name: 30 rama
Enter Date of Joining: 14 5 2010
Given Student details are
Student number =10 and name= raju
Date of Join is = 12- 5-2010
Student number =20 and name= ravi
Date of Join is = 13- 5-2010
Student number =30 and name= rama
Date of Join is = 14- 5-2010
-----------------------------------------------------------------------------------------------------------------------------------------------
Structures with functions:
C language supports the passing of structure values as arguments to functions There are three
methods to pass values of structures to functions.
1. Pass each member of the structure as an actual argument of the function call.
2. Passing of a copy of entire structure to the called function (Call by value method)
3. Passing of an address of a structure to a called function (Call by reference method). This method is more
efficient. For examples,
#include<stdio.h>
#include<conio.h>
struct student
{
106
V.S.M College (Autonomous) Dept. of Computer Science

int sno;
char sname[20];
};
struct student stu[3] ;
void display(struct student s[])
{
int i;
for( i=0;i<3; i++)
{
printf(“ student number = %d and name:= %s\n”, s[i].sno , s[i].sname);
}
}
main()
{
int i;
printf(“Enter 3 students data\n”);
for( i=0;i<3; i++)
{
printf(“ Enter student number and name:”);
scanf(“%d%s”, & stu[i].sno, &stu[i].sname);
}
printf(“ \nStudent details are \n”);
display(stu);
getch();
}
Output:
Enter 3 students data
Enter student number and name: 10 raju
Enter student number and name: 20 ravi
Enter student number and name: 30 rama
Student details are
Student number =10 and name= raju
Student number =20 and name= ravi
Student number =30 and name= rama
Self-referential Structure with an Example:
A self-referential structure is similar to a structure, It contains set of different types data fields along
with a pointer variable of the same structure type. The pointer variable points to another structure of the
same type. For example, a linked list is supposed to be a self-referential data structure. The next node of a
current node is being pointed, which is of the same struct type. For example,
typedef struct linkedlist
{
int data;
struct linkedlist *next;
} node ;
node *start , *temp;
In the above example, the linkedlist is a self-referential structure – because the *next is of the type sturct
linkedlist. Where *start, *temp variables are structure of pointer variables.

107
V.S.M College (Autonomous) Dept. of Computer Science

Linked list Diagram :

Self-Referential Structure is one of the most useful feature of C language. It allows us to create data
structures that contains references to data of the same type as themselves. Self-referential
Structure is used in data structure such as Binary tree, Linked list, Stack, Queue etc.
Advantages of self-referential structure(linked list):
- It is a dynamic structure (Memory is allocated at run-time).
- We can have more than one data type.
- Re-arrange of linked list is easy (Insertion-Deletion).
- It doesn’t waste memory, because Memory is allocated at run-time.
Disadvantages of self-referential structure(linked list):
- In linked list, if we want to access any node, then it is difficult, because it provides sequential access
facility to access nodes in the linked list.
- It is occupying more memory to maintain pointers .
/*Example program for self referential structure */
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#define NULL 0
struct linkedlist
{
int data;
struct linkedlist *next;
};
typedef struct linkedlist node;
node *start , *temp;
void createlist()
{
start=(struct node *)malloc(sizeof(struct node));
printf(“ Enter data , end with 0 :”);
scanf("%d", &start->data);
temp=start;
while (temp->data !=0)
{
temp->next=(struct node *)malloc(sizeof(struct node));
temp= temp->next;
printf("Enter the data, end with 0 : ");
scanf("%d" ,&temp->data);
}
temp->next=NULL;
}
108
V.S.M College (Autonomous) Dept. of Computer Science

void display()
{
temp=start;
printf("The Linked List elements are : \n");
while(temp != NULL)
{
printf("%d--->", temp->data);
temp=temp->next;
}
printf("NULL");
}
main()
{
createlist();
display();
}
Output:
Enter the data end with 0 : 10
Enter the data end with 0 : 20
Enter the data end with 0 : 30
Enter the data end with 0 : 0
The Linked List :
10--->20--->30--->0 -->NULL

Union
Union:
A union is a similar to a structure. A union is a user-defined data type. It contains a collection of
fields(members) with different data types. There is a major difference between structure and union in terms
of storage. In structures, Each member has its own storage location, where as all the members of union use
the same memory location. In union,
The compiler allocates storage that is large enough to hold the largest variable type in the union. In
structure, We can handle all members at a time , where as in union, we can handle one member at a time. In
structure, we can maintain values of all members simultaneously , where in union, we can maintain only one
value for one member at a time. Unions save storage , but, unions lost previous data of members(fields).
The union can be declared using union keyword as follows:
Syntax:
union union_name
{
datatype1 field1;
datatype2 field2;
:
datatypeN fieldN;
};

Union declaration always start with union keyword. union_name is known as tag or union name.
The union declaration is enclosed with in a pair of curly braces { }.
The field1, field2,…. fieldN are members of the union.
After declaring a union, We can define union variables to create memory locations. The union declaration
declares unions, but, this process does not allocate memory.
The memory locations can be allocated , whenever union variables are defined.
Syntax:
109
V.S.M College (Autonomous) Dept. of Computer Science

union union_name unionvariable1, unionvariable2,….unionvariableN;


Here, unionvariable1, unionvariable2,….unionvariableN are variables of union union_name.
/*Example for union */
#include<stdio.h>
#include<conio.h>
union tv
{
int cost;
float price;
};
union tv bpl ;
main()
{
clrscr();
printf(“Enter BPL TV Cost:”);
scanf(“%d”, &bpl.cost);
printf(“ The size of bpl variable = %ld\n”, sizeof(bpl));
bpl.price= bpl.cost + 550.00;
printf(“ \nPrice of BPL TV is : %.2f”, bpl.price);
getch();
}
In the above program, the union variable bpl contains two fields: cost( 2 bytes) and price(4 bytes).
The compiler allocates 4 bytes of storage for the union variable bpl. The first two bytes can be used
by cost field , the four bytes from first location can be used by price field. We can use one field at a time,
where as in structure, 6(2+4) bytes of storage can be allocated for two fields(cost and price) separately.
Output:
Enter BPL TV Cost: 5000
The size of bpl variable = 4
Price of BPL TV is: 5550.00
---------------------------------------------------------------------------------------------------------------
Unions inside Structures:
We can use unions in structures like nesting of structures. For example:
struct Employee
{
int empno;
char empname[20];
union
{
int basicsalary;
float netsalary;
}salary;
};
struct Employee e;
the size of variable e is (2+20+4) 26 bytes only.
Here, the netsalary can be calculated based on basecsalary + 500.00(HRA) +3000.00(TA)
At the time of input, basicsalary field is required, at the time output, netsalary field is required.
Structures inside Unions:
We can use structures in unions like nesting of structures. For example:
union Employee

110
V.S.M College (Autonomous) Dept. of Computer Science

{
struct
{
int basicsalary;
int hra;
int ta;
int da;
}manager;
struct
{
int wages;
int da;
}worker;
};
union Employee e;
the size of variable e is 8 bytes only. The variable e contains two fields 1. manager 2. worker. Therefore,
we can use either manager structure or worker structure at a time based on choice of input in the program.
-------------------------------------------------------------------------------------------------------------------------------------
Differences between Structure and Union.
Structure Union
1.The keyword struct is used to define a structure 1. The keyword union is used to define a union.
2. When a variable is associated with a structure, the 2. When a variable is associated with a union, the
compiler allocates the memory for each member(field). compiler allocates the memory by considering the
The size of structure is greater than or equal to the sum size of the largest data type of a member( field).
of sizes of its members(fields). The smaller members So, The size of union is equal to the size of largest
may end with unused slack bytes. data type of a member(field).
3. Each member within a structure is assigned unique 3. Memory allocated is shared by individual
storage area of location. members of union.
4. The address of each member will be in ascending 4. The address is same for all the members of a
order This indicates that memory for each member will union. This indicates that every member begins at
start at different offset values. the same offset value.
5 Altering(Changing) the value of a member will not 5. Altering the value of any of the member will
affect other members of the structure. alter(change) other member values.
6.Advantage: Individual member can be accessed at a 6.Disadvantage: Only one member can be
time accessed at a time.
7. Advantage: Several members of a structure can 7. Disadvantage: Only the first member of a union
initialize at once. can be initialized.
8.Disadvantage: If all members are not used at a time , 8. Advantage: Common Memory is shared by
Waste of memory individual members of union, So, Save memory .
9 Example : 9 Example :
struct TV union TV
{ {
int cost; int cost;
float price; float price;
}; };
struct TV bpl; union TV bpl;
06 bytes of memory is allocated for the variable bpl. 4 bytes of memory is allocated for the variable bpl,

-----------------------------------------------------------------------------------------------------------------
111
V.S.M College (Autonomous) Dept. of Computer Science

Enumerated data type:


An enumeration is a user defined data type with values ranging over a finite set of identifiers called
enumeration constants. Enumerations are convenient way to associate constant integers with meaningful
names.
Syntax:
enum identifier { value1, value2,……. valueN};
The “identifier” is a user defined enumerated data type, which can be used to declare variables that can
have one of the values enclosed with in braces. After this definition, we can declare variables as follows:
enum identifier var1, var2,…. varN;
The enumerated variables var1, var2,… varN can only have one of the values value1, value2,…valueN.
Example:
enum day {Monday,Tuesday, … Sunday};
enum day weekstart, weekend;
weekstart=Monday;
weekend=Friday;
The compiler automatically assigns integer digits start with 0 to all the enumeration constants.
i.e., enum day {Monday=0,Tuesday=1, Wednesday=2 … Sunday=6};
We can assign values explicitly to the enumeration constants, For example:
enum day {Monday=1,Tuesday, Wednesday … Sunday};
Here, the constant Monday is assigned the value of 1. The remaining constants are assigned values that
increase successively by 1. The definition and declaration of enumerated variables can be combined in one
statement. Example: enum day {Monday=1,Tuesday, Wednesday … Sunday} weekstart, weekend;
------------------------------------------------------------------------------------------------------------------------------------------
*****

112
V.S.M College (Autonomous) Dept. of Computer Science

UNIT –V
FILES
File: A file is a collection of data stored on secondary storage device such as hard disk.
Types of Data Files:
There are two types of files. 1) Sequential Files 2). Random Access Files
1) Sequential Files: In this type, The data (records) can be stored and accessed sequentiallyIt takes
more time.
2) Random Access Files: In this type, The data (records) can be stored, accessed, and modified
randomly. It takes very less time as compared to sequential file.
Categories of Files:
There are two categories of files: 1) Text files 2) Binary files.
1) Text Files:
If the file is specified as text type, The file I/O functions interpret the contents of the file.
Text files contain lines (or records) of text and each of these has an end-of-line marker
automatically appended to the end of line, whenever you indicate that you have reached the end of
a line (EOLN). For Example, Even though the value 12345 is an integer, it requires 5 Bytes of
memory.
2) Binary Files:
A binary file can contain text. But, the text is not considered to be broken up into a number
of lines by the occurrence of end-of-line(EOLN) markers. It saves memory because every data is
converted into binary stream. For example, the value 12345 is an integer, and it is converted into
binary stream, Therefore it requires 2 Bytes of memory only .
Advantages of (Data) Files:
Data Files contains the following advantages:
1. Permanent Storage:
2. Data Security
3. Access Time
4. Editing and Communication
5. Order of Data
------------------------------------------------------------------------------------------------------------------------------------
File operations:
1. Declaring a file pointer variable
2. Open the file
3. Process the file
4. Close the file
Data structure of a file is defined as FILE in the standard library. All files must be declared as type
FILE before they are used.
1.Declaring a file pointer variable:
We should declare a file pointer variable to open a file as follows:
Syntax:
FILE *filepointer;
Example:
FILE *fp; where fp is a file pointer.

113
V.S.M College (Autonomous) Dept. of Computer Science

File handling functions in C language:


The following functions are used to perform operations on file The below functions are
defined in stdio.h header file.
1. fopen() : It creates new file to use. It opens an existing file to use.
2. fclose(): It closes a file which is opened for use.
3. fgetc(): It reads a character from a file.
4. fscanf(): It reads formatted data(set of values) from a file
5. fread(): It reads structure(object) of data from a file
6. fgets(): It reads an entire line of data from a file.
7. fputs(): It writes an entire line of data to a file.
8. fputc(): It writes(stores) a character to a file
9. fprintf(): It writes formatted data(set of values) to a file
10. fwrite() : It writes structure(object) of data to a file
11. fseek() : It sets a position of the file pointer to a desired point to a file.
12. ftell(): It returns the current position of the file pointer.
13. rewind():It sets a position of the file pointer to the beginning of a file.
14. ferror(): It reports the status of a file. If an error is detected in a file, then it returns non-
zero
value(true) , otherwise It returns zero value(false).
15. feof() : It determines that whether the file pointer is reached to the end of the file or
not. If a
file pointer is reached to the end of the file , then it returns non-zero value ,
other wise It returns zero value.
2. Opening a file using fopen() function:
To create a new file, or to open an existing file , we use fopen() function.
Syntax: FILE * filepointer;
FILE *fopen(const char *filename, const char *mode);
filepointer = fopen( “filename”, “mode”);
The first statement declares a variable fp as a pointer to the FILE The second statement opens a file
named filename with a mode , and assigns an address of physical file to a file pointer. The second
argument specifies purpose of the file with mode.
A mode can be one of the following:
r --- It opens a file for reading only.
w---- It opens a file for writing only.
a ---- It opens a file for appending(adding) the data to a file
r+: The existing file is opened to the beginning for both reading and writing
w+ : Same as “w “ mode except both for reading and writing
a+ : Same as “a” mode except both for reading and writing
Binary modes of binary files:
rb --- It opens a binary file for reading only.
wb---- It opens a binary file for writing only.
ab ---- It opens a binary file for appending(adding) the data to a file
r+b --- It opens a pre-existing binary file for reading and writing . (read+write)
w+b --- It creates binary file for writing and reading . (write+ read)
a+b ---- It opens a pre-existing binary file or creates a new file for appending and
writing . (append+write).
Examples:
FILE *fp1, *fp2;
114
V.S.M College (Autonomous) Dept. of Computer Science

fp1 = fopen(“student.dat”, “w”);


fp2 = fopen(“results.dat”, “r”);
The file student.dat is opened for writing purpose. The file results.dat is opened for reading
purpose
3. Input/Output operations on files:
fputc() and fgetc() functions:
fputc() function writes a character to the file.
Syntax:
fputc(ch,fp);
where, ch is a character type variable. fp is a file pointer.
fgetc() function reads a character from the file.
Syntax:
ch =fgetc(fp);
where, ch is a character type variable. fp is a file pointer.
The file pointer moves by one character position for every operation of fputc() and fgetc().
fprintf() and fscanf() functions:
fprintf() function writes a group of mixed data (formatted data)simultaneously to the file.
Syntax:
fprintf(fp , ”control string” , List);
where, fp is a file pointer. Control string contains output specifications for the items in the List. The
List may include variables, constants, strings.
Example:
fprintf(fp., “%d %s %f “, eno, ename, esal);
Where, eno is an int variable. ename is an array variable of type char, esal is float variable.
fscanf() function reads a group of mixed data (formatted data)simultaneously from the file.
Syntax:
fscanf(fp , ”control string” , List);
where, fp is a file pointer. Control string contains input specifications for the items in the List. The
List may include variables, constants, strings.
Example:
fscanf(fp., “%d %s %f “, &eno, &ename, &esal);
Where, eno is an int variable. ename is an array variable of type char, esal is float variable.
fwrite() and fread() functions:
fwrite() function writes block of structured data (equal-sized data) to the file.
Syntax:
fwrite( ptr, size, n, fp);
where, “fp” is a file pointer. “ptr” contains data to be written to a file . “size” indicates length of
each block of data . “n” indicates the number of data blocks to be appended.
Example:
fwrite(student., sizeof(student), 1, fp);
Where, the structure of student data is written to a file.
fread() function reads block of structured data (equal-sized data) from the file.
Syntax:
fread( &ptr, size, n, fp);
where, “fp” is a file pointer. “ptr” contains data to be read from a file . “size” indicates length of
each block of data . “n” indicates the number of data blocks to be read.
Example:
fread(&student., sizeof(student), 1, fp);
115
V.S.M College (Autonomous) Dept. of Computer Science

Where, the structure of student data is read from a file.


fgets() and fputs() functions
These are useful for reading and writing entire lines of data to/from a file. If buffer is a pointer to a
character array and n is the maximum number of characters to be stored, then
fgets (buffer, n, fp);
will read an entire line of text (max chars = n) into buffer until the newline character or n=max,
whichever occurs first. The function places a NULL character after the last character in the buffer.
The function will be equal to a NULL if no more data exists.
fputs (buffer, fp);
writes the characters in buffer until a NULL is found. The NULL character is not written to the
output_file fp.
/* Write a program to create a file */
#include<stdio.h>
#include<string.h>
main()
{
FILE *fp;
char x, fn[20];
clrscr();
printf(“\n Enter the filename:”);
scanf(“%s”,&fn);
fp=fopen(fn,”w”);
printf(“\n Enter contents of a file, to use ctrl+z to close a file”);
while((x=getchar)!=EOF)
{
fputc(x,fp);
}
printf(“\n One file created”);
fclose(fp);
getch();
}
Output
Enter the filename: Letter.txt
Enter contents of a file, to use ctrl+z to close a file
Hello how are you?
^z
One file created
/* write a program to read a file character by character, and display it simultaneously on the
screen */
#include<stdio.h>
#include<string.h>
main()
{
FILE *fp;
char ch, fn[20];
clrscr();
printf(“\n Enter the filename:”);
scanf(“%s”,&fn);
116
V.S.M College (Autonomous) Dept. of Computer Science

fp=fopen(fn,”r”);
if(fp==NULL)
{
printf(“\n Error opening the file”);
exit(1);
}
ch=fgetc(fp);
while(ch!=EOF)
{
putchar(ch);
ch=fgetc(fp);
}
fclose(fp);
}
Output
Run 1:
Enter the filename: Letter.txt
Hello how are you?
Run 2:
Enter the filename: college.doc
Error opening the file
4. Closing a file using fclose() function:
A file must be closed as soon as all operations on it have been completed. To close a file , We use
fclose() function:
Syntax:
fclose(filepointer);
To close all opened files , we use fcloseall(); function .
Example:
FILE *fp;
fp = fopen(“student.dat”, “w”);
------
------
fclose(fp);
Once a file is closed, its file pointer can be reused for another file.
Special functions:
Processing of Random access files : We can manipulate data of a file randomly by using rewind(),
fseek() and ftell() functions.
a) fseek() function: It is used to move a file pointer position to a desired location within the file.
Syntax:
int fseek(FILE *stream, long offset, int whence);
fseek(fp, offset, position);
Where, fp is a file pointer, offset is a number or a variable of type long, and position is an integer
number. The offset specifies the number of bytes to be moved from the location specified by
position. the position takes one of three values:
Value Meaning constant
0 Beginning of file SEEK_SET
1 Current Position SEEK_CUR

117
V.S.M College (Autonomous) Dept. of Computer Science

2 End of File (EOF) SEEK_END


Examples:
fseek(fp.0L,0); File pointer will go to beginning of a file
fseek(fp.0L,SEEK_SET); File pointer will go to beginning of a file
fseek(fp, -m,2); File pointer will go backward by m bytes from end of the file.
b) rewind() function: It takes a file pointer and reset the position to the start of the file.
Syntax:
rewind(fp);
Now, file pointer is moved to beginning of the file.
c) ftell() function: It returns the current position the file pointer.
Syntax:
num = ftell(fp); where, num is an long type variable
Example:
rewind(fp);
num= ftell(fp); Now, the num variable contains a value 0.
Error Handling Functions feof() and ferror():
Sometimes, an error may be occurred during I/O operations on file. Errors may be:
1. Trying to read beyond end of file mark.
2. Device overflow.
3. Trying to use a file, that has not been opened.
4. Opening a file with an invalid filename.
5. Attempting to write to a write-protected file.
To handle these errors, We use feof() and ferror() functions.
a) feof() function can be used to test for an end of file condition. If the file pointer is reached to the
end of the file, then It returns a non-zero integer value, otherwise it returns zero.
Example:
if( feof(fp))
printf(“ End of file “);
b) ferror() function reports the status of the file indicated. If an error has been detected up to that
point during processing, then it returns a non-zero integer value, otherwise it returns zero .
Example:
if( ferror(fp) != 0)
printf(“ An error has occurred during file processing”);
If the file cannot be opened for some reasons, then the fopen() function returns a NULL pointer.
Example:
FILE *fp;
fp= fopen( “student.dat”, “w”);
if( fp ==NULL)
printf(“ File could not be opened”);
------------------------------------------------------------------------------------------------------------------------------------

118
V.S.M College (Autonomous) Dept. of Computer Science

DATA STRUCTURES
Data structure is a crucial part of data management, to define a particular way of storing and
organizing data in a computer so that it can be used efficiently.
Data structures are classified into two types:
1. Linear data structure: If the elements are stored sequentially, then it is a linear data structure.
Example: arrays, stacks, queues and linked lists.
2. Non Linear data structure: If the elements of a data structure are not stored in sequential order,
then it is a non-linear data structure.
Example: Trees, graphs
Stacks: A stack is a linear data structure that can be implemented either using an array or a linked
list. The elements in a stack are added and removed only from one end, which is called top. Hence,
a stack is called a last in, first out (LIFO) data structure as the element that was inserted last is the
first one to be taken out.
Array Representation of stacks:
In computer memory, stacks can be represented as a linear array. Every stack has a variable TOP
associated with it. TOP is used to store the address of the topmost element of the stack. It is this
position from where the element will be added or deleted. There is another variable, MAX, which
will be used to store the maximum number of elements that the stack can hold.
If TOP=NULL, then it indicates that the stack is empty, and if TOP=MAX-1, then the stack is full.
Operations on stack
Stack basic operations are: push and pop. The push operation adds an element to the top of the
stack, and the pop operation removes an element from the top of the stack. The peep operation
returns the value of the topmost element of the stack.
Push operation is used to insert an element into the stack. The new element is added at the
topmost position of the stack. However, before inserting the value, we must first check if
TOP=MAX-1, as it would mean that the stack is full. If a stack that is already full, an overflow
message is printed.
Algorithm to push an element into the stack:
Step 1: IF TOP=MAX-1, then PRINT “OVERFLOW”
[END OF IF]
Step 2: SET TOP=TOP+1
Step 3: SET STACK [TOP] = VALUE
Step 4: END
Example:

1 2 3 4 5
0 1 2 3 Top= 4 5 6 7 8 9

To insert an element with value 6, we will first check if TOP = MAX-1. If the condition is false, then
we will increment the value of TOP and store the new element at the position given by stack [TOP].

1 2 3 4 5 6
0 1 2 3 4 Top=5 6 7 8 9

119
V.S.M College (Autonomous) Dept. of Computer Science

Pop operation is used to delete the topmost element from the stack. However, before deleting the
value, we must first check if TOP=NULL, that the stack is empty, no deletions can be done and
display UNDERFLOW message.
Algorithm to pop an element from the stack:
Step 1: IF TOP=NULL then PRINT “UNDERFLOW”
[END OF IF]
Step 2: SET VAL=STACK [TOP]
Step 3: SET TOP = TOP-1
Step 4: END
Example:
1 2 3 4 5
0 1 2 3 Top= 4 5 6 7 8 9

To delete the topmost element, we will first check if TOP=NULL. If the condition is false, then we
will decrement the value of the top. Thus, the updated stack is follows:

1 2 3 4
0 1 2 Top= 3 4 5 6 7 8 9

/* Write a program to perform push and pop operations on a stack array */


#include<stdio.h>
#include<conio.h>
#define MAX 10
int st[MAX], top=-1;
void push(int st[], int val);
int pop(int st[]);
void display(int st[]);
main()
{
int val, option;
clrscr();
do
{
printf(“\n ************MAIN MENU************”);
printf(“\n 1. PUSH”);
printf(“\n 2. POP”);
printf(“\n 3. DISPLAY”);
printf(“\n 4. EXIT”);
printf(“\n **********************************”);
printf(“\n Enter your choice”);
scanf(“%d”,&option);
switch(option)
{
120
V.S.M College (Autonomous) Dept. of Computer Science

case 1: printf(“\n Enter the number to be pushed on the stack: “);


scanf(“%d”, &val);
push(st, val);
break;

case 2: val = pop(st);


printf( “\n The value deleted from the stack is: %d”, val);
break;
case 3: display(st);
break;
}
}while(option!=4);
getch();
return 0;
}
void push(int st[], int val)
{
if(top==MAX -1)
{
printf(“\n STACK OVERFLOW”);
}
else
{
top++;
st[top]=val;
}
}
int pop(int st[])
{
int val;
if(top==-1)
{
printf(“\n STACK UNDERFLOW”);
return -1;
}
else
{
val=st[top];
top--;
return val;
}
}
121
V.S.M College (Autonomous) Dept. of Computer Science

void display(int st[])


{
int i;
if(top==-1)
printf(“\n STACK IS EMPTY”);
else
{
for(i=top; i>=0; i--)
printf(“\n %d”, st[i]);
}
}
OUTPUT
************MAIN MENU************
1. PUSH
2. POP
3. DISPLAY
4. EXIT
**********************************
Enter your option: 1
Enter the number to be pushed on the stack: 1
************MAIN MENU************
1. PUSH
2. POP
3. DISPLAY
4. EXIT
**********************************
Enter your option: 1
Enter the number to be pushed on the stack: 2
************MAIN MENU************
1. PUSH
2. POP
3. DISPLAY
4. EXIT
**********************************
Enter your option: 3
2
1
------------------------------------------------------------------------------------------------------------------------------------
Queue: A queue is a linear data structure that stores their elements in an ordered manner. A
queue is a first-in, first-out (FIFO) data structure, in which the element that was inserted first is the
first one to be taken out. The elements in a queue are added at one end called the rear, and
removed from the other end called the front.
122
V.S.M College (Autonomous) Dept. of Computer Science

Operations on Queue:
Queues can be easily represented using linear arrays. Every queue will have front and rear variables
that will point to the position from where deletions and insertions, respectively, can be performed.
An example of a queue
12 9 7 18 4 36
0 1 2 3 4 5 6 7 8 9

Algorithm to insert an element in a queue:


Step 1: IF REAR=MAX-1, then;
write OVERFLOW
[END OF IF]
Step 2: IF FRONT=-1 and REAR=-1, then;
SET FRONT=REAR=0
ELSE
SET REAR=REAR+1
[END OF IF]
Step 3: SET QUEUE [REAR] =NUM
Step 4: Exit

Here, front = 0 and rear = 5. If we want to add one more value in the list, another element with
value 45, then rear would be incremented by 1 and the value would be stored at the position
pointed by the rear. Now, front=0 and rear = 6. Every time a new element has to be added, this
process will be repeated. Before inserting a new element in the queue, we must check for overflow
conditions.
Queue after insertion of a new element
12 9 7 18 4 36 45
0 1 2 3 4 5 6 7 8 9

Algorithm to delete an element from a queue:


Step 1: IF Front=-1 OR FRONT > REAR, then;
write UNDERFLOW
ELSE
SET FRONT=FRONT+1
SET VAL=QUEUE [FRONT]
[END OF IF]
Step 2: Exit
If we want to delete an element from the queue, then the value of front will be incremented
Deletions are done from only this end of the queue.
Queue after deletion of an element

9 7 18 4 36 45
0 1 2 3 4 5 6 7 8 9

/* Write a program to implement a linear queue. */


#include<stdio.h>

123
V.S.M College (Autonomous) Dept. of Computer Science

#include<conio.h>
#define MAX 10
int queue[MAX];
int front=-1, rear=-1;
void insert(void);
int delete_element(void);
void display(void);
main()
{
int val, option;
clrscr();
do
{
printf(“\n ************MAIN MENU************”);
printf(“\n 1. Insert an element”);
printf(“\n 2. Delete an element”);
printf(“\n 3. Display the queue”);
printf(“\n 4. EXIT”);
printf(“\n **********************************”);
printf(“\n Enter your choice”);
scanf(“%d”,&option);
switch(option)
{
case 1: insert();
break;
case 2: val = delete_element();
printf( “\n The value deleted from the stack is: %d”, val);
break;
case 3: display();
break;
}
}while(option!=4);
getch();
return 0;
}
void insert()
{
int num;
printf(“\n Enter the number to be inserted in the queue:”);
scanf(“%d”, &num);
if(rear==MAX-1)
printf(“\n OVERFLOW”);
124
V.S.M College (Autonomous) Dept. of Computer Science

if(front==-1 && rear==-1)


front=rear=0;
else
rear++;
queue[rear]=num;
}
int delete_element()
{
int val;
if(front==-1 || front>rear)
{
printf(“\n UNDERFLOW”);
return -1;
}
else
{
val=queue[front];
front++;
return(val);
}
}
int peek()
{
return queue[front];
}
void display()
{
int i;
printf(“\n”);
for(i=front; i<=rear; i++)
{
printf(“\t %d”, queue[i]);
}
}
Output
************MAIN MENU************
1. Insert an element
2. Delete an element
3. Display the queue
4. EXIT
**********************************
Enter your option: 1
125
V.S.M College (Autonomous) Dept. of Computer Science

Enter the number to be inserted in the queue: 1


************MAIN MENU************
1. Insert an element
2. Delete an element
3. Display the queue
4. EXIT
**********************************
Enter your option: 1
Enter the number to be inserted in the queue: 2
************MAIN MENU************
1. Insert an element
2. Delete an element
3. Display the queue
4. EXIT
**********************************
Enter your option: 3
1 2
**** (THE END)

126

You might also like