0% found this document useful (0 votes)
35 views65 pages

r19 CP Unit-1 Complete

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views65 pages

r19 CP Unit-1 Complete

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

0 2020

Unit-
Jntxoduction to Compyte
Computey: A Computer is am electroic device

which takes mput amd process the data amd

Poduces tfe output

Process
/P O/P
doto

tuo types ot
A ts mainy 6uild notth the
A Compute
8oft uore
Compoments ColCed hordwovd and

the System
Hodware Jhe phystca Components of
CaCCed had 0 o r e povts of a Computer Ci.e.,
oxe

which we con touch and feel)


the pats
montter, etc.
: Keyboard, Cabine ts, mouse,
horddare
which makes
A Set 'of proqrams
otudare ane
Colled Soft uove
cotled Soft
the task
Compoments
to pevfovm
MS offce, ètc..,
a: Opevotirg dystem, Games,

Softwaves ave agoun differertly clossifted to tudo tupee


System &oftuwave ond Appl Cation &oftwove

Ie softuove whteh drecty inteocts uotth havd uorre


Copovment.s ave Colled ystem doftwove hese doftoa1e

ats
gots oS mdiotoN betueen a user ond horduDare
Applicotio oofl woie

Ge Sftorse hich oe used fo &oluing the dferewt

Knds o pqa ms
oe Cotted
Appltcotion 8oftuYTe

o(omerS o a Computey

CPU

ALU

CO
Devtces Devrces

Memo

9mput euices The devices uhch ore used to feed

Called 9mput dev ces


data to the Computex ore

&a: Keyboard, Po:tirq detce s, tmouse, etc.

devices whtch are used to show


Output Jevices : Jhe
the e6ults of processed data of a Computey are

Colled Output Devices

Pitevs, Moniton, Spe0ker etc


&

Centrol, Phocessirg Onit CpO) Jhe CP0 is used to ovoCess

he
the dota toD produce the different resutt

CPU mainly
ALO:
Arethemate Lmcol Unit of CPU s used to

of 8ystem, is called ALO


ar tthennatic and Logta unit

Contol Unt
is used to Control the au components
Control unit
pvesent im the 84stem ts colled Control UnYt

MermoYH:
Memory Unit s used toStove dota under pYoCesg

Conpu nviroNMALN
nvdvoneyt the4 ave fouT types.
Sm Computing
énutxonment
9 Pexsonal Computivg

2Jine Shave Computing enuiron


ment

3 Cet devvex Computing Environment


4ptstxbuted ComputingEnu vonment

Pe Soa Computn Enuxgnment:


the ComponentS axe
Environmert alt
Personat Computing
ond (ocated at dome place
tighted togethev
murronmet the
Conmputey Con 6e
9 m perSorat compurtirg
ot a time
he only one user
Used 6y
nuonnments ove
used tn per SOyOl Cormputing
Ihe Computexs

MtCYo Computey
Jime Sho i Computig Envevonment:
time shostq
Shoring Environnment One Cov) nmove usens Can
Comect uoith one Co) more 3ystemS

n Jine shorinq Environment oll the terminals printers

Storoge deuicesare Cormect to ome central System


and oll the Computotions are performed in thoat Centro

