C Lang Module1 Part1
C Lang Module1 Part1
/ •• ;' •: I
•••- • 1."
-
·, ,. -~
I
Programming in C & Data Structures Basics: Module-I
• 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.
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 )
4.
Rhombus: Indicates decision
6.
l 1
<}------)>~
symbols of flowchart.
5
. U1
Programming . C & Data Structures Basics: Module •
1
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.
Output: value of a is I0
6
Programm·mg m
· C & Data Structures Basics: Module-I
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
8
• m C & Data Structures Basics: Module-I
Programming
.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
/ 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
, 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
JI
. . C& Data Str0ctures Basics: Modulc..1
Programming in
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. '• .
12
Programming in C & Data Structures Basics: Module-I
Here a is explicitly changed from int data type to fl oat data type.
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.!
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
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
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
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
Basic conversions:
✓x ~ sqrt(x) /*squareroot of x */
Example 1: A= Sx + 3y
~ A::={ Sx + 3y)/(a+b)
a+b
✓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
5. Operators in C
Operator is a symbol which helps to perfonn mathematical and logical operations on
operands
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 =.
#include<stdio.h>
#include<conio.h>
\'Oid main( )
{
int a= 3 b=4 c d ·
I I I I
getch();
Output C= -1
•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
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
!= 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 ;
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
Negation
&& Logical AND
II Logical OR
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
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.
ifx = 98;
x=x > > 3; right shift for 3 times
Answer ➔ 12
if X =4
X =x <<3 left shift for 3 times
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
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()
if(a>2)
else c 2a +s
C 6a+3
Program mmg
· m· C & Data Structures Basics: Modu1e-I
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.
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
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