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

C Lang Module1 Part1

c language textbook engineering

Uploaded by

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

C Lang Module1 Part1

c language textbook engineering

Uploaded by

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

•,_ • : 'I

/ •• ;' •: I
•••- • 1."
-
·, ,. -~
I
Programming in C & Data Structures Basics: Module-I

2.1. Algorithm and flowchart

• AJgori th ~ is t_he step by step description of program logic where each step is
numbered m hierarchical order.
• Number of steps must be finite
• Every step ~ust be complete, unambiguous and error free.
• Flowchart 1s the graphical representation of the algorithm.

2.2. Advantages of algorithm (pseudocode)

The advantages or benefits of algorithms are as follows·


• Step by step representation of a solution to a given problem, which is very easy to
understand
• It has got a defimte procedure
• It is easy to develop an algorithm and then writing a flow chart and then a computer
program
• It is independent of programming language
• It is easy to debug as every step is got its own logical sequence.

2.3. Basic flow chart symbols

Basic flowchart symbols are used to represent the logic involved in solving a problem. Basic
symbols are listed below:

1.
c==:> Oval: represent terminals
(start or stop )

Rectangle: Represents the process steps


2. .._[___,/ (computational steps initialization )

3.L.--/__7 Parallelogram: Represent input and output operation.

4.
Rhombus: Indicates decision

Arrows : Shows flowchart direction and connect various


5.

6.
l 1
<}------)>~
symbols of flowchart.

Represents the looping condition especially for loop.

Circle: shows continuations from one point in the process flow


7.
0 to another. (connector) . .
used to identify an operation that is more fuJly descnbed m a
B.
I_ I_ Ij d . thi
separate flowchart. Functions are represente usmg s
symbol

5
. U1
Programming . C & Data Structures Basics: Module •
1

. . the advantages of algorithm?


Questions: What is an algonthm? What are . . flowchart?
What is flowchart? List the symbols used for wnting ·

2.4. Structure of C program with example