System
Ihe time shavtng Cormputivg Environmnent is 3(ouder og
thexe tS ov one centrol Computer to mamoge all the

tosks
aoal3o9oo
Clemt- ervev Computinq muionmet

S m client &er ver Envinomment ooY K iS shared 6etneen t

Central s t em md user &ystem

Jhe centval 8ustem ts used o Serve and uer Shstem

Oxe Knouwn as clientsS

As the wor is Shared between the Servey and elient

the pexfomance of this enoiroMment is better than


time shartvg environment
OSeA
ctieR
Pc

Cemlal (emputev

Stomo Pites
Distrrbuted Computig Envronymemt
Sex's

SexexIL
ternet Sevey

Sewe

Drsttbuted Computing Enuiament uSers ae o


gog
g to
to

ith tu»o (ov) moie Sexvers at a time by ust


Conmect

ntemet

Computy a
LovquagS Ore languageS which one desn to
Computer

wtth Computer.
CommuniCate

Computey anguoges
e destqm proqams
By
B u sing
n s t r u c t the Computer to
which
programs
dno deve Cop
Solve the problems

there
p o a m m i n g LonguageS there matnly too level

Longuoges here Ore

Lous CeveC Conauage

High Level Lorguage


cloKKfied into two t
LDUS Level Languoges agoun

Jhey ane

ond Assembly lomqua


Machine Language

Computey Number dystem:

pecimal Numbey dYstem: (Bax 10)

Decimal Number dygtem tt Contoins 10 Tonil


8ymkols Oil
In
0,1,2,3,H,5,6,1,3,9

mumbeys ore formed wtth


Combrnotiom of Above (0 Bymb
Al
in this System
decimal Number System the value of the numbey ts oStd

on the position of the mumber

the postion l u e
the mumber ts multipled orth
Joget
powers
asied to its Posttion
whose

891
8xo+AxIo'+\XI0

800+90+
BinayNumber dystem: (Bay a)
to
t uSes 2 symbolS momily 0,
n binary
Numvbex dystem
form the numberS

n bivmarry Number System the value of a Symbol at a gtven

Posion ts obtoined by mutiply the 6ymbol uhase poler is

Tised to positio
of the 8mbol

Decima o 2 3 5 G 78

oool o010 Ootl olo0 Olol ouO


oL loo0 Ioo I

Binor
Binory 0000

BnarH to DecMaCaRIsion

)Conwet lolO lool ito a decinnal number

Gtven
OlolO0|
1G54 3 2 0

I+LxO +I*2°+ox2+ tY3+ox2'+ox2'x Ix9


1 2 2 +Ot1x 32 +O+Ix8+0 +0+ 1

128+32+3+1

(1otolool), (16o
aConuert (IoiO-UlO) iNtd a decimal mumber

4 32to 1-2-3 -yH

Ix2+0ox?+\x1*+Ix2+0xX°+lx2"+1xTHxT+oK*
G+4+2+05 +0.2 +O12s

)8-8T5
ecimol to Biva Conuexon
)Convert (tG9)nto Binay vnum hev

269
2 84-
42-o
221 o

2-
2 -o

(19-(10loloo)
lo o loo|

Convevt (2 25) 1o nto Binary Numbey

.25
X2
2 6-0
oSO
2 23-o 2

S
2

|oII1O0 O
(12-25.toloo-o1),
Octal Number dy8tem: (Base 3

O c t a t Number 6ystemtt Cotain 8 nanmily Shombols

0,1,2,3,4,5,6,7
AL umberS oxe fomed otth com6tmation of thts Symbo

-
to et te Nalue of a sumbol tn octal Number
the dymbol
ith posrtion
u s t be mut PY otth whoge po DeY T*sd

of the 6mbol
Octal 2 5

oC
Binoy 000 oo ol ol

Octa to Decima Converstom


Comwert (1213)girto denucal Number

23
2 o

=Ix3+2x3 +3x2°
+82+3
G+16+8

83 (12) -(8
Conuert (12 35)jrtb dectmol Number
27 3 5

U®+2xg+1%8 + 3x+ Sx 2
G 4 + 6 +1+0:315+6 0181225

87453125

*|Deciwal to Octa Comyerstoy


umber
into Octal
Conveyt 186),.
D
9186
899-2
212 2
-4

(Iu)g
0etal muwbey
Convet (118 92) tnto 0 92
&)
818 36

23
-6
6-
6&.1210
( 47 o127)
t

CeTvet

Hea Nvk Base 1


Number Sytem it Contaw (6SymboS
Sn a decmial
oiu 0..235699 A8CD,&,F
A numkns are fon med t h Com bination thesE SHm
wéis

et t e values of sywbol i n hexadesinal tumber o

b
dt th ohese oouey is viseo
THL be mutip

of the Symbol
wth pos*en
Octal to Binari Convestoy
N

Corwert (63), into BtnoTy Number

6 3

(11D o)
Convert (63 2)g into 8inanumbe
G3 2
(1oOLtOLo)

Binoy Octo Comerstoy


Conveyt (tlotoo), to Octal number

(154)g
o6), ivto betol mumber
Comvert (tlo \DD

01
5 2

(IS4
Hexa demicol Numbe ystem: (Base 16)
decmiol Number Sy8tem it Contain l6 6ymbolS

nomi 0,1,134,5,6,1,3,9, A, B,C,D, E,F


AU uwbens ave for med tth
Com 6ination of these ®ymco
g e t the Values
vaues of Bymbol tm hexadectmal Nuber of dhe
To get th
6y8tem u ust be mauRply by t h whese powey s vised
u&tem

the ymbe
wtth po6ttion of
Decimal 3 45 6 189 O 17 13 4 y
Hexadecimal 3L4S 6 18 9

o ool Oolo odll olo0 olol otio l0od 1ool


lold lo 0olDI (11O (
OO00

tleva decimat to Dectma Convesfon:


owent (auF)into decimal Number

aF

6 16 t6

+XI6+Fx16°
ax a56 HxlG +IS xI
543
(5H
Corvert 8LF DE)nto deciwol Number
6

&F DE
20 l -2
6 1616 6 t6

+e
8xI6 +IXIG+ Fxl6 +Dx16 xIG
5 1 + 16 +IS t 0 8125 tO 6546 815

(s43-361375)
Decmal to Hexodec?wa Conuersto
into Hevadecimol Numbey
Convert C123)

1671-
tto heya deciv
Covevt (8345 48

6 1934S
7e76

64-33
c 3-
(.1 AE)6
(o39-70 h
10al20o

ConseyvQtton
Hexadecimol
Benor to
8eno
Numbey
(11oI|OIo), to He1ademiol
Convert

IlOIloIO
D A

(DAG
ComverS tOn
tlerodectmalto 8n
umbey
to Bino"u
)Convext (81FG
F

O01O 00o !|t


torn tegerS
numbeYS wtthout ony
An nteger is a Eet of whole

fvaction pat
Integers
tu00 types there oe Um SLgmed
ae 090um din gned Integergs
Integers

Unsigmed ntegeS
(tve) wmbers
aYe Set of posttive
Onsigned
tegers
Un e
irm Computer system,
tstored the unsigned integers f
ourm
m ard
number nttD
numbex
binoy
unto bnoTy
Comyertthe the
and
binary fovm dinectty
directyead
occuned n
Store the digds
authovmatiç
ue can perfovm all
tor umsigned nteger
stored dota
directly on
Operatioms
resuEt
ass
a aa negatie
nega-ie
a
8ubtroctiom if we get
Im
mumber
a.s &qned Snteger
automaticalty
the
number then

19ed tees
a e both posttue ond
aned teq negotive
hove fbuY diffevent
the -Ve nuber we
T o epreset
theie OvekStgm avd Magrtude
0
*Ovne s Complement
* [wos Compleme t
exceSS Comple nent

Magnitude Method:
OLg ond
n san t u d e method the Stan of a number ts

dectded by et most btt of he numbey ( E the numbe

s O t is +ve, it it I t rs _ve)
J o chonae the
San ot NLUMbeY Sa 3
number
the. left most bit ot
o
p + OO O
too zeo
nethnd t Contans +2 O o
n this
&(- ve O ooo) 3 OO
Oooo)

his SySten tS not Suttoble fox


O cthonettc opevatiom
used in
Ihis Sstem is main O
- t o

and qtat syst em


Aol
-31
One's CornplemerrtMethd - oO
5 O
I n this method the sign of a mumbe -- O

is decided by the left most btt of 1


mo. iS +Ne f *t s one to
a number f it is zeno the

all the desim


To chancge the Sm of a giuen o 4tp
of en mo-
(otom two zero v e o (dooo)
n this method tt

- Ve o (u1)
t s uSed in eovi Computer

Jos Complemert Method


I n ths method the 8qn of 0 MUMbeYs
decided 6y the left most 6rt f t is zevo(+ve)

f it is one (-ve) numbr


nunber Gps
stgn of ven
a
Two chorge e
Ovd add One to the esut
oits
hee mbe (r tor r T

7eo

MUmber s urtole for avtherngtie


This
O'

opeotOm
tuo's Complement mumbey
toring ond Petrwing O

of printf ond 8cayf


Explan the wovkng
n C fo 8m inte O

stot
Pead 9teg
Conet the
nteger erto benary

Ve
Ve

Complemert
t h e rauYrber

add

Store

Retrodi end
Retrievin
Stort

Ve Co

Compleme nt
he uume

add1

Convevt binary
to dectmal
odd &qn

(top)
Eomple Complemevnt and des
alopthm of tuooS
0Use stoiung
+l16 tm a t6 6ts ntegen
to tonC
the
the Steps
16

Bunony-
00000000 OlOO Oo
0 0 t 0 o It00 s Stored
O000000

Stoved
yetirg olgovithm hou ho
tn o
Iollous the

l6 bit in etrievina
btue in a

000000000001 0100
CycesS Complemeet Meth

h melhnd oe o*e tn

TUTnhe
golive

BIAS Im ber to the rnurt't rd orer tre


odd

nurber
eiAS numbe
vr Sutot e eAS
t the
the
4he tiw etrq, -fhe ye u . ! t
A o6oined
Ywri ro drpo
Yom he
atoe

19/0/2090
Overflouo

tor ing Reol Numbers


wn
Reot Numbers one wwbers t h foctiorol part

-314.625
e cause Scetitic. nolotion tD epYesert a real nuher
4he cientific notation Covtoirs 3 pis of itorrnotiov
he
egovdin9 the reol vumbev Jhe tvee pYeces ove

a recisiom
3) Pouwer
e Can repvesert -3H 625 os34 G25 xo, Nou the
S .3.146
6 25 X*D
10 dnd the po wer ¢s+2
r e cis ton
ner e Corve e reo nisreS in hvgr
ord Corput e e O1e

foce probler Tegodrgttwr a poitit of

biva Poivt
9binovy 3ystem we Cov oly storve b'ro daits m
not the birory Ponts

o 8 o b u e these problem we one gotrg t use a tehi

Called lovmalizatiov

Dalizatior we orralize ke uwbe 0 tha t

pot
Pot s auoy ot oyes povt /otoThe stav

3houló howe ovly bne bwary dgiE b


Hote t e yurbexs

the let f the poivt.


Molizotor proressfwe ove -the p o t to le,

pe ed to odd e umbey of digits shited-tb he

x wove poit tu Y T ,de need to 8ub he nunbey

of digits shrfted. fowthe pouer.

trun Peal Numbey in BinaTy

AHEN yoolizotit to te e reol u b e y in broy

e uce
u.Se tcee Co povexts iv the eal w u n b -
we

Say, e DOVt ard orissa


ee
+8 325
+8 85

+1000 0tx2

lovmalization l-ooo x2
ol

f:00ool y 2"

Motissa
>O0Ool,êzpomerto1

o Mortis sa
o ,

90l8o830
Retrtevng A hmso Real Numbers
otoringA and
Stor ing
Start

Reod Real Numbe/


+Ve
-vE n

S0

Conueyt the
humber tnto

bunary

Novmaze the nmumber

to Set () s(m)volues

Covert the (e)voue

Gtove 3,e,m Uoue g

Stop
: 183 125
3 8125

)The 6iqn f atven no s e So O

)The einoTy olue is I11oll1o1


6e
br malization number is 1.l6il |6l a 2
3)Afte M

4) Convert e t o eMcessby Addin9 121>137 +6 > (3

(133)1 (loo 0olo)

5) oT mantisse
n TeEe single preciston,it mort

Cotain23 bits i e loI I6l0 90rA 9 Sto


tuol16io
S
Retrieving Algoxi thnn o000olo

&tot

Corrt the \e' into


decimol fovm

AAdinT to tke
ManficSo

Corvet 1

to it
Sian
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

INTRODUCTION TO C

Basic Programming Terminology


Language
A language is a set of characters, words and associated grammar rules which is used for
communication between two human beings either spoken or written. Examples: Telugu, Hindi,
English etc.
Programming Language
A language which is used for communication between a human being and a computer. Human beings
communicate with the computer by writing programs using a programming language. Ex: C, C++, Java
etc.
Program
A program is a set of instructions for solving a particular problem or let the computer perform
operations for completing a task. Programs are written using programming languages.
Programming
The process of writing programs to instruct the computer do something is known as programming.
Programming is done using programming languages.
Programmer
A person who can write programs by using any one of the programming languages is known as a
programmer. A programmer has the knowledge of using atleast one programming language for
writing programs.
Software
Software is a collection of programs. Generally software is developed for solving complex problems. A
person who develops software is known as a software developer.

What is C?
C is a structured mid-level programming language for developing software. C follows structured
programming in which the instructions are arranged or structured using blocks and functions. C is
used for developing operating systems which are system software and also used to create application
software. Hence, C is known as middle level language.

Why C? (Advantages of C)
C is a powerful language using which we can develop operating systems, games and other application
software. The advantages or characteristics of C language are:

1) Powerful and Flexible: C is a flexible programming language. Using the concepts in C, a


programmer can developsoftware for almost any kind of purpose. Various concepts like pointers,
function, structures in C make it a powerful language.
2) Popular: C has wide spread popularity in the programming league as it is very easy to learn,
easy to writeprograms and easy to understand the programs written in C.
3) Portable: C is a machine independent programming language. Code written in C, can be
executed on any machineirrespective of the underlying hardware with little or no modifications.
4) Minimum set of Keywords: C89 has 32 keywords. These small set of keywords add power to
C language. A largeset of keywords does not mean that the language is more powerful.
5) Modular: In C, we can divide a problem into sub problems and solve the sub problems
individually using theconcept called as functions. This makes the programs written in C modular.
6) C and C++: As C++ is a superset of C, it inherits all the concepts in C, to which other new
concepts have beenadded. So, you can know how powerful the C language is.

CSE Page 1
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

Applications of C
The applications which can be developed using C language are literally unlimited. Some of the types of
applications which can be developed using C language are:
• Operating Systems
• Games
• Utilities
• Drivers
• Graphics
• Embedded System Software

History of C

The root of all modern languages is ALGOL (Algorithmic Language), developed in the early 1960’s.
ALGOL was the first language which introduced the concept of structured programming. In 1967,
Martin Richards developed the language called BCPL (Basic Combined Programming Language) for
writing system software. In 1970, Ken Thompson created a new language using the features from
BCPL and called it B. Both BCPL and B were typeless system programming languages.

C was developed by Dennis Ritchie in 1972 by using the features of ALGOL, BCPL and B programming
languages along with new features like data types. For many years, C was used mainly in academic
institutions, but with the release of many C compilers for commercial use and the increasing
popularity of UNIX, it began to gain widespread support among computer professionals. Today, C is
running under a variety of operating system and hardware platforms.

