Programming in C (28!02!2017)
Programming in C (28!02!2017)
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.
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.
Solution:
2
V.S.M College (Autonomous) Dept. of Computer Science
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”
3
V.S.M College (Autonomous) Dept. of Computer Science
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.
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.
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.
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.
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 disadvantages
8
V.S.M College (Autonomous) Dept. of Computer Science
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 disadvantages
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.
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 disadvantages
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.
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.
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.
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.
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
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:
14
V.S.M College (Autonomous) Dept. of Computer Science
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: +, /,-,*)
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.
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
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 : ?
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;
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.)
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 ').
21
V.S.M College (Autonomous) Dept. of Computer Science
22
V.S.M College (Autonomous) Dept. of Computer Science
1. Formatted Functions
2. Unformatted Functions.
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.
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:
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()
clrscr();
printf( “Enter character type data, integer type data and float type data from keyboard \n”);
scanf(“%c%d%f”, &a,&b,&c);
getch();
Output:
Enter character type data, integer type data and float type data from keyboard
A 50 10.55
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
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.
Example:
In the above statement, character type data, integer type data and float type data of three variables
a,b,and c are displayed respectively.
#include<stdio.h>
#include<conio.h>
void main()
clrscr();
printf(“Welcome”);
getch();
Output:
Welcome
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.
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.
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.
#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
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
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().
#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.
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 :
27
V.S.M College (Autonomous) Dept. of Computer Science
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.
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.
======================================================================
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:
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)
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
#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
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 (!).
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.
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:
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”.
33
V.S.M College (Autonomous) Dept. of Computer Science
Output: 20 19 18 17 16 15 14 13 12 11
34
V.S.M College (Autonomous) Dept. of Computer Science
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
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
36
V.S.M College (Autonomous) Dept. of Computer Science
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
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
Branching Looping
d) nested if 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
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
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.
True False
test
condition
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
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-x
{
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.
………………………………………
………………………………………
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
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
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
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;
53
V.S.M College (Autonomous) Dept. of Computer Science
Initialization
False
test condition
Exit
True
Body of loop
Increment/decrement
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 */
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.
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);
{
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:
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:
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:
58
V.S.M College (Autonomous) Dept. of Computer Science
#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
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:
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
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
#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:
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.
========================================================================
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
Output:
Enter how many numbers to be generated 10
The Fibonacci sequences are
0 1 1 2 3 5 8 13 21 34
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
RECURSION ITERATION
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
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
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
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
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();
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
N E W Y \0 \0 \0 \0 \0 \0 \0
84
V.S.M College (Autonomous) Dept. of Computer Science
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
87
V.S.M College (Autonomous) Dept. of Computer Science
88
V.S.M College (Autonomous) Dept. of Computer Science
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
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
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
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
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 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
102
V.S.M College (Autonomous) Dept. of Computer Science
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
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
{
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
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
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
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
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
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
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
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
9 7 18 4 36 45
0 1 2 3 4 5 6 7 8 9
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
126