Computer Programming Notes
Computer Programming Notes
COMPUTER PROGRAMMING
LECTURE NOTES
ld
or
W
TU
JN
ll
A
UNIT-I
INTRODUCTION TO COMPUTERS
COMPUTER SYSTEMS
ld
<A Computer is an electronic device that stores, manipulates and retrieves the data.=
We can also refer computer computes the information supplied to it and generates data.
A System is a group of several objects with a process. For Example: Educational System
or
involves teacher, students (objects). Teacher teaches subject to students i.e., teaching (process).
Similarly a computer system can have objects and process.
The following are the objects of computer System
a) User ( A person who uses the computer)
W
b) Hardware
c) Software
Hardware: Hardware of a computer system can be referred as anything which we can touch and
feel. Example : Keyboard and Mouse.
The hardware of a computer system can be classified as
TU
Input Devices(I/P)
Processing Devices (CPU)
Output Devices(O/P)
MU
CPU
INPUT OUTPUT
CU: Every Operation such as storing , computing and retrieving the data should be governed by
the control unit.
ld
Primary memory: The following are the types of memoruies which are treated as primary
ROM: It represents Read Only Memory that stores data and instructions even when the computer
is turned off. The Contents in the ROM can9t be modified once if they are written . It is used to
or
store the BIOS information.
RAM: It represents Random Access Memory that stores data and instructions when the computer
is turned on. The contents in the RAM can be modified any no. of times by instructions. It is
used to store the programs under execution.
W
Cache memory: It is used to store the data and instructions referred by processor.
Secondary Memory: The following are the different kinds of memories
Magnetic Storage: The Magnetic Storage devices store information that can be read, erased and
rewritten a number of times.
Example: Floppy Disks, Hard Disks, Magnetic Tapes
TU
Optical Storage: The optical storage devices that use laser beams to read and write stored data.
Example: CD(Compact Disk),DVD(Digital Versatile Disk)
COMPUTER SOFTWARE
JN
Software of a computer system can be referred as anything which we can feel and see.
Example: Windows, icons
Computer software is divided in to two broad categories: system software and application
software .System software manages the computer resources .It provides the interface between the
hardware and the users. Application software, on the other hand is directly responsible for
helping users solve their problems.
ll
System Software
A
System software consists of programs that manage the hardware resources of a computer and
perform required information processing tasks. These programs are divided into three classes:
the operating system, system support, and system development.
The operating system provides services such as a user interface, file and database access, and
interfaces to communication systems such as Internet protocols. The primary purpose of this
software is to keep the system operating in an efficient manner while allowing the users access to
the system.
ld
System support software provides system utilities and other operating services. Examples of
system utilities are sort programs and disk format programs. Operating services consists of
programs that provide performance statistics for the operational staff and security monitors to
or
protect the system and data.
The last system software category, system development software, includes the language
translators that convert programs into machine language for execution ,debugging tools to ensure
that the programs are error free and computer 3assisted software engineering(CASE) systems.
W
Application software
Application software is broken in to two classes: general-purpose software and application 3
specific software. General purpose software is purchased from a software developer and can be
used for more than one application. Examples of general purpose software include word
TU
processors, database management systems ,and computer aided design systems. They are labeled
general purpose because they can solve a variety of user computing problems.
Application –specific software can be used only for its intended purpose.
A general ledger system used by accountants and a material requirements planning system used
JN
software layer. The system software provides the direct interaction with the hard ware. The
opening at the bottom of the figure is the path followed by the user who interacts directly with
A
ld
or
COMPUTING ENVIRONMENTS
The word 8compute9 is used to refer to the process of converting information to data. The
advent of several new kinds of computers created a need to have different computing
W
environments.
The following are the different kinds of computing environments available
1. Personal Computing Environment
2. Time Sharing Environment
3. Client/Server Environment
TU
4. Distributed Computing Environment
Personal Computing Environment
In 1971, Marcian E. Hoff, working for INTEL combined the basic elements of the central
processing unit into the microprocessor. If we are using a personal computer then all the
JN
computer hardware components are tied together. This kind of computing is used to satisfy the
needs of a single user, who uses the computer for the personal tasks.
Ex: Personal Computer
ll
A
Time-Sharing Environment
The concept of time sharing computing is to share the processing of the computer basing
on the criteria time. In this environment all the computing must be done by the central computer.
The complete processing is done by the central computer. The computer which ask for
processing are only dumb terminals.
ld
or
W
Client/Server Environment
A Client/Server Computing involves the processing between two machines. A client
Machine is the one which requests processing. Server Machine is the one which offers the
processing. Hence the client is Capable enough to do processing. A portion of processing is
done by client and the core(important) processing is done by Server.
TU
JN
Distributed Computing
A distributed computing environment provides a seamless integration of computing
functions between different servers and clients. A client not just a requestor for processing the
ll
information from the server. The client also has the capability to process information. All the
machines Clients/Servers share the processing task.
A
ld
Example: Ebay on Internet
or
COMPUTER LANGUAGES
To write a program (tells what to do) for a computer, we must use a computer language.
Over the years computer languages have evolved from machine languages to natural languages.
W
The following is the summary of computer languages
19409s -- Machine Languages
19509s -- Symbolic Languages
19609s -- High Level Languages
TU
Machine Language
In the earliest days of computers, the only programming languages available were
machine languages. Each computer has its own machine language which is made of streams of
09s and 19s. The instructions in machine language must be in streams of 09s and 19s. This is also
referred as binary digits. These are so named as the machine can directly understood the
JN
programs
Advantages:
1) High speed execution
2) The computer can understood instructions immediately
3) No translation is needed.
Disadvantages:
ll
1) Machine dependent
2) Programming is very difficult
A
3) Difficult to understand
4) Difficult to write bug free programs
5) Difficult to isolate an error
ld
5 ÿ 0101
--- ---------------
or
Symbolic Languages (or) Assembly Language
In the early 19509s Admiral Grace Hopper, a mathematician and naval officer, developed
the concept of a special computer program that would convert programs into machine language.
These early programming languages simply mirrored the machine languages using symbols or
W
mnemonics to represent the various language instructions. These languages were known as
symbolic languages. Because a computer does not understand symbolic language it must be
translated into the machine language. A special program called an Assembler translates
symbolic code into the machine language. Hence they are called as Assembly language.
Advantages:
TU
1) Easy to understand and use
2) Easy to modify and isolate error
3) High efficiency
4) More control on hardware
JN
Disadvantages:
1) Machine Dependent Language
2) Requires translator
3) Difficult to learn and write programs
4) Slow development time
5) Less efficient
ll
Example:
2 PUSH 2,A
A
3 PUSH 3,B
+ ADD A,B
5 PRINT C
High-Level Languages
The symbolic languages greatly improved programming efficiency they still
required programmers to concentrate on the hardware that they were using working with
symbolic languages was also very tedious because each machine instruction had to be
ld
individually coded. The desire to improve programmer efficiency and to change the focus from
the computer to the problems being solved led to the development of high-level languages.
High-level languages are portable to many different computer allowing the programmer
or
to concentrate on the application problem at hand rather than the intricacies of the computer.
C A systems implementation Language
C++ C with object oriented enhancements
JAVA Object oriented language for internet and general applications using basic C syntax
W
Advantages:
1) Easy to write and understand
2) Easy to isolate an error
TU
3) Machine independent language
4) Easy to maintain
5) Better readability
6) Low Development cost
7) Easier to document
JN
8) Portable
Disadvantages:
1) Needs translator
2) Requires high execution time
3) Poor control on hardware
4) Less efficient
ll
Example: C language
#include<stdio.h>
A
void main()
{
int a,b,c;
scanf("%d%d%",&a,&b);
c=a+b;
printf("%d",c);
}
ld
Feature Machine Assembly High Level
Form 09s and 19s Mnemonic codes Normal English
Machine Dependent Dependent Dependent Independent
or
Translator Not Needed Needed(Assembler) Needed(Compiler)
Execution Time Less Less High
Languages Only one Different Manufactgurers Different Languages
Nature Difficult Difficult Easy
W
Memory Space Less Less More
Language Translators
TU
These are the programs which are used for converting the programs in one language into
machine language instructions, so that they can be excuted by the computer.
10
The executable program is stored in a disk for The executable program is generated in RAM
future use or to run it in another computer and the interpreter is required for each run of
the program
The compiled programs run faster The Interpreted programs run slower
ld
Most of the Languages use compiler A very few languages use interpreters.
or
CREATING AND RUNNING PROGRAMS
The procedure for turning a program written in C into machine Language. The process is
presented in a straightforward, linear fashion but you shuld recognize that these steps are
repeated many times during development to correct errors and make improvements to the code.
W
The following are the four steps in this process
1) Writing and Editing the program
2) Compiling the program
3) Linking the program with the required modules
TU
4) Executing the program
JN
ll
A
11
TEXT EDITOR
ld
COMPILER
or
Library LINKER
RUNNER
OUTPUT
W
TU
Sl. No. Phase Name of Code Tools File Extension
1 TextEditor Source Code C Compilers .C
Edit,
Notepad Etc..,
JN
us enter, change and store character data. Once we write the program in the text editor we save it
using a filename stored with an extension of .C. This file is referred as source code file.
12
Compiling Programs
The code in a source file stored on the disk must be translated into machine language.
ld
This is the job of the compiler. The Compiler is a computer program that translates the source
code written in a high-level language into the corresponding object code of the low-level
language. This translation process is called compilation. The entire high level program is
or
converted into the executable machine code file. The Compiler which executes C programs is
called as C Compiler. Example Turbo C, Borland C, GC etc.,
The C Compiler is actually two separate programs:
The Preprocessor
W
The Translator
The Preprocessor reads the source code and prepares it for the translator. While preparing the
code, it scans for special instructions known as preprocessor commands. These commands tell
the preprocessor to look for special code libraries. The result of preprocessing is called the
translation unit.
TU
After the preprocessor has prepared the code for compilation, the translator does the
actual work of converting the program into machine language. The translator reads the
translation unit and writes the resulting object module to a file that can then be combined with
other precompiled units to form the final program. An object module is the code in the machine
JN
language.
Linking Programs
The Linker assembles all functions, the program9s functions and system9s functions into
one executable program.
Executing Programs
ll
To execute a program we use an operating system command, such as run, to load the
program into primary memory and execute it. Getting the program into memory is the function
A
of an operating system program known as the loader. It locates the executable program and
reads it into memory. When everything is loaded the program takes control and it begin
execution.
13
ALGORITHM
Algorithm is a finite sequence of instructions, each of which has a clear meaning and can be
performed with a finite amount of effort in a finite length of time. No matter what the input
ld
values may be, an algorithm terminates after executing a finite number of instructions.
We represent an algorithm using a pseudo language that is a combination of the constructs of a
programming language together with informal English statements.
or
The ordered set of instructions required to solve a problem is known as an algorithm.
The characteristics of a good algorithm are:
Precision 3 the steps are precisely stated (defined).
Uniqueness 3 results of each step are uniquely defined and only depend on the input
W
and the result of the preceding steps.
Finiteness 3 the algorithm stops after a finite number of instructions are executed.
Input 3 the algorithm receives input.
Output 3 the algorithm produces output.
Generality 3 the algorithm applies to a set of inputs.
TU
Example
Q. Write a algorithem to find out number is odd or even?
Ans.
step 1 : start
step 2 : input number
JN
FLOWCHART
Flowchart is a diagrammatic representation of an algorithm. Flowchart is very helpful in writing
A
14
ld
Symbol Purpose Description
or
Flow line
symbols.
W
Input/Output Used for input and output operation.
15
ld
or
W
Draw flowchart to find the largest among three different numbers entered by user.
TU
JN
ll
A
INTRODUCTION TO C LANGUAGE
C is a general-purpose high level language that was originally developed by Dennis Ritchie for
the Unix operating system. It was first implemented on the Digital Eqquipment Corporation
PDP-11 computer in 1972.
16
The Unix operating system and virtually all Unix applications are written in the C language. C
has now become a widely used professional language for various reasons.
Easy to learn
Structured language
ld
It produces efficient programs.
It can handle low-level activities.
It can be compiled on a variety of computers.
or
Facts about C
C was invented to write an operating system called UNIX.
C is a successor of B language which was introduced around 1970
The language was formalized in 1988 by the American National Standard Institue
W
(ANSI).
By 1973 UNIX OS almost totally written in C.
Today C is the most widely used System Programming Language.
Most of the state of the art software have been implemented using C
Why to use C?
TU
C was initially used for system development work, in particular the programs that make-up the
operating system. C was adoped as a system development language because it produces code that
runs nearly as fast as code written in assembly language. Some examples of the use of C might
be:
JN
Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
ll
Modern Programs
Data Bases
A
Language Interpreters
Utilities
C Program File
17
All the C programs are writen into text files with extension ".c" for example hello.c. You can use
"vi" editor to write your C program into a file.
ld
HISTORY TO C LANGUAGE
C is a general-purpose language which has been closely associated with the UNIX operating
system for which it was developed - since the system and most of the programs that run it are
or
written in C.
Many of the important ideas of C stem from the language BCPL, developed by Martin Richards.
The influence of BCPL on C proceeded indirectly through the language B, which was written by
Ken Thompson in 1970 at Bell Labs, for the first UNIX system on a DEC PDP-
W
7. BCPL and B are "type less" languages whereas C provides a variety of data types.
In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the publication of The C Programming
Language by Kernighan & Ritchie caused a revolution in the computing world.
In 1983, the American National Standards Institute (ANSI) established a committee to provide a
modern, comprehensive definition of C. The resulting definition, the ANSI standard, or "ANSI
TU
C", was completed late 1988.
18
ld
from the system library such as using the #include directive.
3. Definition section: The definition section defines all symbolic constants such using
the #define directive.
or
4. Global declaration section: There are some variables that are used in more than one
function. Such variables are called global variables and are declared in the global
declaration section that is outside of all the functions. This section also declares all
the user-defined functions.
W
5. main () function section: Every C program must have one main function section. This
section contains two parts; declaration part and executable part
1. Declaration part: The declaration part declares all the variables used in the
executable part.
2. Executable part: There is at least one statement in the executable part. These two
TU
parts must appear between the opening and closing braces. The program
execution begins at the opening brace and ends at the closing brace. The closing
brace of the main function is the logical end of the program. All statements in the
declaration and executable part end with a semicolon.
JN
19
ld
or
W
The C Compilation Model
The Preprocessor
The Preprocessor accepts source code as input and is responsible for
removing comments
TU
Interpreting special preprocessor directives denoted by #.
For example
#include -- includes contents of a named file. Files usually called header files. e.g
o #include <math.h> -- standard library maths file.
o #include <stdio.h> -- standard library I/O file
JN
Assembler
The assembler creates object code. On a UNIX system you may see files with a .o suffix
(.OBJ on MSDOS) to indicate object code files.
A
Link Editor
If a source file references library functions or functions defined in other source files the link
editor combines these functions (with main()) to create an executable file.
20
C TOKENS
C tokens are the basic buildings blocks in C language which are constructed together to write a C
program.
ld
Each and every smallest individual unit in a C program is known as C tokens.
C tokens are of six types. They are
Keywords (eg: int, while),
or
Identifiers (eg: main, total),
Constants (eg: 10, 20),
Strings (eg: <total=, <hello=),
Special symbols (eg: (), {}),
W
Operators (eg: +, /,-,*)
C KEYWORDS
C keywords are the words that convey a special meaning to the c compiler. The keywords
cannot be used as variable names.
TU
The list of C keywords is given below:
volatile while
A
21
C IDENTIFIERS
Identifiers are used as the general terminology for the names of variables, functions and arrays.
These are user defined names consisting of arbitrarily long sequence of letters and digits with
ld
either a letter or the underscore(_) as a first character.
There are certain rules that should be followed while naming c identifiers:
They must begin with a letter or underscore (_).
or
They must consist of only letters, digits, or underscore. No other special character is allowed.
It should not be a keyword.
It must not contain white space.
It should be up to 31 characters long as only first 31 characters are significant.
W
Some examples of c identifiers:
Name Remark
_A9 Valid
Temp.var Invalid as it contains special character other than the underscore
TU
void Invalid as it is a keyword
C CONSTANTS
A C constant refers to the data items that do not change their value during the program
execution. Several types of C constants that are allowed in C are:
JN
Integer Constants
Integer constants are whole numbers without any fractional part. It must have at least one digit
and may contain either + or 3 sign. A number with no sign is assumed to be positive.
There are three types of integer constants:
Decimal Integer Constants
Integer constants consisting of a set of digits, 0 through 9, preceded by an optional 3 or + sign.
ll
22
ld
0X. They may also include alphabets from A to F representing numbers 10 to 15.
Example of valid hexadecimal integer constants
0xD, 0X8d, 0X, 0xbD
or
It should be noted that, octal and hexadecimal integer constants are rarely used in programming.
Real Constants
The numbers having fractional parts are called real or floating point constants. These may be
represented in one of the two forms called fractional form or the exponent form and may also
W
have either + or 3 sign preceding it.
Example of valid real constants in fractional form or decimal notation
0.05, -0.905, 562.05, 0.015
Representing a real constant in exponent form
The general format in which a real number may be represented in exponential or scientific form
TU
is
mantissa e exponent
The mantissa must be either an integer or a real number expressed in decimal notation.
The letter e separating the mantissa and the exponent can also be written in uppercase i.e. E
JN
23
C allows us to have certain non graphic characters in character constants. Non graphic characters
are those characters that cannot be typed directly from keyboard, for example, tabs, carriage
return, etc.
These non graphic characters can be represented by using escape sequences represented by a
ld
backslash() followed by one or more characters.
NOTE: An escape sequence consumes only one byte of space as it represents a single character.
Escape Sequence Description
or
a Audible alert(bell)
b Backspace
f Form feed
n New line
W
r Carriage return
t Horizontal tab
v Vertical tab
\ Backslash
TU
< Double quotation mark
8 Single quotation mark
? Question mark
Null
JN
STRING CONSTANTS
String constants are sequence of characters enclosed within double quotes. For example,
<hello=
<abc=
<hello911=
ll
Every sting constant is automatically terminated with a special character 89 called thenull
character which represents the end of the string.
For example, <hello= will represent <hello= in the memory.
A
Thus, the size of the string is the total number of characters plus one for the null character.
24
Special Symbols
The following special symbols are used in C having some special meaning and thus, cannot be
used for some other purpose.
ld
[] () {} , ; : * … = #
Braces{}: These opening and ending curly braces marks the start and end of a block of code
containing more than one executable statement.
or
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Brackets[]: Opening and closing brackets are used as array element reference. These indicate
single and multidimensional subscripts.
W
VARIABLES
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of operations that can be
TU
applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is
case-sensitive. Based on the basic types explained in the previous chapter, there will be the
JN
Type Description
25
C programming language also allows defining various other types of variables like
Enumeration, Pointer, Array, Structure, Union, etc.
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable.
ld
A variable definition specifies a data type and contains a list of one or more variables of that
type as follows −
or
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any
user-defined object; and variable_list may consist of one or more identifier names separated by
commas. Some valid declarations are shown here −
W
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to
TU
create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows −
For definition without an initializer: variables with static storage duration are implicitly
initialized with NULL (all bytes have the value 0); the initial value of all other variables are
A
undefined.
26
Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with the
given type and name so that the compiler can proceed for further compilation without requiring
the complete detail about the variable. A variable definition has its meaning at the time of
ld
compilation only; the compiler needs actual variable definition at the time of linking the
program. A variable declaration is useful when multiple files are used.
or
OPERATORS AND EXPRESSIONS
C language offers many types of operators. They are,
1. Arithmetic operators
2. Assignment operators
W
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
TU
7. Increment/decrement operators
8. Special operators
4 Logical operators
These operators are used to perform logical
27
ld
Conditional (ternary) Conditional operators return one value if condition is
6 operators true and returns another value is condition is false.
or
Increment/decrement These operators are used to either increase or
7 operators decrease the value of the variable by one.
ARITHMETIC OPERATORS IN C
W
C Arithmetic operators are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus in C programs.
TU
Arithmetic
S.no Operators Operation Example
1 + Addition A+B
JN
2 3 Subtraction A-B
3 * multiplication A*B
4 / Division A/B
ll
5 % Modulus A%B
A
28
#include <stdio.h>
int main()
ld
int a=40,b=20, add,sub,mul,div,mod;
add = a+b;
sub = a-b;
or
mul = a*b;
div = a/b;
mod = a%b;
W
printf("Addition of a, b is : %d\n", add);
OUTPUT:
JN
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0
ll
ASSIGNMENT OPERATORS IN C
In C programs, values for the variables are assigned using assignment operators.
A
For example, if the value <10= is to be assigned for the variable <sum=, it can be assigned as
<sum = 10;=
29
Simple
assignment 10 is assigned
ld
operator = sum = 10 to variable sum
or
This is same as
-= sum -= 10 sum = sum 3 10
W
sum *= This is same as
*= 10 sum = sum * 10
This is same as
/+ sum /= 10 sum = sum / 10
TU
This is same as
sum %= sum = sum %
%= 10 10
JN
This is same as
sum = sum &
&= sum&=10 10
Compound
assignment sum ^= This is same as
operators ^= 10 sum = sum ^ 10
ll
In this program, values from 0 3 9 are summed up and total <45= is displayed as output.
Assignment operators such as <== and <+== are used in this program to assign the values and to
sum up the values.
30
# include <stdio.h>
int main()
ld
int Total=0,i;
for(i=0;i<10;i++)
or
Total+=i; // This is same as Total = Toatal+i
W
}
OUTPUT:
Total = 45
TU
RELATIONAL OPERATORS IN C
Relational operators are used to find the relation between two variables. i.e. to compare the
values of two variables in a C program.
x is greater than
1 > x>y y
x is greater than
3 >= x >= y or equal to y
A
x is less than or
4 <= x <= y equal to y
31
5 == x == y x is equal to y
x is not equal to
6 != x != y y
ld
EXAMPLE PROGRAM FOR RELATIONAL OPERATORS IN C
In this program, relational operator (==) is used to compare 2 values whether they are equal
or
are not.
If both values are equal, output is displayed as = values are equal=. Else, output is displayed
as <values are not equal=.
Note: double equal sign (==) should be used to compare 2 values. We should not single
equal sign (=).
W
#include <stdio.h>
int main()
int m=40,n=20;
TU
if (m == n)
else
}
ll
}
A
OUTPUT:
32
LOGICAL OPERATORS IN C
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 (!).
ld
S.no Operators Name Example Description
or
It returns true
when both
logical conditions
1 && AND (x>5)&&(y<5) are true
W
It returns true
when at-least
one of the
logical condition is
2 || OR (x>=10)||(y>=10) true
TU
It reverses the
state of the
operand
<((x>5) &&
(y<5))=
JN
If <((x>5)
&& (y<5))=
is true,
logical NOT
logical operator
3 ! NOT !((x>5)&&(y<5)) makes it false
ll
int main()
33
int m=40,n=20;
int o=20,p=30;
ld
{
or
if (o>p || p!=20)
W
}
{
TU
printf("! Operator : Both conditions are true\n");
else
{
JN
}
ll
OUTPUT:
In this program, operators (&&, || and !) are used to perform logical operations on the given
expressions.
34
&& operator 3 <if clause= becomes true only when both conditions (m>n and m! =0) is true.
Else, it becomes false.
|| Operator 3 <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 3 It is used to reverses the state of the operand.
ld
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).
or
BIT WISE OPERATORS IN C
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 in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR),
W
<< (left shift) and >> (right shift).
x x
& ^
TU
x y x|y y y Operator_symbol Operator_name
0 0 0 0 0 & Bitwise_AND
0 1 1 0 1 | Bitwise OR
JN
1 0 1 0 1 ~ Bitwise_NOT
1 1 1 1 0 ^ XOR
Consider x=40 and y=80. Binary form of these values are given below.
x = 00101000
y= 01010000
35
ld
x^y = 01111000 (binary) = 120 (decimal)
x << 1 = 01010000 (binary) = 80 (decimal)
x >> 1 = 00010100 (binary) = 20 (decimal)
or
Note:
Bit wise NOT: Value of 40 in binary
is0000000000000000000000000000000000000000000000000010100000000000. So, all 09s are
converted into 19s in bit wise NOT operation.
W
Bit wise left shift and right shift : In left shift operation <x << 1 <, 1 means that the bits will be
left shifted by one place. If we use it as <x << 2 <, then, it means that the bits will be left shifted
by 2 places.
int main()
{
JN
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
ll
XOR_opr = (m^n);
36
ld
}
OUTPUT:
AND_opr value = 0
or
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
W
right_shift value = 20
In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else
conditional statements.
JN
int main()
{
ll
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
A
37
OUTPUT:
x value is 1
y value is 2
ld
C – Increment/decrement Operators
PREVNEXT
or
Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.
Syntax:
Increment operator: ++var_name ;( or) var_name++;
Decrement operator: 3 -var_name; (or) var_name 3 -;
W
Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : 3 3 i ; i 3 3 ;
#include <stdio.h>
JN
int main()
int i=1;
while(i<10)
{
ll
printf("%d ",i);
i++;
A
38
OUTPUT:
123456789
ld
In this program, value of <I= is decremented one by one from 20 up to 11 using <i3= operator and
output is displayed as <20 19 18 17 16 15 14 13 12 11=.
or
//Example for decrement operators
#include <stdio.h>
int main()
W
{
int i=20;
while(i>10)
{
TU
printf("%d ",i);
i--;
}
JN
OUTPUT:
20 19 18 17 16 15 14 13 12 11
IN C
Below table will explain the difference between pre/post increment and decrement operators in
C.
A
1 Pre increment
++i Value of i is
39
incremented before
assigning it to variable
i.
ld
Value of i is
incremented after
i++ assigning it to variable
2 Post3increment i.
or
Value of i is
decremented before
4 3i assigning it to variable
3 Pre decrement i.
W
Value of i is
decremented after
i3 4 assigning it to variable
4 Post_decrement i.
TU
EXAMPLE PROGRAM FOR PRE – INCREMENT OPERATORS IN C
//Example for increment operators
#include <stdio.h>
JN
int main()
int i=0;
while(++i < 5 )
{
ll
printf("%d ",i);
A
return 0;
40
OUTPUT:
1234
ld
operator.
Step 2 : This incremented value <1= is compared with 5 in while expression.
Step 3 : Then, this incremented value <1= is assigned to the variable <i=.
Above 3 steps are continued until while expression becomes false and output is displayed as
<1 2 3 4=.
or
EXAMPLE PROGRAM FOR POST – INCREMENT OPERATORS IN C
#include <stdio.h>
int main()
W
{
int i=0;
while(i++ < 5 )
TU
{
printf("%d ",i);
return 0;
JN
OUTPUT:
12345
<1 2 3 4 5=.
41
int main()
ld
{
int i=10;
while(--i > 5 )
or
{
printf("%d ",i);
W
return 0;
OUTPUT:
TU
9876
Above 3 steps are continued until while expression becomes false and output is displayed as
<9 8 7 6=.
int main()
ll
int i=10;
A
while(i-- > 5 )
42
printf("%d ",i);
return 0;
ld
}
OUTPUT:
98765
or
Step 1 : In this program, value of i <10= is compared with 5 in while expression.
Step 2 : Then, value of <i= is decremented from 10 to 9 using post-decrement operator.
Step 3 : Then, this decremented value <9= is assigned to the variable <i=.
Above 3 steps are continued until while expression becomes false and output is displayed as
W
<9 8 7 6 5=.
SPECIAL OPERATORS IN C:
Below are some of special operators that C language offers.
S.no Operators Description
TU
This is used to get the address
of the variable.
Example : * a where, * is
2 * pointer to the variable a.
ll
43
ld
#include <stdio.h>
int main()
or
int *ptr, q;
q = 50;
W
ptr = &q;
printf("%d", *ptr);
TU
return 0;
OUTPUT:
50
JN
#include <limits.h>
ll
int main()
{
A
int a;
char b;
44
float c;
double d;
ld
printf("Storage size for char data type:%d \n",sizeof(b));
or
return 0;
OUTPUT:
W
Storage size for int data type:4
Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8
TU
EXPRESSIONS
Arithmetic expression in C is a combination of variables, constants and operators written in a
proper syntax. C can easily handle any complex mathematical expressions but these
mathematical expressions have to be written in a proper syntax. Some examples of mathematical
JN
C operators in order of precedence (highest to lowest). Their associativity indicates in what order
ll
45
ld
sizeof Determine size in bytes on this implementation
* / % Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
or
< <= Relational less than/less than or equal to left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
W
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
TU
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right
JN
Note 1:
Parentheses are also used to group sub-expressions to force a different
precedence; such parenthetical expressions can be nested and are
evaluated from inner to outer.
Note 2:
Postfix increment/decrement have high precedence, but the actual
increment or decrement of the operand is delayed (to be accomplished
sometime before the statement completes execution). So in the
ll
46
EVALUATION OF EXPRESSION
At first, the expressions within parenthesis are evaluated. If no parenthesis is present, then the
arithmetic expression is evaluated from left to right. There are two priority levels of operators in
C.
ld
High priority: * / %
Low priority: + -
The evaluation procedure of an arithmetic expression includes two left to right passes through
or
the entire expression. In the first pass, the high priority operators are applied as they are
encountered and in the second pass, low priority operations are applied as they are encountered.
Suppose, we have an arithmetic expression as:
x = 9 3 12 / 3 + 3 *2 - 1
W
This expression is evaluated in two left to right passes as:
First Pass
Step 1: x = 9-4 + 3 * 2 3 1
Step 2: x = 9 3 4 + 6 3 1
Second Pass
TU
Step 1: x = 5 + 6 3 1
Step 2: x = 11 3 1
Step 3: x = 10
But when parenthesis is used in the same expression, the order of evaluation gets changed.
JN
For example,
x = 9 3 12 / (3 + 3) * (2 3 1)
When parentheses are present then the expression inside the parenthesis are evaluated first from
left to right. The expression is now evaluated in three passes as:
First Pass
Step 1: x = 9 3 12 / 6 * (2 3 1)
ll
Step 2: x= 9 3 12 / 6 * 1
Second Pass
A
Step 1: x= 9 3 2 * 1
Step 2: x = 9 3 2
Third Pass
47
Step 3: x= 7
There may even arise a case where nested parentheses are present (i.e. parenthesis inside
parenthesis). In such case, the expression inside the innermost set of parentheses is evaluated
first and then the outer parentheses are evaluated.
ld
For example, we have an expression as:
x = 9 3 ((12 / 3) + 3 * 2) 3 1
The expression is now evaluated as:
or
First Pass:
Step 1: x = 9 3 (4 + 3 * 2) 3 1
Step 2: x= 9 3 (4 + 6) 3 1
Step 3: x= 9 3 10 -1
W
Second Pass
Step 1: x= - 1 3 1
Step 2: x = -2
Note: The number of evaluation steps is equal to the number of operators in the arithmetic
expression.
TU
TYPE CONVERSION IN EXPRESSIONS
When variables and constants of different types are combined in an expression then they are
converted to same data type. The process of converting one predefined type into another is called
JN
type conversion.
Type conversion in c can be classified into the following two types:
Implicit Type Conversion
When the type conversion is performed automatically by the compiler without programmer9s
intervention, such type of conversion is known as implicit type conversion or type promotion.
The compiler converts all operands into the data type of the largest operand.
ll
The sequence of rules that are applied while evaluating expressions are given below:
All short and char are automatically converted to int, then,
A
If either of the operand is of type long double, then others will be converted to long double and
result will be long double.
Else, if either of the operand is double, then others are converted to double.
48
Else, if either of the operand is float, then others are converted to float.
Else, if either of the operand is unsigned long int, then others will be converted to unsigned long
int.
Else, if one of the operand is long int, and the other is unsigned int, then
ld
if a long int can represent all values of an unsigned int, the unsigned int is converted to long int.
otherwise, both operands are converted to unsigned long int.
Else, if either operand is long int then other will be converted to long int.
or
Else, if either operand is unsigned int then others will be converted to unsigned int.
It should be noted that the final result of expression is converted to type of variable on left side
of assignment operator before assigning value to it.
Also, conversion of float to int causes truncation of fractional part, conversion of double to float
W
causes rounding of digits and the conversion of long int to int causes dropping of excess higher
order bits.
where, data_type is any valid c data type, and expression may be constant, variable or
expression.
For example, x=(int)a+b*d;
The following rules have to be followed while converting the expression from one type to
another to avoid the loss of information:
All integer types to be converted to float.
ll
49
ld
of low-level languages and the flexibility and simplicity of high-level languages.
C provides standard functions scanf() and printf(), for performing formatted input and output.
These functions accept, as parameters, a format specification string and a list of variables.
or
The format specification string is a character string that specifies the data type of each variable to
be input or output and the size or width of the input and output.
Now to discuss formatted output in functions.
Formatted Output
W
The function printf() is used for formatted output to standard output based on a format
specification. The format specification string, along with the data to be output, are the parameters
to the printf() function.
Syntax:
printf (format, data1, data2,……..);
TU
In this syntax format is the format specification string. This string contains, for each variable to
be output, a specification beginning with the symbol % followed by a character called the
conversion character.
JN
Example:
printf (<%c=, data1);
The character specified after % is called a conversion character because it allows one data type to
be converted to another type and printed.
See the following table conversion character and their meanings.
Conversion Meaning
ll
Character
d The data is converted to decimal (integer)
A
50
ld
Example
printf (<%c\n=,data1);
The format specification string may also have text.
or
Example
printf (<Character is:=%c\n=, data1);
The text "Character is:" is printed out along with the value of data1.
Example with program
W
#include<stdio.h>
#include<conio.h>
Main()
{
TU
Char alphabh="A";
int number1= 55;
float number2=22.34;
printf(<char= %c\n=,alphabh);
printf(<int= %d\n=,number1);
JN
printf(<float= %f\n=,number2);
getch();
clrscr();
retrun 0;
}
Output Here…
ll
char =A
int= 55
A
flaot=22.340000
51
ld
Between the character % and the conversion character, there may be:
A minus sign: Denoting left adjustment of the data.
A digit: Specifying the minimum width in which the data is to be output, if the data has a
or
larger number of characters then the specified width occupied by the output is larger. If
the data consists of fewer characters then the specified width, it is padded to the right or
to the left (if minus sign is not specified) with blanks. If the digit is prefixed with a zero,
the padding is done with zeros instead of blanks.
W
A period: Separating the width from the next digit.
A digit following the period: specifying the precision (number of decimal places for
numeric data) or the maximum number of characters to be output.
Letter 1: To indicate that the data item is a long integer and not an int.
TU
Format specification string Data Output
|%2d| 9 |9|
|%2d| 123 |123|
JN
|%03d| 9 |009|
|%-2d| 7 |7|
|%5.3d| 2 |002|
|%3.1d| 15 |15|
|%3.5d| 15 |0015|
<Output sting=
ll
52
ld
Example based on the conversion character:
#include<stdio.h>
#include<conio.h>
or
main()
{
Int num=65;
printf(<Value of num is : %d\n:, num);
W
printf(<Character equivalent of %d is %c\n=, num , num);
getch();
clrscr();
rerurn o;
TU
}
Output Here…
char =A
int= 55
flaot=22.340000
JN
Formatted Input
The function scanf() is used for formatted input from standard input and provides many of the
conversion facilities of the function printf().
Syntax
scanf (format, num1, num2,……);
The function scnaf() reads and converts characters from the standards input depending on the
ll
format specification string and stores the input in memory locations represented by the other
arguments (num1, num2,….).
A
For Example:
scanf(< %c %d=,&Name, &Roll No);
Note: the data names are listed as &Name and &Roll No instead of Name and Roll No
53
respectively. This is how data names are specified in a scnaf() function. In case of string type
data names, the data name is not preceded by the character &.
Example with program
Write a function to accept and display the element number and the weight of a proton. The
ld
element number is an integer and weight is fractional.
Solve here:
#include<stdio.h>
or
#include<conio.h>
main()
{
Int e_num;
W
Float e_wt;
printf (<Enter the Element No. and Weight of a Proton\n=);
scanf (<%d %f=,&e_num, &e_wt);
printf (<The Element No.is:=,e_num);
printf (<The Weight of a Proton is: %f\n=, e_wt);
TU
getch();
return 0;
}
JN
ll
A
54
UNIT-II
CONTROL STRUCTURES, ARRAYS AND STRINGS
DECISION STATEMENTS
ld
If statement:
Syntax :
if(expression)
or
statement1;
Explanation :
Expression is Boolean Expression
It may have true or false value
W
TU
JN
Meaning of If Statement :
It Checks whether the given Expression is Boolean or not !!
ll
void main()
{
int a=5,b=6,c;
c=a+b;
55
if (c==11)
printf("Execute me 1");
printf("Execute me 2");
}
ld
Output :
Execute me 1
If Statement :
or
if(conditional)
{
Statement No 1
Statement No 2
Statement No 3
W
.
.
.
Statement No N
}
Note :
TU
More than One Conditions can be Written inside If statement.
1. Opening and Closing Braces are required only when <Code= after if statement
occupies multiple lines.
if(conditional)
JN
Statement No 1
Statement No 2
Statement No 3
In the above example only Statement 1 is a part of if Statement.
1. Code will be executed if condition statement is True.
ll
printf("True Condition");
if-else Statement :
56
We can use if-else statement in c programming so that we can check any condition and
depending on the outcome of the condition we can follow appropriate path. We have true path as
well as false path.
ld
Syntax :
if(expression)
{
statement1;
or
statement2;
}
else
{
statement1;
statement2;
W
}
next_statement;
Explanation :
If expression is True then Statement1 and Statement2 are executed
TU
Otherwise Statement3 and Statement4 are executed.
Sample Program on if-else Statement :
void main()
{
int marks=50;
if(marks>=40)
JN
{
printf("Student is Pass");
}
else
{
printf("Student is Fail");
}
}
ll
Output :
Student is Pass
A
57
ld
or
Consider Example 1 with Explanation:
W
Consider Following Example 3
int num = 20;
if(num == 20)
{
printf("True Block");
TU
}
else
{
printf("False Block");
}
If part Executed if Condition Statement is True.
JN
if(num == 20)
{
printf("True Block");
}
True Block will be executed if condition is True.
Else Part executed if Condition Statement is False.
ll
else
{
A
printf("False Block");
}
Consider Example 2 with Explanation :
58
ld
{
printf("True Block");
}
Opening and Closing Braces are required only when <Code= after if statement occupies multiple
lines. Code will be executed if condition statement is True. Non-Zero Number Inside
or
if means <TRUE Condition=
If-Else Statement :
if(conditional)
{
W
//True code
}
else
{
//False code
}
Note :
TU
Consider Following Example 3
int num = 20;
if(num == 20)
{
printf("True Block");
JN
}
else
{
printf("False Block");
}
If part Executed if Condition Statement is True.
if(num == 20)
ll
{
printf("True Block");
A
}
True Block will be executed if condition is True.
Else Part executed if Condition Statement is False.
59
else
{
printf("False Block");
}
ld
More than One Conditions can be Written inside If statement.
int num1 = 20;
int num2 = 40;
or
{
printf("True Block");
}
Opening and Closing Braces are required only when <Code= after if statement occupies multiple
lines.
W
Code will be executed if condition statement is True.
Non-Zero Number Inside if means <TRUE Condition=
TU
Switch statement
Why we should use Switch Case?
One of the classic problem encountered in nested if-else / else-if ladderis
called problem of Confusion.
It occurs when no matching else is available for if .
JN
if(Condition 1)
Statement 1
else
A
{
Statement 2
if(condition 2)
{
if(condition 3)
60
statement 3
else
if(condition 4)
{
statement 4
}
ld
}
else
{
statement 5
}
or
}
First Look of Switch Case
switch(expression)
{
case value1 :
W
body1
break;
case value2 :
body2
break;
TU
case value3 :
body3
break;
default :
default-body
break;
JN
}
next-statement;
Flow Diagram :
ll
A
61
How it works?
Switch case checks the value of expression/variable against the list of case values and
when the match is found , the block of statement associated with that case is executed
Expression should be Integer Expression / Character
ld
Break statement takes control out of the case.
Break Statement is Optional.
#include<stdio.h>
or
void main()
{
int roll = 3 ;
switch ( roll )
{
case 1:
W
printf ( " I am Pankaj ");
break;
case 2:
printf ( " I am Nikhil ");
break;
case 3:
printf ( " I am John ");
TU
break;
default :
printf ( "No student found");
break;
}
}
As explained earlier 3
JN
62
initialization;
while(condition)
{
----------
----------
---------
ld
incrementation;
}
or
Note :
For Single Line of Code 3 Opening and Closing braces are not needed.
W
TU
while(1) is used for Infinite Loop
Initialization , Incrementation and Condition steps are on different Line.
While Loop is also Entry Controlled Loop.[i.e conditions are checked if found true then and then
only code is executed ]
JN
Do while:
Do-While Loop Syntax :
initialization;
do
{
--------------
ll
--------------
--------------
--------------
A
incrementation;
}while(condition);
63
ld
Note :
or
It is Exit Controlled Loop.
Initialization , Incrementation and Condition steps are on different Line.
It is also called Bottom Tested [i.e Condition is tested at bottom and Body has to execute at least
W
once ]
For statement:
We have already seen the basics of Looping Statement in C. C Language provides us different
kind of looping statements such as For loop, while loop and do-while loop. In this chapter we
will be learning different flavors of for loop statement.
TU
Different Ways of Using For Loop in C Programming
In order to do certain actions multiple times, we use loop control statements.
For loop can be implemented in different verities of using for loop 3
Single Statement inside For Loop
Multiple Statements inside For Loop
JN
64
ld
or
W
Way 1 : Single Statement inside For Loop
for(i=0;i<5;i++)
printf("Hello");
Above code snippet will print Hello word 5 times.
TU
We have single statement inside for loop body.
No need to wrap printf inside opening and closing curly block.
Curly Block is Optional.
for(i=0;i<5;i++)
{
printf("Statement 1");
printf("Statement 2");
printf("Statement 3");
if(condition)
{
ll
--------
--------
}
A
}
If we have block of code that is to be executed multiple times then we can use curly braces to
wrap multiple statement in for loop.
65
}
this is bodyless for loop. It is used to increment value of <i=.This verity of for loop is not used
ld
generally.
At the end of above for loop value of i will be 5.
or
Way 4 : Semicolon at the end of For Loop
for(i=0;i<5;i++);
Generally beginners thought that , we will get compile error if we write semicolon at the end of
W
for loop.
This is perfectly legal statement in C Programming.
This statement is similar to bodyless for loop. (Way 3)
statement3;
i++;
}
A
66
for(;i<5;i++)
{
statement1;
statement2;
statement3;
}
ld
we have to set value of 8i9 before entering in the loop otherwise it will take garbage value of 8i9.
or
i = 0;
for(;;)
{
statement1;
statement2;
statement3;
W
if(breaking condition)
break;
i++;
}
TU
Infinite for loop must have breaking condition in order to break for loop. otherwise it will cause
overflow of stack.
Form Comment
Statement2;
Statement3;
}
A
for ( i=0 ; i < 10;i++) ; For Loop with no Body (Carefully Look at the
Semicolon)
67
for ( ; i<10 ; )
ld
Initialization & Update not used
or
JUMP STATEMENTS:
Break statement
Break Statement Simply Terminate Loop and takes control out of the loop.
W
Break in For Loop :
for(initialization ; condition ; incrementation)
{
Statement1;
Statement2;
break;
TU
}
Statement1;
Statement2;
incrementation
break;
}
initialization ;
do
{
Statement1;
A
Statement2;
incrementation
break;
}while(condition);
68
ld
or
Way 2 : Nested for
W
TU
69
ld
or
Continue statement:
loop
{
W
continue;
//code
}
Note :
It is used for skipping part of Loop.
TU
Continue causes the remaining code inside a loop block to be skipped and causes execution to
jump to the top of the loop block
JN
for
ll
A
70
while
ld
or
do-while
W
TU
Goto statement:
goto label;
-------
JN
-------
label :
Whenever goto keyword encountered then it causes the program to continue on the line , so long
as it is in the scope .
ll
Types of Goto
Forward
A
Backward
71
ld
or
ARRAYS:
What is an array? W
TU
An array is a collection of similar datatype that are used to allocate memory in
a sequential manner.
Syntax : <data type> <array name>[<size of an array>]
Subscript or indexing: A subscript is property of an array that distinguishes all its stored
elements because all the elements in an array having the same name (i.e. the array name). so to
JN
So on……………………
Last element will be: int ar[19];
72
ld
· Multiple elements are stored under a single unit.
· Searching is fast because all the elements are stored in a sequence.
or
Types of Array
1. Static Array
2. Dynamic Array.
W
Static Array
An array with fixed size is said to be a static array.
Types of static array:
1. One Dimensional Array
2. Two Dimensional Array.
TU
3. Multi Dimensional Array.
73
Dynamic Array.
ld
This type of array also does not exist in c and c++.
Example: Program based upon array:
WAP to store marks in 5 subjects for a student. Display marks in 2nd and 5thsubject.
or
#include<stdio.h>
#include<conio.h>
void main()
{
W
int ar[5];
int i;
for(i=0;i<5;i++)
{
printf(< \n Enter marks in <,i, <subject=);
TU
scanf(<%d=,&ar[i]);
}
printf(<Marks in 2nd subject is: =,ar[1]);
printf(<Marks in 5th subject is: =,ar[4]);
JN
}
STRINGS
What is String?
· A string is a collection of characters.
· A string is also called as an array of characters.
ll
74
ld
Example: Program based upon String.
WAP to accept a complete string (first name and last name) and display hello message in the
output.
or
# include<stdio.h>
#include<conio.h>
#include<string.h>
void main ()
W
{
char str1[20];
char str2[20];
printf(<Enter First Name=);
scanf(<%s=,&str1);
TU
printf(<Enter last Name=);
scanf(<%s=,&str2);
puts(str1);
puts(str2);
JN
String Functions in C:
Our c language provides us lot of string functions for manipulating the string.
All the string functions are available in string.h header file.
ll
2. strupr().
3. strlwr().
4. strcmp().
75
5. strcat().
6. strapy().
7. strrev().
ld
1. strlen().
This string function is basically used for the purpose of computing the ength of string.
or
Example: char str==Gaurav Arora=;
int length= strlen(str);
printf(<The length of the string is ==,str);
W
2. strupr().
This string function is basically used for the purpose of converting the case sensitiveness of the
string i.e. it converts string case sensitiveness into uppercase.
3. strlwr ().
JN
This string function is basically used for the purpose of converting the case sensitiveness of the
string i.e it converts string case sensitiveness into lowercase.
Example: char str = <gaurav=
strlwr(str);
printf(<The Lowercase of the string is :%s =,str);
ll
4. strcmp ().
This string function is basically used for the purpose of comparing two string.
A
76
Case 2: if first string < than second string then, result will be false.
Case 3: if first string = = to second string then, result will be zero.
Example:
ld
char str1= <Gaurav=;
char str2= <Arora=;
char str3=strcmp(str1,str2);
or
printf(<%s=,str3);
5. strcat().
This string function is used for the purpose of concatenating two strings ie.(merging two or more
W
strings)
Example:
char str1 = <Gaurav=;
char str2 = <Arora=;
TU
char str3[30];
str3=strcat(str1,str2);
printf(<%s=,str3);
JN
6. strcpy()
This string function is basically used for the purpose of copying one string into another string.
char str1= <Gaurav=;
char str2[20];
str2 = strcpy(str2,str1);
printf(<%s=,str2);
ll
6. strrev()
A
This string function is basically used for the purpose of reversing the string.
char str1= <Gaurav=;
char str2[20];
77
str2= strrev(str2,str1);
printf(<%s=,str2);
ld
WAP to accept a string and perform various operations:
1. To convert string into upper case.
2. To reverse the string .
or
3. To copy string into another string.
4. To compute length depending upon user choice.
# include<stdio.h>
W
# include<conio.h>
#include<string.h>
void main()
{
TU
char str[20];
char str1[20];
int opt,len;
printf(<\n MAIN MENU=);
JN
switch(opt)
{
case 1: strupr(str);
78
case 2: strrev(str);
ld
printf(<The reverse of string is : %s=,str);
break;
case 3: strcpy(str1,str);
or
printf(<New copied string is : %s=,str1);
break;
case 4: len=strlen(str);
printf(<The length of the string is : %s=,len);
W
break;
default: printf(<Ypu have entered a wrong choice.=);
}
TU
JN
ll
A
79
UNIT-III
FUNCTIONS
ld
A function is itself a block of code which can solve simple or complex task/calculations.
A function performs calculations on the data provided to it is called "parameter" or "argument".
A function always returns single value result.
or
Types of function:
1. Built in functions(Library functions)
a.) Inputting Functions.
W
b.) Outputting functions.
3. Function Definition.
1.)Function Declaration:
Syntax: <return type > <function name>(<type of argument>)
The declaration of function name, its argument and return type is called function declaration.
ll
80
The process of writing a code for performing any specific task is called function defination.
Syntax:
<return type><function name>(<type of arguments>)
{
ld
<statement-1>
<statement-2>
return(<vlaue>)
or
}
Example: program based upon function:
WAP to compute cube of a no. using function.
#include<stdio.h>
W
#include<conio.h>
void main()
{
int c,n;
int cube(int);
TU
printf("Enter a no.");
scanf("%d",&n);
c=cube(n);
printf("cube of a no. is=%d",c);
JN
}
int cube(int n)
{
c=n*n*n;
return(c);
}
ll
#include<stdio.h>
#include<conio.h>
void main()
81
{
int n,f=1;
int fact(int)
printf("Enter a no.");
ld
scanf("%d",&n);
f=fact(n);
printf("The factorial of a no. is:=%d",f);
or
}
int fact(int n)
int f=1;
{
W
for(int i=n;i>=n;i--)
{
f=f*i;
}
return(f);
TU
}
Recursion
Firstly, what is nested function?
JN
#include<stdio.h>
#include<conio.h>
void main()
82
{
int n,f;
int fact(int)
printf("Enter a no.");
ld
scanf("%d",&n);
f=fact(n);
printf("The factorial of a no. is:=%d",f);
or
}
int fact(int n)
int f=1;
{
W
if(n=0)
return(f);
else
return(n*fact(n-1));
}
TU
Passing parameters to a function:
Firstly, what are parameters?
parameters are the values that are passed to a function for processing.
JN
83
ld
1.) Call by reference:
In this method of parameter passing , original values of variables are passed from calling
or
program to function.
Thus,
Any change made in the function can be reflected back to the calling program.
W
2.) Call by value.
In this method of parameter passing, duplicate values of parameters are passed from calling
program to function defination.
Thus,
Any change made in function would not be reflected back to the calling program.
TU
Example: Program based upon call by value:
# include<stdio.h>
# include<conio.h>
JN
void main()
{
int a,b;
a=10;
b=20;
void swap(int,int)
ll
void swap(a,b);
printf("The value of a after swapping=%d",a);
printf("The value of b after swapping=%d",b);
84
}
void swap(int x, int y)
{
int t;
ld
t=x;
x=y;
y=t;
or
}
STORAGE CLASSES
Every Variable in a program has memory associated with it.
W
Memory Requirement of Variables is different for different types of variables.
In C, Memory is allocated & released at different places
Term Definition
Lifetime of variable
A
85
B. Scope of Variable
Scope of Variable tells compile about the visibility of Variable in the block. Variable may have
Block Scope, Local Scope and External Scope. A scope is the context within a computer
program in which a variable name or other identifier is valid and can be used, or within which a
ld
declaration has effect.
C. Default Initial Value of the Variable
Whenever we declare a Variable in C, garbage value is assigned to the variable. Garbage Value
or
may be considered as initial value of the variable. C Programming have different storage
classes which has different initial values such as Global Variable have Initial Value as 0 while
the Local auto variable have default initial garbage value.
W
D. Lifetime of variable
Lifetime of the = Time Of variable Declaration - Time of Variable Destruction
Suppose we have declared variable inside main function then variable will be destroyed only
when the control comes out of the main .i.e end of the program.
TU
Different Storage Classes:
Auto Storage Class
Static Storage Class
Extern Storage Class
JN
Storage Memory
86
ld
Value
Example
or
void main()
{
auto mum = 20 ;
{
W
auto num = 60 ;
printf("nNum : %d",num);
}
printf("nNum : %d",num);
}
Output :
TU
Num : 60
Num : 20
Note :
JN
Two variables are declared in different blocks , so they are treated as different variables
External ( extern ) storage class in C Programming
Generally , External variables are declared again in the function using keyword extern
In order to Explicit declaration of variable use 8extern9 keyword
A
87
Storage Memory
ld
Life time
Retains value within the function
or
Example
int num = 75 ;
W
void display();
void main()
{
extern int num ;
printf("nNum : %d",num);
display();
TU
}
void display()
{
extern int num ;
printf("nNum : %d",num);
}
JN
Output :
Num : 75
Num : 75
Note :
ll
Declaration within the function indicates that the function uses external variable
Functions belonging to same source code , does not require declaration (no need to write extern)
A
If variable is defined outside the source code , then declaration using extern keyword is required
88
The static storage class instructs the compiler to keep a local variable in existence during the
life-time of the program instead of creating and destroying it each time it comes into and goes
out of scope. Therefore, making local variables static allows them to maintain their values
between function calls.
ld
The static modifier may also be applied to global variables. When this is done, it causes that
variable's scope to be restricted to the file in which it is declared.
In C programming, when static is used on a class data member, it causes only one copy of that
or
member to be shared by all the objects of its class.
#include <stdio.h>
/* function declaration */
void func(void);
W
static int count = 5; /* global variable */
main() {
while(count--) {
func();
TU
}
return 0;
}
/* function definition */
void func( void ) {
JN
i is 6 and count is 4
i is 7 and count is 3
A
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
89
ld
unary operator [&] is not associated with it because Value is not stored in RAM instead it is
stored in Register.
This is generally used for faster access.
or
Common use is <Counter<
Syntax
{
register int count;
}
W
Register storage classes example
#include<stdio.h>
int main()
{
int num1,num2;
register int sum;
TU
printf("\nEnter the Number 1 : ");
scanf("%d",&num1);
return(0);
}
Explanation of program
Refer below animation which depicts the register storage classes 3
ll
A
90
ld
or
In the above program we have declared two variables num1,num2. These two variables are
W
stored in RAM.
Another variable is declared which is stored in register variable.Register variables are stored in
the register of the microprocessor.Thus memory access will be faster than other variables.
If we try to declare more register variables then it can treat variables asAuto storage variables as
TU
memory of microprocessor is fixed and limited.
Why we need Register Variable ?
Whenever we declare any variable inside C Program then memory will be randomly allocated at
particular memory location.
We have to keep track of that memory location. We need to access value at that memory location
JN
Keyword register
91
Keyword register
ld
Scope Local to the block.
or
Preprocessor directives
Before a C program is compiled in a compiler, source code is processed by a program called
preprocessor. This process is called preprocessing.
Commands used in preprocessor are called preprocessor directives and they begin with <#=
W
symbol.
Below is the list of preprocessor directives that C language offers.
92
condition
#undef is used to
undefine a defined
ld
macro variable.
#Pragma is used to
call a function before
or
and after main
Other function in a C
4 directives #undef, #pragma program
W
A program in C language involves into different processes. Below diagram will help you to
understand all the processes that a C program comes across.
#include <stdio.h>
void main()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
ll
}
OUTPUT:
93
ld
value of backslash_char : ?
or
A) EXAMPLE PROGRAM FOR #IFDEF, #ELSE AND #ENDIF IN C:
<#ifdef= directive checks whether particular macro is defined or not. If it is defined, <If= clause
statements are included in source file.
Otherwise, <else= clause statements are included in source file for compilation and execution.
#include <stdio.h>
#define RAJU 100
int main() W
TU
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in " \
"this C file\n");
#else
printf("RAJU is not defined\n");
#endif
JN
return 0;
}
OUTPUT:
#ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined, <If= clause
statements are included in source file.
A
Otherwise, else clause statements are included in source file for compilation and execution.
#include <stdio.h>
#define RAJU 100
94
int main()
{
#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going to " \
"define here\n");
ld
#define SELVA 300
}
#else
printf("SELVA is already defined in the program=);
or
#endif
return 0;
}
OUTPUT:
W
SELVA is not defined. So, now we are going to define here
#include <stdio.h>
#define a 100
int main()
{
JN
#if (a==100)
printf("This line will be added in this C file since " \
"a \= 100\n");
#else
printf("This line will be added in this C file since " \
"a is not equal to 100\n");
#endif
return 0;
ll
OUTPUT:
A
95
ld
void main()
{
printf("First defined value for height : %d\n",height);
#undef height // undefining variable
#define height 600 // redefining the same for new value
or
printf("value of height after undef \& redefine:%d",height);
}
OUTPUT:
W
value of height after undef & redefine : 600
void function1( );
void function2( );
int main( )
{
printf ( "\n Now we are in main function" ) ;
return 0;
}
void function1( )
ll
{
printf("\nFunction1 is called before main function call");
}
A
void function2( )
{
printf ( "\nFunction2 is called just before end of " \
"main function" ) ;"
}
96
OUTPUT:
ld
Function2 is called just before end of main function
or
S.no Pragma command description
W
This directive executes function
#Pragma exit named <function_name_2= just
2 <function_name_2> before termination of the program.
97
POINTERS
Pointer Overview
ld
or
Consider above Diagram which clearly shows pointer concept in c programming 3
i is the name given for particular memory location of ordinary variable.
Let us consider it9s Corresponding address be 65624 and the Value stored in variable 8i9 is 5
W
The address of the variable 8i9 is stored in another integer variable whose name is 8j9 and which
is having corresponding address 65522
thus we can say that 3
j = &i;
TU
i.e
j = Address of i
Here j is not ordinary variable , It is special variable and called pointer variable as it stores the
address of the another ordinary variable. We can summarize it like 3
JN
i 5 65524
j 65524 65522
#include <stdio.h>
int main()
A
{
int *ptr, i;
i = 11;
98
ptr = &i;
return 0;
ld
}
See Output and Download »
You will get value of i = 11 in the above program.
C. Pointer Declaration Tips :
or
1. Pointer is declared with preceding * :
int *ptr; //Here ptr is Integer Pointer Variable
int ptr; //Here ptr is Normal Integer Variable
W
2. Whitespace while Writing Pointer :
pointer variable name and asterisk can contain whitespace because whitespace is ignored by
compiler.
int *ptr;
int * ptr;
TU
int * ptr;
All the above syntax are legal and valid. We can insert any number of spaces or blanks inside
declaration. We can also split the declaration on multiple lines.
D. Key points for Pointer :
Unline ordinary variables pointer is special type of variable which stores the address of ordinary
JN
variable.
Pointer can only store the whole or integer number because address of any type of variable is
considered as integer.
It is good to initialize the pointer immediately after declaration
& symbol is used to get address of variable
ll
Pointer is Special Variable used to Reference and de-reference memory. (*Will be covered in
upcoming chapter)
99
When we declare integer pointer then we can only store address of integer variable into that
pointer.
Similarly if we declare character pointer then only the address of character variable is stored into
the pointer variable.
ld
Pointer storing the address of following DT Pointer is called as
or
Character Character Pointer
W
Float Float Pointer
#include<stdio.h>
int main()
{
int a = 3;
int *ptr;
ptr = &a;
ll
return(0);
}
Explanation of Example :
A
100
ld
Address of Variable 2001 (Assumption) 4001 (Assumption)
or
#include<stdio.h>
int main()
{
int a = 3;
W
int *ptr,**pptr;
ptr = &a;
pptr = &ptr;
return(0);
}
Explanation of Example
With reference to above program 3
TU
JN
101
ld
Pointer address operator in C Programming
Pointer address operator is denoted by 8&9 symbol
or
When we use ampersand symbol as a prefix to a variable name 8&9, it gives the address of that
variable.
lets take an example 3
&n - It gives an address on variable n
W
Working of address operator
#include<stdio.h>
void main()
{
int n = 10;
printf("\nValue of n is : %d",n);
TU
printf("\nValue of &n is : %u",&n);
}
Output :
Value of n is : 10
Value of &n is : 1002
JN
Consider the above example, where we have used to print the address of the variable using
ampersand operator.
In order to print the variable we simply use name of variable while to print the address of the
variable we use ampersand along with %u
printf("\nValue of &n is : %u",&n);
Understanding address operator
ll
int main()
{
int i = 5;
int *ptr;
102
ptr = &i;
printf("\nAddress of i : %u",&i);
printf("\nValue of ptr is : %u",ptr);
return(0);
ld
}
After declaration memory map will be like this 3
int i = 5;
int *ptr;
or
W
after Assigning the address of variable to pointer , i.e after the execution of this statement 3
ptr = &i;
TU
JN
Only variables have an address associated with them, constant entity does not have
corresponding address. Similarly we cannot use address operator over character literal 3
A
&('a')
Character 8a9 is literal, so we cannot use address operator.
Address of expressions
103
(a+b) will evaluate addition of values present in variables and output of (a+b)is nothing but
Literal, so we cannot use Address operator
&(a+b)
ld
Memory Organization for Pointer Variable:
When we use variable in program then Compiler keeps some memory for that variable
depending on the data type
or
The address given to the variable is Unique with that variable name
When Program execution starts the variable name is automatically translated into the
corresponding address.
W
TU
Explanation :
Pointer Variable is nothing but a memory address which holds another address .
In the above program <i= is name given for memory location for human understanding , but
compiler is unable to recognize <i= . Compiler knows only address.
In the next chapter we will be learning , Memory requirement for storing pointer variable.
JN
Asterisk(*)
Asterisk is called as Indirection Operator
It is also called as Value at address Operator
It Indicates Variable declared is of Pointer type
104
pointer_name
Must be any Valid C identifier
Must follow all Rules of Variable name declaration
Ways of Declaring Pointer Variable:
ld
[box] * can appears anywhere between Pointer_name and Data Type
int *p;
int * p;
int * p;
or
Example of Declaring Integer Pointer:
int n = 20;
int *ptr;
W
Example of Declaring Character Pointer:
char ch = 'A';
char *cptr;
Example of Declaring Float Pointer:
float fvar = 3.14;
TU
float *fptr;
How to Initialize Pointer in C Programming?
pointer = &variable;
Above is the syntax for initializing pointer variable in C.
JN
int main()
{
int a; // Step 1
int *ptr; // Step 2
105
a = 10; // Step 3
ptr = &a; // Step 4
return(0);
}
Explanation of Above Program :
ld
Pointer should not be used before initialization.
<ptr= is pointer variable used to store the address of the variable.
Stores address of the variable 8a9 .
or
Now <ptr= will contain the address of the variable <a= .
Note :
[box]Pointers are always initialized before using it in the program[/box]
Example : Initializing Integer Pointer
W
#include<stdio.h>
int main()
{
int a = 10;
int *ptr;
TU
ptr = &a;
printf("\nValue of ptr : %u",ptr);
return(0);
}
Output :
Value of ptr : 4001
JN
Pointer arithematic
Incrementing Pointer:
Incrementing Pointer is generally used in array because we have contiguous memory in array and
ll
106
Address + 1 = Address
Address++ = Address
ld
++Address = Address
Pictorial Representation :
or
W
Data Older Address stored in Next Address stored in pointer after
Type pointer incrementing (ptr++)
#include<stdio.h>
int main(){
A
ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
107
return 0;
}
Output :
New Value of ptr : 1002
ld
Live Example 2 : Increment Double Pointer
#include<stdio.h>
int main(){
or
double *ptr=(double *)1000;
ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
W
return 0;
}
Output :
New Value of ptr : 1004
Live Example 3 : Array of Pointer
TU
#include<stdio.h>
int main(){
float var[5]={1.1f,2.2f,3.3f};
float(*ptr)[5];
JN
ptr=&var;
printf("Value inside ptr : %u",ptr);
ptr=ptr+1;
printf("Value inside ptr : %u",ptr);
return 0;
}
ll
Output :
Value inside ptr : 1000
A
108
ld
or
Explanation :
Address of ptr[0] = 1000
We are storing Address of float array to ptr[0]. 3
Address of ptr[1]
W
= Address of ptr[0] + (Size of Data Type)*(Size of Array)
= 1000 + (4 bytes) * (5)
= 1020
Address of Var[0]…Var[4] :
TU
Address of var[0] = 1000
Address of var[1] = 1004
Address of var[2] = 1008
Address of var[3] = 1012
Address of var[4] = 1016
JN
109
ld
float 1000 0996
or
Explanation:
Decrementing a pointer to an integer data will cause its value to be decremented by 2
This differs from compiler to compiler as memory required to store integer vary compiler to
W
compiler
Pointer Program: Difference between two integer Pointers
#include<stdio.h>
int main(){
TU
float *ptr1=(float *)1000;
float *ptr2=(float *)2000;
printf("\nDifference : %d",ptr2-ptr1);
return 0;
}
JN
Output :
Difference : 250
Explanation :
Ptr1 and Ptr2 are two pointers which holds memory address of Float Variable.
Ptr2-Ptr1 will gives us number of floating point numbers that can be stored.
ptr2 - ptr1 = (2000 - 1000) / sizeof(float)
ll
= 1000 / 4
= 250
A
Live Example 2:
#include<stdio.h>
struct var{
110
char cvar;
int ivar;
float fvar;
};
int main(){
ld
struct var *ptr1,*ptr2;
or
printf("Difference= %d",ptr2-ptr1);
return 0;
}
W
Output :
Difference = 142
Explanation :
ptr2-ptr1 = (2000 - 1000)/Sizeof(struct var)
= 1000 / (1+2+4)
TU
= 1000 / 7
= 142
Adding integer value with Pointer
In C Programming we can add any integer number to Pointer variable. It is perfectly legal in c
programming to add integer to pointer variable.
JN
ptr = ptr + 3;
Live Example 1 : Increment Integer Pointer
A
#include<stdio.h>
int main(){
111
ptr=ptr+3;
printf("New Value of ptr : %u",ptr);
return 0;
}
ld
Output :
New Value of ptr : 1006
Explanation of Program :
or
In the above program 3
int *ptr=(int *)1000;
this line will store 1000 in the pointer variable considering 1000 is memory location for any of
the integer variable.
W
Formula :
ptr = ptr + 3 * (sizeof(integer))
= 1000 + 3 * (2)
= 1000 + 6
= 1006
TU
Similarly if we have written above statement like this 3
float *ptr=(float *)1000;
then result may be
ptr = ptr + 3 * (sizeof(float))
JN
= 1000 + 3 * (4)
= 1000 + 12
= 1012
Suppose we have subtracted <n= from pointer of any data type having initial addess as
<init_address= then after subtraction we can write 3
ptr = initial_address - n * (sizeof(data_type))
ll
ptr = &n ;
ptr = ptr - 3;
112
int main(){
ld
int *ptr=(int *)1000;
or
ptr=ptr-3;
printf("New Value of ptr : %u",ptr);
return 0;
W
}
Output :
New Value of ptr : 994
Formula :
ptr = ptr - 3 * (sizeof(integer))
TU
= 1000 - 3 * (2)
= 1000 - 6
= 994
Summary :
JN
#include<stdio.h>
int main()
{
113
ptr1 = &num ;
ptr2 = ptr1 + 2 ;
printf("%d",ptr2 - ptr1);
ld
return(0);
}
Output :
2
or
ptr1 stores the address of Variable num
Value of ptr2 is incremented by 4 bytes
Differencing two Pointers
Important Observations :
W
Suppose the Address of Variable num = 1000.
= 1004 - 1000
=4
A
114
ld
Consider the below statement and refer the following table 3
int num = ptr2 - ptr1;
and
or
If Two Pointers are of Following Data Numerical Technical
Type Difference Difference
Integer 2 1
W
Float 4 1
Character 1 1
TU
Comparison between two Pointers :
Pointer comparison is Valid only if the two pointers are Pointing to same array
All Relational Operators can be used for comparing pointers of same type
All Equality and Inequality Operators can be used with all Pointer types
Pointers cannot be Divided or Multiplied
JN
int main()
{
int *ptr1,*ptr2;
ll
return(0);
}
115
int main()
{
ld
int *ptr1;
float *ptr2;
or
if(ptr2 > ptr1)
printf("Ptr2 is far from ptr1");
return(0);
}
W
Explanation :
Two Pointers of different data types can be compared .
In the above program we have compared two pointers of different data types.
It is perfectly legal in C Programming.
[box]As we know Pointers can store Address of any data type, address of the data type is
TU
<Integer= so we can compare address of any two pointers although they are of different data
types.[/box]
Following operations on pointers :
== Equals
A
!= Not Equal
116
int main()
{
int *ptr1,*ptr2;
ld
return(0);
}
Output :
or
W
TU
JN
Pointer to pointer
Pointer to Pointer in C Programming
Declaration : Double Pointer
int **ptr2ptr;
ptr2ptr = &ptr;
117
ld
or
W
Statement What will be the Output ?
*ptr 45
**ptr2ptr 45
TU
ptr &n
ptr2ptr &ptr
JN
Notes :
Conceptually we can have Triple ….. n pointers
Example : *****n,****b can be another example
Live Example :
#include<stdio.h>
ll
int main()
{
int num = 45 , *ptr , **ptr2ptr ;
A
ptr = #
ptr2ptr = &ptr;
printf("%d",**ptr2ptr);
118
return(0);
}
Output :
45
ld
or
W
TU
JN
ll
A
119
UNIT-IV
ld
INTRODUCTION TO STRUCTURE
As we know that Array is collection of the elements of same type , but many time we have to
store the elements of the different data types.
or
Suppose Student record is to be stored, then for storing the record we have to group together all
the information such as Roll, name, Percent which may be of different data types.
W
A structure is a convenient way of grouping several pieces of related information together.
Definition of Structure in C
Structure is composition of the different variables of different data types, grouped under same
name.
TU
typedef struct {
char name[64];
char course[128];
JN
int age;
int year;
} student;
char name[64];
A
char course[128];
int age;
int year;
120
Structure member may be of different data type including user defined data-type also
ld
typedef struct {
char name[64];
char course[128];
or
book b1;
int year;
} student;
W
Here book is user defined data type.
In C we can group some of the user defined or primitive data types together and form another
compact way of storing complicated information is called as Structure. Let us see how to declare
TU
structure in c programming language 3
struct tag
{
JN
data_type1 member1;
data_type2 member2;
data_type3 member3;
};
ll
struct <structure_name>
A
structure_Element1;
structure_Element2;
121
structure_Element3;
...
...
ld
};
or
Members of structure are enclosed within opening and closing braces.
W
Memory is created, very first time when the variable is created /Instance is created.
struct date
TU
{
int date;
char month[20];
JN
int year;
}today;
struct date
A
int date;
char month[20];
122
int year;
};
ld
struct date today;
or
struct Book
int pages;
W
char name[20];
int year;
}book1,book2,book3;
TU
C Structure Initialization
Let us discuss very familiar example of structure student , we can initialize structure variable in
different ways 3
JN
struct student
char name[20];
ll
int roll;
float marks;
A
}std1 = { "Pritesh",67,78.3 };
In the above code snippet, we have seen that structure is declared and as soon as after declaration
we have initialized the structure variable.
123
std1 = { "Pritesh",67,78.3 }
ld
struct student
char name[20];
or
int roll;
float marks;
std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};
W
In this example, we have declared two structure variables in above code. After declaration of
TU
variable we have initialized two variable.
std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};
struct student
int mark1;
int mark2;
ll
int mark3;
} sub1={67};
A
Though there are three members of structure,only one is initialized , Then remaining two
members are initialized with Zero. If there are variables of other data type then their initial
values will be 3
124
integer 0
ld
float 0.00
char NULL
or
Way 4 : Initializing inside main
struct student
W
int mark1;
int mark2;
int mark3;
};
TU
void main()
{
JN
- - - - --
- - - - --
- - - - --
};
ll
When we declare a structure then memory won9t be allocated for the structure. i.e only writing
below declaration statement will never allocate memory
A
struct student
125
int mark1;
int mark2;
int mark3;
ld
};
or
Some Structure Declarations and It9s Meaning :
struct
W
int length;
char *name;
}*ptr;
*name = "programming";
++ptr->length
126
(++ptr)->length
ld
Content of the length is fetched and then ptr is incremented.
Expression Meaning
or
++ptr->length Increment the value of length
W
(ptr++)->length Increment ptr after accessing length
Array elements are accessed using the Subscript variable, Similarly Structure members are
accessed using dot [.] operator.
ll
Live Example :
#include<stdio.h>
127
struct Vehicle
ld
int wheels;
char vname[20];
char color[10];
or
}v1 = {4,"Nano","Red"};
int main()
W
{
Output :
JN
Vehicle No of Wheels : 4
Note :
Dot operator has Highest Priority than unary, arithmetic, relational, logical Operators
ll
128
struct Book
char bname[20];
ld
int pages;
char author[20];
float price;
or
}b1[3] = {
{"Let us C",700,"YPK",300.00},
W
{"Complete C",1200,"Herbt Schildt",450.00}
};
Explanation :
As soon as after declaration of structure we initialize structure with the pre-defined values. For
TU
each structure variable we specify set of values in curly braces. Suppose we have 3 Array
Elements then we have to initialize each array element individually and all individual sets are
combined to form single set.
{"Let us C",700,"YPK",300.00}
Above set of values are used to initialize first element of the array. Similarly 3
JN
struct Book
ll
{
A
char bname[20];
int pages;
char author[20];
129
float price;
};
void main()
ld
{
{"Let us C",700,"YPK",300.00},
or
{"Wings of Fire",500,"Abdul Kalam",350.00},
};
W
}
#include<stdio.h>
TU
struct Book
char bname[20];
JN
int pages;
char author[20];
float price;
}b1[3] = {
{"Book1",700,"YPK"},
ll
{"Book2",500,"AAK",350.00},
A
{"Book3",120,"HST",450.00}
};
130
void main()
ld
printf("\nBook Name : %s",b1[0].bname);
or
printf("\nBook Price : %f",b1[0].price);
W
Output :
Explanation :
In this example , While initializing first element of the array we have not specified the price of
book 1.It is not mandatory to provide initialization for all the values. Suppose we have 5
JN
structure elements and we provide initial values for first two element then we cannot provide
initial values to remaining elements.
{"Book1",700,,90.00}
struct Book
A
char bname[20];
int pages;
131
char author[20];
float price;
}b1[3] = {
ld
{},
{"Book2",500,"AAK",350.00},
{"Book3",120,"HST",450.00}
or
};
Output :
Book Name :
W
Book Pages : 0
Book Author :
It is clear from above output , Default values for different data types.
TU
Data Type Default Initialization Value
Integer 0
JN
Float 0.0000
Character Blank
Live Example :
132
#include<stdio.h>
#include<conio.h>
//-------------------------------------
ld
struct Example
int num1;
or
int num2;
}s[3];
//-------------------------------------
W
void accept(struct Example sptr[],int n)
int i;
for(i=0;i<n;i++)
TU
{
scanf("%d",&sptr[i].num1);
JN
scanf("%d",&sptr[i].num2);
//-------------------------------------
ll
int i;
for(i=0;i<n;i++)
133
printf("\nNum1 : %d",sptr[i].num1);
printf("\nNum2 : %d",sptr[i].num2);
ld
}
//-------------------------------------
or
void main()
int i;
W
clrscr();
accept(s,3);
print(s,3);
getch();
TU
}
Output :
Enter num1 : 10
JN
Enter num2 : 20
Enter num1 : 30
Enter num2 : 40
Enter num1 : 50
Enter num2 : 60
ll
Num1 : 10
A
Num2 : 20
Num1 : 30
Num2 : 40
134
Num1 : 50
Num2 : 60
ld
Explanation :
When reference (i.e ampersand) is not specified in main , so this passing is simple pass by value.
or
Elements can be accessed by using dot [.] operator
W
Pointers are used to store the address of memory location.
Example :
struct Sample
TU
{
}s1;
s1.ptr = #
s1.name = "Pritesh"
Here num is any variable but it9s address is stored in the Structure member ptr (Pointer to
ll
Integer)
Similarly Starting address of the String <Pritesh= is stored in structure variable name(Pointer to
A
Character array)
Whenever we need to print the content of variable num , we are dereferancing the pointer
variable num.
135
printf("Name : %s",s1.name);
ld
#include<stdio.h>
struct Student
or
{
W
}s1;
int main()
{
TU
int roll = 20;
s1.ptr = &roll;
JN
s1.name = "Pritesh";
return(0);
A
Output :
136
ld
We have stored the address of variable 8roll9 in a pointer member of structure thus we can access
value of pointer member directly using de-reference operator.
or
Similarly we have stored the base address of string to pointer variable 8name9. In order to de-
reference a string we never use de-reference operator.
Array of Structure :
Structure is used to store the information of One particular object but if we need to store such
W
100 objects then Array of Structure is used.
Example :
struct Bookinfo
{
TU
char[20] bname;
int pages;
int price;
JN
}Book[100];
Explanation :
In case if we need to store the Information of 100 books then Array of Structure is used.
b1[0] stores the Information of 1st Book , b1[1] stores the information of 2nd Book and So on
ll
137
ld
Accessing Pages field of Second Book :
Book[1].pages
or
Live Example :
#include <stdio.h>
W
struct Bookinfo
char[20] bname;
int pages;
TU
int price;
}book[3];
int i;
for(i=0;i<3;i++)
ll
gets(book[i].bname);
138
scanf("%d",book[i].pages);
scanf("%f",book[i].price);
ld
}
for(i=0;i<3;i++)
or
{
W
printf("\nPrice of Book : %f",book[i].price);
return 0;
}
TU
Output of the Structure Example:
139
ld
Price of Book : 200
or
Price of Book : 300
W
Price of Book : 500
Union in C Programming :
{ {
JN
}s1; }s1;
ll
If we look at the two examples then we can say that both structure and union are same except
Keyword.
A
int roll;
char name[4];
140
int marks;
We have collected three variables of different data type under same name together.
ld
or
W
For the union maximum memory allocated will be equal to the data member with maximum size.
In the example character array 8name9 have maximum size thus maximum memory of the union
will be 4 Bytes.
Suppose we are accessing one of the data member of union then we cannot access other data
member since we can access single data member of union because each data member shares
same memory. By Using Union we can Save Lot of Valuable Space
JN
Simple Example:
union u
char a;
ll
int b;
}
A
Union is similar to that of Structure. Syntax of both are same but major difference between
structure and union is 8memory storage8.
141
In structures, each member has its own storage location, whereas all the members of union use
the same location. Union contains many members of different types,
Syntax :
ld
union tag
or
union_member1;
union_member2;
union_member3;
W
..
..
..
union_memberN;
TU
}instance;
Note :
Unions are Declared in the same way as a Structure.Only <struct Keyword= is replaced
JN
with union
union stud
{
ll
int roll;
char name[4];
A
int marks;
}s1;<
142
ld
or
W
How Memory is Allocated ?
TU
Union Members that compose a union, all share the same storage area within the computers
memory
Each member within a structure is assigned its own unique storage area
Unions are useful for application involving multiple members, where values need not be
assigned to all the members at any one time.
A
While accessing union, we can have access to single data member at a time. we can access single
union member using following two Operators 3
In order to access the member of the union we are using the dot operator. DOT operator is used
inside printf and scanf statement to get/set value from/of union member location.
ld
Syntax :
variable_name.member
or
consider the below union, when we declare a variable of union type then we will be accessing
union members using dot operator.
union emp
W
int id;
char name[20];
}e1;
TU
id can be Accessed by 3 union_variable.member
Syntax Explanation
Instead of maintain the union variable suppose we store union at particular address then we can
access the members of the union using pointer to the union and arrow operator.
ll
union emp
{
A
int id;
char name[20];
}*e1;
144
Syntax Explanation
ld
e1->name Access name field of union
or
C Programs
#include <stdio.h>
W
union emp
int id;
char name[20];
TU
}e1;
e1.id = 10;
JN
printf("\nID : %d",e1.id);
strcpy(e1.name,"Pritesh");
printf("\nName : %s",e1.name);
return 0;
ll
Output :
A
ID : 10
Name : Pritesh
#include <stdio.h>
union emp
ld
int id;
char name[20];
}e1;
or
int main(int argc, char *argv[])
e1.id = 10;
W
strcpy(e1.name,"Pritesh");
printf("\nID : %d",e1.id);
printf("\nName : %s",e1.name);
return 0;
TU
}
Output :
ID : 1953067600
JN
Name : Pritesh
As we already discussed in the previous article of union basics, we have seen how memory is
shared by all union fields. In the above example 3
= sizeof(name)
ll
= 20 bytes
Firstly we have utilized first two bytes out of 20 bytes for storing integer value. After execution
A
of statement again same memory is overridden by character array so while printing the ID value,
garbage value gets printed
146
#include <stdio.h>
union emp
ld
int id;
char name[20];
}*e1;
or
int main(int argc, char *argv[])
e1->id = 10;
W
printf("\nID : %d",e1->id);
strcpy(e1->name,"Pritesh");
printf("\nName : %s",e1->name);
return 0;
TU
}
Output :
ID : 10
JN
Name : Pritesh
Bit fiels:
struct {
ll
} status;
147
This structure requires 8 bytes of memory space but in actual, we are going to store either 0 or 1
in each of the variables. The C programming language offers a better way to utilize the memory
space in such situations.
If you are using such variables inside a structure then you can define the width of a variable
which tells the C compiler that you are going to use only those number of bytes. For example,
ld
the above structure can be re-written as follows −
struct {
or
unsigned int widthValidated : 1;
} status;
W
The above structure requires 4 bytes of memory space for status variable, but only 2 bits will be
used to store the values.
If you will use up to 32 variables each one with a width of 1 bit, then also the status structure will
use 4 bytes. However as soon as you have 33 variables, it will allocate the next slot of the
memory and it will start using 8 bytes. Let us check the following example to understand the
concept −
TU
#include <stdio.h>
#include <string.h>
JN
struct {
} status1;
ll
A
struct {
148
} status2;
int main( ) {
ld
printf( "Memory size occupied by status1 : %d\n", sizeof(status1));
return 0;
or
}
When the above code is compiled and executed, it produces the following result −
W
Memory size occupied by status2 : 4
struct {
TU
type [member_name] : width ;
};
Elements Description
width The number of bits in the bit-field. The width must be less than or equal
A
The variables defined with a predefined width are called bit fields. A bit field can hold more
than a single bit; for example, if you need a variable to store a value from 0 to 7, then you can
define a bit field with a width of 3 bits as follows −
149
struct {
} Age;
ld
The above structure definition instructs the C compiler that the age variable is going to use only
3 bits to store the value. If you try to use more than 3 bits, then it will not allow you to do so. Let
us try the following example −
#include <stdio.h>
or
#include <string.h>
struct {
W
} Age;
int main( ) {
Age.age = 4;
TU
printf( "Sizeof( Age ) : %d\n", sizeof(Age) );
Age.age = 7;
Age.age = 8;
return 0;
}
ll
When the above code is compiled it will compile with a warning and when executed, it produces
the following result −
A
Sizeof( Age ) : 4
Age.age : 4
Age.age : 7
150
Age.age : 0
Typedef:
The C programming language provides a keyword called typedef, which you can use to give a
type, a new name. Following is an example to define a termBYTE for one-byte numbers −
ld
typedef unsigned char BYTE;
After this type definition, the identifier BYTE can be used as an abbreviation for the
type unsigned char, for example..
or
BYTE b1, b2;
By convention, uppercase letters are used for these definitions to remind the user that the type
name is really a symbolic abbreviation, but you can use lowercase, as follows −
W
typedef unsigned char byte;
You can use typedef to give a name to your user defined data types as well. For example, you
can use typedef with structure to define a new data type and then use that data type to define
structure variables directly as follows −
TU
#include <stdio.h>
#include <string.h>
char title[50];
JN
char author[50];
char subject[100];
int book_id;
} Book;
int main( ) {
ll
Book book;
A
151
book.book_id = 6495407;
ld
printf( "Book subject : %s\n", book.subject);
return 0;
or
}
When the above code is compiled and executed, it produces the following result −
W
Book author : Nuha Ali
typedef vs #define
TU
#define is a C-directive which is also used to define the aliases for various data types similar
to typedef but with the following differences −
typedef is limited to giving symbolic names to types only where as#define can be used to define
alias for values as well, q., you can define 1 as ONE etc.
JN
#include <stdio.h>
#define TRUE 1
ll
#define FALSE 0
A
int main( ) {
152
return 0;
ld
When the above code is compiled and executed, it produces the following result −
Value of TRUE : 1
Value of FALSE : 0
or
Enumerated data type:
An enumeration is a user-defined data type consists of integral constants and each integral
constant is give a name. Keyword enum is used to defined enumerated data type.
W
enum type_name{ value1, value2,...,valueN };
Here, type_name is the name of enumerated data type or tag. And value1,value2,....,valueN are
values of type type_name.
By default, value1 will be equal to 0, value2 will be 1 and so on but, the programmer can change
the default value.
TU
// Changing the default value of enum elements
enum suit{
club=0;
JN
diamonds=10;
hearts=20;
spades=3;
};
Above code defines the type of the data but, no any variable is created. Variable of
type enum can be created as:
A
enum boolean{
false;
true;
153
};
ld
Example of enumerated type
#include <stdio.h>
or
int main(){
today=wednesday;
W
printf("%d day",today+1);
return 0;
Output
TU
4 day
You can write any program in C language without the help of enumerations but, enumerations
helps in writing clear codes and simplify programming.
The exact size of array is unknown untill the compile time,i.e., time when a compier compiles
code written in a programming language into a executable form. The size of array you have
declared initially can be sometimes insufficient and sometimes more than required. Dynamic
memory allocation allows a program to obtain more memory space, while running or to release
space when no space is required.
Although, C language inherently does not has any technique to allocated memory dynamically,
ll
there are 4 library functions under "stdlib.h" for dynamic memory allocation.
A
154
malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
ld
Allocates space for an array elements, initializes to zero and then returns a pointer to
calloc()
memory
or
free() dellocate the previously allocated space
W
malloc()
The name malloc stands for "memory allocation". The function malloc()reserves a block of
memory of specified size and return a pointer of type voidwhich can be casted into pointer of
any form.
TU
Syntax of malloc()
ptr=(cast-type*)malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory
with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
ptr=(int*)malloc(100*sizeof(int));
JN
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively
and the pointer points to the address of first byte of memory.
calloc()
The name calloc stands for "contiguous allocation". The only difference between malloc() and
calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple
ll
blocks of memory each of same size and sets all bytes to zero.
Syntax of calloc()
A
ptr=(cast-type*)calloc(n,element-size);
This statement will allocate contiguous space in memory for an array of nelements. For example:
ptr=(float*)calloc(25,sizeof(float));
155
This statement allocates contiguous space in memory for an array of 25 elements each of size of
float, i.e, 4 bytes.
free()
Dynamically allocated memory with either calloc() or malloc() does not get return on its own.
ld
The programmer must use free() explicitly to release space.
syntax of free()
free(ptr);
or
This statement cause the space in memory pointer by ptr to be deallocated.
Write a C program to find sum of n elements entered by user. To perform this program, allocate
W
memory dynamically using malloc() function.
#include <stdio.h>
#include <stdlib.h>
int main(){
TU
int n,i,*ptr,sum=0;
scanf("%d",&n);
JN
if(ptr==NULL)
exit(0);
ll
}
A
for(i=0;i<n;++i)
156
scanf("%d",ptr+i);
sum+=*(ptr+i);
ld
printf("Sum=%d",sum);
free(ptr);
return 0;
or
}
Write a C program to find sum of n elements entered by user. To perform this program, allocate
memory dynamically using calloc() function.
W
#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;
TU
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr==NULL)
JN
exit(0);
}
ll
for(i=0;i<n;++i)
A
scanf("%d",ptr+i);
157
sum+=*(ptr+i);
printf("Sum=%d",sum);
ld
free(ptr);
return 0;
or
realloc()
If the previously allocated memory is insufficient or more than sufficient. Then, you can change
memory size previously allocated using realloc().
W
Syntax of realloc()
ptr=realloc(ptr,newsize);
#include <stdio.h>
TU
#include <stdlib.h>
int main(){
int *ptr,i,n1,n2;
scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
for(i=0;i<n1;++i)
ll
printf("%u\t",ptr+i);
scanf("%d",&n2);
ptr=realloc(ptr,n2);
158
for(i=0;i<n2;++i)
printf("%u\t",ptr+i);
return 0;
ld
}
or
W
TU
JN
ll
A
159
UNIT-IV
FILES
ld
Until now we are using Console Oriented I/O functions.
<Console Application= means an application that has a text-based interface. (black screen
window))
or
Most applications require a large amount of data , if this data is entered through console then it
will be quite time consuming task
Main drawback of using Traditional I/O :- data is temporary (and will not be available during re-
execution )
W
TU
JN
Consider example 3
We have written C Program to accept person detail from user and we are going to print these
details back to the screen.
ll
Now consider another scenario, suppose we want to print same data that we have entered
previously.
A
160
ld
In C we have many functions that deals with file handling
A file is a collection of bytes stored on a secondary storage device(generally a disk)
Collection of byte may be interpreted as 3
or
Single character
Single Word
Single Line
Complete Structure.
W
TU
JN
161
ld
or
W
Standard Input Stream Device
stdin stands for (Standard Input)
Keyboard is standard input device .
TU
Standard input is data (Often Text) going into a program.
The program requests data transfers by use of the read operation.
Not all programs require input.
Standard Output Stream Device
stdout stands for (Standard Output)
JN
Stands
Standard Input Standard Output
For
A
162
Data (Often Text) going into a data (Often Text) going out from a
Data Flow
program program
ld
Operation Read Operation Write Operation
or
Point Input Stream Output Stream
W
IO Function scanf and gets printf and puts
163
ld
accepted by the system terminal or simple text editor.
Files with the .txt extension can easily be read or opened by any program that reads text and, for
that reason, are considered universal (or platform independent).
or
Text Format Contain Mostly English Characters
What are Binary Files
Binary Files Contain Information Coded Mostly in Binary Format.
Binary Files are difficult to read for human.
W
Binary Files can be processed by certain applications or processors.
Only Binary File Processors can understood Complex FormattingInformation Stored in
Binary Format.
Humans can read binary files only after processing.
All Executable Files are Binary Files.
TU
JN
Explanation :
As shown in fig. Binary file is stored in Binary Format (in 0/1). This Binary file is difficult to
read for humans. So generally Binary file is given as input to the Binary file Processor. Processor
ll
Executable Files
Database files
164
Before opening the file we must understand the basic concept of file in C Programming , Types
of File. If we want to display some message on the console from the file then we must open it in
read mode.
Opening and Defining FILE in C Programming
ld
Before storing data onto the secondary storage , firstly we must specify following things 3
File name
Data Structure
or
Perpose / Mode
Very first task in File handling is to open file
File name : Specifies Name of the File
W
TU
165
Opening Previous
Purpose
Mode Data
ld
Writing File will be opened just for writing purpose Flushed
or
file
W
Firstly we need pointer variable which can point to file. below is the syntax fordeclaring the file
pointer.
FILE *fp;
Step 2 : Opening file hello.txt
fp = fopen ("filename","mode");
TU
Live Example : Opening the File and Defining the File
#include<stdio.h>
int main()
{
FILE *fp;
JN
char ch;
return(0);
}
If we want to open file in different mode then following syntax will be used 3
ll
166
void main()
{
ld
FILE *fp;
char ch;
fp = fopen("INPUT.txt","r"); // Open file in Read mode
while(1)
or
{
ch = fgetc(fp); // Read a Character
if(ch == EOF ) // Check for End of File
break ;
printf("%c",ch);
W
}
fclose(fp); // Close File after Reading
}
File Opening Mode Chart
r Reading 3 NULL
Create New
w Writing Over write on Existing
JN
File
Create New
a Append 3
File
167
Appending File
Explanation :
File can be opened in basic 3 modes : Reading Mode, Writing Mode, Appending Mode
ld
If File is not present on the path specified then New File can be created using Write and
Append Mode.
Generally we used to open following types of file in C 3
or
File Type Extension
C Source File .c
W
Data File .dat
TU
Writing on the file will overwrite previous content
EOF and feof function >> stdio.h >> File Handling in C
Syntax :
int feof(FILE *stream);
JN
What it does?
Macro tests if end-of-file has been reached on a stream.
feof is a macro that tests the given stream for an end-of-file indicator.
Once the indicator is set, read operations on the file return the indicatoruntil rewind is called, or
ll
A ] In Text File :
Special Character EOF denotes the end of File
As soon as Character is read,End of the File can be detected
168
ld
{
printf("%d", EOF);
}
or
B ] In Binary File :
feof function is used to detect the end of file
It can be used in text file
feof Returns TRUE if end of file is reached
W
Syntax :
int feof(FILE *fp);
Ways of Writing feof Function :
Way 1 : In if statement :
if( feof(fptr) == 1 ) // as if(1) is TRUE
TU
printf("End of File");
Way 2 : In While Loop
while(!feof(fptr))
{
JN
--- - --
--- - --
}
argc
A
argv[]
where,
169
In real time application, it will happen to pass arguments to the main program itself. These
arguments are passed to the main () function while executing binary file from command line.
ld
For example, when we compile a program (test.c), we get executable file in the name <test=.
Now, we run the executable <test= along with 4 arguments in command line like below.
or
Where,
argc = 5
argv[0] = <test=
<this=
W
argv[1] =
argv[2] = <is=
argv[3] = <a=
argv[4] = <program=
argv[5] = NULL
#include <stdlib.h>
if(argc!=5)
return 1;
A
170
ld
printf("3rd arg : %s \n", argv[3]);
or
return 0;
W
OUTPUT:
171