The language became more popular after publication of the book, “The C Programming Language” by
Brian Kerningham and Dennis Ritchie in 1978. The book was so popular that the language came to be
known as “K&R C”. The rapid growth of C led to the development of different versions of the language
that were similar but often incompatible. This was a serious problem for system developers.

In 1983, ANSI (American National Standards Institute) appointed a technical committee to define a
standard for C. The committee a version of C in 1989 which is now known as ANSI C. It was then later
in 1990 approved by ISO (International Standards Organization). This version of C is also referred as
C89.
In 1999, the standardization committee of C has added some new features to enhance the usefulness
of the language. The result was the 1999 standard for C, which also known as C99. In 2011, some more
new features are added to the C language, which is known as C11.

CSE Page 2
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

CREATING AND RUNNING C PROGRAMS:

The steps for creating and running programs are: writing/editing, compiling, linking and execution.
This can be viewed diagrammatically as shown below:

Writing/Editing: The first step in creating programs is, writing or editing the program. A program
can be written inany text editor like notepad. After writing a program, the program must be saved, In
C language, the program is saved with the extension “.c”. This is the source program written in a high-
level language.
Compilation: After writing and saving the source program, the next step is compilation. Here we will
use a softwarecalled as compiler, which converts a program written in high-level language into
machine language. The resultant file is known as an object file in C. The extension of that file is “.obj”.
Linking: After compilation the next step is linking. Here software called linker is used. The linker links
the programwith external library files which contains the code for predefined functions and creates
an executable file. The extension of the executable file is “.exe”.
Execution: Finally after the executable file is created after linking, the next step is execution. The
operating systemexecutes the executable file which is the machine code with the help of the CPU and
other hardware components.

CSE Page 3
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

STRUCTURE OF A C PROGRAM
Structure Of A C Program:
Every program written in C follows a certain structure. That structure is as shown below:

Documentation Section:
The documentation section is used to improve the readability and to understand various elements in
the program. This section is used to provide help for the general users. This section consists of plain
text written in English and includes information like author, purpose of the program, date on which
the program was created etc.
This section is included inside comments.
// is used for single line comment & /* */ is used for multi line comments
Example:
/******************************** *
* Author: Name *
* Date: 7/10/2012 *
* Purpose: Theme of the program *
**************************** *** */
Link Section:
The link section is used to include the external header files in which the pre-defined functions are
available. To use the pre-defined functions in our C programs, these files must be linked with our
program. Files can be included by using the “include” directive.
Example: #include<stdio.h>
In the above example “stdio.h” is a header file which is available in the system area in the
programmer’s computer. The angular brackets “< and >” tells the compiler to search the file “stdio.h”
in the system area. If we specify the above example as #include”stdio.h”, then the compiler searches
for the file “stdio.h” in the current directory.
Definition Section:
This section is used to define symbolic constants. Symbolic constants can be declared by using the
#define
directive. Example:
#define PI 3.142
Global Declaration Section:
This section is used for declaring global variables which can be throughout the program and for
declaring function prototypes. The global variables can be accessed by any function within the file.

CSE Page 4
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

main() Function Section:


The main() function is necessary in every C program. It specifies the starting point of
execution in a program. There should be a main() declared in every C program. The main() function
consists of the executable instructions and declaration statements. It may call other user defined
functions.
Subprogram Section:
This section includes the definitions of user-defined functions. A function is essentially a set of
instructions for performing a task. We can divide a problem into sub problems and write a function
for solving each sub problem.

Example: HelloWorld Program


/******************************** *

* Author: Teja *
* Date: 7/10/2012 *
* Purpose: To print Hello
World *
**************************** *** */
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf(“HelloWorld!”);
getch();
}

In the above example we can see three sections: documentation section, link section and main()
function section.

In the above program, /* and */ denotes multi-line comments. The /* indicates the starting of multi-
line comment and the */ indicates the ending of multi-line comments. Everything included between /*
and */ is ignored by the compiler. In the next line after the multi-line comments, #include is a pre-
processor directive which is used to link the program with external files like header files in which the
predefined functions are declared. The main() function is essential in every C program, as it specifies the
starting point of execution in a program. Everything starting from { to} is known as the body of the main
function. clrscr() function is used to clear the output screen (console). The printf() function is used to
output characters onto the console. Thegetch() function pauses the execution of theprogram, and waits
for a single character input from the user. The declaration of printf() is available in stdio.h (Standard
Input Output) header file and the declarations of clrscr() and getch() are available in conio.h (Console
Input Output) header file.

CSE Page 5
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

C TOKENS

Introduction
A programming language is designed to help process certain kinds of data consisting of numbers,
characters and strings and to provide useful output known as information. The task of processing data
is achieved by writing instructions. These set of instructions is known as a program. Programs are
written using words and symbols according to the rigid rules of the programming language known as
syntax

Character Set
The characters that can be used to form words, numbers and expressions depend upon the computer
on which the program is run. The characters in C, are grouped into the following four categories:
1) Letters
2) Digits
3) Special Characters
4) Whitespaces
The compiler ignores the white spaces unless they are part of the string constants. White spaces are
used to separate words from each other, but they cannot be used in between the characters of
keywords and identifiers.

C Tokens
In a paragraph of text, individual words and punctuation marks are considered as tokens. Likewise in
a C program, the smallest individual units are known as C tokens. C has six types of tokens as shown
below. C programs are written using these tokens and the syntax of the language.

Keywords
Every word used in a C program is classified as either a keyword or as an identifier. A keyword in C is
a reserved word which has a specific meaning. Keywords in C cannot be used as identifiers. Keywords
serve as the basic building blocks for program statements. Keywords in C are always in lowercase.
ANSI C supports 32 keywords & C99 supports 37 which are listed below:

CSE Page 6
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

_Bool

_Complex
_imaginary
Inline
restrict

Identifiers
Identifiers refer to the names of variables, functions and arrays. These are user-defined names and
consist of sequence of letters and digits, with a letter as a first character. Both uppercase and
lowercase letters can be used, although lowercase letters are generally used. The underscore
character is also permitted in identifiers. There certain rules while writing identifiers. They are as
follows:
1) First character must be an alphabet or underscore.
2) Must consist of only letters, digits or underscore.
3) Only first 31 characters are significant.(in C99 it accept first 63 characters)
4) Cannot use a keyword.
5) Must not contain white space.

Constants
Constants are fixed values, which do not change during the execution of a program. C supports several
types of constants, which are as shown below:

Boolean Complex
Constants Constant

Boolean constants: (added from C99)


C programming language (from C99) supports Boolean data type (bool) . A Boolean data type can take
only two values( i.e., true (= 1) or false (= 0) ). So for Boolean constants we can assign either true or
false value. A header file stdbool.h must be included to use bool in C.
Integer Constants
An integer constant refers to a sequence of digits. Generally in programs, the number systems used
are: decimal, octal and hexadecimal. Decimal integers consists of umbers from 0 to 9, preceded by an
optional + or – sign. Some valid examples of decimal integer constants are: 133, +45, -15, 0, 342332
etc. Embedded spaces and non-digit characters are cannot be used between digits.
An octal integer consists of numbers from 0 to 7. Octal integer numbers are always preceded by a
zero. For example if we have to represent 35 in octal system, we must write it as 035 in the program.
Some valid examples of octal integer constants are: 035, 02, 0435, +025 etc

CSE Page 7
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

An hexadecimal integer consists of numbers from 0 to 9 and 10, 11, 12, 13, 14 and 15 are represented
as A, B, C, D, E and F. Hexadecimal numbers are always preceded by 0x or 0X. Some valid examples of
hexadecimal integer constants are: 0x54, 0X23, +0x1F, -0X56 etc.
Real Constants
Integer numbers are not sufficient to represent quantities that vary continuously, such as distances,
height, prices etc. These quantities are represented by numbers containing fractional parts like
25.234. Such numbers are called as real or floating point constants. Some valid examples of real
constants are: 0.067, -12.5, +4.67, .87, 121. Etc.
A real number may also be expressed in exponential (scientific) notation. For example, 45.2344 can be
written 0.452344e2. The exponential notation is: mantissa e exponent. The mantissa is either a real
number expressed in decimal notation or an integer with an optional + or – sign. The exponent is an
integer number with an optional + or – sign. Some valid examples of real constants in exponential
notation are: 0.34e2, 13e-2, -1.23e-1 etc.
Complex Constants: (added from C99)
A complex constant approximates the value of a mathematical complex number. The constant is a pair
of real or integer values, separated by a plus sign. The first constant represents the real part of that
number; the second constant represents the imaginary part. The imaginary part is coded as a real
number times(*) the imaginary constants(_Complex_I). if complex library( complex.h) is included, the
imaginary constant can be abbreviated as I.
Example: 12.3+14.4*I
Single Character Constants
A single character constant or character constant contains a single character enclosed in between
single quotes. Some valid examples of character constants are: ‘f’, ‘A’, ‘/’, ’;’, ‘ ‘, ‘4’. The character
constant ‘4’ is not equal to the number 4. Every character constant will have an associated integer
value known as ASCII code. Since each character constant has an associated integer value, we can
perform arithmetic operations on them.
String Literals or String Constants
A sequence of characters that are enclosed between double quotes is known as a string literal or
string constant. The characters in a string literal can be either letters, digits or special symbols or
white spaces. The string literal does not have an associated integer value like the character constants.
Some valid examples of string constants are: “hai”, “hEllO”, “hi5”, “Wel come” etc.
Escape Sequences
C supports some special backslash character constants that are used in output functions like printf() .
For example to move the cursor from the current line to next line, there is no standard way to achieve
it. So, for such special cases, C provides escape sequences. In this case \n is used to move the cursor to
next new line. Even though the escape sequences consist of a backslash (\) and a character or symbol,
it is treated as a single character. C supports the following escape sequences:

