r19 CP Unit-1 Complete
r19 CP Unit-1 Complete
Unit-
Jntxoduction to Compyte
Computey: A Computer is am electroic device
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
ats
gots oS mdiotoN betueen a user ond horduDare
Applicotio oofl woie
Knds o pqa ms
oe Cotted
Appltcotion 8oftuYTe
o(omerS o a Computey
CPU
ALU
CO
Devtces Devrces
Memo
he
the dota toD produce the different resutt
CPU mainly
ALO:
Arethemate Lmcol Unit of CPU s used to
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
MtCYo Computey
Jime Sho i Computig Envevonment:
time shostq
Shoring Environnment One Cov) nmove usens Can
Comect uoith one Co) more 3ystemS
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
Cemlal (emputev
Stomo Pites
Distrrbuted Computig Envronymemt
Sex's
SexexIL
ternet Sevey
Sewe
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
Jhey ane
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
Tised to positio
of the 8mbol
Decima o 2 3 5 G 78
Binor
Binory 0000
BnarH to DecMaCaRIsion
Gtven
OlolO0|
1G54 3 2 0
128+32+3+1
(1otolool), (16o
aConuert (IoiO-UlO) iNtd a decimal mumber
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|
.25
X2
2 6-0
oSO
2 23-o 2
S
2
|oII1O0 O
(12-25.toloo-o1),
Octal Number dy8tem: (Base 3
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
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
(Iu)g
0etal muwbey
Convet (118 92) tnto 0 92
&)
818 36
23
-6
6-
6&.1210
( 47 o127)
t
CeTvet
b
dt th ohese oouey is viseo
THL be mutip
of the Symbol
wth pos*en
Octal to Binari Convestoy
N
6 3
(11D o)
Convert (63 2)g into 8inanumbe
G3 2
(1oOLtOLo)
(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
the ymbe
wtth po6ttion of
Decimal 3 45 6 189 O 17 13 4 y
Hexadecimal 3L4S 6 18 9
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
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
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)
- Ve o (u1)
t s uSed in eovi Computer
7eo
opeotOm
tuo's Complement mumbey
toring ond Petrwing 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
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
-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
biva Poivt
9binovy 3ystem we Cov oly storve b'ro daits m
not the birory Ponts
Called lovmalizatiov
pot
Pot s auoy ot oyes povt /otoThe stav
e uce
u.Se tcee Co povexts iv the eal w u n b -
we
+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
S0
Conueyt the
humber tnto
bunary
to Set () s(m)volues
Stop
: 183 125
3 8125
5) oT mantisse
n TeEe single preciston,it mort
&tot
AAdinT to tke
ManficSo
Corvet 1
to it
Sian
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I
INTRODUCTION TO C
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:
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
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
* 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
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
data types
Floating-
Integral
point
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:
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)
CSE Page 11
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I
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:
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:
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:
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:
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.
CSE Page 12
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I
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:
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 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.
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.
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;
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.
#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
#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.
#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
#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();
}
#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
#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();
}
#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();
}
#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;
}
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
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.
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:
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
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:
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:
CSE Page 21
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I
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.
CSE Page 22
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I
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.
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)
CSE Page 23
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I
#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);
Output:
Enter the value of num1:20
Enter the value of num2:10
CSE Page 24
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I
#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
#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
#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
#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
#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
#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
#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:
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.
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
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.
CSE Page 31
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I
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:
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.
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.
(type-name)expression
#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
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()
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
CSE Page 34
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I
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.
Format O/P
printf(“%d”, 9876) 9876
printf(“%6d”,9876) __9876
printf(“%2d”,9876) 9 876
printf(“%-6d”,9876) 9876__
printf(“%06d”,9876) 009876
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.
CSE Page 35
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I
Format O/P
%s RaJURajeshRaN i
%18s RaJURaJEshRan i
CSE Page 36
PROBLEM SOLVING AND PROGRAMMING USING C UNIT-I
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();
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
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.
“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.
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