C Programming Chapter 2 Notes
C Programming Chapter 2 Notes
BCA Computer Concepts & C Prog- IKUD Algorithms Flowcharts 102 Unit 2 2.
0 Computer Programming The basic structure of a computer and Von Neuman's stored
program concept revealed us that a computer has a storage unit called its memory:
It holds a set of instructions called a program to be executed and a set of data
to be processed.
In other words CPU reads one instruction at a time from the memory unit and
executes it on the relevant data.
Likewise, the execution continues from instruction to instruction.
At the end of last instruction execution, the results of computation will be
stored back in the memory and later they may be displayed on the output unit, the
display:
d screen.
► Therefore computer is termed as a General Purpose programmable machine.
In other words any specific work can be carried out by the computer at a given
time, just by instructing it to do so, but in a simple systematic step by step
procedural instructions that necessitates the computer programming both knowledge
and skills The language with which computer can understand the instructions and
proceed to execute the specified task - are the two important aspects of
programming the computer.
2.
1 Basic Programming Concepts Many of the devices, mechanical and electromechanical
machines can be operated and the specific work can be got done just by switching on
the machine, and / or by loading work piece in them.
Manual supervision of the functioning of the machines and timely hand operations
on the buttons and levers may lead to the production of good quality finished
products.
er Unlike all these machines, computer being an information processing machine
need clear cut guidance interms of sequence of instructional steps in order to
carry out the specified work, apart from switching on the computer and supplying
electricity to it! In other words, problem solving with computer involve preparing
a set of procedural instructions for determining the solution.
Using these instructions, computer can solve the problem to compute the results.
Therefore Computer programming is concerned with design ing a set of instruction
and expressing it using a precise notation known as a computer program.
A notation used for the precise description of the set of instructions is called a
computer programming language.
Thus computer programming involve the design, development and implementation of a
computer program in order to solve the given problem on a computer.
A finite set of instruction expressed using a precise notation is called a
computer program • Programming is both art as well as a science.
Because art of programming differs with different persons involved in computer
programming.
For example for the given ( same ) problem, three ( 3 ) persons may write 3
different computer programs with their own approaches.
These programs when executed give the same results.
Therefore programming is an Art.
• But the programs written by 3 persons ( programmers ) have the precise notation
also called scientific notation.
A specific scientific method or procedure may have to be used to design and write
each and every program.
Therefore a scientific approach to be followed and reasoning skills to be
incorporated while writing a program Thus programming is a science too.
7 Why programming language It is clear that a precise set of instruction called, a
computer programs is essential in order to solve the given problem.
Such compuier programs are written to instruct the computer that what operation to
perform?
( for example an arithmetic operation or a logizal operation ) Where and How to
locate data?
How to print the result?
When to take certain decisions?
and so on .
.
.
The computer being an electronic machine and the people working with computers,
( representing the external world ) are the two disjoin ends or the parties in
which a common understanding is required Then only both the computer and man can
establish a communicat on for problem solving e As nction nction
103 Par Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 105 5 O Computer being an electronic machine has
its own programming language called Machine language.
Any communication with the computer for problem solving must be in its machine
language.
Now computer can interpret and execute a set of a binary coded instructions called
its machine language instruction.
Writing a program for a computer machine consists of specifying directly or
indirectly, a sequence of machine instruction.
Machine instruction inside the computer form a binary pattern of O's and I's which
is difficult for people to work with and understand the machine language
programming.
Programming in machine language involve writing of computer programs that consists
of series of binary code patterns.
These binary streams of O's and I's forming a machine instruction consists of
instruction code also called the operation code and the operand address that
specify memory location to hold data operands.
Introductory Note # 1 Algorithms and Flowcharts are fundamental notations in the
context of computer programming.
Actually, the computer science branch is concerned with design and development of
Algorithms.
In fact in each and every stage of problem - solving, computer cannot be used to
solve the problem.
One has to devise a method and detailed procedure or a sequence of procedural
steps have to prepared.
This approach give rise to the concept of Algorithm pictorial representation of
which is a Flowchart.
Flowchart is used as an aid in preparing computer programs.
As algorithms and flowcharts assist the fundamental knowledge while preparing a
solution to the problem ( to be solved using computers ), a complete chapter is
dedicated to the detailed discussion on algorithms and flowcharts.
2.
2 Algorithms Algorithm consist of limited number of procedural steps, each the step
may perform one or more operation.
Therefore algorithe is a scientific procedure to solve a problem, thereby solution
to the particular problem is definitely achieved The word Algorithm comes from the
name of a persian mathem tician Abu Ja'far Mohammed ibn Musa al Khowarigmi.
He wrote text books on Mathematics.
Characteristics of Algorithms A well defined algorithm has the five basic
characteristics; They are 1.
Input:
Algorithim starts with procedural step to accept input data:
These data elements are processed by the subsequent steps on instructions in the
algorithm.
Therefore algorithm must accept one or more input data to be processed.
2.
Definite:
Each operational step or operation must be definite i.
e.
each and every instruction must specify clearly that, what should be done.
In other words there should not be any confusing instructions.
For example instructions such as i ) compute 5 = 0 ii ) Add 10 or -7 to x are not
allowed because it is not clear what the result is in case of 5/0.
Since ( infinity ) is not defined in computer.
Which of the two numbers ( 10 or -7 ) should be added to x.
Therefore there is no definiteness in these instructions.
In otherwords, procedural step or instruction must be precise and it should tell
in a definite manner What is to be done.
3.
Effective:
Each operation and hence procedural steps must be effective to carry out.
Effectiveness property of the Algorithm says that each operational step can at
least in principle be carried out by a person using a paper and pencil in a minimum
amount of time In otherwords operations must be simple and can be carried out a one
or more levels of complexity 4.
Terminate:
After some minimum number of operations algorithm must come to an end.
i.
e.
, the total time to carry out all the steps in algorithm must be limited
( finite ).
1 Algorithm Definition An algorithm can be defined as a finite number of well
defined procedural steps used to solve the problem.
109 Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 110 A In the above algorithm nl, n2, n3 are
three numbers to be read ( input ).
The results are stored in Sum & Average ( output ).
The operational step 2 adds the three numbers with following instruction Sum ( nl
+ n2 + n3 ) here ( leftwords arrow ) specify the assignment.
i.
e.
, sum of nl, n2, & n3 is assigned to ( stored ) sum ( a variable name that hold the
result ) The symbol is equivalent to =.
The above instruction is as good as writing sum = ( nl + n2 + n3 ) But in
algorithmic notations = is replaced by + symbol.
2 ) Consider a second example:
( 6.
4.
2 ) Given the problem:
to find largest of given three numbers.
We shall write the algorithm with the assumption that the three numbers A, B and C
are read and biggest among these, is assigned to BIG.
Thus the BIG holds Biggest among A, B, & C numbers, at the end Given 3 numbers say
for example A = 10 B = 30 C = 20 Biggest can be found by assuming the first number
as Biggest i.
e.
, BIG = A ( BIG = 10 ).
► Now by making pairwise comparisons with remaining numbers B & C, if either B or
C is greater than BIG, then contents of BIG ( i.
e.
, 10 ) have to be replaced with B or C.
- > In other words if B > BIG is true i.
e.
, 30 > 10 then BIGB is true.
:
.
BIG = 30 now next if C > BIG is true i.
e.
, 20 > 30 False then BIG C i.
e.
,:
C = 20 is not stored in BIG :
:
Biggest of 10, 30, 20 is 30 only BIG = 30 is still valid.
Algorithm:
LARGEST OF THREE NUMBERS Step 1:
[ Read 3 numbers ] Read A, B, C Step 2:
[ Assume that first number A is BIGGEST initially let BIG A Step 3:
[ Compare BIG with the remaining two numbers to find the Biggest ) if B > BIG then
BIG B if C > BIG then BIG C Step 4:
[ Print the Largest number ] write " LARGEST of 3 Numbers is ", BIG Step 5:
[ End of procedure ] Stop In the above algorithm a simple method or technique is
adapted to compute the Biggest.
2.
3 Flowcharts Flow chart - the definition " A Flow chart can be defined as the
pictorial for graphical ) represen tation of an Algorithm ".
► In the content of problem solving with computer, first the given problem is
analysed; a sequence of procedural steps are formulated called an algorithm.
Algorithm specify the sequence of operations to be performed to arrive at the
solution.
Now this agorcnm expressed in a programming language, is called program.
it is with computer program, the computer machine actually works wisi.
> Therefore the algorithm is usually represented in a diagrammatic form before
being expressed into a programming language hereby it is easy for anybody to
understand clearly the flow of sequence of operations graphically, > Flow chart for
the given algorithm consist of a complete Viagram of boxes of standard shapes
( basic symbols ) by directed line segments ( arrow marks ).
The elementary steps of the alithm or the operating instructions are placed in
these boxes and t.
row mark connections to these boxes show the flow of operatione of the given
algorithm
P " Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 112 for i - l to N By drawing a flow chart,
algorithm can be better understand and can be convinced to others very easily since
it is in pictorial form.
FLOW CHARTS are normally introduced as an intermediate step to assist the
preparation of a computer program Program Flow Chart A program flowchart is a
flowchart that purely specify only the flow of operations of an algorithm,
pictorially.
It is of merely diagram matic representation of the the given algorithm.
The program flow chart illustrate graphically how the program instructions or
opera tions flow in a sequence, when the sequence of execution of instructions
changes etc.
But program flowchart never specify the computer environment in which the program
will be executed i.
e.
, it will not reveal whether the program is stored on magnetic disk, whether data
will be coming in from keyboard, also whether the results or output are printed out
on a printer.
► In other words program flowchart does not contain the basic symbols ( Standard
boxes ) to represent peripherals or I / O devices connected to the computer.
Therefore one cannot visualise pictorially the operational environment of computer
if he / she prefer to draw program flow charts.
Of course program flowchart consist only one basic symbol to represent Read /
Write instructions of an Algorithm.
The symbol is known as “ Parallelogram used to indicate standard input / output
operations, Basic Symbols Used in Drawing Flowchart > The following table shows the
standard conventions or basic symbols used to draw a program flowchart.
Each of the symbol is used to indicate a specific operations or elementary steps
of the algorithm.
Table:
Basic Symbols used in the FLOW CHARTS Symbol Name The symbol is used to indicate
input Parallelogram output operations i.
e.
, Read or Write instructions The symbol is a Processing box ' used Rectangle to
indicate arithmetic operations, as signment operations and any other computational
steps like initializations.
Diamond The symbol is a decision box or shape selection point.
It is used to indicate conditions tested.
Based on the TRUE or FALSE conditional results one path is selected for branching
the execution.
The symbol is also called a " Test box ".
The symbol is a group instruction box used to represent the repetition loops A
group of instructions to be executed, for a specified number of times, are included
within this sym bol.
The symbol indicates a predefined process.
For example sub programs like C Functions can be represented using this symbol The
symbol is a connector circle usca Small Circle to connect two parts of a flowchar
that indicates the continuity.
The syn bol is also called as " On page conner tor ".
The symbol is annotation box " os comment box.
The useful comment explaination of Flow - Chart steps can written into this symbol
The symbol arrows or directed lines Arrows indicate the flow of operations.
These Flow - Lines are used to inter - connect different boxes of Flow chart.
Used to represent Oval The symbol is used to denote either the beginning or end of
the flowchart.
119 Sem BCA Computer Concepts & Prog ( KUD ) Algorithms and Flowcharts 125 ► Now
let's draw flowchart for solving quadratic equation Flowchart:
To compute all possible roots of given quadratic equation START READ А, В, С Step
1 in algorithm NO IS 07 YES Step 2 in algorithm Step 3 in algorithm db 4ac TOOL с b
0 < O Step 4 in algorithm IS d?
Print root > 0 Let's write now algorithm to compute these roots Algorithm:
To compute all possible roots of given quadratic equation Step 1:
Read the values of coefficients a, b and c ] Read a, b, c Step 2:
Is a = 0 and b, c = 0 compute single root|
If a = 0 then root - e / b:
print root; exit; Step 3:
Compute the value of discriminant d ] let de bob - 4 ac Step 4:
Compute 3 possible roots of quadratic equation ] if ( d = 0 ) then print " Roots
are Real and Equal ":
let root root2 = -b / ( 2a ); print rootl, root2 stop else if ( d > 0 then print "
Roots are Real and Distinct ":
let root ( b + d ( 2 * a ); root2 ( -0 - VD ( 2 * a ):
print rootl, root2 Stop else ( ie .
.
d < 0 ) print " Roots are Imaginary and Complex Conjugate "|
let XI -b / ( 2 * a ); Y labs ( d ) / ( 2 * a ); print " root = ".
XI, " + 1 ".
Yl; print " oo2 ", XI.
" - i ", YI:
Stop Print roots real & Equal " Print roots ral & Distinct " Exit Print " roots
Imaginary & Complex Conjugate " Compute b rool 2a Compute root -b + Compute rool -b
( 2.
a ) abs root2 ( 2.
a ) r02 - 2a root2 - Jä Print root, root2 Print root, root2 Printrext = " xl ".
+1 " yl Print " ro " xl.
" - 1 " yl STOP Step 5 ir algorithm 85 Fished:
End of Procedure > Factorial of a given integer Write an algorithm to find the
factorial of a given in number.
Draw a flow chart.
Factorial of a given number N given by 1 x x x N! = 1 x 2 x 3 x --------- XN
/ " Sem.
BCA Computer Concepts & C Prog.
( RUD ) Algorithms and Flowcharts 124 Write an algorithm to find the area &
circumference of a circle given radius.
Draw a flow chart.
Geometric Formula to compute the area of a circle is = str?
Geometric Formula to compute the circumference is = 2tr it is defined PIE = 3.
142 riven data:
Radius of circle ' R ' is to be read ( input ) Area of circle is denoted by ' AREA
' Circumference of circle is denoted by ' CIRCUM AREA = 3.
142 x R XR CIRCUM = 2 x 3.
142 x R Using the above two formula, the algorithm can be written as below:
Algorithm:
To calculate area & circumference of a circle Step 1:
[ Read the value of radius R of a circle ] Read R.
Step 2:
[ Calculate the area of Circle ] let AREA + 3.
142 x R XR Step 3:
[ Calculate the circumference of circle ] CIRCUM + 2 x 3.
142 x R Step 4:
[ Print the area of & circumference of circle ] Print ' Area of Circle = ', AREA,:
" CIRCUMFERENCE = " .
CIRCUM Step 5:
[ End of procedure ] Stop Write an algorithm to find whether a given number is odd
even.
Draw a flowChart.
Consider a memory location ' NUMBER ' where the number to be tested is stored.
An integer division is made to find the remainder also thus REMAINDERENUMBER MOD2
( MOD is the remainder operator ) gives the remainder.
If remainder is equal to zero then the number is even else odd.
Algorithm:
To find whether the given number is even or odd Step 1:
[ Read the number to be tested ) Read NUMBER Step 2:
[ Compute the remainder using remainder operator ] REMAINDER + NUMBER MOD 2 Step
3:
[ Test and print the number for odd or even IF Remainder = 0 Print " the given
number is Even "; else print " the given number is ODD ".
Step 4:
[ Finished ] Exit.
Flow Chart:
To find whether the given number is even or odd.
START Flow Chart:
To calculate area & circumference of a circle.
START READ NUMBER READ REMAINDER NUMBER MOD2 Here the remainder is calculated
using a mod operator also called Remainder operator AREA 3.
142 x RxR Area of Circle is calculated here using the formula A = Ter?
IS REMAINDER = 0?
YES Print " the given number is EVEN " CIRCUM - 23.
142 R Circumference of Circle is calculated using the formula C = 2tr NO
Circumference --Circum Print given number is ODD STOP STOP
131 Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 132 Flow Chart:
.
.
9 is divisible by a number between 2 to 9 4 in other words 3 = 3 START Read N For
example let N = 13 it is a prime number since it is not 13 divisible by any number
between 2 to 2 ( i.
e.
, 2 to 6 ) As usual to check the divisibility of number N, modules operator mod is
used; if R = 0 the number N is divisible else not divisible.
L 니 Interval L is taken half of the magni tude of the number N.
2 to N / 2 interval is sufficient to check the N is divisible or not for checking
it's prime property for i 2 to L REN modi Algorithm:
To test whether the given number is prime or not Step 1:
[ Read the number ] Read N Step 2:
Test the number for prime property ] Yes Is R = 0?
No Print N.
" is NOT A PRIME Text Repeat for i = 2, 3, -- .
.
N 2 Print ' N is Prime STOP REN mod i if ( R = 0 ) Print the number is not a prime
number ' stop ( the operation ) Step 3:
[ Print the number specifying its prime property ] Print the given number is prime
number ', N.
Step 4:
( Finished ) Exit Write an algorithm to compute compound interest for the given
principal amount, rate of interest and the number of years Draw a Flowchart.
Let P - Principal amount R- Rate of interest n - number of years Then compound
interest C is given by the formula 1 +
145 Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 2.
8 Programming Style 146 Er it could be a better practice to write as follows C is a
free form language that is, C program statements can be typed and appear from any
column number on a row ( line ).
Every C statements, braces, keywords etc.
, need not be typed from the 1st column:
int a, b, C; itself, on that line.
scanf ( " % d ", & a, Gb, & c ); Where as this flexibility does not apply while
writing programs in FORTRAN and COBOL languages!.
sum = a + b + c;:
avg = sum / 3; Thus, the freedom of typing flexibility offered by C language
compiler - should be better adopted to write a readable C source code with proper
indentation of braces ( { and } symbols ) and statements wherever necessary.
printf ( " sumed average = td \ n ", sum, avg ); Consider a tiny C program:
main ( ) A good alignment of braces and indentation of statements encour age
modular or block - structured approach to program modules.
This would further help assist in understanding program logic and flow control of
instructions in large C programs.
Consequently, program debugging will also be easier.
1 char = name; For instance:
<|
printf ( " your name please:
" ); 1.
scanf ( " % s ", name ); Recom mended Practice while writing C programs Rather
writing C program statements as ( X )|
printf ( " % s Hi! Welcome to c ", name ); ) int a, b, c, scanf ( " % d8d8d ", &
a, & b, & c ); it could be written continuously in a line or two as follows:
sum - a + b + c; avg - sum / 3; printf ( " sum - ed average = % d \ n ", sum,
avg ); ( X ) main ( ) ( char * name; printf ( " your name please:
" ); scanf ( " % s ", name ); printf ( " % s Hi! Welcome to C ", name ) NOTE 6 PRO
O MI OR V Please note that there is no readability and looks like you're taking
down / writing down the notes.
This kind of writing style is a poor programming practice and difficult to
understand program instruc tion flow.
Also, program debugging is a tedious task in case of lengthy programs 6 ) & int a,
b, c; scanf ( " % d9d % d ", & a, b, c ); sum wa + b + cavg = sum / 3; printf ( "
sum = sd average - % d \ n ", sum, avg );
149 I Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 150 Now you will be placed into Turbo C's IDE
screen as shown in figure below:
C:
\ > cd TC ( i.
e.
, Press Enter key ) C:
\ TC > TC Main Menu sia Edit Run Compile Project Options Debug Break / Watch -Edit
Line 1 Col 1 Insert Indent Tab Fill Unindent C:
NONAME.
C Editor Window Turbo C Version 2.
0 Copyright ( c ) 1987.
1988 by Borland International, Inc.
integrated development environment ( IDE ) or simply IDE screen for creating,
developing and executing C programs.
The IDE of Turbo C is menu - driven and user - friendly.
It allows the user / programmer to write new C programs, edit them, store them
compile and execute C programs using different dialogue boxes Almost all
operations, concerning editing compiling and executing C programs ( on IDE screen
of Turbo C ) can be performed by using single keystroke or easy - to - use on -
line menus ( Pull - down menus ).
> Turbo C Compiler displays diagnostic error messages in case errors ( syntax
errors ) are detected during compilation.
Once the errors are noticed, they have to be corrected ( called debugging ) and
the C program must be compiled once again.
This process of debugging ( correcting errors ) and re - compilation of a C
program must be repeated until the program becomes error free.
However during the course of C program development and execution, first one has to
write the source code C program ) by creating or opening a source code file ( a
file with.
C extension for example NONAME.
C ).
Then the C program hence written must be com piled, linked and finally run if
there are no errors.
The original C program is called source program or source code.
The compiled or translated version of C program that contain machine code ( binary
code ) is termed as object program or object code ( a file with.
obj extension ).
► It is by executing object program and entering necessary data during its
execution, one can expect useful end results what is known as Output Invoking Turbo
C Compiler At this stage, it is assumed that, Turbo C Compiler Version 2.
0 is already installed in TC sub - directory of root - directory C:
\ ( i.
e.
, in hard disk drive C :
) in your PCs.
Now let us invoke Turbo C Compiler as follows:
Step1:
go to the TC sub - directory from C:
\ Step2:
type te and press Enter keyo Message + Message box → status bar F1 - Help F5 -
Zoom 76 - Switch 97 - Trace F9 - Step F9 - Make F10 - Menu As seen from the figure
above, the IDE screen consist of four parts:
Main menu ( top line ) Editor window Message box Status bar ( bottom line ) Main
Menu Main menu consist of a number of items or options that are required for the
program development and execution.
These options inturn give rise to pull - down sub - menus for further selection of
sub - items or actions.
The main menu can be activated by pressing PRO O MI
163 Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 164 165 assigned meaning of the language syntax
and not to store values in it.
For examples the word int is reserved word because in C language it refiers to a
data type int.
It is used to declare variable to be of type in that refer to integer constants
only.
Therefore int is reserved by and for the language C to carry a specific meaning.
C compiler shows error -message if there would be an attempt to declare and use
reserved words of Cas variable names in a C program.
The following list specify the possible reserved words of C language.
auto double int break else long switch Keywords register typedef char extern
return union const float short unsigned continue for signed void default goto
sizeof volatile do if while struct case ** One or more of the alphanumeric
character combinations including special symbols, from C character set are used to
form valid C tokens.
These tokens are also known as Lexical elements of C language.
Appropriate combinations of one or more C tokens give rise to language constructs.
You will find various language con structs that are going to form a wide variety
of C programs in accordance with programmer's requirements.
For instance function ( definition / declaration ) header in C, a preprocessor
directive state ment, a declaration statement for variables used in a C program,
goto statement, if .
.
.
.
statement, Assignment statement likewise one can list out various language
constructs or building blocks used in a C program An example:
consider a declaration statement in a C program ----------------- int nl .
n2, sum E Here C tokens are int a keyword nl, n2, sum identifiers / variables →
special symbols used as delimiters * Consider an assignment statement in a C
program:
bal = amount - debit; enum in c static 2.
12 Identifiers 2.
* Here C tokens are → operators bal, amount, debit — identifiers / variables →
special symbol used as state ment terminator Identifiers in C are the names of
variables representing data, labels, function names, array names, user - defined
objects etc.
, An identifier in C consists of a sequence of letters ( upper case or lower
case ), digits and / or underscore symbols.
Also, the first character of an identifier must be a letter of alphabet or it can
be an underscore character too.
** There should not be any other special characters or operators in an Indentifier
except underscore symbol! Also keywords of C cannot be used as identifiers !!
Usually, the first eight characters of an identifier are guaranteed to be
significant i.
e.
, distinctly identified, although one can make use of more than eight characters to
form an identifier.
However, this is implementation dependent ( on C compiler being used at your local
installations! ) Examples of valid identifiers in C sumup2 at a rate story of 1942
tick20 check balance Q123 qity_02 PRO MI 2.
11 C Keywords Keywords or Reserved words of the language are the words whose
meaning is already defined and xplained to the C language Compiler.
Therefore reserved words cannot be used as identifiers or variable names.
They should only be used to carry the pre - defined or pre ping mesgool
165 Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 166 Examples of Invalid identifiers in C:
1stnum + point rate in s flash @ min bal Rs break continue Identifiers in care
case sensitive.
Also same identifier once declared as say variable name or label cannot be used as
say function name or arrayname in a single program.
One can use identifiers of any convenient length to assign meaning ful names for
the data being used as in array names, function names, structure names and variable
names.
However number of significant characters to be recognised in an Identifier varies
from C compiler to C compiler.
( Only first 31 characters are significant ).
> C variable / identifier should not contain a blank space ( white space )! > To
conclude identifiers are variable names in C.
2.
13 Constants > Numeric constants are simply numbers, a collection of one or more
decimal digits > Non - numeric constants comprises both numerals and letters of
alphabet including special symbols.
* You'll find two distinct types in each of these categories:
+ Integer Constants Integer constants in C represent whole numbers without any
fractional part.
An integer constant is simply an integer number consisting of one or more digits
of decimal number system.
Integers as input data, there should not be any special symbols or any in between
blank spaces, commas.
At the most negative ( minus ) sign, - can precede the number to indicate that
given number is a Negative integer.
When minus sign doesn't precede the number, the integer is assumed to be a
positive one! That is prefixing a plus sign + is optional E Examples of valid
integer constants include:
1942, 144, -26, +791, 999, 0, 202, 7, 42 *** Examples of Invalid integer constants
include:
0.
0, -15 ° C, 1,25,968, 10 B 48, 23,666, 0.
0003 ( k - blank space ) Integer constants in C further classified In C, one can
use 3 types of integer constants:
viz Decimal Numbers:
Any combination of one or more digits from 0, 1, 2, 5, 6, 7, 8, 9 Octal Numbers:
Any sequence of one or more digits from 0, 1, 2, 3, 6, 7 An octal constant must
start with O It must be written without decimal point It can be a positive or
negative octal number with signs or Example for octal numbers 027, -0126, +052 A
constant can be defined as " a value or quantity which does not change during the
execution of a program ".
Constants are also termed as Literals.
In short, the meaning and value of a constant remain constant! ( doesn't change ).
In C, constants can be classified as follows:
Constants in C PRO O MLÕUAL CAMERA Numeric Constants Non - Numeric Constants
( Character cosntans ) Single Integer Floating - Point Constants ( real constants )
Constants String Cosntants Character Constants
171 Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 172 2.
15 Declaration of Variables as same or single variable name since, the first eight
characters are same.
Therefore compiler may produce errors or computer may given wrong results In C.
upper case and lower case alphabets are recognized as separate symbols.
Therefore the variable names product, Product, & PRODUCT are treated as 3 separate
variable names.
- A variable name should not contain any other special symbols like blanks, comma,
question mark etc.
A variable name should not be a reserved word or keyword of the C language.
For example C language reserved words like if, switch, case, continue, break, long
etc.
cannot be used as variable names One can construct useful and meaningful variable
name by refer ring to the above rules Examples of VALID ( correct ) variable names
total income loss Sum of avg_temp interest rate _point marks1 test2 year_95 P123
Each variable used in a C program must be declared.
Such declarations are necessary to indicate to the C compiler, the type of
variable used and specific number of memory locations required ( size ) to hold the
different constants or values.
In other words the variable name can store constants in its memory location,
belonging to any four data types int, float, double, char.
For example if we want to use variable names marks and marks to store an integer
constants say marks 65 and 80; now we must declare that marks1 and marks2 variable
are of data type in meaning that the variables marks and marks2 hence declared,
always hold only integer values ( number without fractions ) throughout programs
execution.
This declaration is given as follows:
int marksi, marks2;.
The above specified declaration is known as Type Declaration ( Data type )
statement.
Therefore any variable to be used in the program must be declared with type
declaration statement before using it in any other C statements.
Usually the type declaration statement appears at the beginning of the C program.
* The general syntax for declaring a variables can be given as:
datatype variable - list Here datatype is a valid fundamental datatypes in C with
type modifiers if any ( like long int, unsigned char, short int etc.
, ) where as variable - list contain one or more variable names separated by comma
• Examples of INVALID ( incorrect ) variable names ( X ) 1942 story Ps - in how?
34d - cs level 2.
16 Data Types C language supports four basic ( fundmental or primary or built - in
types of constants called data types, VIZ int, float, double, char > int data type:
An integer constant or simply an integer number in C language, consist of sequence
of one or more digits of decimal PRO MI
175 " Sem RCA Computer Concepts & C Prog ( KUD ) Algorithms and Flowcharts
Examples of Variable declaration in length, height, area; float ratio, int_rate,
balance; char code alty_sign p_indicator; double sum, grand total, avg_rate; char
name [ 20 ], ch, option; int p, q, r, bal; float total [ 20 ), min bal, percent;
char color_code [ 10 ], answer; floar p = 3.
142, r, a; int count = 0; char ch - ' Q ':
single character information at a time.
Here char is a keyword in C to denote char data type A character constant is
always represented within a pair of single quotes where as a string constant is
enclosed within a pair of double quotes and string constant can contain one or more
than one characters a character constant string constant " abed " string constant "
Wishes on 12th morning " string constant To summarise, in general > int type is for
an integer constant to be stored; int occupies 2 bytes of memory typically ► floar
type is for floating point numbers to be stored and occupies 4 bytes of memory
floar type can hold numbers with six decimal digits of precision Please note that
floating - point numbers are used to represent values, which require a decimal
point precision for fractions associated with it ► double type is for floating
point numbers to be stored in exponent and mantissa form.
double type occupies 8 bytes of memory and it can hold floating point numbers with
ten decimal digits of precision for a character constant to be stored one character
at a time occupying 1 byte of memory ** There exists void data type specifying
empty set of values or simply no datatype in return! However the size in bytes of
storage and range of data values to be represented by these data types greatly vary
with each processor type and with every newer implementation of the C compiler A
Thus while declaring variables one can initialise them in the declaration statement
itself.
* → Datatype Modifiers The storage size in bytes and range of values being
represented by basic datatypes can be modified with the help of following modifiers
as prefixes:
+ signed → unsigned + long + short Signed data type modifier can be applied to
integer variables although the default integer declaration assumes a signed integer
number When signed modifier is prefixed to char data type, small integers in the
range -128 to +127.
unsigned data type modifier can be applied to both int and chard type variables.
However char datatype is unsigned by default and holds integer values in the range
0 to 255.
char type can hold
I " Sem.
( KUD ) Algorithms and Flowcharts 184 Please note that variable name that appears
on both sides of an assignment operator is now Written only once on the left
handside of + = a shorthand assignment operator.
In general, the assignment expression of the form:
variable name operator = expression; Where operator can be any one of +.
*, / % and when combined with =, assignment operator as its suffix.
will be treated as variable name = variable_name operator expression; like any
other assignment statements.
Accordingly, operator combinations appearing in such assignment expressions are
termed as shorthand assignment operators.
The possible combinations of shorthand assignment operators that could appear in
an assignment expression are and can be interpreted as 1 1 add Subtract Multiply
Divide Find remainder & & & & & assign assign assign assign assign 1 > You can
observe that, when operators + =:
--:
* = = % = are used in an assignment expression, the right hand side ( part of the
expression that appears after such shorthand assignment operators ) is assumed to
be enclosed in a pair of parenthesis > Generally such shorthand assignment operator
notations are incorpo rated in professionally written C programs code.
Such assignment expressions are also known as self - referential expressions.
> To conclude an assignment expression consists of a shorthand assignment operator
short hand assignment operators are + = - =, * =.
/ =, % when we use them in an assignment expression, the right handside of the
operator is assumed to appear in a pair of parenthesis > Benefits of using
shorthand assignment operators include assignment expressions are concise and easy
to code considerable saving over length of source code.
The variable name to be used as an input operand in the expression and for
assignment on the left handside, need not be typed and / or written on the right
hand side of short hand assignment operator.
Multiple Assignment Statements C permits you to assign a single value to more than
one varuble name at a time and in a single statement.
This can be achoved using multiple assignment.
For instance x = y = z = 0.
0; > Here, variable z will be assigned first with a float value ull And now value
of z will be assigned to y; At the end, xill be assigned the value of y.
In otherwords all the 3 variables x.
and z will hold now a value 0.
0.
► In case of multiple assignments, the operator = is said to right associative as
evaluation or assignments takes place f right to left For example, let's consider
the following assignment expression Their Meaning / Evaluated as sum + = heights; →
sum = sum + heights; down count - = 1; down_count = down count -1; x_topn = a; →
x_topn = x - to - pn * a; income tax; → income = income tax; profit = ( invest 4 -
loan ); → profir = profit % ( investe 4 - loan ), let's consider a second example:
P + = a - b; → P = P + ( a - b ):
ql = 1 + r:
+ 4 = g / ( 1 + r );
184 Sem.
BCA Computer Concepts & Prog.
( KUD Algorithms and Flowcharts 186 are the tors ) Therefore in the following
multiple assignment statement:
a = b = ( x + y + 2 ) / 2; 1.
evaluation of ( x + y + z ) / 2 takes place first; 2.
Then the result is assigned to variable name b; 3.
At last a will receive now, the value of b.
consider another example of multiple assignment I = m = n * = p; тро ment 1.
Thus multiple assignment statement make use of more than one assignment operator.
Statements in C AC program comprise variety of statements that can cause different
actions when executed.
In otherwords individual C statements can directly transform into one or more
executable machine instructions for computer hard ware.
( ofcourse during compilation process ).
In all, C language define 11 ( eleven ) kinds of C statements as depicted below
ment is evaluated as 1 = m = n * = p.
1 P = ( m = ( n = = * = p ) ) ( right - to - left ) n = n * p:
1 Null:
ight of mn:
Expressions 2 return X { compound st.
) the be and conditional с Statements labelled To conclude ► 1, m and n will get
here the result of evaluation of n * p.
Thus evaluation is from right - to - left.
Multiple assignments cannot be done during declaration of variable names For
instance int p = in q = ini r = 0; is not a valid assignment! Also multiple
initializations / assignments during variable declaration is invalid and leads to
syntax errors.
For instance int x = y = z = 144; signals compiler error as y and z undefined !!!
Therefore, before doing multiple assignments, all the variables must be declared
( with appropriate data type ) a priori ole wed switch Iteractive looping PRO MI
break ky Accordingly, continue be om int x, y, z; and then * = y = 2 = 144, will
assign 144 to x, y, and z goto n.
О O
( KUD ) 189 Algorithms and Flowcharts section 190 framed to perform a specified
task.
For instance Input Function - to perform input task.
In C, the library functions employed for input and output operations can broadly
be classified as Formatted I / O Functions Unformatted I / O Functions The
following figure depicts Input / output statement's provisions in Input and Output
Statements in C Formatted I / O Functions .
scanf ( ) - For input .
printf ( ) - For output Unformatted I / O Functions For Input For Output .
getch ( ) .
getche ( ) putchar ( ) .
getchar .
gets ' ( ) putch ( ) Accordingly, the individual quantities hence read through
scanſo formatted input function, can easily be identified and stored in memory as
integer, character, floating - point number etc.
Formatted Outpur Function:
the printf ( ) To display a data value or result of type int, char, floar, string,
or double, the printf ( ) library unction is used.
The formatted output function permits the use of conversion characters or format
control characters to enable the printing of data and / or computed results
belonging to a specific data type.
Such format specifications via formar specifiers or conversion specifiers in a
printf ( ) allows the user or programmer to have an explicit control over the range
and type of data being displayed • Format Specifiers Format Specifiers give rise to
conversion characters or format characters that specify what type of value ( say
for example integer, floating - point, double - precision number or character ) is
to be read or displayed, when used in Formatted I / O functions.
The conversion characters specify the format with which the given number or
character is to be printed.
Therefore these format characters or conversion characters are also called as
formar control characters or simply format specifiers.
Following table depicts a list of conversion characters used in C and their
respective use in displaying / reading a specific data type.
Conversion Used for Reading / Printing a constant Character belonging to a
specific data type % d integer numbers % f floating - point or double precision
number ( % e ) % c Character ( Single ) % s strings ( sequence of characters ) TPUT
guage ts of ta to print h an user ance nds.
ssed it of Ter's age put 1 to puts ( ) Fig.
A Formatted and unformatted I / O Functions For example scanf ( ) and printf ( )
are formatted functions used for input and output operations respectively,
Formatted Input Function:
the scanf ( ) To read a data value of type int, char, float, string or double, the
scanf ( ) library function is used.
The formatted input function supports the use of format specifiers ( also called
as formar control characters ) to enable the reading of data belonging to a
specific data type.
Such format specifications via conversion specifiers or formar specifiers in a
scanf ( ) allows the user to control the range and type of data being read.
Table A List Conversion Characters / Specifiers 728 * and of me.
e * The percent sign % is a special character recognised by functions.
The character that immediately appears after % sigh,
( KUD ) Algorithms and Flowcharts 192 2.
20 Reading a Character These functions will read any single value ( digit or
character or special symbol ) typed in, but the value is always taken to be a
character only.
There is no provision to use format control character ( conversion character ) to
identify the values read as integer, float, char etc.
This is because whatever may be the quantity or number typed in, it will be simply
treated as a character only.
Therefore the name unformated Input functions.
Only one character will be read in at a time.
Example of unformatted input functions are:
getch ( ), getche ( getchar ( ), fgetchar getch ( ); will read a single character,
the moment it is typed on the keyboard without waiting for Enter key to be pressed
point out what type of value is to be read or displayed into from the variable name
belonging to a specific data type.
For example % d specifies an integer constant ( integer number ) is to be accessed
( read / write ).
The getchar ( ) and putchar ( ) functions The getchar ( ) and putchar are
unformatted single character input and output functions respectively.
The getchar ( ) takes the following form.
variable - name = getchar ( ); >> getchar ( ) function reads and returns the
single character input i.
e.
, the key that is being pressed on Keyboard.
Here variable - name is to be declared as char - type For example:
char p_code = getchar ( ); If you type ' A ' or say ' S ', the same will be read
and stored into char variable p_code.
where as putchar takes the following form:
putchar ( variable - name ):
purchar ( ) function will display the single character at the output i.
e.
, on VDU screen.
Here variable - name must be declared to be of type char and contains a single
character.
For example:
char option = ' y ' purchar ( option ):
will now display the single character y as output.
Also, purchar ( ' \ n ' ); P_code:
For exmaple:
char p; p = getch ( ); getche ( ); Similar to the above function but echoes the
character typed into the screen.
i.
e.
, also prints the character read, on to the screen.
getchar ( ); > Both functions will read a single character typed in fgetchar ( );
and echo the character to the screen, but require an enter key to be pressed.
In addition to the above functions for reading single character.
We have gets ( ) functions in C that will read a sequence of characters ( or a
string ) at a time.
The end of input string is indicated by pressing an Enter key.
will now cause the cursor on the VDU screen to jump to the beginning of the next
new line.
This is due back slash constant In for newline display.
We shall discuss a little more about unformatted I / O functions in the following
sections:
2.
21 Writing a Character These functions will display or print any single character
va a a time.
These functions will not permit the use of format control character ( or
conversion specifiers ) therefore called as unformatted output for tions.
Whatever information that they will print, -it will only be in the form of
characters.
Examples of unformatted output functions are:
putch ( ), putcha fputchar
( KUD ) Algorithms and Flowcharts 194 putch ( ); putchar ( ); ser or тасtет ersion
his is Il be fputchar (:
Input le of tchar All these functions print the contents of a character variable
on the display screen, i.
e.
, a single character will be displayed at a time.
For example putchar ( "?
" ); will display?
on your screen Similarly, char option; putch ( option ):
will display the contents of option a char variable.
> C also provides a standard library function puts ( ) to output a string ( a
sequence characters at a time ) to the display screen.
For example in a C program, the puts ( ) function can be used as follows:
puts ( " Good Morning * ); The execution of the same will display the following on
the screen:
Good Morning ed on be acter acter format string or control string and the second
one is a list of arguments or variable names into which the values typed in, are to
be read / stored.
As scanf is a formatted function, the format string specify the format characters.
According to the format characters ( conversion characters ) the input data is
stored into the respective variables specified arguments.
It is important to note that the number of format characters & type of format
character specifying the data type in a given control / format string, must match
the number of variables and their respective data type, that are specified as
arguments in a given scanf function.
Let us consider a few examples of scanf functions:
i ) scanf ( " % d ", & first_num ); here the variable first_num is already
declared to be of data type int, in the type declaration statement int first_num;
the scany function has two parameters; format string and argument list.
Format string is always included within double quotes.
Format string in the above example consists of a single conversion character % d
and the argument list consists of only one variable name " first_num " prefixed by
an ampersand ( & ).
This and symbol is necessary whenever a single numeric value or a character is to
be read in to a simple variable.
Ampersand ( & ) symbol merely serves as an address operator specifying the address
of mem .
.
location for the variable first_num.
Observe that the number of format characters and its conversio type ( in this case
% d for integer ) matches with the number variables ( arguments ) & its data type (
in this case first_n variable is declared to be of type int ).
Thus when this scord function is executed in a C program, it stops program
execution until an integer value ( whole number ) is typed in ( Since % d spec.
integer ) and Enter key is pressed.
After typing the necessary day the execution will be continued.
The scanf scans for integer number in accordance with the format character
specified in its format string and stores it in the respecti variable name ( memory
location specified in its argument list.
in an 2.
22 Formatted Input Statement:
the scanf ( function Now we shall discuss in detail the formatted input function:
the scanf ( ) the scanf ( In a C program when the scanf formatted input function
is used, it allows the program to be halted temporarily during program execution in
order to accept ( to read the required data value.
After typing necessary data values following pressing of an ENTER key on the
keyboard, the program execution continues to compute the results.
The function name scanf stands for " scan formatted " or " scan function ".
It is just similar to input statements of any other high level programming
language.
Thus scanfo ), a standard C library functions permit the programmer to type in
operands or input data necessary for the given program execution.
* The general form of scanf ( ) is:
scanf ( " control string ", argi, arg2, .
.
.
.
.
.
.
.
.
argn ); scanf function has to contain two parameters, the first one is a we ters
by at cter inc the -0.
( KUD ) Algorithms and Flowcharts 194 ii ) Now let us consider a second example
that reads two integer numbers scanf ( " d ", & numl, & num2 ); Two integers will
be read in by the scanf function since two format characters % d & % d are
specified in the format string and the integers will be stored in the variables num
] & num2 respectively, iii ) Consider another example that reads one floating -
point number & two integer numbers scanf ( " % d ", & int_rate, & principal, &
period ); 2.
23 Formatted Output Statement:
the printf ( function The printf formatted output function is used to display the
values or results or messages at the display screen.
The function name printf stands for " print function " or " print formatted ";
print function's work is just equivalent to an output statement of any high level
programming language.
Thus printf ( ), a standard C library function when used in a c program, display
the messages and also the results stored in variables, on to the output device -the
display screen * The general form of printf ( is:
printf ( " control string ", argi, arg2, .
.
.
.
.
.
, argn ); first value read in will be a number with decimal point & fractions and
stored in the first variable of argument list i.
e.
, in int_rate, specify interest rate on bank deposits say 00.
05 ( 5 % ).
scanf reads second & third value as integers and stores them in variables
principal and period respectively.
The variables principal and period hold the amount deposited and the number of
years of deposit respectively iv ) Consider the following example, that reads 3
characters and one integer number Usually the printf function consists of two
parameters, one the format string or control string consisting of format characters
like % d, % f, % c etc.
and the second is the argument list.
The argument list consists of one or more variables whose contents have to be
displayed on to the output unit.
In addition to the format characters, the format string can also contain any
useful message, titles specifying the name & type of result; for example.
" the largest of 3 number is = ", or " simple interest = " etc.
* It is important to note that the number of format characters and their type in a
given format string must match the number of variables and their respective data
type whose contents and shar posed to be displayed.
scanf ( " % ctctcid ", & color_1, & color_2, Ecolor_3, & code ) color_1, color_2 &
color_3 variables are declared to be of type char and can hold a single character
information.
Similarly variable code is defined to be of type in that store integer number i.
e.
, char color_1, color_2, color_3; int code; ** Now consider a few examples of
printf function i ) printf ( " The result is % d ", sum ); Now say for example
color ' r ' - for red, ' y ' for yellow, ' b'- for blue and integer number 14 are
all read & stored respectively in the variables color_1, color_2, color_3 & code
respectively.
In the above example four format characters correspond to four argument list
variables that matches both in order & type.
A Here the variable name sum has been declared earlier as an int type in a type
declaration statement:
int sum:
The format string content The result is copied to the screen as it is and the
format chatavad % d tells the computer that it should display an integer m which is
the content of argument list variable the sum.
There argument list consists of one or more variables whose contents
( KUD ) Algorithms and Flowcharts 206 ed nh Where as printf ( " loc = 9-6d \ n ",
loc ) wall print loc = 5140 3 * 4 « observe printing in left justified manner * / /
* effect of minus sign / / * here the last two columns goes as blanks:
- / The following table summarises a list of format control characters that can be
used in format control string of printf ( ).
conversion To perform .
.
.
.
.
separating format characters.
Otherwise scanf expects same special character to be typed in while entering from
one data value to another data value.
scanf ( ".
ded \ n ", sp, q ); / * wrong / A common mistake is to forget the ampersand symbol
- & while typing the program, that must precede each and every variable of
parameter / variable list in scanf ( ).
The & symbol is optional in case of string variable like an array of char.
One need not specify any escape characters ( For example \ n ) leave 1 blank space
in format control string of scanf ( ).
DV The address operator ( & ):
Re - visited The symbol & ampersand ) when precedes a declared variable name,
serves as an address operator.
It specifies the address of memory location associated with that variable.
When used in a scanf ( ) function, address operator conveys the path or memory
location address ( represented by the corresponding variable name ) at which the
input data value is to be stored specifier % d % u 50 % x % X % ld print signed
decimal integer number print unsigned decimal integer number print unsigned octal
number print unsigned hexadecimal number ( using a - f ) print unsigned hexadecimal
number ( using A - F ) print a long decimal integer number print a real or floating
- point decimal value print a real or floating - point decimal value in exponent
form ( for example -1.
46e - 08 ) print a single character ( For example ' k ' one at a time ) print a
character string ( For example " Point 4590 ", at a stretch ) % f For instance Же %
c scanf ( " % d % f ", & deposit, & int_rare ) > Address operator finds its use in
pointer manipulation operations For example a pointer variable can be assigned the
address of memory location to serve the purpose of indirection ( indirecco
addressing ).
% s Common mistakes not to be committed in scanf ( ) For instance For example int
* ptl, pscore; INT t marks, total; and now prl - & r_marks pscore = & total Ó REDMI
NOTE 3 PRO MI scanf ( " 8 de def ", 61,6m, & n ); / * wrong / There should not be
any blank spaces between format characters in a format control string.
Otherwise scanf expects same number of blank spaces from one data to another data
value while reading scanf ( " od, d, & p, & q ); / * wrong / There should not be
comma or semicolon etc.
, special symbols A Thus pointers can be initialised to denote corresponding memor
locations.