Constant Meaning
\a Alert
\b Backspace
\f Form feed
\n New line
\r Carriage Return
\t Horizontal tab
\v Vertical tab
\’ Single quote
\” Double quote
\? Question mark
\\ Backslash
\0 Null

CSE Page 8
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

VARIABLES
Variables:
In the programs, generally we need to store values in the memory and perform operations on those
values. This can be achieved in C, by the concept of variables. A variable is a placeholder for holding a
value in the main memory (RAM). As the name implies, the value in the variable can change at any
point of execution of the program. For using variables in our programs, there are essentially two
steps:
1) Declare the variable
2) Initialize the variable

Declaring a Variable
Before using a variable in the program, we have to declare the variable. The syntax for declaring a
variable in a program is as shown below:

type variable-name;

The “type” in the above syntax represents the data type. The “variable-name” is the identifier. There
are certain rules that must be followed while writing the variable name. They are as follows:
1. A variable name must always start with an alphabet (letter) or an underscore ( _ ).
2. The variable name must not be more than 31 characters. The suggested length of a variable
name is 8 characters. (from C99 onwards name can contain 63 characters)
3. C is case sensitive. So, the variable name “average” is different from “AVERAGE”.
4. Keywords must not be used for declaring variables.
5. White spaces are not allowed within the variable name.

Initializing a Variable
After declaring the variable, we can assign a value to the variable. This process of assigning a value to
the variable is known as initialization. Syntax for initializing a variable is as shown below:

variable-name = value;

The value we assign to the variable depends on the data type of the variable.

Example:

int a;
a = 10;

The declaration and initialization can be combined into a single line as shown below:

int a = 10;

CSE Page 9
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

DATA TYPES
Data Types
A data type specifies the type of value that we use in our programs. A data type is generally specified
when declaring variables, arrays, functions etc. In ANSI C, the data types are divided into four
categories. They are:
1) Primitive or Fundamental data types
2) User-defined data types
3) Derived data types
4) Empty Data Set(i.e void)

Primitive or Fundamental data types


The primitive data types in C99 are as shown in the below diagram:

Primitive
data types

Floating-
Integral
point

Boolean Character Integer Float Imaginary Complex

Boolean DataType: (added from C99)


C programming language (from C99) supports Boolean data type (bool) . A Boolean data type can take
only two values( i.e., true (= 1) or false (= 0) ). So for Boolean constants we can assign either true or
false value. A header file stdbool.h must be included to use bool in C. bool variable size is 1 byte.
Character Datatype:
A character is any value that can be represented in computers alphabet or computer character set
C supports two character types:
char: for ASCII Character set
wchar_t (wide character type): for non English languages
Integer Datatype:
An integer isa number without fraction part. C supports four different sizes of integer types. They are
Short int , int , long int , long long int.
Each integer can be signed or unsigned. The signed data types are used for storing both positive and
negative values where as the unsigned data types are used to store only positive values
Float Datatype:
A float type value contains of integral and fractional parts,such as 34.52. C supports three different
sizes of float .they are float,double,long double. Unlike integers ,always floating point values are
signed.
Imaginary Datatype: (added from C99)
An imaginary number is a real number multiplied by square root of -1. C support three different sizes
of imaginary type . they are float imaginary ,double imaginary ,long double imaginary
Complex Datatype: (added from C99)
A Complex number is a pair of real or integer values, separated by a plus sign. The first constant
represents the real part of that number; the second constant represents the imaginary part. The

CSE Page 10
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

imaginary part is coded as a real number times(*) the imaginary constants(_Complex_I). if complex
library( complex.h) is included, the imaginary constant can be abbreviated as I.
Example: 12.3+14.4*I
C supports three different sizes of complex type .they are float complex ,double complex ,long double
complex.

The most fundamental data types that every C compiler supports are: int, char, float and double.
Other compilers support the extended versions of these fundamental data types like: short int, long
int, long double etc. The memory capacity of these data types are based on the hardware. The memory
capacity of all the fundamental data types is as shown below:

Data Type Size(Bytes) Range Format Specifier

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

short int 2 -32,768 to 32,767 %hd

unsigned short int 2 0 to 65,535 %hu

unsigned int Atleast 2, usually 4 0 to 4,294,967,295 %u

int Atleast 2, usually 4 -2,147,483,648 to 2,147,483,647 %d or %i

long int Atleast 4, usually 8 -2,147,483,648 to 2,147,483,647 %ld

unsigned long int Atleast 4, usually 8 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld

unsigned long long


8 0 to 18,446,744,073,709,551,615 %llu
int

float(6 decimal
4 1.2E-38 to 3.4E+38 %f
places)

double(15 decimal
8 2.3E-308 to 1.7E+308 %lf
places)

long double(19 Atleast 10,usually


3.4E-4932 to 1.1E+4932 %Lf
decimal places) 12 or 16

CSE Page 11
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

User-Defined data types


ANSI C allows the users to define identifiers as their own data types, based on the already existing
primitive or fundamental data types. This concept is known as “type definition” and the data types
thus created are known as user-defined data types. We can create user-defined data types in two
ways:
1) By using the “typedef” keyword
2) By using the “enum” keyword

typedef Keyword
The “typedef” keyword can be used to declare an identifier as a user-defined data type. The syntax for
using typedef is as shown below:

typedef int rollno;

typedef float average;

In the above example, rollno and average are new user-defined data types. Now we can use rollno and
average as data types as shown below:

rollno r1, r2;

average a1, a2;


enum Keyword

The “enum” is used to declare identifiers as user-defined data types. Such data types are also called as
enumerations. The “enum” keyword can be used to declare an identifier as data type which can store a
limited set of integer values. The syntax of using “enum” keyword is as shown below:

enum identifier {value1, value2,….., value n} ;

Example usage of enum is as shown below:

enum days {Mon, Tue, Wed, Thu, Fri, Sat};

In the above example, “days” is a new user-defined type. All the variables created using the “days”
data type can only contain values in the range Mon to Sat as shown in the above example. We can
declare variables by using the “days” data type as shown below:

enum days day1 = Mon;

If we display “day1” in the printf() statement, it will display it as zero. Generally, the value of a first
element in an enumeration always starts with zero and the next element’s value is previous element’s
value plus 1. So, the value of “Tue” will be one and so on.

Derived data types


The data types which are created using the already existing primitive or fundamental types are known
as derived data types. Like user-defined data types we cannot declare new variables using the derived
data types. Examples of derived data types in C are: arrays, functions, structures, unions and pointers.

CSE Page 12
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

DECLARING VARIABLE AS CONSTANTS:


Constants in C are fixed values which cannot be changed during the execution of the program. In C, we
can declare variables as constants in two ways. They are:
1) By using “const” keyword
2) By using “#define” preprocessor directive

const Keyword
We can declare a variable as a constant by using the const qualifier. A variable that is declared using
const cannot change its value once it is initialized. The syntax of using the const is as shown below:

const type variable-name = value;

Example of using the const keyword is as shown below:

constint max = 200;

#define Preprocessor Directive

We can also declare constants in a program by using the #define preprocessor directive. Such
constants declared using the #define preprocessor directive are known as symbolic constants. The
syntax of using #define is as shown below:

#define NAME value

Example of using #define is shown below:

#define PI 3.142

Take care that there is no semi-colon (;) at the end of #define statement. In the above example we
have assigned the value 3.142 to the symbol PI. Now, whenever PI is encountered in the program, it
will be replaced with the value 3.142.

Following are the rules that apply to a #define statement:

1) All rules that apply to variables also apply to symbolic name. Generally symbolic names are
written in CAPTIAL LETTERS, to distinguish them from the normal variable names.
2) No blank space between # and define is allowed.
3) # must be the first character in the #define statement.
4) A blank space is required between #define and the symbolic name and between symbolic
name and the value.
5) #define statements must not end with a semi-colon.
6) After declaring a symbolic constant, we must not use it in an assignment statement.
7) Symbolic names are not declared for data types. Its data type depends on the type of the
constant value.
8) #define statements may appear anywhere in the program, but before they are referenced in
the program.Generally they are placed at the top of the program after the #include statements.

constVs #define
The purpose of both const and #define is to declare constants in a C program. The difference between
them is: when we declare a variable as a constant using const, it is still treated as a variable but the
value will be fixed and cannot be changed. But, when we use #define, we are declaring symbolic
constants, which are not treated as variables. Instead the compiler searches for the symbol

CSE Page 13
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

throughout the program and replaces the symbol with the value. Another difference is, const is a
keyword, where as#define is a preprocessor directive.

DECLARING A VARIABLE AS VOLATILE :


ANSI standard defines another qualifier volatile that could be used to tell the compiler that a
variable’s value may be changed at any time by some external sources (from outside the program).
Example usage of the volatile keyword is shown below:
Volatile int date;

The value of date can be modified by its own program too. If you don’t want the program to modify
the value of date variable, but it can be modified by external factors, then date can be declared as both
volatile and const as shown below:
Volatile const int date = 21;

ASCII (American Standard Code for Information Interchange) Code

