0 ratings 0% found this document useful (0 votes) 18 views 21 pages C Language
This document serves as an introductory guide to the C programming language, covering its history, basic concepts, and fundamental components such as constants, variables, and keywords. It emphasizes the importance of starting with C before moving on to more advanced languages like C++ or Java, and outlines the structure of a C program, including the main function and the use of comments. The chapter also provides rules for constructing constants and variable names, as well as the significance of the printf() function for output.
AI-enhanced title and description
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save C language For Later
“Well begun is half done...”
You cannot be great at the start, but you have to start to be
great. So, making a beginning is important. This chapter will
help you wet your feet, before beginning a more arduous CG
journey...2 —
° What is C?
Which C are we ‘©
» Getting Started with C
coe
Learning?
Alphabets, Digits and Special Symbols
Constants, Variables and Keywords
Types of C Constants
Rules for Constructing Integer Constants
Rules for Constructing Real Constants
Rules for Constructing Character Constants
Types of C Variables
Rules for Constructing Variable Names
C Keywords
The First C Program
Form of a C Program
Comments in a C Program
What is main( )?
Variables and their Usage
printf() and its Purpose
Compilation and Execution
Receiving Input
Programs
Exercises
KanNotesrem rrr re
Chapter 1: Getting Started ?
efore we i : :
Be out et begin to write programs in C, it would be interesting t©
compare with ee is C, how it came into existence and how does it
i er Programming la i we would
briefly outline these issues. g languages. In this chapter,
Four i
et rhe aspects of any language are—the way it stores data, the
it cee upon this data, how it accomplishes input and output,
ow it lets you control the sequence of execution of instructions in
a program. We would discuss the first three of these building blocks in
this chapter.
What is C?
Cis a programming language developed at AT & T's Bell Laboratories of
USA in 1972 by Dennis Ritchie. C became popular because it is simple
and easy to use. An opinion that is often heard today is—“C has been
already superseded by languages like C++, C# and Java, so why bother =
learn C today”. | seriously beg to differ with this opinion. There are
several reasons for this. These are as follows:
Trogramming (OOP) to organize programs which offers many
advantages. While using OOP, you need basic programming skills.
So, it makes more sense to first learn C and then migrate to C++, cH
or Java. Though this two-step learning process may take more time,
but at the end of it, you will definitely find it worth the trouble.
(b) Major parts of popular operating systems like Windows, UNIX, Linux
and Android are written in C. Moreover, if one is to extend the
operating system to work with new devices, one needs to write
device driver programs. These programs are written exclusively in C.
(c) Common consumer devices like microwave ovens, washing
machines and digital cameras are getting smarter by the day. This
smartness comes from a microprocessor, an operating system anda
program embedded in these devices. These programs have to run
fast and work in limited amount of memory. C is the language of
choice while building such operating systems and programs.
(d) You must have seen several computer games where the user
navigates some object, like say a spaceship and fires bullets at
invaders. The essence of all such games is speed. To match this
expectation of speed, the game has to react fast to the user inputs.
The popular gaming frameworks (like DirectX) that are used for
creating such games are written inc.4
4 _ tert
| hope that these are very convincing reasons Why YoU should aq,
the first step in your quest for learning programming. Pt Cay
Which C are we Learning?
ae afte description of the C programming language was pubjish
rian Kernighan and De it i a
vet Yennis Ritchie in 1978. It is commonly referee!
ar ae American Na jonal Standards Institute formed a comm
S311 to enablsha standard specification of C. The ANSI standard
s in 1989 and ratified as ANS! X3.159-1989 "Program, "tt
guage C." This version of the language is often referred to =a
Ns}
C". It is sometimes also known as C89.
In 1995, the ISO published i
, an extension to ANSI C which j,
ore as ISO C. In March 2000, ANSI adopted ISO C. This stay te
monly referred to as C99. All programs in this book are baw’
C99 standard. aise 3
Getting Started with C
There is a close analog
gy between learning English langu:
lage
C language. This is illustrated in the Figure 1.1. an ae
‘Steps in learning English language:
"Alphabets | + Words +! sentences 4 Paragraph |
Steps in learning C language:
* Instructions |» Program
As with English, C lan
1, C language too has a s
ale cae mee et of rules that one must follow
Alphabets, Constants,
Digits + Variables
Special Symbols | Keywords
Figure 1.1 Steps in learning a language.
Alphabets, Digits and Special Symbols
alphabets, numbers and special symbols
Figure “1.2 shows the val
‘Alphabets
8, By mes Vit
| cits © 0,1,2,3,4,5,6.7,89
Special symbols
ene ye IU cc
Figure 1.2 Alphabets, digits, special symbols used in C
Lends os,
Constants, Variables and Keywords
bols when properly ri
‘The alphabets, digits and special symbols when ProPeTy TN doesn’t
constants, variables and keywords. A constant is a0 £0 isa
change, whereas, a variable is an entity that may change-& keer
ne ners ial meaning. In programming IanguaBes. O77 ys
are often called literals, whereas variables are called dentifiers,
now see what different types of constants ‘and variables exist in ©
combined form
Types of C Constants
Constants in C can be divided into tw
Uo Primary Constants — Integer, Real, Character
Ab) Secondary Constants — Pointer, Array, String, structure,
Enum
At this stage, we would rest
Integer, Real and Character constants.
j down for constructing these different type:
Rules for Constructing Integer Constants
ant must contain at least one digit.
10 major categories:
union,
rict our discussion to only Primary constants,
Following Rules have
.s of constants:
(a) Aninteger const
(b) It must not contain a decimal point.
Its value can be zero, positive or negative.
integer constant, it is assumed to be positive:
fed within an integer constant.
s is -2147483648 to
) If no sign precedes an
(d)_ Commas or blanks are not allow’
The allowable range for integer constant:
+2147483647,
+782 -8000 -7605
(e)
Ex: 4266 Let Us¢
Oe -
Truly speaking, the range of an Integer constant depends Upon
compiler. For compilers like Visual Studio, GCC, it is “2147483649 he
#2147483647, whereas for compilers like Turbo C or Turbo cH at
range is -32768 to +32767. i
Rules for Constructing Real Constants
Real constants are often called Floating Point constants, Real Constan
could be written in two forms—Fractional form and Exponential for s
Following rules must be observed while constructing real constant
S
expressed in fractional form:
(a) Areal constant must contain at least one di
(b) It must contain a decimal point.
(c)_ It can be zero, positive or negative. Default sign is positive,
(d) Commas or blanks are not allowed within a real constant,
Ex.: +325.34 426.0 -32.76 ~48.5792
The exponential form is usually used if the value of the constant js ej ither
£00 small or too large. It, however, doesn’t restrict us from usin
exponential form for other real constants. :
In exponential form, the real constant is represented in two parts, The
part appearing before ‘e’ is called mantissa, whereas the part folloy ving
/£' is called exponent. Thus 0.000342 can be written in exponential fond
as 3.42e-4 (which in normal arithmetic means 3.42 x 10%),
Following rules must be observed while constructing real constants
expressed in exponential form:
(a) The mantissa part and the exponential part should be separated by
aletter e or E, :
(b) The mantissa part may have a positive or negative sign. Default sign
is positive.
(c) The exponent must have at least one digit, which may be a positive
Or negative integer. Default sign is posi
e,
(d) Range of real constants i
expressed in e;
Ee ees xponential form Is
Ex.: +3.2e-5 4.1¢e8 -O0.2E+3— -3.2e-5
7
Chapter 1: Getting Started ee
ee a
Rules for Constructing Character Constants
(a) A character constant is a single alphabet, digit or SI
enclosed within single inverted commas.
(b) Both the single inverted commas. should poin!
‘éxample, ’A’ is a valid character constant, whereas
pecial symbo!
t to the left. For
“p’ is not.
of constant. —
A particular type of variable can store only the same nye constant, 2
For example, an integer variable can store only an ae variable can
aah acter variable cot
real variable can store only a real constant and a ET CnY types of
Store ¢
Sore only a character constant. Hence there are a5
variables in C, as the types of constants in it.
z Its of these
In any C program many calculations are done. The ee sae
calculations are stored in some cells (locations) of comp
emory cells
To make the retrieval and usage of these values easy, the = eee
are given names. Since the value stored in each location
7 i S.
the names given to these locations are called variable name:
e different.
; ar
The rules for constructing different types of constants are @TICT NE
i sa
However, for constructing variable names of all types, the
rules applies. These rules are given below.
Rules for Constructing Variable Names :
(a) A variable name is any combination of 1 to 31 alphabets, digits or
me con allow vari th
Gnderscores. Some compilers allow variable names whose leng!
you should not create
could be up to 247 characters. However, poi
unnecessarily long variable names as it adds to your typing effort.
(b) The first character in the variable name must be an alphabet or
underscore (_).
avg _ basic_salary
|_int pop_e_89
We should always create meaningful variable names. For example, while
calculating simple interest, we should construct variable names like prin,
roi, noy to represent Principle, Rate of interest and Number of years,
rather than arbitrary variables'like a, b, c.
Scnsaie
9
ani a
Chapter 1: Getting Started
8
same for all the types of
in
james fem ip differentiate betweg,,
The first program is very simple. It calculates simple interest for a set of
ble
Jes for creating varia Ss
mary and secondary variables 5 ey ae tha
sg mec” eee values representing principal, number of years and rate of interest.
is type dee
wish to use in a program. This t¥ /* Calculation of simple interest */ z hs
ex: int si, m_hra;
int main()
char code ;
int pn;
e meaning has already Been explained to tos
Keywords are the words whose Oe se computer) There are only 37 p10
the C compiler (or in a broad s keynote z tp
/* formula for simple interest */
Figure 1.3 gives @
leinC.
si=p*n*r/100;
printf ( "%6f\n", si
return
i
Let us now understand this program in det
Form of a C Program
Form of aC program indicates how it has to be written. Though C is free-
form language, there are certain rules about the form of a C program
that are applicable to all C programs. These are as under:
{a) Each instruction in a C program is written as a separate statement.
SERN SS 4 SOAS Serer
The statements in a program must appear in the same order in
Figure 1.3 C keywords.
Ké not be used as variable names. However, some C
‘The keywords shoul
compilers alow you to construct variable names that exactly resemble ibs
~ the keywords. which we wish them to be executed.
Compiler vendors provide additional keywords apart from the ones (c) Blank spaces may be inserted between two words to improve the
given in Figure 13. Though it has been suggested by the ANSI committee readability of the statement.
that every such compiler-specific keyword should be preceded by two (d) Allstatements should be‘in lower case letters.
underscores (as in_asm), not every vendor follows this rule. a
(e) Every C statement must end with a semicoion ( ; ). Thus ; acts as 2
The First C Program statement terminator. eee
(f)_ Usually, each line contains one statement. However, you can write
le statements in one line, provided each statement is
Once armed with the knowledge of variables, constants and keywords,
the next logical step isto combine them to form instructions. However,
instead of this, we would write our frst C program now. Once we have
done that, we would see in det Comments in a C Program
Comments are used in a C program to clarify either the purpose of the
program or the purpose of some statement in the program. It is a good
terminated with a ;.—_
10
dicating the Purpose of
tine
coma the program Is writen,
on
ina ¢ program:
a combination. They
first two statements jn
gram with &
a proy
practice to begin 2 Pi aie
the program, its author and the
‘comments
case, capital ©
ye t/. Thus, the
Here are a few tips for writing
{a) Comments can be ir J
should be enclosed within
sci a soo
tomention the purpose of
mple int
100
lace in the
written at any Pl e
ne mpefore the statement, after
wn beloW.
‘of comments can be
a comment can be writen 0°
1 within the statement as s
(¢) Any number
program. $0,
the statement or
sizp*n*
‘Comments cannot be nested. This means. oe be
written inside another commient. So, following com
25/03/2021,*/*/
S1/* Author: gekay date:
(e) Acomment can be split over more than one line, 25
comment has
(f)ANSIC permits comments tobe written in another way as follows:
// Calculation of simple inter
// Formula
What is main( )?
main ) forms a crucial part of any C program, Let us understand its
Purpose as well as its intricacies,
Chapter 1: Getting Started 11
‘program may have multiple functions. (if it contains only one.
function its name has to be main( ). All statements that belong to
“main{ ) are enclosed within a pair of braces {}.)
(b) Like functions in a calculator, functions in C also return a value.
function always returns an integer value, hence there is an
it is known as return type of the function. The
a non-zero number from main{ ). This would indicate failure.
(c) The way to watch the value returned by main( ) varies from one
compiler to another, as shown below.
Turbo C, Turbo C++ - Alt C | Information
Visual Studio - $ReturnValue in Watch Window of Debugger
Linux - echo $? at command prompt after execution of the program
(d) Some compilers like Turbo C/C++ even permit us to return nothing
irom main( ). In such a case we should precede it with the keyword
void. But this is the non-standard way of writing the main( )
function. We would discuss functions and their working in det
Chapter 8. ee AL aera Ta)
Variables and their Usage
Let us understand the significance of constants and variables with
reference to our program.
Any variable used in the program must be declared before it is
used. For example,
int p.n; 7* declaration */
float r, /* declaration */
sizp*n2r/100; /* usage */
(b) Inthe statement,
si=p*n*r/100;
* and / are the arithmetic operators. The arithmetic operators
available in Care +, -, *, / and %.
(NNNfet Usc
pe eer
he scree,
intf() and its Purpose output on t All
printf() 10 dsPlAY OF brary functions like
y keywor
does not contain an ea
tutput to screen is achieved UI in respet to our Program
tion wit
ct
sderstand this fun sto be ds13708 On the
intl OOF itis necessary to use
ction,
funetine program. include is q
clarified in Chapter 12.—~
{b) To be able to use the
since 2
sew
Frrorocessor rete Bu
al form of printf) function '»
tof variables?)
«format string> can contain,
ing real values
Sa for printing integer values
‘Ke for printing character values
ye sf, d and %c, the format
In addition to format species IME TT hese characters are
!
string may also contain any of es
printed as they are when prints executes
of printf) function:
(
pri
print ("hd Sd FF, BM
printf ("Simple interest = RS.
print (“Principal = lnRate = 8F
this.
The output ofthe last statement would look
Principal = 1000
Rate = 8.500000
The output i split over two lines because of newline character ‘\n’.
It sends the cursor to next line, It is one of the several Escape
‘Sequences availble in C. These are discussed in detall in Chapter~
18.
(e) printt() can print values of variables as well as result of an
expressions lke 3, 3+ 2, cand a+b * c- das shown below.
ae 13
Chapter 1: Getting Started
Chapter 1: Getting Sturted Se
printf ( "%6d %d %d %6d", 3,3 +2, c,a+b*c—d);
Note that 3 and ¢ also represent valid expressions.
Compilation and Execution
‘Once you have written the program, you need to type it and instruct the
machine to execute it. Two other programs are needed to do
Editor and Compiler. Editor lets us type our program, whereas Compiler
converts our program into machine language program. This conversion
iF necessary, since machine understands only machine language.
‘Apart from these two, there are other programs which you may need to
improve your programming efficiency—Preprocessor, Linker_and
Debugger. Working with each one of them idually is a tedious job.
Hence, often all these are bundled together with a layer of GUI on top of
them. GUI makes these programs easier for you. This bundle is
often called Integrated Development Environment (IDE).
There are many IDEs available. Each IDE is targeted towards a particular
operating system + microprocessor combination. This combination is
known as a platform. A compiler created for one platform does not work
with other platforms. Details of which IDE to use, from where to
download it, how to install and use it are given in Appendix A. Insteac
installing an IDE, there are online options available for compiling and
executing programs. These are also discussed in Appendix A.
Receiving Input
In our first C program we assumed the values of p, n and r to be 1000, 3
and 8.5. Every time we run the program; we would get the same value
for simple interest. if we want to calculate simple interest for some
other set of values then we are required to incorporate these valides in
the program, and again compile and execute it. This means that our
program is not general enough to calculate simple interest for any set of
values without being required to make changes in the program. This is
not a good practice.
To make the program general, the program itself should ask the user to
supply the values of p, n and r through the keyboard during execution.
This can be achieved using a function called scanf{ ). It helps us receive
input values them from the keyboard. This is illustrated in the program
Biven below./* Calculation of
* Author gekay
stdio.h>
return 0
: enter values Of PP, ON the
The fst prin) cutouts the MEST on in print] which meang
ot use
screen. Here we have n« ay
ee saan ve the variables in the scant)
(&) befor
fm the use of ae Saree operator. ves the seemton
function is ee is sable eno awe "8 we
number (address) Ee : vs
‘at which memory ghee
supplied rays from the keyboard The detailes 7
‘operator would be taken up in Chapter % Stan
blank, a tab or a new line must separate t! il a ~pe es a
7 cea Pa bank scrated using 2 aa f z "y
7 /
‘ard new line using the Enter key. This s shown
x: Three values separated by blank:
10005 15.5
x: Three values separated by tab:
1000 5 15.5.
Ex.: Three values separated by newline:
1000
5
155
Chapter 1: Getting Started 15
P
int main( )
{
float bp, da, hra, grpay
kbp);
erpay = bp +da + hra
printf (“Basic Salary of Ramesh =
printf ( "Dearness Allowance = %f\n", da
printf ( "House Rent Allowance = %f\n",
printf ( "Gross Pay of Ramesh is %f\n", grpay ) ;
return 0;
bp)
}
Output
Enter Basic Salary of Ramesh: 1200
Basic Salary of Ramesh = 1200,000000
Dearness Allowance = 480.000000
House Rent Allowance = 240.000000
Gross Pay of Ramesh is 1920.000000,
Problem 1.2
The distance between two cities (in kilometers) is input through the
keyboard. Write a program to convert and print this distance in meters,
feet, inches and centimeters.Se . .Llrle.rrr
Chapter 1: Getting Started 17
wi
Program {
/* Conversion of distance */ ie abl
tdio.h> n
# include (c) C language programs can easily interact with hardware of a PC /
int main() Laptop.sed ll
1 expre’
(d) A real constant 1” c can BF
; Exponential forms: creo
integer conta
The maxim
UO rpe compiler 13" .
1c statements ar
betwee!
ers.
Oe ene lett
wa
two wor
chine aM
rovid
«if any, in the following programms:
he errors,
at bint ¢;
23.24;c2at+b*b~35;
(b) tinclude
int main()
in both Fractional apy
one character.
¢ can have varies fro,
sina statement,
guage with the help of.
je an Editor tO type a ¢
to machine language.
main, printf and scang
—_
Chapter 1: Getting Started
19
Ghopter1:Getting Started
}
(a)
[Fl
(b)
()
{
int a= 35; float
printf ( "%d %F 9d", a, b + 1.5, 235);
}
Hinclude
int a,b,c;
scant ("%d %d 96d", a, b, ¢) ;
}
Hinclude
it main( )
{
int m1, m2, m3
scanf ( "9%d %d %d", &m1, &m2, &m3 )
Printf ( "You entered %d %d %d", m1, m2, m3)
)
Attempt the following questions:
‘Temperature of a city in Fahrenheit degrees is input through the
keyboard. Write a program to convert this temperature into
Centigrade degrees.
The length and breadth of a rectangle and radius of a circle are
input through the keyboard. Write a program to calculate the area
and perimeter of the rectangle, and the area and circumference of
the circle.
Paper of size AO has dimensions 1189 mm x 841 mm. Each
subsequent size A(n) is defined as A(n-1) cut in half, parallel to its
shorter sides. Thus, paper of size Al would have dimensions 841
mm x 594 mm. Write a program to calculate and print paper sizes
AO, Al, A2, ... AB.
kong
3 top reasons for learning C:
- Good base for learning C++, C# or Tava later
~ Unix, Linwe, Windows, Gaming frameworks are written in C
itsoy
oe
__——_——
pitten in c
— Embedded systems progran® are i
Constants = Literals -? cannot chang}
er sari primary 2) Secondary
it d constants *
Types of variables an ee eT
2 types in Primary dager 2) Ral (fos!)
Ranges +
z-byte integers * ~
} ihe ste, Cae
3) fds: pasion 2A oie
otes
ina char constant both 4
Variable has two meanings *
sean entity whose value can Change
Deeg elaonine Daas
friable ames ae case-sensitive and must begin PI
Variable n
Total keywords = 32. Example char, ints float, ett.
tf) a fanction ta cn print mulple constants and variablee
printf()
Format specifiers in printf()y seand() + int - is float - %f, char - %¢
san() i afmction cat must aways return integer value «
0-ifit meets success | -ifit encounters failure
veid man() i wrong. Correct form is int mmain()
Use /* un */ or [| for a.comment in a program
ie ‘ddrese oP opertor and must be used before a variable in
eax)
C Instructions
L pra
Me ra
bers
“On your mark, get set, go...”
Captain of a Cricket team is as good as his team. If the team is
‘not good enough, captain alone cannot do much. Same is the
case with C programming. Unless you know the instructions that
it offers, you can hardly write a good program. This chapter
discusses these instructions...
21«Types of Instructions
# Type Declaration In
« Arithmetic Instruction
+ Integer and Flat Conversion '
«Type Conversion in ASSI6N
« Hierarchy of Operations
« Assocativity of OPer=tOrs
«© Control Instructions
« Programs
«Exercises
© KanNotes
chapter 2: C Instructions 23
gram is nothing but a set of instructions. Different
Arete ‘ceachieve different tasks in a program. In the last chapter we
how to write simple C programs by using different instructions. In
sav Mhapter we would explore the instructions that we used In these
thi
programs.
types of Instructions
ere are three types of instructions in C:
(@) Type Declaration Instruction ~ This instructions used to declare the
types'of variables used in a C program.
Avithmetic_Instr = This instruction is used to perform
‘rithmetic operations on constants and variables.
(@) Control_Instruction ~ This instruction is used to control the
sequence of execution of various statements in a C program.
Let us now take a closer look at these instructions.
(o)
Type Declaration Instruction mom CY)
This instruction is used to declare the types of variables being used in
the program. The type declaration instruction is written at the beginning
of main( ) function. A few examples are shown below.
int bas;
float rs, grosssal ;
char name, code ;
Here are a few subtle variations of the type declaration instruction...
(a) While declaring the type of a variable, we can also
shown below.
int 1= 10,)=25;
float a= 15,b=199+2.4" 1.44;
(b) A variable must stand defined before using it. The following
statement is illegal since we are using variable a before defining it.
float b=a+3.,a=18; 9 \
(©) The following statements would work:cet.
int a,b,c, signed a value 19 «
a=b= 210; /* each variable would be 25°" ye)
id not work:
r
However, the following statement WOU
int a=b=c=d=10;
(toassign to) before defn
The error is we are trying to use B
Arithmetic Instruction
‘An arithmetic instruction in C con
hand side of = and variable name
‘operators on the right hand side of =
ss of 2 vORBBIE FAME ON the jog
and constants connected ysint
Ex: int ad;
float kot, deta, alpha, beta, 68M i
ad = 3200;
= 0,006;
kot = 0.0054 a
deta = alpha * beta / gamma +32
+ are the arithmetic operators.
an assignment operator.
2,5 and 3200 are integer constants.
3.2 and 0.0056 are real constants.
adisaninteger variable.
kot, deta, alpha, beta, gamma are real variable
The variables and constants together are called ‘operands!. While
executing an arithmetic statement, the operands on right hand side are
‘operated upon by the ‘arithmetic operators’ and the result is assigneq,
Using an assignment operator, tothe variable on et-hand side,
An arithmetic statement in C could be of three types. These are as
statement, all operands
i king, issac, noteit ; :
ied;
ei ee
eT
2: C Instructions 25
king =issac * 234 + noteit - 7689 ;
{o)Real mode arithmetic statement ~ In ths statement, all operands
are either real constants or real variables.
Ex: float qbee, antink, si, prin, anoy, rt ;
bee = antink + 23.123 / 45 * 0.3442;
si= prin * anoy * roi / 100.0;
{o) Mixed mode arithmetic statement ~ In this statement, some
‘operands are integers and some operands are real.
Ex: float si, prin, anoy, roi, avg;
int a,b, ¢, num
si= prin * anoy * roi / 100.0;
avg=(a+b+c+num)/4
Note the following points about Arithmetic instructions carefully
on left-hand side of =. That is, z= k * lis
legal, whereas k* | legal
(b) In addition to the division operator, C also provides 3 modular
division operator. This operator returns the remainder on
‘one integer with another. Thus, the expression 10 / 2 yi
whereas, 10 %2 yields 0.
s 5,
Note that the modulus operator
cannot be used with floats.
Ao Rote that on using %, sign of the remainder is always same as
e
sign of the numerator. Thus -5 % 2 yields -1, whereas, 5 % -2
ign of the numerate
(c) Arithmetic operations can be performed on ints, floats and chars.
jing statements are val
pee
218
b
ASCII codes are used to represent any character in memory. ASCII
codes of ‘a’ and ‘b’ are 01100001 and 01100010, Their decimal
equivalents are 97 and 98. The addition is performed on these
decimal values and not on characters(6) No operator is assumed to De Pr
In the following example, the
be explicitly written.
a= c.d.b(xy) etatement
acctdtb*(x*y)
(e) There is no operator in
Exponentiation has to be
vc necessary to include — /* for sqrt1 Z ——$——_
Herons friacule he sfs-a)(s- b).bstuas
TET
ter 2: C instructions 33
chapter 2: Clnstructions _S5,
Xt main
; i
1+ specitier%d Is used for printing @
pene ay : 1 serovars number 16." FeVRET
scant ("%6F 6660", 8a, Bb, return 0;
sp=(arbse)/2i )
area = sqrt (sp * (5-2) *
wsarea of triangle = 1" output
bo enter afive digit number (less than 32767): 12345
: ‘The reversed number is 54321
__
Output
problem 2.3
consider @ currency system in which there are notes of six
anes corsminations, namely, Re. 2, Rs. 2, RS. 5, RS. 10, Rs. 50, Rs. 100. If a
7 Sam of Rs. N is entered through the keyboard, write a program to
compute the smallest number of notes that will combine to give Rs. N.
Enter sides of a triangle: 456
‘Area Je = 9.921567
Problem 2.2 poard, write a program to.
UG se number input trout Pe Mastttt® arid Be ihe?
reverse the number- ete lb e a include
‘ ae int main()
rogram ase {
“ Siiabe lat int amount, nohun, nofifty, noten, nofive, notwo, n ‘
/* Reverse digits of 5-d8it ‘as printf ("Enter the amount: " ); ane total
ft include sd (paite'n dS 2 Mild 2 scanf ("%d", &amount ) ;
u i Fe
mami Bade Tdsoe nohun = amount / 100 ;
amount = amount % 100
int m5, d8, 03, 2,42 = :
ge nofifty = amount / 50 ;
en ante amount = amount % 50 ;
me noten = amount / 10;
amount = amount % 10 ;
+ sth digit */
1. mania sas */ native» amount 5
it"! amount = amount % 5 ;
‘J cemaining digs */ notwo = amount / 2;
[ed dgit*7 j amount = amount % 2 ;
ng digits */ noone = amount / 1;
mount % 1 ;
total = nohun + nofifty + noter
+ noten + nofive +
dien%i0; [ts ; print ("Smallest numberof notes sey" tel) on
return 0; = %d\n", tota
S41 4 rem sqye art ed © FAY | )LS Ot”
wo
Chapter 2: C Instructions
chapter 2:Cinstuctions agg
35
Output
‘Smallest number of notes = 8 to eerie
as (b) b=3/2+5°4/3;
© (d) x=2-34+5°2/8%3;
Exercises 4
EXwaz (e) 2=5%3/8"3+4
fan the fllowing C statements: () y=22-3%-8 /2+7;
joi wren
ywing programs?
be the output of the fol
TA] Point out the errors, i
(a) x=(y+3);
(b) cir =2* 3.141593 * Fr; (a) #include
(o) char= 3"; int main)
(a) 4/3* 3.14% r¢rt r=voLoL sphere? Gor fon sai
be
(e) volume =
(f) area=1/2 * base * height
(e) sieptr?n/100;
printf ( "%6d 96d %F %f\n", k, |, a, b);
(h) area of circle =3.14° °C
(i) peri_of_trizatb+e;
W) slope =(y2-yi)# (22-2) ; return 0;
(k) 3=b=4=a;
(I) count = count +1; (b) #include
(x= 3.5, assume R to be a float) ; it main( )
float a=5, b=2;
the following expressions would be
int c,printf ("6d\n", 4)
return 0;
)
(4) include
int main( )
{ .
printf ( "an \n\n n\n
printf ("nn /a/n nn
return 0
)
(e) include
int main( )
{
int a,b;
printf ( “Enter values of a and
scanf(" %d %d
printf ("a =%d b= %d", 3
return 0;
}
er the following statements 27° True or False:
{E] State wheth
sents the correct hit
Ge eee - we jerarchy of arithmetic
‘operators in C.
and {}can be used in
les which operator is Use’
truction cannot contain
‘Arithmetic instructions.
od first.
constants on left side of
(b)
(c) Hierarchy 4
(d)_ In C, Arithmeti
* operators used for exponentiation operation.
(e) In
with floats.
(f) % operator cannot be used
[F}_Fillin the blanks:
(a) Iny=10*x/2+2;__operatio
ita isan integer variable, a= 11 / 2 would store — ina.
The expression, a= 22/7* 5/3 would evaluate to A
The expression x = -7 % 2 - 8 would evaluate to_-
n will be performed first.
copter 2:Cinstrctions
37
{e) fis a float the operation d= 2/7.0 would store__in
weeeain’
{[] Attempt the following questions
if a five-digit number is input throug
igh the k
program to calculate the sum of its digits. thine Use te meats
7 ulus
)
operator %)
Write a program to receive Cartesian co-ordinates (x, y) of a point
(b)
and convert them into polar co-ordinates (r, @).
Hint: r= sqrt (x? +y?) and 9 =tan*(y/x)
Write a program to receive values of latitud
le (L1, L2) and longit
(G1, G2}, in degrees, of two places on the earth and cana
distance (D) between them in nautical miles. The foi ta for
distance in nautical miles is: " ree
(co)
1p = 3963 cos ( sin L1 sin L2 + cos L1 cos L2 * cos (G2-G1))
Wind-chill factor is the felt air tem
perature on exposed ski
wind. The wind-chill temperature is always lower a i
temperature, and is calculated as per the following formula a
Bo
wef = 35.74 + 0.6215t + ( 0.4275t - 35.75) * v6
where ‘temperature and
" wind velocit
receive vlucs of t andy and calculate yan Tactr a ee
(wef).
If value of an angle is in
f put through
to print alitsTrigonometic ratios, oon
(f) Two numbers are in
b put through the keyboard i
ad D:Wite apropam te lnurhngethecomensoreoeabe +
and.
© Standard steps in interchanging contents of two variables :
teas a=bsbets
© [gives quotient, % gi i
! ient, % gives remainder. While taking %, si i
tt pcb 3 ate
© C offers 3 types of instructions38
Let Us c
ee
i) Type declaration 2) Arithmetic 3) control
Declaration and assignment can be combined: ex.:inta=55
© 2 tupes of Arithmetic instruction?
i) Integer mode 2) Real mode 2)
© Rules for arithmetic instructions *
mixed mode
- one operand is float, result ig afloat
= esi int only both operas ET
* a= pow (2,5) would store Zine remember to include
emath.h>
© Every operator has i) Priority 2) associ
© Priotityis * /% +> —pronty abe ced using ()
aay cannot decide which
© Aesociaivity comes into. pla when prior a
operation to perform first. pssociativity | ether LtoRorRtol,
was tb has to R= has Rio ae#e"
© Format string of printf) can contain +
i) Format specifiers - he 6d, oF
2) Escape sequences * (ny Mes many others
3) Any other character
© Format string of sscant() can contain only format specifiers
«Control instructions control the sequence of execution of
instructions ina program
© 4 types of control instructions +
i) Sequence 2) Decision 3) Repetition 4) Case