To develop a c program, the basic • lements are preprocessor statements, comments, global
e f · ( ) fun f d d
declaration of vanables or functions, implementation mam ° c ion an user efined
functions. h bJ •
The arrangements of these basic elements in C progr_am are ~ s own e ow·
• The execution of C-program begins from main function •
• Preprocessor is a program which is invoked by complier before the compilation of
user written program. The declaration of preprocessor statements always begin with
(#), usually these are placed before the main( ) function.
• Functions mcluding the main( ) function declare the variables to store temporary
values. These vanables are called local variables and are accessible only within the
function it is declared.
• Global declarartions: variables which are declared globally can be used by or
accessible from any functions present in a program
• Generally comment line gives the description of the program.
• C allows user to write or create their own functions to perform specific task. These are
called as user defined functions and are usually defined after the main() function.
• C program can be compiled and executed using C compiler such as Turbo and
Borland.

Pre processor directives


Comment lines
Global declarations
main()
{
local declarations of variables
expressions and statements
}
_User defined functions

Figure I: Structure of a C program


Example 9: #include<stdio.h>
/* prints value of a • ;
main ()
{
int a= 10·
'
printf ( " value of a is % d \ ,, )·
getch( ); n ,a •
}

Output: value of a is I0

6
Programm·mg m
· C & Data Structures Basics: Module-I

In the above example,


1. #include<stdio.h>
. . is preproccssor stateme t d
. Next 1me 1s comment line descr'b· n use for standard Input output funct"
2
3. main( ) ~ction where executio1 mgf program purpose ion
.thin • . n o program b .
4 • Wt mam function mt a= 10 • 1Ocal egms.
statement. , ts declaration of variable, followed by printf

Question: Explain the structure of a C program with


. example.

2.S. C language and its features

C programming language was developed at Bell Lab . .


important features of C programming languag o~tones
e are as 101lows:m 1972 by DeMis Ritchie. The

• Structured programming language


• Provides various operators (an'thmetic,
• increment
• decrement)
• Helps to develop efficient programs '
• Can ?e com~iled and executed on any computer.
• Provides vanous _data types (int, float, char etc.)
• Allows use of pointers for array, memory functions etc provide high level constructs
• Allows user to make exclusive use of function calls.

2.6. C Tokens
C-Tok~ns are the smallest individual units of a C-prograrn. These are the basic building
blocks m a C program that cannot be further broken down into elements.
There are mainly five C tokens namely:
• Keywords
• Identifiers
• Constants
• Strings
• Operators

Keywords
Key words are the predefined words in a C compiler which are meant to perform specific
function in C program. Keywords cannot be used for naming variables, identifiers and
functions. C language supports 32 keywords namely int, float, double, long, short, char, it
else, switch, case, for, while, gqto, do, break, continue, struct, enum, extern, typedef, cons~
auto, register, default, volatile, sizeof, static, signed, return, union, void, unsigned.

Identifiers
Identifiers are the names provided to the elements of a program such as variables, functions
and arrays. Identifier consists ofletter, number or an under score. Rules for writing identifiers
are as follows: (same rules are applicable for writing variables as it is a type of identifiers)

7
. C & Data StrUccurc:~ u""'""· iv10<1uJe•I
Programming in
. an have considerable nurnber
d then Jt c
underscore, an
• First character must be letter or
of digits, letter, under score tifiers
• Key words cannot be used as Iden u·ve under scores.
ha ·e two consecu d
• Identifier should not \ . bols cannot be use
• Punctuation, spaces, sp~c_iaJ sym
• Identifiers are case sens1t1ve salary, int_nurn, . . . ) @um (
L: v
Example 1or a 1
I'd identifiers· Salary, num, avg_
• • • (keyword) 9num ~
(~tarted with digit • n special
Example for Invalid identifiers: mt '
symbol @).
· that holds a data.
Note: Variables are the named storage locat10n

Constants
. . ble which cannot be modified in a program. In C
Constant is a fixed vaJue assigned to a vana d t
program constant is declared by using key wor ,~~ns ·
Example: const mt a = 3. J4, const char letter- .
Types of constants are as follows
• Integer constants
• Real or floating point constants
• Octal and hexadecimal constants
• Character constants
• Stnng constants . . .· .
Integer constants: these constants must have digits without decimal pomt and it can be either
positive or negative. Examples: 53, 462, -82 etc. . . . .
Real or floating point constants: these constants must have the digits along with decimal
point and it can be either posi6ve or negative. Examples: 3.142, 4.35, -1.234 etc.
Octal and hexadecimal constants: these are the numerical constants which start with Oand
Ox respectively. Example for octal: 075, Example for Hexadecimal: Ox75.
Character constants: these constants are a single alphabet, single digit or single special
symbol enclosed within single quotes. Example: 'a', '7', '@'etc.
Stri~g constants: these ~onstants are a single or several a]phabet(s), single or several digit(s)
or single or several special symbols or combination of these enclosed within double quotes.
Example: ''a@34", "74Y', "nanjesh" etc.

Operators

Operator is a symbol which hel t .£ .


0 t t . ps o per orm mathematical and logical computations.
Upera or ac s upon op~rands. MaJor types of operators are as follows·
l!~::.:: 1
: ,:::;;,~ :~:'f:;:3~ :J:appended
0
with an o~rand. Example: +a.
Ternary operator: consists of 3 0 er~ds _d_by binary ope~a!or. Example: a+b.
Example: (a>b)?a:b. P Joined by conditional expression operator.
Operators and its types are dis d· d . .
cusse in etail m section 5 of this Module.
Questions: Define tokens in c language and E .
c
What are the rules ior .. xp1am.
wnting variable in C .
programming.

8
• m C & Data Structures Basics: Module-I
Programming

2.7. Data types in C

. . the keywords w h tch


Data types are ' ar
ata stored m ;1t.F There are two major edata
usedtYPfor as Signing
• a type to a variable based on the
d • Basic d
. un amental / Built . da es namely:
• Den ved data types m ta types
• User defined data types ( usmg . typedef)

Basic / primitive / fundamental I b uilt


. in data types

.char
t d adata
Lll
type:
ta type: . it
1t . is
1s
used to sto har
used to storere ch 1 acter type data of one byte
or a computer - - n I to + 2wn-to e number
fi . s and ·its range depends on word length defined
fi
floating nwnber. 2 - 1 or 81 gned, 0 to 2 ° - l for unsigned. 1t cannot store
float data type: it is used to store rea l numbers th t h
prov1'des 6 d'1g1ts
· a~e~ decimal point. ·
a ave smgle precision floating point . lt
double data
provides of data. It providC:°;' 1 ~u,nbers !hat have double precision floating point. It
type: tt 1s used to store
accuracy
6
void data type: it stores no values W igtts after decnnal pomt.
as void. It has no range. · e cannot perform any operation on a variable declared

Table 1: Summary of basic data types

/ Types
Data
type
Size
(in bytes)
over 16 bit
Range

comouter
signed -128 to 127
Character char 1 unsi®ed Oto 255
signed -32768 to
2 +32767
Integer - Int
unsi®ed Oto 65535
3.4 e-38 to
Floating point float 4 3.4. e + 38
or Real
Double 1.7 e - 308 to
precision double 8 1.7 e + 308
floating point -
void 0
Non specific

Derived data
Derived data types
types are the data types derived from the fundamental data types. There ate
mainly three derived data types namely array, string and structure which are discussed in
detail in Module 4.

User defined
Type definitiondata typesof C allow user to define an identifier which acts as data type using an
feature
existing basic data type. Such identifier is called as user defined data types. It will be
discussed in detail in section 1.5 of Module IV.

9
· ·ts
and explalJ\ 1 types,minS•
onS'. Define data. typdetas M'ICS
QutSt\ the \,aSlC a •1 r in Cp,ograin
Write anote on

nme quallfitr ao d modifier


1.s. oat• •1 r
hlpe Qualifiers types of data type qual
Data •1 . troduced two ifiers
. 1sumdard Institute (ANSI) Ul ,
Amert·can Nationa
namely: nst
• co . during execution of pr
• volatile . . The va . is constant ogram, then
Const Type Qoahfier lue of va na bl e
such variables are dee\. ~~ in keyword c~nst. .
1
Example: const float p1 -Th. 42
g const int size~ 90, h
ge at any time by an ou .
. v~ lue of varia ble nnght c an tside factor,
Volatile type qualifierd: ing
e 1 ·1
such variables ~eclare u\ keyword vo au e.
Example: volaule mt a, otatile float a [201 ,

Datt Type Modifier

, Built mdata types exce 'd data type can eas1.1Y b modified by usin .g
data type mou1tfi
·
pt v0 1 . e er.
There are main. ly &o ur data type modifiers na 1 .
1
' me Y•
• signed
• unsigned
• long
• ort
signed:shindicates that value stored in
values in range of -2 n-t to a variab_le is c_ · ·
+ 2 n-t -1, where n 1s th apa~le ~f stonng nega~ive va1ues. The
Example: -128 to+ 127 for e size (m bits) of that part
tcul~ data type.
Declaration example: signe characters since n is 8 bits.
d int a; here variable a ca
unsigned: indicates value n store both positive an
stored in a variable is ca d negative values.
values in range of Oto 2n -1 pable of storing only po
, where n is the size (in sitive values. The
0 to+ 255 for characters bits) of that particular
since data type. Example:
Declaration ex~ple: unsig n is 8 bits.
:!: we ~ mcrease the storag
ned int a; here variable a
e ca pacity of a
can store only positive
variable from the stora
values.
. type usmg keyword ge
vanable lon g. long doubles the stora capacity of basic
ge capacity of data ty
Example: long int a; here pe used to declare
va ria ble a's e with 1 .
declaration taksiz
16 bit computer), long int
short: we can decrease es b ou~ ong 15 2 _b . .
the sto 4
rage capacit oi es o~ th yte s as it ts declared as int (in
data type using keyword e va nable a.
Example: short int a; sh or t short reduc Y a vana
ble _from th
es st0rage capacity of dae storage capacity of basic
By default int a reserves ta type to half
2 bytes for the . bl
vana e a but h .
' s ort mt a takes 1
byte only.
Questions: Explain brief
ly data tYP r
qua tfiers and modifiers
in C.

10
s Basics: Module-I
Programming in C & Data Structure

sequences in C
2.9. Backslash constants/ escape
ksl h
ash con stants h · h s. Mostly used bac as
C provides backsl ow : w Jc perfonns specific action
constants are listed bel

in C
Table 2: Iist of backslash constants

Backslash
constant Purpose
'\ a' Represents system alann
'\ b' Represents back space
'\ f' Represents form feed (next page)
'\n ' Represents new line
' \ r' Carriage return
' \ t' Tab space (Horizontal)
'\ v' Vertical tab
' \ "' Double quote
'\" Singe quote
' \ O' Null characters
'\\ ' Back slash character

2.10. Format specifiers


using standard
cifiers are used to specify the type of the value to be read or written These
Format spe
ns. Below table giv es the list of commonly used format specifiers.
input output functio ns.
fix within the standard I/O functio
are used along with % symbol as pre
Table 3: list of format specifiers

Format specifiers Representation


d, i signed integer
u unsigned integer
1 Long
h Short
Id long integer
hd short integer
f float point
If Double
e floating point in exponential fonn
C
character
s String

JI
. . C& Data Str0ctures Basics: Modulc..1
Programming in

2.11. Type conversion I Type casting . . f given type to another tyPe,


press1on o 8
of converltng an ex
Type conversion is the process
Types of con\'crsion are: ..
• Implicit type convers~on
• Explicit type conversion

Im licit type con,·ersion


P . A:«- rent, C automatically converts one type to
·
mhen the two operands m an ex press1on are
.
wu e
" . d I 1·
another. This 1s calle mp ict ·, type conversion.
Example I:
#includc<stdio. h>
#include<conio.h>
void main()
{
charb= 'A':
int a:
a=-b;
printn"¾d" ,a);
getch( );
l
Output: 65

Because here 'b' is character type, 'a' is integer type so 'C language' provides implicit
conversion of 'b' (char type) into integer type, ASCII value of A is 65 so it displays 65.

Example 2
#include<stdio.h>
#include<como. h>
v01d main()
{
double d = 123.456;
int a;
a=d;
pnnt (''%d", a);
getch( ),
}
Output:123
Since a 1s an integer. '• .

Eiplicit type conversion

~h~n the two operands in an expression are .


this is known as explicit conversion. different, user explicity changes th d
Example: e ata type,

12
Programming in C & Data Structures Basics: Module-I

void main() Can be changed as


void main()
{ ⇒
{
int a =4;
j' int a =4;
float b;
float b;
b= 1 /a~ b = l / (float)a ;
} }

Ou ut: 0.000000 Ou ut: 0.250000

Here a is explicitly changed from int data type to fl oat data type.

Questions: Define typecasting in C pro grarnmmg


conversions. · an d explam the different types of

3. Declaration, Assignment and Print statements

3.1. Declaration, Assignment and Initialization of variables

Definition: Varia bl es are the named storage location that holds a data. The rules for writing
variables are same as for identifiers.
• First character must be letter or underscore, and then it can have considerable number
of digits, letter, under score
• Key words cannot be used as Identifiers
• Variable should not have two consecutive under scores.
• Punctuation, spaces, special symbols cannot be used
• variables are case sensitive
Example: age, mun, _ sal etc.

Declaration
Each variable that are used in program must be declared. It is nothing but creating a variable.
Declaration of the same variable is not allowed in programming.
Example: int mun;

Assignment
The declared variables can be assigned a value using '=' operator. The values can assigned
any number of times in programming. Old value will be replaced by new value. This is called
assignment.
Example: age=l8, num=55 etc.

Initialization
The declaration of a variable and assigning a value at the declaration time 1s called as
initialization. Later the assigned value can be changed.
Example: int age=18; int num=55; etc.

13
- --- - - - - - - - - - - - - ~= ~;&lData :scruclwci; nas1cs: M0c:t
p
,.. prograJJl ming in C& lllt.!

• 5 r. ""' input/ output operations t ,


3l Joput Output u
F nct100 t peno, .. , . h · th · vo
t functions o tput library, stdio. ts e header fil
.• I input outpud d input / ou Ie
Clanguage prov1
.des severa
. l known as
stan ar
• are c0Uect1vc y
funcuons d' functions
that contains st ,o
stdio functions are:
• scanf
1 prinlf
• getchar
• putchar
• gets
• puts

formatted 1/0 functions . da types and way in which it should he


which specifies ta .
d r /0 functions are those tted I/0 functions
Formattc . anf and pnntf are the forrna
lt3d or pnnted. sc . function which reads input from the
. is fonnatted inpu 1
scanf( ) fuoction: scanf function
standard input device. , ddresslist )·
Syntax: scanf("control character' a
1
. ' type and fonn of value to be read.
where: control character ~etermdmdres of memory locations where values of input
address hst detenmnes a ess
variables should be read.
Example 1: scan~ "% d" , &b);
Reads integer value and stores in address of b.
Example 2: scanf( "¾c", &b);
Reads character and stores in address of b.

printf() function: printf function is fonnatted output function which displays (information)
output on the standard output device.
Syntax : printf("control character", variableslist);
where: control character determines type and fonnat of values to be displayed.
variable list is list of variables whose value has to be displayed
Example I : printf (" nanjesh");
Prints the string nanjesb on output screen
Example2: if a= I0, printf ("% d", a);
Prints the value IO stored in variable a.
Unformatted 1/0 functions

Unfonnatted 1/0 functions are those wh· h d . ·


should be read or printed. getchar putcb~cr O not specify data types and way in which it
' ' gets and puts are the unformatted 1/0 functions.
getchar( ) and putcbar( ): getchar and t h
. I h . pu c ar are un£
Ssingtax
e c faracter at a
t h . har
time and displays sin I h onnatted I/O functions which reads
g e c aracter at a t· .
yn o ge c ar. c acter = getchar( ); nne respectively at run time.
Syntax of putchar: putchar(character);
where character is of t .
Example: #include < stdio.h> yPe char variable.

14
Progranun tog m C & Data Structures Basics: ModuJe-J

#incJude<conio.h>
void main()
{
char character·
'
character = getchar( ) ·
putchar (character); '
getch( );
.
Ou tput: it reads a single character and a stores m a v ana · bl e named as character and displays
.
1t.
puts are th fi a string at a
gets( ) and puts( ): gets and respec t~v: ~nnatted J/0 functions which reads
time and drspla ys string at a tim e
Y
Syntax of gets: gets(string);
Syntax of puts: puts(string);
where: strmg is string variable nam e
Example : #include < stdio.h>
#include<conio.h>
void main()
{
char string[20];
gets(string);
puts(string) ;
} ys it.
re in a variable named as string and displa
Output: it reads a string and a sto

ut output functions in C.
Questions: Explain standard inp
) functions .
Write a note on printf() and scanf(

), getche( ), getcb( ):
. }, Difference between getchar(
v,,, During the
to get or rea d the inp ut (i.e a single character) at run time.
getcbar() is use d
cha rac ter is rea d thr oug h the getchar( ). The given value is
program execution, a single wa it for ano the r character to be typed. If you pre
ss
the com pil er
displayed on the screen and n onl y the given character is printed thr
ough
er cha rac ter s and the
the enter key/any oth
the printf function.
rac ter fro m con sol e, and ech oes to the screen. During the
getche( ) is used to get a cha rea d throug h the getche( ). The given value is
cha rac ter is
program execution, a single iler doe s not wait for another character to
be
and the co mp
displayed on the screen ction.
Then, afterw ard s the cha rac ter is printed through the printf fun
typed.
During the
get a cha rac ter fro m con sol e but does not echo to the screen.
getch( ) is used to d through the getcb( ). The given
value is not
, a sin gle cha rac ter is rea
program execution s not wait for another character
to be typed. And
scr een and the com piler doe
displayed on the
d through the printf function.
then, the given character is printe
r' Data Structures Basics: MOd
Programming in C& Ulc,1

JJ. Width sptcifica t•100 In p'rintf( ) h'ch is exp Iame


· d beJow using

si
.11 of the output w I tnpJe
•ntlY ) allows user to spec1·ry the w1 u
d
pn a, . 'fi d
examples. . (unction is right JUStt te .
. be s using printq )
Note: By default, displaying num r

Examples for Integer:


Output
If a= 12
pnntfl''% d'', a) 12 .5 lank here 4 indicates number of colurnns)
printr (''¾ 4d'', a) bb12 ( b ! bl k, here 4 indicates number of columns
prmtf ("% 4,2d",a) bbl2 ( b 1,5 ban 'umber of digits in 4 columns)
d 2 indicates n f
an 12 ere 4 indicates number o columns and 3
printf(" %4.3d''. a) ?O . ( h mber of digits in 4 columns bu.t here only
md1ca~e~ nu. ngmal number 12 hence It will be
two d1g1ts m o . I
. d
d1splaye as O12 without changing actua meaning)·
printn "%4.Id", a) ⇒
bbl 2 ( here 4 indicates number of columns and I
. d t number of digits in 4bcolumns h but here
m 1ca es . .there
are two digits in original num er .12 ence 1t w1!l be
displayed as 12 only without changing actual meaning.)

Note: Using ,_, symbol we can make it as left justified.

printn''¾ d", a) ⇒ 12
printf (''% -4d", a) ⇒ 12bb (bis blank, here 4 indicates number of columns)
printf ("% -4.2d",a) ⇒ 12bb ( b is blank, here 4 indicates number of columns
and 2 indicates number of digits in 4 columns)
print£{" %-4.3d", a) ⇒ 012b ( here 4 indicates number of columns and 3
indicates number of digits in 4 columns but here only
two digits in original number 12 hence it will be
printf{" %-4. Id", a)
displayed as 012 without changing actual meaning.)

12bb ( here 4 indicates number of columns and I
indicates number of digits in 4 columns but here there
are two digits in original number 12 hence it will be
displayed as 12 only without changing actual meaning.)
printf ("% .ld", a)
⇒ 12
printf ("% .2d",a)
⇒ 12
printf ("% Jd",a)
⇒ 012

Note: When number of columns is not specified that . .


having only%. number d (Example· o/cd
0
2d) d ' is - symbol m case of printf function
• • oes not make any effect on justification.
printf (''%-.Id", a) ⇒
12
printf ("% -.2d",a) ⇒
12
printf (''% -Jd",a) ⇒ 0
12

16
,
odule-I
.
Pro&rammin gm C & Data Structu
res Basics: M

ting number:
Examples for floa
If float a = I03 .267 Output 6 digits
printf('o/of', a) 103 7
by de fault, float provides
af te } !ec~00(
unal point.)
ple :
Generalized exam
x)
printf("¾a.bf'', .
r o f columns r,or- an integer part.
e num be
a is
where . . th th
o f digits to be r
. mal point.
b 1s e number oring floatingimi~ed aftere.the deci
x is the variable st pomt valu

8
If float x= l03 . 16 the numb Of r an integer partinan
d
⇒ I03. I 7 (here 4 is d. er •columns fo al po t.)
pnntf{''%4.2 f' , x) f decim
2 is the number o igits to be limited after the
.
e w e ha ve sp ecif ie d tw o d. .
te r de ci m al po m t, 1t results 103.17
e exampl ifg,ts af " .1ts aft er decimal pomt)
Note: In the abov6, because the value at the po SJ·t·ion o b (numb er Of d1g
instead o f J03 .1
cceeding value.
depends on its su
th en increm en t th I
es en t at th e po si tion b or elseljustb
ding value is >=
5 • e va ue pr ple . th b e examp e
If the succee ber o f digits witho t any increment. For exam '. ~ e a ovde l point
limit the num . . after decimal oint) 15
u · Th
2 e pr esen t at po si tion 2 after· cuna 6 b
e valu 5h
(number o f digits ch is greate r th an ence increment Y

.P f 6 is 8 w hi
. . cceeding va lu e o
is 6 (m 10 3.168). Tsheassu10 3.17.
lt
one. Hence it resu
part and
oa t x=103. 16 5 m ber o f co lu m ns for an integer
If fl
f',x) ⇒ 1 ~3 .1 7 ( here 4 is the nu lim ite d af te r th e decimal point.)
printf("%4 .2 f digits to be
2 1s the number o
in t) is 2. T he value present at
cimal po is equal to 5 henc
e
e b (n um be r o f digits after de o f 6 is 5 w hi ch
ampl value
In the above ex al p o in t is 6. The succeeding
de cim
position 2 after H en ce it results as l 03.1
7.
b y on e.
increment 6
co lu m ns fo r an integer part and
4 number o f
If float x= 103.16 I 03 .1 6 ( here 4 is the ed af te r the decimal poin
t.)
⇒ be li m it
printf("%4.2f',x) 2 is the number
o f digits to
esent at
m al po in t) is 2. The value pr
b (n u m b er o f digits after deci is 4 w hi ch is less than 5 hence it
ample lue o f 6
In the above ex al p o in t is 6. T he succeeding va en t. H en ce it results as I03 .16.
position 2 after de
cim any increm
its af te r de ci m al point without
dig
is limited to two

4. Expressions ce s to a sing le value where an


ch redu
ce o f op eran ds and operator whi al or logical operations and an
sequen athemat ic
Expression is a at tells co m p iler to perform m
bol th ed.
operator is a sym w hich an op eration is perform ,~,= etc.
operand is an ob
ject on
8 etc. E xa m ple for operators:+
ands: a, b, 5,
Example for oper
ression: c=a+b;
Example for exp
e5 of Eipressioll
4,t. TYP t,e}ow:
classified as
E.xpressions are
• prunatY
• postfix
• prefix
• UnarY
• B1J1arY
• ternarY . . t of only one operand with no operator.
• Assigrune?t . .rnar)' expression cons is s
.
Prtnlary expression.
,, ,, , , pn
etc. d followed by an operator ('increment
faaroples: age , a ,5 . t of an operan or
• o· cons1s s
Postfix eipress10 .
decrement).
les· a++ b·· etc. ~ nowed by an operand (mcrement
. or decrement)
Exarop . ,' . onsists of an operator o .
Pref11 expression. c .
Examples: ++a, ..a etc.. t r followed by one operand as m prefix expression
. ns1sts of one opera o .
. can have vanable as
Unary expressto~: co . bl as operand But unary expression
but Prefix expression needs a vana e
well expression as operand.
Examples: +a,·~, +(al+t~/a~•brm)
Binary E1press10n: ts 10
:~-by an operand operator and then followed by an operand
' •
Example: a+b, a•b, a*b, a%b, alb.
Ternary Expression: It is of the form operand?operand:operand
Example: y=(a>b)?a:b;
if the expression(a>b) is true then y is assigned with 'a' value or else 'b' value.
Assignment e1pression: Evaluates operand or expression on the right side of operator (=)
and stores in variable on left.
Example: if a=lO, b=5, if expression is c=a+b, then c=l5, that is the addition of 'b' and 'c' is
evaluated and stored in 'c' using assignment(= )operator.

Writing C expression for the mathematical expression

Basic conversions:

✓x ~ sqrt(x) /*squareroot of x */

lxl ~ abs(x) /*absolute value ofx*/

xY ~pow(x,y) /* x to the power y*/


X
e ~ exp(x) /*exponential power of x */

sin x ~ sin(x) I* sine ofx*/

sin 450 gin ((45*3.142)/180)


and dividing by J80*/ /*converting degree to radians b . .
Ymultiplymg with pi value
Priority
. given for the an'thmet'IC Operati
are given first priority and then subtractns are as follows multipli .
ion and addition ~ CODsi~tion, division and mod
18 The first preference
Progranun· .
mg tn C & Data Structures Basics: Module-I
(he left most operator in case of sam . .
to d d e pnonty ope tor is
. .
given. This concept is explained
. detail in prece cnce an associativity sc • . ra
1n cuon of this module.

Example 1: A= Sx + 3y
~ A::={ Sx + 3y)/(a+b)
a+b

Example 2: B = ✓ s(s-a)(s-b)(s-c) 8 =sqrt(s*(s-a)*(s-b)*(s-c))


lx+y-101
Example 3: C = e c::=:::> C i:: exp(abs(x+y-10))
Example 4: D = x2s + y3s ~ D = pow(x.25) + pow(y,35)

✓x
Example 5: E = e + e ~ E=(exp(sqrt(x))+exp(sqrt(y)))/(x•sin(sqrt(y))
X sin✓y
2
Example 6: X = -b + "1l -4ac ~ X = (-b + sqrt(b*b-4*a*c))/(2*a)
2a

Questions: Define an Expression in C. Explain its categories with example.

5. Operators in C
Operator is a symbol which helps to perfonn mathematical and logical operations on
operands

5.1. Types of operator

Following are the types of operators available in C:


• Unary Operator
• Assignment operator
• Arithmetic operator
• Increment and Decrement operator
• Relational operator
• logical operator
• Bitwise operator
• Conditional operator
• Special Operator
• Shorthand Assignment Operator

S.2. Unary operator


. h. d to operate upon only one operand is called as unary operator.
Operator wh1c 1s use
Examplel: a== 5, b == 7
c=(+a)+(-b)
C =(+5)+(-7) =-2

19
Programming in C& Data Structures 8 .
asics: ~
• °<lu1
+ lllld _ are the unary operators actmg on the O '·I

~ dI
In the abo1 e examP1e JlCrands
,cspccrively, a
Example 2: a~s
1 1
a-:::.ath of •a' is changed to -5 where • is the unary operator.
here evaIue
S.3. Assignmtot operator
OpcralOI' »hich is used to assign a new value to a variable is called as assi
• . l t &nment 0 10
•=' s)mbol 1s the ass1gnmenopera or. JJera
£.<ample: a= 3, b= 4 t,
d=a+ b, here a+b value is assigned to d using assignment operator =.

E.<amplc program: Cprogram to demonstrate unary and assignment operator

#include<stdio.h>
#include<conio.h>
\'Oid main( )
{
int a= 3 b=4 c d ·
I I I I

c~ a+ (-b), t • unary as well assignment•/


pnntf ( c = %d\n", c)·'
11

getch();

Output C= -1

5.4. Arithmetic operators

•C provides operators
namely: . . to perfonn anfhmetlc
. . operations . There are
five arithm t· .
multtphcation e IC operal!ons
I division a*b
% modulus (mod) a/ b
subtraction a %b
+ addition a- b
a+b
Rules for Aritbmeti
• First evaluat/ operator evaluation
• peuonn
..c.
mulf unary
r .plus or mmus · if • any
• Perfo .'P ication or division .
• . mt add11ton or subtr . or mod operators fr
Finally use assignment o action from left to right om 1eft to right (if multiple)
perator. ·
Example 1: 5%3=2
Modulus operator gives the remainder.
.

Example 2: b =a+ ( *
Ifa =5 c=4 d=6 -c) d I e %f
' , , e=3, f=2
then b = 5 +(-4) * 6 /3 %2

.,sn
. . Programm·mgmC&D
. ata Structures Basics: Module-I

flow of evaluation usrng above ti


b = 5 +(-4) • 6 /3 % 2 our rules:.
b = 5- 4*6 / 3%2 ~ mmus is evaluated
b = 5- 24/3 %2 ~ m~l~i~lication is performed
24 3
b = 5-8¾2 8o/c 2 d1v1s1_on is performed
b = 5- 0 ° mod ts performed
b =S a ·subtraction
5-0 · is perfiorme d
ss1gmng value 5 to b

Example
• 1 program:
l uJ C program to demonstrate 'thm .
s1mp e ca c ator operations) an ehc operators
(
#include< stdio.h>
#include<conio.h>
void main()
{
int a,b,c,d;
int sum, sub, mul, rem·
float div; '
printf ("enter value of a and b")·
scanf("¾d¾d", &a,&b); '
sum = a+b;
sub = a-b·
'
mul = a*b;
div= alb;
rem= a% b;=%din, sub= %din, mu1=%dln div=% fin
printf("s~
0
rem= '¼din" sum
sub,mul,div, rem) ; ' ' '

getch( );

Output:
Enter value of a and b
8
4
sum=12
sub=4
mu1=32
div=2
rem=O

S.S. Relational operator


Relational operator compares two operands to find the relation between them.
Different relational operators are:
< less than
<= less than or equal to
> greater than
>= greater than or equal to
= = equal to (used within conditional, iterative statements)

!= not equal to
21
trate relational operators.
to demons rson •/
1: Cpro~)igibility of a pe
Example pr~beck voung e
1•cpro~. h>
#include<s '?· h>
#include<conlO,
void main ()

{ .
in~ a.~.:enter age of person ,
'')·
Pnnu\ )'
. -n" ...,
.,_.,l\ iou
J'', & age '
1• use of> =
•/
'f(age >-= 18) ")
• printf (''eligible ;

else printf ("not eligible");


getch( );
}
Output I:
Enter age of person
16
Not eligible
Output2:
Enter age of person
19
Eligible

The above conditions can be changed as


if (age<= 18)
printf("not eligible"); /* use of< =* /
else
printf{'' eligible");

Example program2: C program to demonstrate relational operators


t • C program to find biggest of two numbers * /
#include< stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf("enter the value of a and b'')-
scanf("¾d¾d", &a,&b); '
if( a=b)
Printf("a and b are equal"); /* use of== ==• /
else if ( a >b)

cl~ printf(" a is greater than b")·


,
I* USe of>•/
printf("a is less than b")·
getch( ); '
}
Prograrom·mg m
. C & Data Struotures Basics: Modu1e-l

utl:
the value of a and b:

is greater than b

Qutput2:
Enter the value of a and b
8
12
a is less than b

Qutput3:
Enter the value of a and b
8
8
a and b are equal

The above conditions can be changed as


if( a= b) .
printf (" a and bare equal'');
/* use of <*/
else if( a <b)
printf (" a is less than b");
else
printf (..a is bigger than b"):

S.6. Logical operators


Logical operators are used to perform logical operations or to combine results of multiple
relations. Logical operators in C are as follows:

Negation
&& Logical AND
II Logical OR

Let Rl, R2, be the relations then


Table 4: Logjcal operators

Rll\R2 ! Rl
Rl R2 Rl &&R2 T F
T
T T T F
f
T F T T
T F
F F T
F F
F
Note: Consider Tor True as I and For False as Othen && operation is multiplication of
RI& R2, II operation is addition of R1 & R2 and ! as opposite of R\.

23
, --al ,o de"'
onsuate logical operattons
t,ers • /
l: Cp!0!9 -- st of3 nUJl1
~pit~fiidtht b1¢
,.c~o.lv
#ind~·oh'7
. 1~oru ·
s,nc ·-')
1
\oid rnat "
l in• a.b,c; ..aiues of .,i,&c"); .
nrinttr•enter o1. ,,,. &a,&b,&c ),
t'". ff .../,d o/.d ,O'J '

~(~b)&&(aX)) . •')
1f ( . f (''a is bigger
pnnt ))
else if((b~t~'tr:igget);
pnn 1\
else printf ( ., c is bigger");
getch();
}
Outpot:
Enter values of a,b, & c
11
13
09
bis bigger
Example program2: Cprogram to demonstrate logical operations
#include<stdio.h>
#include<conio.h>
void main()
{
int age;
printQ'' enter the age ");
~can~ "%d", & age);
if (age _18) II (age> 18))
pnnt~"eligible")·
else ' /*use of II •/
Printf("n t 1· ·
getch( ); o e igible");

Output!:
Enter the age
19
Eligible

Output2;
Enter the age
18
Eligible I • .~
Programming in C & Data Structures Basics: Module-I

5.7. Bitwise operator

Bitwise operator assumes operand as string of bits and bit operations are done on this operand
The bitwise operators are as follows:
&: Bitwise ~ oper~tor compares each bit of first operand with corresponding bit of
second operand tf both bits are 1_, t!1en corresponding bit is set to 1 else to 0.

\: Bitwise inclusive OR op~rator co?1~ares each of bit of first operand with the corresponding
bit of second operand. If either of btt 1s 1, the result is set to 1, else-0 . ,

[ ,. : Bitwise Exclusive OR op~rator compares each bit of first operand with corresponding bit
01 second operand. If one bit is Oand other bit is 1, the result is set to l, otherwise set to 0.
...
,.., : Bitwise negation operator assigns Ofor each 1 bit and l for each Obit.

<<: left shift operator shifts the bits position to left.

>>: right shift operator shifts the bits position to right.

Working of right shift and left shift

ifx = 98;
x=x > > 3; right shift for 3 times

(move right keep on adding zero to left part)


64 32 16 8 4 2 1
+ + + + + + +
1 1 0 0 0 1 0 given x=98
' 0- 1 1 0 0 0 1 first right shift
O O 1 1 0 0 0 second right shift
O O O 1 1 0 0 third right shift) stop

Answer ➔ 12

if X =4
X =x <<3 left shift for 3 times

(move left keep on adding zero to right part)


64 32 16 8 4 2 1

i i i i i i i
0 0 0 0 1 0 0 given x=4
0 0 0 1 0 0 0 firstl~
0 0 1 0 0 0 0 second left shift
0 1 0 0 0 0 0 third left shift
~

Answer➔ 32

Note: a<<n gives the value a*2°


a>>n gives the value a/2°

25
, dernonstrate
left and right shift operation
nrarn to
gram: c pro!Y-
nxafl'Ple pro
d ~tdio,h;,
#include <conio,h::;,
#incJU ~
vo1
'drnatn()
{ int x, Y
x::::98;
y::::4;
X:::: X,-:,,3;
_ <<3; after 3 right shifts = %d",x);
y::::prt~tf (''The value offxy after 3 left shifts = %d" ,y);
''The value o
prttnf (
getch()

Output 'ght shifts === 12


The value of x after 3 n . -
The "atue of y after 3 left shifts - 32

S.S. Conditional operators


Condittonal operators are called as ternary operator which uses ? and : operator.
Syntax: el? e2:e3
where el, e2, and e3 are expressions
First el is evaluated , if it is true then e2 is evaluated or else e3 is evaluated
Example I: a= 4
b=3
y= (a>b)? 1 : 0
el ? e2 : e3
. here y value becomes 1 since a >b
It 1s equivalent to ·
if ( a>b)
y=l;
else
E y=O·
xample2: consider belo; equaf
c- ions:
-26a + 3 for a < 2
C= a+ S -
the above equations can be for a > 2
represented us.
tng conditional
c= (a>2)? (2 operator as below·
• · a + 5) : (6a+3 ·
It is equivalent to )

if(a>2)
else c 2a +s
C 6a+3
Program mmg
· m· C & Data Structures Basics: Modu1e-I

5.9. Special operators

Special opei:ators in_ C are used to per£ . functions


.
expressions into a smgle expression us·mgormcomma
special such
• as. combining multiple
.
sizeof() operator. operator, gettmg size of data type usmg

comma operator:
. combines multiple ex press1ons
. intO · 1
The value of nght most expression is assi d smg e expression.
Example 1: x =(a = 4, b= 5, c= 2, c+a•b ); gne to left variable.
x == (c+(a•b))
X = 22
Exarnple2: a = (c=2, b=3 );
a=b==3
a=3
Size of operator: used to determine size of the operand based •
Example 1: float x = 13.21; on its data type.
int y;
y=sizeof(x);
here the value of y is 4 since the size of float is 4 bytes.

Example pro~am: C program to demonstrate special operators.


#include<std10.h>
#incJude<conio.h>
void main ()
{
int d, a, b;
d =(a = 5I b= 4 ' a+b)·'
printf("value of dis ¾d\n", d);
printf ("size of d is ¾d\n", sizeof ( d) );
getch( );
}
Output:
Value of dis 9
Size of dis 2

5.10. Short band assignment operator


Short hand Assignment operator is used to write or use operators of C in compact manner. lt
mainly considers arithmetic and bitwise operators. If the operand at left side of the
assignment operator (=) is same as the first operand in right side expression then it can be
written as common operand, operator, then assignment operator then followed by remaining
expression at the left.
Example: a = a+b ➔ a + = b
Similarly we can write for other bitwise and arithmetic operators:
a=a+b ⇒ a+=b
a=a-b ⇒ a-=b

a*=b
a=a*b

a%,=b
a=a%b
27
aJ:::::b
a= a/b ⇒ a<<::::: b
a== a<<b ⇒ ..">>= b
iV

a= a >>b ⇒ a":::: b
a == a "b ⇒ a&::::b
a== a&b ⇒ al= b
a = alb ⇒ f short hand assignment operators
mto demonstrate use o
Example program: C progra
#include<stdio.h>
#include<conio.h>
void main()
{
int a=8, b::4,c==2; •!
/* a==a+b
a+==b; ;• b==b-c *I
~c;_ /* c==c*b *I
c -b, 01 d\n" a,b c)·
printf("a==¾d\n, b=¾d\n, c= 10 ' ' '
getch( );
}
Output:
a= 12
b==2
c=4

5.11. Increment and decrement operator

We can increment or decrement the value of a variable using increment (++) or decrement
(-) operator. Increment operator adds one to variable. Decrement operator subtracts one from
variable.
Preincrement and predecrement: the value at right is first incremented or decremented,
then assigned to variable at left.

Example:
if a= 5, b=++a b= - - a
⇒ a=a+l=5+1 ⇒ a=a-1=5-1
⇒ b=6 ⇒ b=4

Postincrement or postdecrement· th . .
variable at right is incremented or d.e e va1uedis firS t asSigned to variable at left and then the
Examp Ie: cremente .
ifa=5, b=a++
b= a- -
⇒ b=a=5 ⇒ b=a=5
then a=a+ I == 6 then a=a-1 =4
Note: ++a is equivalent to a=a+ 1
--a is equivalent to a=a-1

You might also like