CSE Page 14
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

Examples
/* C program to illustrate integer constants */

#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf("%d \n",20);
printf("%d \n",-55);
printf("%u \n",65535U);
printf("%ld \n",999999999L);
printf("%o \n",040);
printf("%x \n",0x23);
getch();
}

Explanation:
In the above c program, 20, -55, 65535 and 999999999 represent decimal integer constants. Whereas
040 represents octal integer constant and 0x23 represents hexadecimal integer constant. %d is the
format specifier for displaying decimal integers, %u for displaying unsigned decimal integers, %ld for
displaying long decimal integers, %o for displaying octal integers and %x or %X for displaying
hexadecimal integer values.

/* C program to illustrate real constants */

#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf("%f \n",1.5232);

printf("%f \n",-45.2f);
printf("%f \n",32.);
printf("%f \n",.56);
printf("%e \n",2.3e2);
getch();
}

Explanation:
In the above program, 1.5232, -45.2, 32., .56 are example of real constants. 2.3e2 is also real constant
which is represented in scientific notation. %f is used to display real values and %e for displaying real
values in scientific notation. By default all the real values are treated as double precision values. If you
want to specify a single precision real value, you can use the letter ‘f’ after the real value like -45.2f in
the above program.

CSE Page 15
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

/* C program to demonstrate character constants */

#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf("%c \n", 'a');
printf("%c \n", 'f');
printf("%s \n", "hai");
printf("%s \n", "hello");
getch();
}

Explanation:
In the above program, ‘a’ and ‘f’ are single character constants, whereas “hai” and “hello” are string
constants. %c is used to display single characters and %s is used to display strings.

/* C program to demonstrate the use of variables */

#include<stdio.h>
#include<conio.h>
main()
{
int a; /*variable a declaration*/
int b; /*variable b declaration*/
clrscr();
a = 10; /*Initialization of variable a*/
b = 20;/*Initialization of variable b*/
printf("Value of a+b is: %d",(a+b));
getch();
}

Explanation:
In the above program, a and b are variables which can hold integer values as specified by the int
keyword in the declaration. Later, a is initialized to 10 and b is initialized to 20.

CSE Page 16
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

/* C program to demonstrate different data types */

#include<stdio.h>
#include<conio.h>
main()
{
int i = 10;
unsignedintui = 65535;
shortintsi = 30;
unsigned short intusi = 255;
longint li = 2147483647;
unsigned long intuli = 4294967295;
float f = 23.4897897897;
double d = 23.4235423542;
long double ldouble = 24.562343546546;
charch = 'a';
unsigned char uch = 'g';
clrscr();
printf("i = %d\n",i);
printf("ui = %u\n",ui);
printf("si = %hd\n",si);
printf("usi = %hu\n",usi);
printf("li = %ld\n",li);
printf("uli = %lu\n",uli);
printf("f = %f\n",f);
printf("d = %f\n",d);
printf("ldouble = %.Lf\n",ldouble);
printf("ch = %c\n",ch);
printf("uch = %c\n",uch);
getch();
}

/* C program to demonstrate user defined data


types */

#include<stdio.h>
#include<conio.h>
main()
{
/*Declaring sum as a user defined data type*/
typedefint sum;
/*Declaring days as a user defined data type*/
enum days {mon,tue,wed,thu,fri,sat,sun};
sum s;
enum days day1;
int a=10,b=20;
clrscr();
s = a+b;
day1 = wed;
printf("sum of a and b is: %d\n",s);
printf("day1 value is: %d",day1);
getch();
}

CSE Page 17
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

/* C program to demonstrate const keyword */

#include<stdio.h>
#include<conio.h>
main()
{
/*Declaring a constant pi*/
const float pi = 3.142;
float area;
clrscr();
area = pi*10*10;
printf("Area of circle is: %f",area);
getch();
}

/* C program to demonstrate symbolic constants by using #define directive */

#include<stdio.h>
#include<conio.h>
/*Declaring a symbolic constant PI*/
#define PI 3.142
main()
{
float area;
clrscr();
area = PI*10*10;
printf("Area of the circle is: %f",area);
getch();
}

/*C program to demonstrate use of scanf() function */

#include<stdio.h>
#include<conio.h>
main()
{
int num1,num2;
clrscr();
printf("Enter the value of num1:\n");
/* To accept the value into num1 */
scanf("%d",&num1);
/* To accept the value into num2 */
printf("Enter the value of num2:\n");
scanf("%d",&num2);
printf("Sum of num1 and num2 is: %d",(num1+num2));
getch();

CSE Page 18
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

SCOPE:
A scope is a region of the program, and the scope of variables refers to the area of the program where the
variables can be accessed after its declaration.
In C every variable defined in scope. You can define scope as the section or region of a program where a
variable has its existence; moreover, that variable cannot be used or accessed beyond that region.
In C we can have four types of scopes depending on the region where variables are declared and used.
They are
1. Block scope
2. Function scope
3. Program scope
4. File scope

Block Scope
A block refers to any sets of statements enclosed in braces ({ and }). A variable declared within a block has
block scope. Thus, the variable is active and accessible from its declaration point to the end of the block.
Sometimes, block scope is also called local scope.

For example, the variable i declared within the block of the following main function has block scope:
int main()
{
int i; /* block scope */
.
.
.
return 0;
}

Nested Block Scope


You can also declare variables within a nested block. If a variable declared in the outer block shares the
same name with one of the variables in the inner block, the variable within the outer block is hidden by
the one within the inner block for the scope of the inner block
Example:
#include <stdio.h>
int main()
{
int a = 10,i;
printf("%d ",++a);
{
int a = 20;
for (i=0;i<3;i++)
{
printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
}
}
printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
}

Output
11 20 20 20 11

CSE Page 19
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

Function Scope
Function scope indicates that a variable is active and visible from the beginning to the end of a function.
Example:

int main()
{
int i; /* block scope */
.
.
func()
return 0;
}
func()
{
int a; /* function scope*/
.
.
}

Program Scope
A variable is said to have program scope when it is declared outside a function. For instance, look at the
following code:
int x = 0; /* program scope */
float y = 0.0; /* program scope */
int main()
{
int i; /* block scope */
.
.
.
return 0;
}
Here the int variable x and the float variable y have program scope.

Variables with program scope are also called global variables, which are visible among different files.
These files are the entire source files that make up an executable program. Note that a global variable is
declared with an initializer outside a function.
File Scope
In C, a global variable declared with the static specifier is said to have file scope. A variable with file scope
is visible from its declaration point to the end of the file. Here the file refers to the program file that
contains the source code. Most large programs consist of several program files.
The following portion of source code shows variables with file scope:
int x = 0; /* program scope */
static int y = 0; /* file scope */
static float z = 0.0; /* file scope */
int main()
{
int i; /* block scope */
.
.
.
return 0;
}
Here the int variable y and the float variable z both have file scope.
CSE Page 20
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

STORAGE CLASS
A storage class represents the visibility and a location of a variable. It tells from what part of code we can
access a variable. A storage class is used to describe the following things:
 The variable scope.
 The location where the variable will be stored.
 The initialized value of a variable.
 A lifetime of a variable.
 Who can access a variable?
There are total four types of standard storage classes.
Storage Declaration Storage Default Initial Scope Lifetime
Class Value

auto Inside a Memory Unpredictable Within the Within the


function/block function/block function/block

register Inside a CPU Garbage Within the Within the


function/block Registers function/block function/block

Static Inside a Memory Zero Within the program


(local) function/block function/block runtime

Static Outside all Memory Zero Global program


(global) functions runtime

extern Outside all Memory Zero Entire the file program


functions and other files runtime
where the
variable is
declared as
extern

AUTOMATIC
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they are defined.
o The scope of the automatic variables is limited to the block in which they are defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.

CSE Page 21
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

Example:
#include <stdio.h>
int main()
{
int a = 10,i;
printf("%d ",++a);
{
int a = 20;
for (i=0;i<3;i++)
{
printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
}
}
printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
}
Output
11 20 20 20 11

REGISTER
o The variables defined as the register is allocated the memory into the CPU registers depending upon
the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator for the register variable.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the CPU register. However, it
is compiler?s choice whether or not; the variables can be stored in the register
o We can store pointers into the register, i.e., a register can store the address of a variable.
o Static variables can not be stored into the register since we can not use more than one storage
specifier for the same variable.

Example:
#include <stdio.h>
int main()
{
register int a = 0;
printf("%d",a);
}
Output
0

STATIC
o The variables defined as static specifier can hold their value between the multiple function calls.
o Static local variables are visible only to the function or the block in which they are defined.
o A same static variable can be declared many times but can be assigned at only one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has declared.
o The keyword used to define static variable is static.
Example:
#include<stdio.h>
void sum()
{
static int a = 10;
static int b = 24;
printf("%d %d \n",a,b);
a++;
b++;
}
CSE Page 22
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I
void main()
{
int i;
for(i = 0; i< 3; i++)
{
sum(); // The static variables holds their value between multiple function calls.
}
}

output
10 24
11 25
12 26

EXTERNAL
o The external storage class is used to tell the compiler that the variable defined as extern is declared
with an external linkage elsewhere in the program.
o The variables declared as extern are not allocated any memory. It is only declaration and intended to
specify that the variable is declared elsewhere in the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize the external variable
within any block or method.
o An external variable can be declared many times but can be initialized at only once.
o If a variable is declared as external then the compiler searches for that variable to be initialized
somewhere in the program which may be extern or static. If it is not, then the compiler will show an
error.
Example
#include <stdio.h>
int main()
{
extern int a; // Compiler will search here for a variable a defined and initialized
. somewhere in the pogram or not.
printf("%d",a);
}
int a = 20;

Output:
20

TYPE QUALIFIERS
The keywords which are used to modify the properties of a variable are called type qualifiers.
There are two types of qualifiers available in C language. They are,
1)size qualifiers( short, long)
2)sign qualifiers(unsigned, signed)
3)constant qualifier(const )
4)volatile qualifier(volatile)

CSE Page 23
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

OPERATORS IN C
Operators
An operator is a symbol that tells a computer to perform certain mathematical or logical operations.
Operators are used in programs to manipulate data and variables. Operators are usually a part of the
mathematical or logical expressions. Generally the usage of an operator is as shown below:

Operand1 Op Operand2

In the above format, operand1 and operand2 can be either data or variables or expressions. Op is the
operator. In C, based on the number of operands on which an operator can operate, the operators are
divided into three types namely: unary, binary and ternary. Unary operators work on single operand,
binary operators work on two operands and ternary operators work on three operands. In C, based on
the functionality, operators are classified into 8 categories. They are:

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators

Arithmetic Operators
C provides all the basic arithmetic operators as shown below. The arithmetic operators can operate on
any built-in data type in C. The unary minus operator multiplies its single operand with -1. Integer
division truncates any fractional part. The modulo division operator (%) produces the remainder of
an integer division. The modulo operator cannot be used on floating point values.

Operator Meaning Example


+ Addition or unary plus a+b
Subtraction or unary
- minus a-b
* Multiplication a*b
/ Division (Quotient) a/b
% Modulo (Remainder) a%b

Relational Operators
In C, whenever there is a need to compare two values and make a decision based on the outcome of
the comparison, we use relational operators. For example, we can compare a person’s age with a value
and based on whether the person’s age is less than or equal or greater than the value, we may take a
decision. The relational operators in C are as shown below:

Operator Meaning Example


< Less than a<b
<= Less than or equal to a<=b
> Greater than a>b
Greater than or equal
>= to a>=b
== Equal to a==b
!= Not equal to a!=b
The relational operators are generally used in decision making statements like if, else if and in looping
statements like for, while, do while etc. Relational operators always evaluates to 0 (false) or 1 (true)

CSE Page 24
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

Logical Operators
The relational operators are used to compare at most two values i.e. testing one condition. To test
more than one condition, we use logical operators along with relational operators. The logical
operators always evaluates to either 0 or 1 like relational operators. The logical operators available in
C and their corresponding truth tables are as shown below:
Operator Meaning Example
(a>b)&&(a>c
&& Logical AND )
|| Logical OR (a>b)||(a>c)
! Logical NOT !(a>b)

Assignment Operators
The assignment operators are used to assign value of an expression to a variable. The general
assignment operator is = (equal). In C, there are some special assignment operators known as
shorthand operators. The syntax of shorthand operators is as shown below:
Var op= exp;

In the above shown syntax, var is a variable, op is an arithmetic operator and exp can be any
expression or value or a variable.
The use of shorthand operators has three advantages:
1. Easier to write.
2. The statement is more concise and easier to read.
3. The statement is more efficient.
The assignment operators in C are as shown below:

Operator Example
= a = 10
+= a+=10 (a=a+10)
-= a-=10 (a=a-10)
*= a*=10 (a=a*10)
/= a/=10 (a=a/10)
a%=10
%= (a=a%10)

CSE Page 20
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

Increment and Decrement Operators


The increment and decrement operators provided by C are used to increment or decrement the
operand by a value of one. Both the increment and decrement operators are unary operators. These
operators are used extensively inside for loop and while loop. There are two variations in how the
increment and decrement operators can be used. They are as shown below:

Var++ Var--
OR
++Var --Var

In the above shown syntax, var++ is known as post increment and ++var is known as pre increment.
Although both of them increment the variable by a value of one, they behave differently when they are
used in expressions. In expressions, when post increment is applied, the value of the variable is used
in the evaluation of the expression and after the expression is evaluated, the value of the variable is
incremented by a value of one. When pre increment is applied, the value of the variable is
incremented by one first and then that value is used for evaluation of the expression.
The increment and decrement operators available in C are:

Operator Meaning Example


++ Increment by 1 A++ or ++A
Decrement by
-- 1 A-- or --A

Conditional Operator
The conditional operator “? :” in C, is a ternary operator, which operates on three operands. This
operator is used to construct conditional expressions of the form:

exp1?exp2:exp3

In the above syntax, exp1, exp2 and exp3 refer to expressions. The “? :” works as follows: It evaluates
the exp1 first and then based on the result of the exp1 it evaluates either exp2 or exp3. If the result
of exp1 is true or non-zero, then exp2 is evaluated or if the result of exp1 is false or zero, then exp3
is evaluated.

Bitwise Operators
C supports a set of operators which operate at bit-level. These operators are known as bitwise
operators. The bitwise operators are used for testing a bit, setting a bit, complementing a bit or for
shifting the bits to left or right. The bitwise operators available in C are as shown below:

Operator Meaning Example


& Bitwise AND a&b
| Bitwise OR a|b
Bitwise Exclusive
^ OR a^b
~ Bitwise NOT ~a
<< Left Shift a<<1
>> Right Shift a>>1

CSE Page 21
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

The truth table for the bitwise operators is as shown below:

Bitwise AND (&)


The bitwise AND operator is used to test whether a bit at particular position is zero or one. If it is one,
it returns a non-zero value.

In the above example, we are testing whether the bit at position 4 in the number 20 is set to one or
not. Since it is zero, the result is zero.

Bitwise OR (|)
The bitwise OR operator is used to set a bit at particular position to one. Example usage of the bitwise
OR operator is shown below:

As you can see in the above example, we are trying to set the bit at position 4 in the number 20 to one.
If the bit at the specified position is zero, the bitwise OR sets it to one. If it is already one, it leaves it as
it is.

Bitwise Exclusive OR (^)


The bitwise Exclusive OR returns zero, if both the bits are equal. Otherwise, it returns one. Example
usage of this operator can be seen below:

CSE Page 22
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

Bitwise NOT (~)


The bitwise NOT operator is used to complement every bit of the operand. If the bit is zero, it is set to
one and if it is one, the bit is set to zero.

Left Shift (<<)


The left shift operator is used to shift the bits in the operand to the left. The result of the left shift
operation is equal to the operand multiplied by powers of two.

As seen in the above example, by left shifting the number 20 one time, we get the result as 40 which is
20 multiplied by 2. If we again left shift 20, we get the result 80 which is 20 multiplied by 4 and so on.

Right Shift (>>)


The right shift operator is used to shift the bits in the operand to the right. The result of the right shift
operation is equal to the operand divided by powers of two.

As seen in the above example, by right shifting the number 20 one time, we get the result as 10, which
is actually dividing 20 by 2. If we again left shift 20, we get the result as 5 which is 20 divided by 4 and
so on.

Special Operators
C supports some special operators such as comma “,” operator, sizeof operator, address “&” operator,
pointer operator “*” and some others.

Comma Operator
The comma “,” operator is used to combine multiple related expressions together. A comma
separated list of expressions is evaluated from left to right and the value of the right most expression
is the value of the combined expression

sizeof Operator
The sizeof operator computes the size of an expression or variable or constant or a data type. This
operator is used extensively for determining the length of an array, structure or union when the
programmer does not know their actual sizes. The sizeof operator is also used in dynamic memory
allocation. The general syntax of sizeof operator is as shown below:
sizeof(operand)

The operand can be either a value or variable or data type or an expression.

CSE Page 23
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

/* C program to demonstrate arithmetic operators


*/

#include<stdio.h>
#include<conio.h>
main()
{
int num1, num2;
int result;
clrscr();
printf("Enter the value of num1:");
scanf("%d",&num1);
printf("Enter the value of num2:");
scanf("%d",&num2);
result = num1 + num2;
printf("Value of adding num1 and num2 is: %d\n",result);
result = num1 - num2;
printf("Value of subtracting num1 and num2 is: %d\n",result);

result = num1 * num2;


printf("Value of multiplying num1 and num2 is: %d\n",result);
result = num1 / num2;
printf("Value of dividing num1 and num2 is: %d\n",result);
result = num1 % num2;
printf("Value of modulus on num1 and num2 is: %d",result);
getch();
}

Output:
Enter the value of num1:20
Enter the value of num2:10

Value of adding num1 and num2 is: 30


Value of subtracting num1 and num2 is: 10
Value of multiplying num1 and num2 is: 200
Value of dividing num1 and num2 is: 2
Value of modulus on num1 and num2 is: 0

CSE Page 24
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

/* C program to demonstrate relational operators


*/

#include<stdio.h>
#include<conio.h>
main()
{
int a, b;
clrscr();
printf("Enter the value of a:");
scanf("%d",&a);
printf("Enter the value of b:");
scanf("%d",&b);
if(a>b)
printf("a is greater than b");
else if(a<b)
printf("a is less than b");
else
printf("a is equal to b");
getch();
}

Output:
Enter the value of a:30
Enter the value of b:5
a is greater than b

/*C program to demonstrate logical operators */

#include<stdio.h>
#include<conio.h>
main()
{
int num1, num2;
clrscr();
num1 = 10, num2 = 20;
if(num1<20 && num2<30)
printf("Logical AND works!\n");
if(num1<20 || num2<20)
printf("Logical OR works!\n");
if(!(num1==20))
printf("Logical NOT works!");
getch();
}

Output:
Logical AND works!
Logical OR works!
Logical NOT works!

CSE Page 25
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

/* C program to demonstrate assignment operators */

#include<stdio.h>
#include<conio.h>
main()
{
int num1;
clrscr();
num1 = 10;
printf("num1 = %d\n",num1);
num1 += 10;
printf("num1 = %d\n",num1);
num1 -= 10;
printf("num1 = %d\n",num1);
num1 *= 10;
printf("num1 = %d\n",num1);
num1 /= 10;
printf("num1 = %d\n",num1);
num1 %= 10;
printf("num1 = %d\n",num1);
getch();
}

Output:
num1 = 10
num1 = 20
num1 = 10
num1 = 100
num1 = 10
num1 = 0

/* C program to demonstrate increment and decrement */

#include<stdio.h>
#include<conio.h>
main()
{
int num1;
clrscr();
num1 = 10;
printf("num1 = %d\n",num1++);
printf("num1 = %d\n",++num1);
printf("num1 = %d\n",--num1);
printf("num1 = %d\n",num1--);
getch();
}

Output:
num1 = 10
num1 = 12
num1 = 11
num1 = 11

CSE Page 26
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

/* C program to demonstrate conditional operator */

#include<stdio.h>
#include<conio.h>
main()
{
int num1;
clrscr();
num1 = 15;
(num1>10)?(num1=20):(num1=5);
printf("num1 = %d",num1);
getch();
}

Output:
num1 = 20

/* C program to demonstrate bitwise operators */

#include<stdio.h>
#include<conio.h>
main()
{
int num1, num2;
clrscr();
printf("Enter value of num1:");
scanf("%d",&num1);
num2 = 8;
printf("Bitwise AND on num1 is: %d\n",(num1&num2));
printf("Bitwise OR on num1 is: %d\n",(num1|num2));
printf("Bitwise Ex-OR on num1 is: %d\n",(num1^num2));
printf("Left shift on num1 is: %d\n",(num1<<1));
printf("Right shift on num2 is: %d\n",(num1>>1));
getch();
}

Output:
Enter value of num1:20
Bitwise AND on num1 is: 0
Bitwise OR on num1 is: 28
Bitwise Ex-OR on num1 is: 28
Left shift on num1 is: 40
Right shift on num2 is: 10

CSE Page 27
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

/* C program to demonstrate the use of comma operator and sizeof operator */

#include<stdio.h>
#include<conio.h>
main()
{
int num1, num2;
int sum;
clrscr();
/*Using the comma operator*/
sum = (num1=5, num2=5, num1+num2);
printf("Sum = %d\n",sum);
/*Using the sizeof operator*/
printf("Size of int is: %d bytes",sizeof(int));
getch();
}

Output:
Sum = 10
Size of int is: 4 bytes

CSE Page 28
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

EXPRESSION IN C
Expression
An expression is a sequence of operands and operators that reduces to a single value. For example, the
expression, 10+5 reduces to the value of 15. Based on the operators and operators used in the
expression, they are divided into several types. Some of them are:

1. Integer expressions – expressions which contains integers and operators


2. Real expressions – expressions which contains floating point values and operators
3. Arithmetic expressions – expressions which contain operands and arithmetic operators
4. Mixed mode arithmetic expressions – expressions which contain both integer and real
operands
5. Relational expressions – expressions which contain relational operators and operands
6. Logical expressions – expressions which contain logical operators and operands
7. Assignment expressions - expressions which contain assignment operators and operands
8. E.t.c

Expression Evaluation
Expressions are evaluated using an assignment statement of the form:

variable = expression

In the above syntax, variable is any valid C variable name. When the statement like the above form is
encountered, the expression is evaluated first and then the value is assigned to the variable on the left
hand side. All variables used in the expression must be declared and assigned values before evaluation
is attempted. Examples of expressions are:
x = a*b-c
y=b/c*a
z=a-b/c+d

Expressions are evaluated based on operator precedence and associativity rules when an expression
contains more than one operator.

Operator Precedence and Associativity


Every C operator has a precedence (priority) associated with it. This precedence is used to determine
how an expression involving more than one operator is evaluated. There are different levels of
operator precedence and an operator may belong to one of these levels. The operators at the higher
level of precedence are evaluated first. The operators in the same level of precedence are evaluated
from left to right or from right to left, based on the associativity property of an operator. In the below
table we can look at the precedence levels of operators and also the associativity of the operators
within the same level. Rank 15 indicates the lowest precedence and Rank 1 indicates highest
precedence.

Example 1
Let’s understand the operator precedence and associativity rules with the help of an example. The
expression that we consider for this example is:
if(x==10+15&&y<10)

In the above expression, the operators used are: ==,+,&& and <. By looking at the operator precedence
table, + operator is at level 4, < operator is at level 6, == operator is at level 7 and && operator is at
level 11. So clearly, the + operation is performed first. Then our expression becomes:
if(x==25&&y<10)

Now, since < operator has the next highest precedence, y<10 is evaluated. If we assume value of x is 20
and value of y is 5, then the value of y<10 is true. Then the == operator is evaluated. Since value of x is
20, x==25 evaluates to false. So, our expression becomes:

CSE Page 29
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

if(false&&true)
Now, the only operator left is &&. It is evaluated next and the result is false.

CSE Page 30
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

Example 2
Let us try to evaluate an arithmetic expression as shown below:
x = a-b/3+c*2-1
Let a = 9, b =12, and c=3. Then our expression becomes:
x = 9-12/3+3*2-1
From the above table, we can see that the * and / operators are having higher precedence than + and –
operators. Also, the * and / operators are at the same level of precedence, so we have to apply the
associativity rules. Since the associativity rule is left-to-right, we apply the / operator first and the
expression evaluates to:
x = 9-4+3*2-1
Next, we apply the * operator and the expression becomes:
x = 9-4+6-1
Next, we apply the first – operator as the – and + operators are from same level and the associativity is
the left to right. The expression becomes:
x = 5+6-1
Now, we apply the + operator and the expression become:
x = 11-1
Finally, we apply the – operator and the result is:
x = 10

/* C Program to demonstrate expressions and operator precedence */


#include<stdio.h>
#include<conio.h>
main()
{
int m1=60,m2=60,m3=60;
int average;
average = m1+m2+m3/3;
printf("Average is: %d",average);
}

Ouput:
Average is: 140

SIDE EFFECTS :A side effect is an action that result from the evaluation of expression. For example if we
consider an expression x=3+4 now C first evaluate the right of assignment operator and then place the result
in left variable. Changing the value of left variable is a side effect. Here changing x value is side effect

In C six operators generate side effects ,they are: prefix increment and decrement, postfix increment and
decrement,assignment and function call.

Example:
Expression with no side effect: a*4+b/2-c*b
In above expression even after evaluation also a,b,c variable values won’t change.

Expression with side effects: --a*4+b/2-c++*b


In above expression after evaluation a value is decremented by 1 and c value is incremented by 1

CSE Page 31
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

Type Conversion and Casting

Converting a data type of an expression to another data type is known as type conversion. Here
expression refers to either a variable or value or sub expression. There are two types of conversions.
They are:
1. Implicit conversion or Type Promotion or Coercion
2. Explicit conversion or Type Casting

Implicit Conversion
While evaluating expressions, it is common to have operands of different data types. C automatically
converts the data type of operands or any intermediate values to the proper type so that expression
can be evaluated without losing any significance. This automatic conversion performed by C is known
as implicitconversion.
In C, the expression on the right hand side of an assignment statement is evaluated first. So, C
evaluates the expression based on the conversion hierarchy as shown in the below diagram. Finally,
the type of the result acquired from the expression is again converted to match the type of variable on
the left hand side. The conversion hierarchy is as shown below:

Example Let’s try to evaluate the following expression: x = l / i + i * f – d


x=l / i + i * f – d

long int
int float double
f loat
long
long float

float

float

double
x= double

where, i and x are of the type int, f is of type float, d is of type double and l is of type long int.

CSE Page 32
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

When the above expression is evaluated, the operand i in the sub expression l/i, is converted to long
int since, l is a long int. In the sub expression i*f, i is converted into float, since f is of the type float. The
result of the sub expression l/i is converted to float, as it will be added to the result of i*f which is
already a float. Finally the result of the sub expression l/i+i*f is converted into double, as d is a double.
After obtaining the final result which is of the type double, it is again converted into int as the variable
x is of the type int.

Explicit Conversion or Casting


In C programming, there will be instances where a programmer wants to change the type of an
expression into another type which is not possible by the implicit conversion. In such cases, the
programmer himself/herself specifies the type conversion. Such conversion is known as explicit
conversion or type casting.
For example, let num1 and num2 are variables of integer type and value of num1 is 3 and value of
num2 is 2.
For the purpose of calculating the average of num1 and num2, let us declare another variable result of
the type float.
So the statement for calculating the average will be as shown below:
result =( num1+num2)/2

Mathematically the result of the above expression should be 2.5. But when we execute the above
statement in a C program, we get the result 2.000000. Even though C applies implicit conversion from
int to float, the result we obtained is wrong. In such case we apply explicit casting. The statement will
be as follows:

result = (float)(num1+num2)/2

Now, the result of num1+num2 is converted into float. Since one operand is of type float, 2 will also be
converted to float. The result of the whole expression on the right hand side is a float. Now, we obtain
the correct value in the variable result which will be 2.500000.

The general syntax for explicit type casting is as shown below:

(type-name)expression

/* C program to demonstrate implicit and explicit conversion */

#include<stdio.h>
#include<conio.h>
main()
{
int num1,num2;
float average;
num1=3,num2=2;
/*Type casting from int to float*/
average = (float)(num1+num2)/2;
printf("Average is: %f",average);
}

Output:
Average is: 2.500000

CSE Page 33
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

MANAGING INPUT AND OUTPUT OPERATIONS

Managing input and output operations:


Reading, processing and writing of data are the three essential functions of a computer program.
Most programs take some data as input and process it and display the output.
We have two methods of providing data to the program variables.
1) One method is to assign values to variables through the assignment statements like x=5, a=0
and so on.
2) Another method is to use the input function scanf, which can read data from a keyboard.
We have used both the methods in programs. For outputting results, we have used extensively the
function printf, which sends results out to a terminal.

C language has 2 types of I/O statements:


1. Formatted I/O statements
2. UnFormatted I/O statements

Formatted Input/Outpur Functions: Formatted I/O refers to input and output that has been
arranged in a particular format.
Formatted I/P functions : scanf( ) , fscanf()
Formatted O/P functions : printf() , fprintf()

Formatted input/Interactive Input:


C provides scanf( ) function for entering input data. This function accepts all types of data as
input (numeric, character, string).
scanf( ) : -scanf() function is used to read information from the standard I/P device.
Syntax:-
scanf(“controlstring”, arg1,arg2,………,argn);
This function should have at least two parameters.
 First parameter is control string which is conversion specification character. It should be
within double quotes. This may be one or more, it depends on the number of variables.
 The other parameter is variable names or arguments. Each variable must preceded by
ampersand (&) sign. This gives starting address of the variable name in memory.
 Control string and arguments are separate by comma
 Control string includes
i) Field or format specifications consisting of conversion character %, a datatype
character(type specifier) and an optional number specifying field width.
ii) Blanks, tabs or newlines but these are ignored

a. Inputting Integer Numbers:


The field specification for reading an integer number is:
%w d
The percentage sign(%) indicates that a conversion specification follows. w is an integer
number that specifies the field width of the number to be read and d known as data type
character indicates that the number to be read is in integer mode.

Ex:- scanf(“%2d,%5d”,&a,&b);
The following data are entered at the console:
50 31426
Here the value 50 is assigned to a and 31426 to b

b. Inputting Real Numbers:


The field width of real numbers is not to be specified unlike integers. Therefore scanf reads
real numbers using the simple specification %f.

CSE Page 34
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

Ex: scanf(“%f %f”,&x,&y);


Suppose the following data are entered as input:
23.45 34.5
The value 23.45 is assigned to x and 34.5 is assigned to y.

c. Inputting character strings:


The field specification for reading character strings is
%ws or %wc
%c may be used to read a single character.
Ex: scanf(“%s”,name1);
Suppose the following data is entered as input:
Griet
Griet is assigned to name1

Formatted Output:
printf( ): This function is used to output any combination of data. The outputs are produced
in such a way that they are understandable and are in an easy to use form. It is necessary for the
programmer to give clarity of the output produced by his program.

Syntax:- printf(“control string”, var1,var2……);

This function should have at least two parameters.


 The control string indicates how many arguments follow and what their types are.
 The var1, var2 etc.. are variables whose values are formatted and printed according to
the specifications of the control string.
 Control string consists of 3 types of items
1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the O/P format for display of each item.
3. Escape sequence chars such as \n , \t and \b…..
 The arguments should match in number, order and type with the format specifications.

a) O/P of integer number: - Format specification :%wd

Format O/P
printf(“%d”, 9876) 9876
printf(“%6d”,9876) __9876
printf(“%2d”,9876) 9 876
printf(“%-6d”,9876) 9876__
printf(“%06d”,9876) 009876

b) O/P of real number:- Format specification: %w.pf

w ---- Indicates minimum number of positions that are to be used for display of the value.
p ------ Indicates number of digits to be displayed after the decimal point.

Format y=98.7654 O/P


Printf(“―%7.4f”,y) 98.765 4
printf(“―%7.2f”,y) _ _ 98.7 7
printf(“―%-7.2f”,y) 98.77_ _
printf(“―%10.2e”,y) __9.88e+0 1

CSE Page 35
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

a) O/P of single characters and string:


Format specification: %wc or %ws

Format O/P
%s RaJURajeshRaN i
%18s RaJURaJEshRan i

Format specifiers or Format Modifiers:


The format specifiers used in both printf() and scanf() are
Format
Data Type Display
specifier
%c char Single character
%c unsigned char
%s Sequenceofcharacters (String)
int Signed integer (both +veand –ve
%d values)
%u unsigned int Unsigned integer (only+vevalues)
%hd short int Signed short integer
%ld long int Long integer
unsigned long Unsigned long integer (only +ve
%lu
int values)
%o int Octal values
%x int Hexadecimal values
%f float Floating-pointvalue
long Double precision floating-point
%lf
float/double value
long double Double precision floating-point
%Lf
value
%p pointer Address stored in pointer
%% none Prints %

Flag characters used inprintf


Flag Meaning
− Left justifythe display
+ Displaythe positiveor negativesign of value
0 Pad with leading zeros
space Displayspaceif thereisno sign

CSE Page 36
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

Unformatted Input/Output Functions:-


getchar( ):- It reads single character from standard input device. This function don‘t require any
arguments.
Syntax:- char variable_name = getchar( );
Ex:- char x;
x = getchar( );

putchar ( ):- This function is used to display one character at a time on the standard output
device.
Syntax:- putchar(char_variable);
Ex:- char x;
putchar(x)

getc() :- This function is used to accept single character from the file.
Syntax: char variable_name = getc();
Ex:- char c;
c = getc();

putc():- This function is used to display single character.


Syntax:- putc(char variable_name);
Ex:- char c;
putc(c);
These functions are used in file processing.

gets( ):- This function is used to read group of characters(string) from the standard I/P device.
Syntax:- gets(character array variable);
Ex:- gets(s);

puts( ):- This function is used to display string to the standard O/P device.
Syntax:- puts(character array variables);
Ex:- puts(s);

getch():- This function reads a single character directly from the keyboard without displaying on
the screen. This function is used at the end of the program for displaying the output (without
pressing (Alt-F5).
Syntax: char variable_name = getch();
Ex:- char c
c = getch();

getche():- This function reads a single character from the keyboard and echoes(displays) it to
the current text window.
Syntax:- char variable_name = getche();
Ex:- char c
c = getche();

CSE Page 37
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

C Mathematical Library Functions:

All C inbuilt functions which are declared in math.h header file are given below. The source code for
math.h header file is also given below for your reference.

List Of Inbuilt C Functions In Math.H File:

 “math.h” header file supports all the mathematical related functions in C language. All the
arithmetic functions used in C language are given below

Function Meaning
Trigonometric
asin(x) Arcsin of x.
acos(x) Arc cosine of x
atan(x) Arctangent of x
atan2(y,x) Arctangent ofy/x
sin(x) sine of x
cos(x) cosine of x
tan(x) tangent of x
Hyperbolic
sinh(x) hyperbolicsine of x
cosh(x) hyperbolic cosine ofx
tanh(x) hyperbolictangent ofx
Otherfunctions
exp(x) eto thepower of x(ex)
ceil(x) xrounded up to thenearest integer.
floor(x) xrounded down to the nearest integer
fabs(x) absolute value|x|
log(x) Natural logarithm of x,x>0.
log10(x) Base10 logarithm x,x>0.
fmod(x,y) Remainder ofx/y
sqrt(x) squareroot ofx, x>=0.
pow(x,y) xto thepowery.

An example ‘C’ program that illustrates the use mathematical function


#include <stdio.h>
#include <math.h>
int main()
{
printf("sin 90 = %.0f\n",sin(90));
printf("cos 0= %.0f\n",cos(0));
printf("sqrt(9) = %.0f\n",sqrt(9));
printf("floor(9.56) = %.2f\n",floor(9.56));
printf("ceil(9.56) = %.2f\n",ceil(9.56));
printf("abs(-9) = %.2f\n",fabs(-9));
printf("power(2,3) = %.0f\n",pow(2,3));
printf("Remainder of 9/3 = %.0f\n",fmod(9,3));
return 0;
}

CSE Page 38
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I

Output
sin 90 = 1
cos 0= 1
sqrt(9) = 3
floor(9.56) = 9.00
ceil(9.56) = 10.00
abs(-9) = 9.00
power(2,3) = 8
Remainder of 9/3 = 0

Command Line Arguments: An executable program that performs a specific task for operating system
is called a command. Some arguments are to be associated with the commands hence these arguments are
called as command line arguments.
The command line arguments supply parameters to the program during its execution.
Command line arguments allows passing the information when we ran the program, generally the
information can be passed into the programs using main function via command line arguments.
Command line arguments provide the information that follows the name of the programs and the name of
the command line of the operating system.
Example : /* Program using command line arguments */ File_name: vanini.c
#include<stdio.h>
int main(int argc, char *argv[])
{
int i;
float s=0.0; To compile:
for(i=1;i<argc;i++) c:\turboc2>vahini 20 40 60
s+=atoi(argv[i]); o/p: The average is: 40
printf("The average =%f\n",s/(float)(argc-1));
return 0;
}

CSE Page 39

You might also like