2 Computer Problem Solving
2 Computer Problem Solving
TOP-DOWN DESIGN
The primary goal in computer problem-solving is an algorithm which is capable of being implemented as
a correct and efficient computer program. In our discussion leading up to the consideration of algorithm
design we have been mostly concerned with the very broad aspects of problem-silving. We now need to
consider those aspects of problem-solving and algorithm design which are closer to the algorithm
implementation.
Once we have defined the problem to be solved and we have at least a vague idea of how to solve it, we
can begin to bring to bear powerful techniques for designing algorithms. The key to being able to successfully
design algorithms lies in being able to manage the inherent complexity of most problems that require
computer solution. People as problem-solvers are only able to focus on, and comprehend at one time, a very
limited span of logic or instructions. A technique for algorithm design that tries to accommodate this human
limitation is known as top-down design or stepwise refinement.
Top-down design is a strategy that we can apply to take the solution of a computer problem from a
vague outline to a precisely defined algorithm and program implementation. Top-down design provides us
with a way of handling the inherent logical complexity and detail frequently encountered in computer
algorithms. It allows us to build our solutions to a problem in a stepwise fashion In this way, specific and
complex details of the implementation are encountered only at the stage when we have done sufficient
groundwork on the overall structure and relationships among the various parts of the problem.
IMPLEMENTATION OF ALGORITHMS
The implementation of an algorithm that has been properly designed in a top-down fashion should be an
almost mechanical process. There are, however, a number of points that should be remembered.
If an algorithm has been properly designed the path of execution should flow in a straight line from top
to bottom. It it important that the program implementation adheres:: this top-to-bottom rule. Prohgrams (and
subprogrars implemented in this way are usually much easier understand and debug. They are also usually
much easier to modify should the need arise because the relationships between various parts of the program
are much more apparent.
THE EFFICIENCY OF ALGORITHMS
Efficiency considerations for algorithms are inherent tied in with the design, implementation, and
analysis of algorithms. Every algorithm must use up some of a computer's resources to complete its task. The
resorces most relevant in relation to efficiency are central processing time (CPU time) and internal memory.
Because of the high cost of computing resources it is always desirable to algorithms that are economical in the
use of CPU : memory. This is an easy statement to make but one that is often difficult to follow either because
of bad design habits, or the inherent complexity of the problem, or both. As with most other aspects of
algorithm design, there is no recipe for designing efficient algorithms. Despite there being some generalities
each problem has its own characteristics which demand specific responses to solve the problem efficiently.
Within the framework of this last statement we will try to make a few suggestions that can sometimes be
useful in designing efficient algorithms.
EARLY DETECTION OF DESIRED OUTPUT CONDITIONS
The bubble sort also provides us with an example of another related type of inefficiency involving
termination. It sometimes happens, due to the nature of the input data, that the algorithm establishes the
desired output condition before the general conditions for termination have been met. For example, a bubble
sort might be used to sort a set of data that is already almost in sorted order. When this happens it is very
likely that the algorithm will have the data in sorted order long before the loop termination conditions are
met. It is therefore desirable to terminate the sort as soon as it is established that the data is already sorted.
To do this all we need to do is check whether there have been any exchanges in the current pass of the inner
loop. If there have been no exchanges in the current pass the data must be sorted and so early termination can
be applied (a check of algorithm 5.3 reveals how this is implemented for the bubble sort). In general, we must
include additional steps and tests to detect the conditions for early termination. However, if they can be kept
inexpensive (as in the bubble sort) then it is worth including them. That is, when early termination is possible,
we always have to trade tests and maybe even storage to bring about the early termination.
TRADING STORAGE FOR EFFICIENCY GAINS
A trade between storage and efficiency is often used to improve the performance of an algorithm. What
usually happens in this type of tradeoff is that we precompute or save some intermediate results and avoid
having to do a lot of unnecessary testing and computation later on.
One strategy that it sometimes used to try to speed up an algorithm is to implement it using the least
number of loops. While this is usually possible, inevitable it makes programs much harder to read and debug.
It is therefore usually better to stick to the rule of having one loop do one job just as we have one variable
doing one Job. When a more efficient solution to a problem is required it is far better to try to improve the
algorithm rather than resorting to "programming tricks" that tend to obscure what is being done. A clear
implementation of a better algorithm is to be preferred to a "tricky" implementation of an algorithm that is
not as good. We are now left with the task of trying to measure the efficiency of algorithms.
THE ANALYSIS OF ALGORITHMS
There are usually many ways to solve any given problem. In computing, as in most efforts of human endeavor,
we are generally concerned with "good" solutions to problems. This raises certain questions as to just what do
we mean by a "good" solution to a problem? In algorithm design "good" has both qualitative and quantitative
aspects. There are often certain esthetic and personal aspects to this but, on a more practical level, we are
usually interested in a solution that is economical in the use of computing and human resources. Among other
things, good algorithms usually possess the following qualities and capabilities :
1. They are simple but powerful and general solutions.
2. They can be easily understood by others, that is the implementation is clear and concise without being
"tricky".
3. They can be easily modified if necessary.
4. They are correct for clearly defined situations.
5. They are able to be understood on a number of levels.
6. They are economical in the use of computer time, computer storage and peripherals.
7. They are documented well enough to be used by others who do not have a detailed knowledge of
their inner workings.
8. They are not dependent on being run on a particular computer.
9. They are able to be used as a sub procedure for other problems.
10. The solution is pleasing and satisfying to its designer-a product that the designer feels proud to have
created
These qualitative aspects of a good algorithm are very important but it is also necessary to try to provide
some quantitative measures to complete the evaluation of "goodness" of an algorithm. Quantitative measures
are valuable in that they can give us a way of directly predicting the performance of an algorithm and of
comparing the relative performance of two or more algorithms that are intended to solve the same problem.
This can be important because the use of an algorithm that is more efficient means a saving in computing
resources which translates into a saving in time and money.
EXCHANGING THE VALUES OF TWO VARIABLE
PROBLEM ~
Given two variables, a and b, exchange the values assigned to them.
ALGORITHM DEVELOPMENT
The problem of interchanging the values associated with two variables involves a very fundamental
mechanism that occurs in many sorting and data manipulation algorithms. To define the problem more clearly
we will examine a specific example.
Consider that the variables a and b are assigned values as outlined below. That is,
Starting configuration
a b
721 463
This means that memory cell or variable a contains the value 721, and memory cell or variable b contains the
value 463. Out task is to replace the contents of a with 463, and the contents of b with 721. In other words we
want to end up with the configuration below:
Target configuration
a b
463 721
To change the value of a variable we can use the assignment operator. Because we want a to assume the
value currently belonging to b, and b the value belonging to a we could perhaps make the exchange with the
following assignments:
a : = b ; (1)
b : = a ; (2)
where": =" is the assignment operator. In(1)": =" causes the value stored in memory cell b to be copied into
memory cell a.
Let us work through these two steps to make sure they have the desired effect. We started out with the
configuration
a b
721 463
Rechecking with our target configuration we see that a and b have now been interchanged as required
The exchange procedure can now be outlined.
ALGORITHM DESCRIPTION
1. Save the original value of a in t.
2. Assign to a the original value of b.
3. Assign to b the original value of a that is stored in t
The exchange mechanism as a programming tool is most usefully implemented as a procedure that accepts
two variables and returns their exchanged values
APPLICATIONS
Sorting algorithms.
COUNTING
PROBLEM
Given a set of n student's examination marks (in I range 0 to 100) make a count of the number of stud€ that
passed the examination. A pass is awarded for all i of 50 and above.
ALGORITHM DEVELOPMENT
Counting mechanisms are very frequently used in computer algorithms.
Generally a count must be made of the number of items in a set which possess some particular
property or which satisfy some particular condition or conditions. This class of problems is typified by the
"examination marks" problem.
As a starting point for developing a computer algorithm for this problem we can consider how we
might solve a particular example by hand. Suppose that we are given the set of marks
55, 42,77 63, 29,57, 89
To make a count of the passes for this set we can start at the left, examine the first mark (i.e. 55), see if it is >
50, and remember that one student has passed so far.
The second mark is then examined and no adjustment is made to the count.
When we arrive at the third mark we see it is > 50 and so we add one to our previous count.
The process continues in a similar manner until all marks have been tested.
In more detail we have :
Marks Counting details for passes
55 previous count = 0
current count = 1
Order in 42 previous count = 1
current count = 1
which 77 previous count = 1
current count = 2
marks 63 previous count = 2
current count = 3
are 29 previous count = 3
current count = 3
examined 57 previous count = 3
current count = 4
89 previous count = 4
current count = 5
.-. Number of students passed = 5
1
* After each mark has been processed the current count reflection the number of students that have passed
in the t marks list so far encountered.
We must not ask, now can the counting be achieved? From our example above we see that every time we
need to increase the count we build on the previous value. That is
current_count = previous_count + 1 ,
When, for example, we arrive at mark 57, we have
previous_count = 3
Current_count therefore becomes 4. Similarly when we get to the next mark (i.e. 80) the current_count
of 4 must assume the role of previous_count.
This means that whenever a new current_count is generated it must then assume the role of
previous_count before the next mark is considered.
The two steps in this process can be represented
by
current_count = previous_count + 1 (1)
previous_count = current_count (2)
These two steps can be repeatedly applied to obtain the count required. In conjunction with the
conditional test and input of the next mark we executed step (1), followed by step (2), followed by step (1),
followed by step (2) and so on.
Because of the way in which previous_count is employed in step (1) we can substitute the expression for
previous_current : in step (2) into step (1) to obtain the simpler expression
current_count: = current_count + 1
Tt
(new value) (old value)
The current_count on the RHS (right-hand side) of the expression assumes the role of previous_count. As this
statement involves an assignment rather than an equality (which would be impossible) it is a valid computer
statement. What is describes is the fact that the new value of current_ count is obtained by adding 1 to the old
value of current_ count.
Viewing the mechanism in this way makes it clear that the existence of the variable previous_count in its
own right is unnecessary. As a result we have a simpler counting mechanism.
The essential steps, in our pass-counting algorithm can therefore be summarized as : while less than n
marks have been examined do (a) read next mark, (b) if current mark satisfies pass requirement then add one
to count.
Before any marks have been examined the count must have the value zero. To complete the algorithm
the input of the marks and the output of the number of passes must be included. The detailed algorithm is
then as described below.
ALGORITHM DESCRIPTION
1. Prompt then read the number of marks to be processed.
2. Initialize count to zero.
3. Which there are still marks to be processed repeatedly do
APPLICATIONS
All forms of counting.
SUMMATION OF A SET OF NUMBERS
PROBLEM
Given a set of n numbers design an agorithm that adds these numbers and returns the resultant sum. Assume
n is greater than or equal to zero.
ALGORITHM DEVELOPMENT
One of the most fundamental things that we are likely to do with a computer is to add a set of n
numbers. When confronted with this problem in the absence of a computer we simply write the numbers
down one under the other and start adding up the right-hand column. For example, consider the addition of
421, 583 and 714.
421
583
714
...8
In designing a computer algorithm to perform this task we must take a somewhat different approach. The
computer has a built-in device which accepts two numbers to be added, performs the addition, and returns
the sum of the two numbers (See Fig. 1). In designing an algorithm to add a set of numbers a primary concern
is the mechanism for the addition process. We will concentrate first on this aspect of the problem before
looking at the overall design.
The simplest way that we can instruct the computer's arithmetic unit to add a set of numbers is to write
down an expression that specifies the addition we wish to be performed. For our three numbers mentioned
previously we could write
S : = 421 + 583 + 714 (1)
The assignment operator causes the value resulting from the evaluation of the right-hand side of
statement (1) to be placed in the memory cell allocated to the variable s.
Expression (1) will add three specific numbers as required. Unfortunately it is capable of doing little else.
Suppose we wanted to sum three other numbers. For this task we would need a new program statement.
FIRST NUMBER
(A)
It would therefore seem reasonable that all constants in expression (1) could be replaced by variables.
SECOND
We would(B)
NUMBER then have
S : = a + b + c (2) Expression (2) adds any three numbers provided they have been previously assigned as
vlaues or contents of a, b, and c respectively. Expression (2) as the basic of a program for adding numbers is
more general and more useful than expression (1).
It still has a serious deficiency- it can only add sets of three numbers.
A fundamental goal in designing algorithms and implementing programs is to make the programs general
enough so that they will successfully handle a wide variety of input conditions.
That is, we want a program that will add any n numbers where n can take on a wide range of values.
The approach we need to take to formulate an algorithm to add n numbers in a computer is different
from what we would do conventionally to solve the problem. Conventionally we could write the general
equation.
S = (a1 + a2 + a3 +……..+ an) (3)
n
Or equivalently S = ∑ ai (4)
i =l
. . .
s:=s+an
From step (2) onwards we are actually repeating the same process over and over- the only difference is
that values of a and s change with each step.
th
For general i step we have
s : = s + ai+1 (i)
This general step can be placed in a loop to iteratively generate the sum of n numbers.
The algorithm we want to develop for summing n numbers should perform correctly for all values of n
greater than or equl to 0 (i.e. n > 0). It must therefore work correctly forthesumofzero(n = 0)and the sum of 1
(n = 1) numbers. This means the step (1) we have used is not appropriate. However, if we replace i + 1 in the
general step (i, by i and substitute i = 1 we get:
s : = s + a1 {r)
The step (1') will be correct provided s : = 0 before this step is executed. It follows that all sums for n > 1
can be generated iteratively. The instance where n = 0 is a special case which cannot be generated iteratively.
The sum of zero numbers is zero and so we can generate the first sum directly by the assignment.
s:=0
The core of the algorithm for summing n numbers therefore involves a special step followed by a set of n
iterative steps. That is,
1. Computer first sum (s = 0) as special case.
2. Build each of the n remaining sums from its predecessor by an iterative process.
3. Write out the sum of n numbers.
The only other considerations involve the input of n, the numbers to be summed, and the input of successive
numbers with each iterative step. Our complete algorithm can now be outlined.
ALGORITHM DESCRIPTION
Given a number n, compute n factorial (written as n!) where n > 0.
ALGORITHM DEVELOPMENT
1. Prompt and read in the number of numbers to be summed.
2. Initialize sum for zero numbers.
3. While less than n numbers have been summed repeatedly do
PROBLEM
We can start the development of this algorithm by examining the definition of n ! We are given that
n! = 1 x 2 x 3 x ........... x (n - 1) x n for n > 1
and by definition 0! = 1
In formulating our design for this problem we need to keep in mind that the computer's arithmetic unit
can only multiply two numbers at a time.
Applying the factorial definition we get
0! = 1; 1! = 1 x 1 ; ' 2! = 1 x 2;
3! = 1 x 2 x 3; 4! = 1 x 2 X 3 X 4
We see that 4! contains a//the factors of 3!. The only difference is the inclusion of the number 4. We can
generalize this by observing that n! can always be obtained from (n-1)! by simply multiplying it by n (for n > 1).
That is,
. n! = nx (n- 1)! for n > 1
Using this definition we can write the first few factorials as:
11 = 1 x 0!; 2! = 2 x 1!; 3! = 3 x 2!; 4! = 4 * 3!
p:=p*1 =1!
p:=p*3 =3!
p:=p*4 =4!
From step (2) onward we are actually repeating the same process over and over. For the general (i + 1
)th step we have.
p: = p*1 (i+1)
This general step can be placed in a loop to interatively generate n!. This allows us to take advantage of
the fact that the computer's arithmetic unit can only multiply two numbers at a time.
In many ways this problem is very much like the problem of summing a set of n numbers (algorithm
2.3).
In the summation problem we performed a set of additions, whereas in this problem we need to
th
generate a set of products. It follows from the general (i + 1 ) step that all factorials for n > 1 can be
generated iteratively. The instance where n = 0 is a special case which must be accounted for directly by the
assignment
p:=1 (by definitions of 0!)
The central part of the algorithm for computing n! therefore involves a special initial step followed by n
iterative steps.
1. Treat 0! as a special case ( p : = 1)
2. Build each of the n remaining products p from its predecessor by an iterative process.
3. Write out the value o n factorial.
ALGORITHM DESCRIPTION
1. Establish n, the factorial required where n > 0.
2. Set product p for 0! (special case). Also set product count to zero.
3. While less than n products have been calculated repeatedly do
PROBLEM
Design an algorithm that accepts a positive integer and reverses the order of its digits.
ALGORITHM DEVELOPMENT
Digit reversal is a technique that is sometimes used in computing to remove bias from a set of numbers.
It is important in some fast information-retrieval algorithms. A specific example clearly defines the relationship
of the input to the desired output. For example.
Input: 27953
Output: 35972
Although we might not know at this stage exactly how we are going to make this reversal one thing is
clear-we are going to need to access individual digits of the input number. As a starting point we will
concentrate on this aspect of the procedure.
The number 27953 is actually
4 3 2
2 x 10 + 7 x 10 + 9 x 10 + 5 X 10 + 3
To access the individual digits it is probably going to be easiest to start at one end of the number and
work through to the other end.
The question is at which end should be start ? Because other than visually it is not easy to tell how many
digits there are in the input number it will be best to try to establish the identity of the least significant digit
(i.e. the rightmost digit).
To do this we need to effectively "chop off' the least significant digit in the number. In other words we
want to end up with 2795 with the 3 removed and identified.
We can get the number 2795 by integer division of the original number by 10
i.e. 27953 div 10 ^2795
This chops off the 3 but does not allow us to save it. However, 3 is the remainder that results from
dividing 27953 by 10. To get this remainder we can use the mod function. That is,
27953 mod 10 -> 3
Therefore if we apply the following two steps
r: = nmod 10 (1) =» (r = 3)
n : = ndiv 10 (2) => ( n = 2795)
we get the digit 3, and the new number 2795. Applying the same two steps to the new value of n we can
obtain the 5 digit. We now have a mechanism for iteratively accessing the individual digits of the input
number.
Our next major concern is to carry out the digit reversal, when we apply our digit extraction procedure to
the first two digits we acquire first the 3 and then 5. In the final output they appear as :
3 followed by 5 (or 35)
If the original number was 53 then we could obtain its reverse by first extracting the 3, multiplying it by
10, and then adding 5 to give 35. That is,
3 x 10 + 5 -> 35
The last three digits of the input number are 953. They appear in the "reversed" number as 359.
Therefore at the stage when we have the 35 and then extract the 9 we can obtain the sequence 359 by
multiplying 35 by 10 and adding 9. That is,
35 x 10 + 9 ->359
Similarly
359 x 10 + 7 ->3597
and
3597 x 10 + 2 -> 35972
The last number obtained from the multiplication and addition process is the "digit-reversed" integer we
have been seeking. On closely examining the digit extraction, and the reversal process, it is evident that they
both involve a set of steps that can be performed iteratively.
We must now find a mechanism for building up the "reversed" integer digit by digit.
Let us assume that the variable dreverse is to be used to build the reversed integer. At each stage in
building the reversed integer its previous value is used in conjunction with the most recently extracted digit
Rewriting the multiplication and addition process we have just described in terms of the variable
dreverse we get
iteration Value of dreverse
[1] dreverse : = dreverse * 10 + 3 3
[2] dreverse : = dreverse * 10 + 5 35
[3] dreverse : = dreverse * 10 + 9 359
. .
. .
. .
ALGORITHM DESCRIPTION
Establish n, the positive integer to be reversed. Set the initial condition for the reversed integer dreverse.
While the integer being reversed is greater than zero do
Use the remainder function to extract the rightmost digit of the number being reversed,
Increase the previous reversed integer representation dreverse by a factor of 10 and add to it the
most recently extracted digit to give the current dreverse value;
(c)
Use integer division by 10 to remove the rightmost digit from the number being reversed.
This algorithm is most suitably implemented as a function which accepts as input the integer to be reversed
and returns as output the integer with its digits reversed.
APPLICATIONS
Hashing and information retrieval, data base applications.
String Constants :
A String constant is a stream of characters enclosed within the quotation marks whose maximum length
is 255 characters. Following are the valid string constants :
□ 1 "the total value ="
□ 2 "$2000"
□ 3 "Welcome to the world of computers" .
Following is the list of invalid string constants:
□ 1 "hello pintu □ 2 'welcome home'
In the first the closing double quotation marks are not putted whereas in second the characters are not
enclosed in double quotation marks.
Numeric Constants :
Numeric constants are positive or negative numbers. There are two types of numeric constants -Integer
Constants and Real Constants. An integer constant is a sequence of digits. There are three types of integers
namely decimal, octal and hexadecimal. Example of valid decimal numeric constant" are as under:
- 120 0
213 23 + 128
The octal integer constants can be the combination of digits from the set 0 through 7 with a leading 0.
Examples of valid octal numeric constants are as under:
033
0
0441
Tho sequence of digits preceded by OX is considered as hexadecimal numeric constants. The
combination of digits from 0 to 9 and A to F will make a hexadecimal integer. Examples of valid hexadecimal
numeric constants are as under:
0X2
OXbaf
OX
| The general usage of octal and hexadecimal integers is not done in the programming. The second type of
numeric constant is real constant. These type of constants are used to represent the physical quantities like
pressure, temprature etc which vary continuously. These quantities are represented by numbers containing
fractional parts like 15.234. Such type of numbers are called real constants. Examples of real constants are as
under:
0.122
- 4.32
+ 23.33
Character constants :
A character within single quotation marks will represent a character constant. Examples of character
constants are as under:
'X'
'x'
' ?'
V
There are some backslash character constants used in the interactive C language programming. The
backslash (/') is used to denote the non printing cha^cters and other special characters for a specific
[Link] following is the list of backslash character constants.
•\a Alert a bell character
'
'\t' Horizontal Tab
'\n' New Line
'\b' Backspace
'\f Form Feed
V Carriage Return
'\v' Vertical Tab
'\" Single quote
'\0' Null character
'\?' Question Mark
'\000' Octal Value '\Xhhh' Hexadecimal Value
DATA TYPES
The types of data structures provided by C can be classified under the categories :
• Fundamental data types
• Derived data types
DEFINING DATA
Definition of memory for any data, both fundamental and derived data types, is done in the following format.
[data type] [variable name],...;
All data are normally defined in the beginning of a function.
The definition
char ans;
The above statement defines a memory location of size one byte, of character type referred to as ans. The
following table illustrates the definition of various data types.
Data Data Memory Size Value
Definition Type Defined (Byte) Assigned
char a,c; char a and c 1
char a='Z'; char A 1 Z
int count; int count 2 —
int c = 10; int c 2 10
float ff; float ff 4
float f=10.1; float f 4 10.1
There is a rich list of operators available in C language. The different types of C operators and their usage
are explained in the following sections.
In C, there are some unusual operators used to perform the task of logical decision making, unlike the
other higher level language.
Following is the operators category in C language
1 Arithmetic operators
2 Assignment operators
3 Comparison and Logical operators
4 Bitwise operators
5 Unary operators
6 Ternary cperators
Arithmetic Operators :
These are the basic operators used in any programming language. Normally, these operators are
considered as basic operators and known as binary operators as they require two variables to be evaluated.
The following table shows the basic arithmetic operators.
Operator Operators Meaning
+ For Addition
— For Subtraction
* For Multiplication
/ For Division
% For Remainder (Modulo)
The / operator is used for division purpose. When we are dividing the value 40 by 8 then the answer will
be 5 but when we are dividing the 11 by 2 then the answer will be stored as 5. In this case one of the operands
should be a floating point value and the result will also be of floating point type. Identically, this also applies to
addition, subtraction and multiplication. For Is fer operations the value of the result is not seriously affected by
the type of operands.
For Example
5 + 3 = 8 (integer form),
0 + 3.0 = 8.0 (Floating point form)
The following notations will show that what will be the result of every expression.
Integer/Integer = Integer
Integer/Float = Float
Float/Integer = Float
Float/Float = Float
11/2 = 5 => 11.0/2.0 = 5.5
v
The result of / operator will give the quotient but when we want \ \e remainder then we should use the
operator %. 11 % 2 will give the remainder as 1.
Assignment operators :
The symbol = is use as a assignment operator. Fo example we want to store the value 10 to the integer
variable i then we will use the assignment operator = .
in» j = 10; z = x + y;
where x and y are added and the result of this expression is assigned in the variable z.
Bitwise operators :
There are certain situations wherein bitwise operations are to be performed, and this is possible in C
language. Following are the bitwise operators in the C language.
Operator Operators Meaning
& Bitwise AND
A Bitwise exclusive OR
I Bitwise inclusive OR
» Bitwise right shift
« Bitwise left shift
Bitwise compliment
Unary Operators :
The unary operators require only a single expression to produce a line. Unary operators usually precede their
single operands. Sometimes some unary operators may be followed by the operands such as incrementer and
decrementer. The most common unary operation is unary minus, where a minus sign precedes a numerical
constant, a variable or an expression. The following table shows the unary operators in C language.
Ternary operators :
C includes a very special operator called the ternary or conditional operator. It is called ternary because
it uses three expression. The ternary operators act like a shorthand version of the if else construct. The
general format of the ternary operator is : expM ? expr2 : expr3 which result either in expr2 or expr3 being
evaluated. If exprl is true, then expr2 is evaluated otherwise expr3 is evaluated.
For example,
result = (tot % 2 == 0) ? true : False;
In the above statement if tot % 2 returns 0 then the result will be true otherwise the result will be false.
STATEMENTS
A statement in a computer program carries out some action. There are three types of statements used in
C language; they are expression statement, compound statement and control statement.
Expression Statement:
An expression statement consists of any valid C expression followed by a semicolon. The expression
statement is used to evaluate a group of expressions.
For example,
x=y; /*The value of y is assigned to variable x7 sum=x+y; /*
The value of x is added with the value of y and assigned to the variable sum*/
Compound Statement:
A group of valid C language expression statements placed within a { and } statement is called a
compound statement. The individual statement may be an expression statement, a compound statement or
even a control statement.
Note that the compound statement is not completed with a semicolon.
For example,
{
a=b+c;
x=x*x;
y=a+x;
Control Statement:
The control statement is used for the program flow and to check the conditions of the given expression
or a variable or a constant. The keywords of the control statements are normally predefined or reserved
words and the programmer may not use them as ordinary variables.
For example,
if (a>b) {
statement;
statement;
statement;
}
while (condition) {
statement;
statement;
statement;
}
The condition within brackets defined should be true then only the C compiler will execute the body of
the loop.
C Language
The C Language environment assumes that the standard input device (Keyboard), the output device
(Monitor) and the standard output device (Monitor) are always linked to the environment. For standard input
output operations, the C environment uses stdin, stdout, stderr as references for accessing the devices.
C language as such does not provide for any input output operations as part of the language. They exists
as functions written in C language and are available in the standard C library along with other functions. These
input and output functions may be used by an.
programmer.
Any input or output operation takes place as a stream of characters. The standard input-output
functions may be dealt under character based input output functions and under string based(stream of
characters) input output functions.
The standard input output functions are buffered i.e. each device has an associated buffer through which
any input or output operation takes place. After an input operation from the standard input device, care must
be taken to clear the standard input buffer lest the previous contents of the buffer interfere with subsequent
input operations. After output operations, the buffer need not be cleared since subsequent output data will
overwrite the previous buffer contents.
Character input Output Functions :
The following small program will accept a single character from the keyboard and will displays it on the
standard output device monitor.
# include <stdio.h>
main()
{
/*program for accept & display a character*/
char chr;
chr = getc(stdin);
fflush(stdin);
putc([Link]);
}
The function main first defines a memory location, chr of char data type and then invokes the functions
getc & putc.
/* ------ */ this is the comment entry. We can put the comment entries in every program for programmers
convenience.
The funtion getc accepts the input device-reference (stdin) to read one character from the standard input
device. The character react is returned in the variable chr of type character. The function putc accepts two
parameters one as the variable in which the read value is stored and another is the reference stdout for
standard output device to output one character. The funtion fflush() clears the buffer associated with a
specified input output device. It is a good programming practice to clear the buffer even if there are no
subsequent input operation in a function.
The #include includes the specified file as part of a function at the time of compilation. Hence contents of
the included file are compiled along with the function being compiled.
The statement #include <stdio.h> includes, at the time of compilation, the contents of the standard
input output file , stdio.h which contains definitions of stdin, stdout and stderr. Whenever the references
stdin, stdout and stderr are used in a function, the statement #include <stdio.h> has to be used.
TEST : Write a program to accept a character and display it 3 times.
getchar() & putchar() are the another character handling funtions which can be used instead of getc() and
putc() functions. The above written program can be write by using the getchar and putchar functions.
# include <stdio.h>
main()
{
/*program for accept & display a character*/
char chr;
chr = getchar();
fflush(stdin);
putchar(chr);
TEST : Write a program to accept a character and display it 3 times unsing getcharQ and putcharQ functions.
Formatted Output:
The function printf() is used for formatted output to standard output based on a format specification.
The format specification alongwith the data to be output, are the parameters to the printf() function.
The syntax of the printf() function is as follows:
printf("Format specification",Datal, Data2,..);
For example, printf("%d\n",num);
The following are the format specification available in C language
%d - The data value will be of type integer.
%c - The data value will be of type character.
%S - The data value will be of type string (stream of characters).
%f - The data value will be of type float or double.
Other symbols permitted in the format specification string are :
\n For new line. \t For tab.
The format specification string may also have text.
For example:
Printf(“The total value is %d Rs.",val);
If the value of val is 100 then the output of the above said statement will be the total value is 100 Rs.
TEST :
1) What will be the output of the following program
#include <stdio.h>
main()
{
char c,str[10];
int i=10;
float f= 10.10;
printf("Enter the string\n");
gets(str);
fflush(stdin);
printf("i=%d\tf=%f\nc=%c\tstr=%s \n",i,f,c,str);
getch();
}
Between the character, % and the conversion character, there may be :
• a minus sign denoting left adjustment of the data.
• a digit specifying the minimum width in which the data is to be output. If the data has the larger number
of characters than the specified width, the width occupied by the output is larger. If the data consists of fewer
characters than the specified width, it is padded to the right (if minus sign is specified) o*to the left (if no
minus sign is specified) with blanks. If the digit is prefixed with a zero, the padding is done with zeros instead
of blanks.
• a period separates the width from the next digit.
• a digit specifying the precision (number of decimal places for numeric data) or the maximum number of
characters to be output.
letter l(ell) to indicate that the data item is a long integer and not an int.
Following table shows the resulting output of data, according to the format specification string :
Format specifi- Data Output
cation string
l% 2dl 9 | 9|
l% 2dl 123 |123|
l% 03d! 9 |009|
I%- 2dl 7 |7 |
l% 5.3dl 2 |002|
l% 3.1 dl 15 | 15|
l% 3.5dl 15 |00015|
i% 5sl "output string" loutput stringl
l%15J "output string" I output string I
l%15.5sl "output string" I output string I
l%fl 83.88 I 88.880000 I
l%4.1fl 88.88 I 88.8 I
The following example shows that the data can be output as another datatype based on the conversion
character.
#include <sdtio.h>
main()
{ int num = 65;
printf(“The value of num is %d\n",num);
printf("Character equivalent of %d is %c\n",num,num);
}
The output of the above program is:
The value of num is 65 Character equivalent of 65 is A
TEST :
1) Write a program to display the appropriate character value of number 71.
2) What will be the output of the following program.
#include <stdio.h>
main()
{
printf("%c",65);
}
Formatted Input:
The function scanf() is used for formatted input from standard input and provides many of the
conversion facilities of the function printf().
The syntax of the scanf() is as follows :
scanf("format specification",datal, data2,...);
The scanf function reads and converts characters from the standard input and according to the format
specification string and store the input in memory locations represented by the other arguments.
The following example will show you how scanf will be used.
scanf ("%d",&i);
where i is an integer type of variable. The & sign is 'jsed with the integer, char & float type of data values
not with the string type of format specification e.g. scanf ("%s",name);
This will accept a stream of characters & terminated on space. The difference in gets() & scanf() function
is that the gets() funtion accepts the string up to enter key pressed means that string is terminated by NULL
('\0') character whereas the scanf terminates the string on space.
#include <stdio.h>
main()
{
char str1[25],str2[25];
printf("Enter first string\n");
scanf("%s",str1);
fflush(stdin);
printf(“Enter second string\n");
gets(str2);
fflush(stdin);
printf(“The first string is %s\n",str1);
printf(“The second string is %s",str2);
getch();
}
TEST :
1) Write a program to accept a name and age of a student and print it with the help of scanf & printf
statements.
CONTROL STATEMENTS
The control statement is used for the program flow and to check the conditions of the given expression
or a variable or a constant. The keywords of the control statements are normally predefined or reserved words
and the programmer may not use them as ordinary variables. Control statements or control structures are
mainly used to have the control over the programs. When programmer wants to use the conditions in his
programs or wants to do some repetitive tasks then he has to use the control statements. There are many
control structure which are available in C language. They are : if……else, switch..case, while, do..while and for.
If construct:
The first control statement of C language is construct. It works on the condition, if the condition i true
then it will execute the true part of the construct and if the condition is false then it will execute the el or false
part of the construct. For example
if (a>b)
printf(“a is greater\n");
else
printf(“b is greater\n");
In the above example if the condition is true then "a is greater will be printed on to the screen else it will
display the message "b is greater". Here there is only one statement in if and else part so, we don't have to
write the statements in opening and closing curly braces.
TEST :
1) Write a program to accept two numbers and find greater of two numbers. We can also do the nesting
of if statement means that if within a if statement. The following structure will display the nested if
if (cond)
if(cond)
{ statement;
statement;
}
else
{ statement;
statement;
}
else if(cond)
{ statement;
statement;
}
else
{ statement;
statement;
}
TEST :
1) Write a program to accept a number between 1 to 7 & display the appropriate day assume Monday is
first day. e.g.
Input Number: 3
Output : Wednesday
LOOPS
}
In the above example the values from 1 to 10 will be printed on the screen. But it will not print anything
if the value of i is 11 initially. So, this is the difference between the while and do..while loop that in case of
while loop the condition is checked first whereas in the do...while loop the body of loop will be executed first
then the condition, will be checked.
The last but least loop is for loop. Generally this loop is used by the programmers. The function of this loop is
same as while loop but the initialization, condition and incr/decr will be defined in one statement. The syntax
of for loop is
for(initialisation; condition; incr./decr.)
{ statement;
statement;
statement;
}
For example
int i;
for(i=0; i<=10; i++)
{
“
printf( %d”,i);
}
Again, the result will be same as in the previous example. But the syntax is changed.
TEST :
1) Write a program to print the even numbers from 1 to 50 with while, do..while and for loop.
SOLVED PROGRAMS
Write a program to interchange the values of two variables.
#include<stdio.h>
main()
{ int a,b,c;
clrscr();
printf(“enter the value of a,b ");
scanf("%d%d",&a,&b);
c = a;
a = b;
b = c;
printf("%d %d",a,b);
getch();
}
Write a program to interchange the values of two variables without using third variable.
#include<stdio.h>
main()
{ int a,b;
clrscr();
printf("enter the value of a,b ");
scanf("%d%d",&a,&b);
a = a + b;
b = a - b;
a = a - b;
printf("%d %d",a,b);
getch();
L
Write a program to generate a series
2 2 2 2
2 , 3 , 4 ......... n .
#include <stdio.h>
#include <conio.h>
main()
{
int i=0,n=0;
clrscr();
printf("Enter the value of n\n");
scanf("%d",&n);
fflush(stdin);
/*Series Starts*/
for(i=2;i<=n;i++)
{
printf("%d",i*i);
}
getch();
}
2 3 4 n
Write a program to generate a series 2 ,3 ,4 ,..n .
#include <stdio.h>
#include <conio.h>
#include <math.h>
main() {
int i=0,n=0;
clrscr();
printf(“Enter the value of n\n");
scanf("%d",&n);
fflush(stdin);
/*Series Starts*/
for(i=2;i<=n;i++)
{
printf("%d",pow(i,i));
}
getch();
}
Write a program to print the fibonnaci series
#include<stdio.h>
main()
{ long int c,i,n,a = 0,b = 1;
clrscr();
printf("How many numbers of ths series do you want ");
scanf("%ld",&n);
printf("%6ld\n%6ld\n", a,b);
for(i=3; ;i++)
{ c = a + b;
a = b;
b = c;
if(c<=n)
printf("%6ld\n", c);
else break;
}
getch();
}
Write a program to reverse a digit..
/*Reversing a digit*/
#include <stdio.h>
#include <conio.h>
void main()
{ int n=0,i=0,rn=0,r=0,q=0;
clrscr();
printf("Enter the Number for reversing\n");
scanf("%d",&n);
fflush(stdin);
printf("The reversed number is ");
while ( n > 0 )
{ r = n%10;
rn = rn * 10 + r;
q = n / 10;
n = q;
}
printf("%d",rn); getch();
}
Write a program to check the prime number.
#include<stdio.h>
#include<conio.h>
enum check { PRIME, NOTPRIME } flag;
main()
{ int i=1 ,n;
clrscr();
printf("Enter the number: ");
scanf("%d",&n);
flag = PRIME;
for(i=2;k=n/2;i++)
{ if(n%i==0)
{flag = NOTPRIME;
break;
}
}
if(flag == PRIME)
printf("\n%d is a prime number",n);
if(flag == NOTPRIME)
printf("%d is not a prime number",n);
printf("\nPress any key to continue....");
getch();
}
Write a program to print the arm strong numbers between 1 to 500.
#include<stdio.h>
main()
{ int i,a,b,temp,n,x,sum=0; clrscr();
for(i=1;i<=500;i++) { n=i;
sum=0;
while(n > 0)
{ a = n%10;
b = n/10;
n = b;
x=a*a*a;
sum=sum+x;
}
if(sum==i)
{ printf("\n%d°,sum);
printf("ars no."); •
}
}
getch();
}
Write a program to check the arm strong number.
#include<stdio.h>
main()
{ int i,a,b,n,x,sum=0;
clrscr();
printf("Enter the number\n");
scanf("%d",&n);
fflush(stdin);
i=n;
sum=0;
while(n > 0)
{ a = n%10;
b = n/ 10;
n = b;
x=a*a*a;
sum=sum+x;
}
if(sum==i) {
printf("ars no.\n");
}
else {
printf(“Not an ars no.\n");
}
}
getch();
}
Write a program to print the factorial of a given number.
/*Factorial*/
#include <stdio.h>
#include <conio.h>
void main()
{
int n = 0,f = 1,i=0;
clrscr();
printf("Enter the number for finding factorial\n");
scanf("%d",&n);
for(i = 1; i<=n; i++)
{
f = f*i ;
}
printf("The Factorial is : %d",f);
getchQ;
Defining Arrays
In general, defining an array of any type, whether of fundamental data type or of derived data type is
done in the following format:
<data type> <name of array> [number of elements]
char str[10];
is for defining a character array, str to store 10 characters where str[0] to str[9] is for storing valid characters
and str[10] for storing the string terminator
'\0\
When a string is input using any of the string based functions, namely scanf() and gets(), the null character is
automatically appended to the string in memory as the string terminator. In same manner we can define the
integer and float type arrays.
int a[10];
float b[ 15];
Array Manipulation
There is more than one way for handling arrays in terms of performing operations on arrays namely,
through the use of subscript and through the use of pointers which Will be discussed later. In this section ,
arrays will be manipulated through the use of subscripts. Following programs on arrays will show that how the
arrays can be manipulated.
- Average of n numbers
#include <stdio.h>
#include <conio.h>
main()
{ int n[5],sum,i;
float avg; .'
clrscr();
printf(“Enter the numbers\n");
sum=0;
for(i=0;i<5;i++)
{ scanf("%d",&n[i]);
sum=sum+n[i];
}
avg =(sum / i);
printf("%f",avg);
getch();
}
Maximum number from n number of elements
#include<stdio.h>
main()
{ int a[9],i,x,n;
clrscr();
printff How many numbers do you want\n");
scanf("%d",&n);
if(n>9)
exit(0);
else {
printf(“Enter the value of a[0]\n”);
scanf("%d",&a[0]);
x = a[0];
for(i=1 ;i<n;i++)
{ scanf("%d",&a[i]);
if(a[i] > x)
x = a[i];
}
Printf(“Maximum number is ......... ");
printf("%d",x);
}
getch();
}
Reverse a String
#include <stdio.h>
main()
{ char a[10];
int i;
clrscr();
printf("enter the string”);
gets(a);
for(i=0;a[i]!='\0';i++);
for(;i!=-1;i--)
printf("%c",a[i]);
getch();
TEST
1) Write a program to print the the number of possible combinations of the number 1,2 and 3. This is
about the one dimensional arrays. There is another kind o x array which is called es multi dimensional array.
When there are two or more than two dimensions then it is ^aiied as multidimensional array. The declaration
of this type of array is as under.
char a[5][5];
int a[4][4];
float a[3]T2];
Where a is the array name and there are two subscript values representing the row and columns. The
number of elements in these arrays will be the multiplication of the [Link] example if we have an array
of 2 by 3 order then the number of elements of this array will be six. Mainly we are using the 2-D arrays which
is used for soiving the problems related with matrices. Here are some programs on the 2-D arrays.
Addition of two matrix
#include <stdio.h>
#include <conio.h>
main()
{ int a[2}[2],b[2][2],c[2][2],i=0,j=0;
clrscr();
printf(“Generate first matrix\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++) {
scanf ("%d",&a[i][j]);
fflush(stdin);
}
}
printf(“Generate second matrix\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{ scanf(“%d”,&b[i][j]);
fflush(stdin);
}
}
/'Matrix Addition*/
c[0][0]=0;
for(i=0;i<2;i++) {
for(j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
/'Printing the resultant matrix*/
Printf(“The Resultant matrix is \n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf f%d\t",c[i]0]);
}
printf f\n");
}
getch();
}
Multiplication of matrix
#include <stdio.h>
#include <conio.h>
main()
{
int a[2][2],b[2][2],c[2][2],i=0,j=0,k=0;
clrscr();
printf ("Generate first matrix\n”);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&a[i][j]);
fflush(stdin);
}
}
printf("Generate second matrix\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&b[i][j]);
fflush{stdin);
}
}
/'Matrix Multiplication*/
for(i=0;i<2;i++)
{
for(j=0;j<2;j++) {
c[i][j]=0;
for(k=0;k<2;k++) {
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
/'Printing the resultant matrix*/
Printf(“The Resultant matrix is :\n");
for(i=0;i<2;i++) {
for(j=0;j<2;j++) {
printf ("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
Transpose of a matrix
#include <stdio.h>
#include <conio.h>
main()
{ int a[2] [2],b[2] [2],!=0>0;
clrscr();
printf(“Generate the matrix\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++) {
scanf("%d",&a[i][j]);
fflush(stdin);
}
}
/*Transpose of Matrix */
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
b[i][j]=afj][i];
}
}
/*Printing the resultant matrix*/
printf(“The Resultant matrix is :\n");
for(i=0;i<2;i++) {
for(j=0;j<2;j++) {
printf("%d\t",b[i][j]);
}
printf("\n");
}
getch();
}
TEST :
1) Write a program to store and print the sales of 4 salesmen for products p1 ,p2, p3 and p4 also give the
total sales.
POINTERS
Consider the following declaration : int i=10;
The above statement implies that space in memory is reserved for the variable i.
This variable has the value 10 and is supposed to stce at memory location (or address) 1001. The
following picture will show you an idea about how space is occupied by the variable i.
i
10
1001
Now there is another variable ptr which holds the address 1001 then this ptr is nothing but the pointer.
So, pointers are the variables which holds the address of another variable. See the following instructions for
defining the pointers.
int i = 10;
int *ptr; /'Declaration of the pointer*/
ptr = &i; /"Initialisation of the pointer*/
Here ptr is the pointer which holds the address of the variable i. We had assigned the address of i to the
pointer ptr. This is done with the help of the symbol &. & means the address. Whereas, pointers can be
defined by the symbol *. The * makes the difference and the implication is : ptr is a pointer to an integer
variable. At the time of pointer manipulation we are using two symbols & and *. The * represents the value at
the address. The & represents the address.
So, if we print the value of *ptr from the above instructions then it will print the value 10 because ptr
pointing to the address 1001 and whatever will be the value at that address that will be printed.
TEST :
1) What will be the output of the following program.
main()
{
int i = 5,*ptr; ptr=&i;
printf("%d\t%d",i,*ptr);
}
If we want to define the character pointer then use that data type. We can also increase or decrease the
position of the pointers by ptr++ or ptr--. String handling is much more comfortable after by using the pointers.
Following programs can explain the pointers in more detail.
main()
{
int i,*j,**k;
clrscr();
i = 10;
j = &i;
k = &j;
printf("\n%5d %5u",i,&i);
printf("\n%5u %5u %5d",j,&j,*j);
printf("\n%5u %5u %5u %5d\n ",k,&k,*k,**k);
(**k)++;
printf("\n%5d %5u",i,&i);
printf("\n%5u %5u %5d",j,&j,*j);
printf("\n%5u %5u %5u %5d\n ",k,&k,*k,**k);
(*k)++;
printf("\n%5d %5u",i,&i);
printf("\n%5u %5u %5d",j,&j,*j);
printf("\n%5u %5u %5u %5d\n ",k,&k,*k,**k);
getch();
}
String copy
#include<conio.h>
#include<stdio.h>
main()
{
char *sourse="gfdgfdgfg";
char *des="fhdhfd";
int i;
clrscr();
printf("Enter the string: ");
gets(sourse);
for(i=0;sourse[i]!='\0';i++)
des[i] = sourse[i];
des[i] = '\0';
printf(“The string is: %s",des);
printf("\nPress any key to continue: ");
getch();
}
Length of a string (Method 1)
#include<conio.h>
#include<stdio.h>
main() {
char *str="gfdgfdgfg"; int i;
unsigned count=0; printf("Enter the string: "); gets(str);
for(i=0;str[i]!='\0';i++) count++;
printffThe length of the string is: %d",count); printf("\nPress any key to continue: "); getch();
L
Length of a string (Method 2)
#include<conio.h>
#include<stdio.h>
main()
{
char *str="gfdgfdgfg";
int i = 0;
unsigned count=0;
clrscr();
printf(“Enter the string: ");
do
{
fflush(stdin);
str[i] = getche();
if(str[i] == V)
break;
i++;
}
while(1);
str[i]= '\0';
for(i=0;str[i]!='\0';i++)
count++;
printf("\nThe length of the string is: %d",count);
printf("\nPress any key to continue: ");
getch();
}
TEST :
1) Write a program to reverse a string using pointer.
FUNCTIONS
Functions are used when we want to break a complete program into sub modules. These are nothing but
the subroutines of a main program. They are called from the main program and after manipulating the
instructions a value will be returned. As explained earlier, functions are the building blocks of C. All programs
definitely consist of one function - main() -and inevitably refer to, or, in programming terminology call or
invoke standard functions of C such as printf(), scanf() etc. as well as user-defined functions
Advantages of functions
Besides the obvious advantages of :
- reusability
- structuring of programs
functions also provide programmers a convenient way of designing programs in which complex
computations can be built into the functions. The programmer has to simply ensure that the required
parameters are passed to the function.
Generally, the standard functions require parameters like printf(), scanf() etc.
Similarly, user-defined functions may or may not have parameters. Consider following example:
main()
{
func();
}
func()
{
printf(“Hello World");
}
main() {
c=add(a,b);
printf("%d",c);
}
int add(int x,int x)
{
int z;
z = x + y;
return(z);
}
Invoking Functions
In C programs, functions that have parameters, are invoked in two ways.
1) call by value
2 ) call by reference
In call by value method the values of the actual parameters are passed to the formal parameters.
Following example illustrates the call by value method.
main() {
int a,b; a=10,b=20;
interchange(a,b);
}
interchange(int a, int b)
{
int c;
c=a;
a=b;
b=s.
printf("%d\t%d",a,b);
}
Here the values of a and b 10 and 20 will be passed to the formal parameters of the function interchage.
Call by reference means that the called function should be able jto refer to the variables of the caller
function directly, and not create its own copy of the values in different variables. This would be possible only if
the addresses of the variables are passed as parameters to the function. Consider the same program written
using call by reference :
main() {
int a=10,b=20;
interchage(&a,&b);
printf("%d\t%d",a,b);
}
interchage(int *x,int *y)
{
int *z;
*z=*a;
*a=*b;
*b=*z;
}
Here in this program the address of a and b will be hold by the pointers x and y.
TEST :
1 ) Write a program using function 'o calculate the area of a circle.
Programs on Functions
Convert into given base equivalent
#include<stdio.h>
#include<conio.h>
int convert(int num,int base);
main()
{
int n,b;
clrscr();
printf("Enter the decimal number:");
scanf("%d",&n);
printf(“Enter the base in which U want to convert the number: ");
scanf("%d",&b);
printf(“The equivalent is: ");
convert(n.b);
printf(“\nPress any key to continue....");
getch();
}
int convert(int num,int base)
{
int i;
if(num==0)
return 0;
i = num%base;
num = num/base;
convert(num,base);
if(i==10)
printf("A");
if(i==11)
printf ("B");
if(i==12)
printf ("C");
if(i==13)
printf("D");
if(i==14)
printf("E");
if(i==15)
printf("F");
if(i>=0 && i<=9)
printf("%d",i);
}
Length of a string (Method 3)
#include<conio.h>
#include<stdio.h>
int len(char *ptr);
main()
{
char *str="gfdgfdgfg";
int count;
clrscr();
printf("Enter the string: ");
gets(str);
count = len(str);
printf("The length of the string is: %d",count);
printf(“\nPress any key to continue: ");
getch();
}
int len(char *ptr)
{
int i,count=0;
for(i=0;ptr[i]!='\0';i++)
count++;
return count;
}
Number to Word Conversion
#include<stdio.h>
#include<conio.h>
{
char a[10];
int i=0,len,fiag=1;
clrscr();
printf("Enter any number\n");
gets(a);
for(i=:0;a[i]!=’\0';i++)
{ if(a[i]>='0'&&a[i]<='9');
else
flag = 0;
}
. if(flag==0)
{ printf("\n not a valid number");
getch();
exit(0);
}
i=0;
len = strlen(a);
if(len==7)
{ number(a[i],a[i+1]);
i++;
if(a[i]>’0’&&a[i-1]>’1’)
write_digit(a[i++]);
else
i++;
print(“lakh”);
len-=2;
}
if(len==6)
{ write_digit(a[i++]);
printf("lakh ");
len--;
}
if(len==5)
{ number(a[i],a[i+1]);
i++;
if(a[i]>'0' && a[i-1]>’1’)
write_digit(a[i++]);
else i++;
printf("thousand");
len-=2;
}
if(len==4)
{ write_digit(a[i++]);
printf("thousand");
len--;
}
if(len==3)
{ if(a[i]==’0’)
i++;
else
{ write_digit(a[i++]);
printf("hundred");
}
len—;
}
if(len==2)
{
if(a[i]=='0')
{
write_digit(a[i]);
}
else
{
number(a[i],a[i+1]);
i++;
STRUCTURES
When we want to define the records then we have to use the structures. The structure is nothing but the
user defined data type. It is a collection of different types of data values. The structures are defined by the
keyword struct. A sample declaration of structure is given below.
struct emp {
int eno;
char enm[20];
float sal;
};
So, emp is a structure consist of eno, enm and sal having different data types. The structure name is used
along with the variable name when referring to any member of the structure.
For example :
[Link] refers to the variable employee number
[Link] refers to the variable employee name
[Link] refers to the variable employee salary.
Following program will tell you that how to input the values and print the values from a structure.
main()
{ struct emp
{
int eno;
char enm[20];
float sal;
};
struct emp e1
printf("Enter the employee number\n");
scanf("%d",&[Link]);
printf("Enter the employee name\n");
gets([Link]);
printf("Enter the employee salary\n");
scanf("%f",&[Link]);
printf(“The values stored are\n");
printf("%d\t%s\t%f",e1 .[Link] .enm, e1 .sal);
getch();
}
You can define the structure before the function main(). Here e1 is the variable of type struct emp and
we are referring all the different variables with the help of e1.
This is how we can store a record with e: variable but the problem is when we want to store the records of
10 employees then it is not possible to store it in one variable for that we have to define 10 different structure
type variable again it is logically incorrect. So, how can we solve this type of problem?
This can be solved by defining the array of structures if we know the number of employees and if we
don't know the number of employees then we have to use the pointer to a structure.
Here we are discussing only array of structures. The following program will store the information of 10
employees.
#include <stdio.h>
#include <conio.h>
struct emp
{
int eno;
char enm[20];
float sal;
};
main()
{
struct emp e[10]; int i=0;
printf ("Enter the information of 10 employees\n");
for(i=0;i<10;i++)
{
scanf("%d",&e[i].eno);
gets(e[i].enm);
scanf("%f",&e[i].sal);
}
printf("Display the information of 10 employees\n");
for(i=0;i<10;i++)
printf("%d\t%s\t%f\n",e[i].eno,e[i] .enm, e[i].sal);
getch();
}
The structures are importantly used for solving data structure problems. See some structure declarations
and see the output after compilation.
#include<stdio.h>
#include<conio.h>
void main(void)
{
struct student {
char name[20];
struct date {
int d;
int m;
int y;
} dob;
}
s1 = {"Gajanan",21,9,74};
clrscr();
printf("%s\n%d/0%d/19%d", s1 .name, [Link].d, [Link], [Link].y);
getch(); .
}
#include<stdio.h>
#include<conio.h>
void main(void)
{
struct st1
{
char name[10]; char*ptr1;
};
struct st2
{
char *ptr2; struct st1 a;
};
struct st2 b = {"amit", "atul", "anup"}; clrscr();
printf("%s\n%s\n",b.ptr2,b.a.ptr1);
printf("%s\n%s\n",b.ptr2++,b.a.ptr1++);
printf("%s\n%s\n",b.ptr2++,b.a.ptr1++);
getch();
}
TEST :
1) Write a program to store the records of 50 students and count the number of girls and boys using
structure.
2. Alphanumeric Representation
A set containing alphabets (in both cases), the decimal digits and special characters consist of at least 70-
80 elements. One such code generated for this set popularly used is ASCII (American National Standard code
for Information Interchange). This code uses 7 digits to represent 128 characters.
Ex. Partial listing of 7 bit ASCII code.
character 7 bit ASCII Hexa
A 100 0001 41
... … … …
… … … …
… … … …
Z 101 1010 5A
0 001 0000 31
... … … …
… … … …
… … … …
9 011 1001 39
= 011 1101 3D
> 011 1110 3E
? 011 1111 3F
1 bit 7 bit
sign magnitude
The decimal position can be represented by a position between the flip-flops (Storage cells in computer)
To determine this decimal position, two methods are :
(i) Fixed point representation where the decimal position is assumed either at the beginning or at the
end of a number.
(ii) Floating point representation where a second register is used to determine the position of the
decimal in a number.
4. Complement of a Number :
There are two types of complements for a number of base r. These are called r's complement
and (r - 1)'s complement
The 9'th complement is obtained by subtracting each digit of a number from 9 (the highest
digit value).
Ex. 1. 9's complement of 329
= 9 9 9
- 3 2 9
= 6 7 0
The1’s complement is obtained by subtracting each bit of a binary number from 1or by
replacing 1->0 and 0->1 or by complementing each bit .
Ex. 2. 1's complement of 10010
= 1 1 1 1 1
- 1 0 0 1 0
= 0 1 1 0 1
Ex. 3. 1's complement of 101011
= 010100 {By complementing each bit}
When an integer binary number is positive, the sign is represented by 0 and the magnitude by
a positive binary number. When the number is negative the sign is represented by 1 but rest of the
number may be represented in one of the three possible ways :
1. Signed - magnitude representation
2. Signed - 1's complement representation
3. Signed - 2's complement representation
(Assumption size of register = 7 bit, 8th bit is used for error checking and correction or other
purposes).
Ex. Representation of +8 and - 8 in these three ways.
Signed magnitude representation :
+8 -8
0 001000 1 00 1000
6. Arithmetic Addition :
The addition of two numbers follows the rules of ordinary arithmetics in signed magnitude
representation and require comparison and subtraction. The implementation of such a scheme in digital
hardware will require a long sequence of control decisions and circuits.
By contrast, the rule for adding numbers in the signed 1's or 2's complement system does not require
comparison or subtraction (only addition and complementation are required).
Ex. Add + 30 and + 15 in binary using 7 bit register in
Signed 1's complement
Signed 2's complement
Sol. Signed 1's complement :
Signed 1's complement have a rule. Add the two numbers including the sign bit. If carry of the most
significant bit or sign bit is one, then increment the result by 1 and discard the carry over. (The negative
numbers should be stored in the signed 1's complement form in the registers.). Here
+30 0 011 110
+15 0 001 111
Now,
+30 0 011 110
+15 0 001 111
+45 0 101 101
carry out is 1 so add 1 to the sum and discard the carry over
.-. Sum = 0 001 111 which is + 15.
This procedure requires only one control decision and only one circuit adding the two numbers.
But negative numbers should be stored in signed 2's complement form in the registers.
Signed 2's complement have a rule. Add the two numbers including the sign bit.
If carry of the most significant bit or sign bit is one then discard the carry over
In signed 2's complement notation
+30 0 011 110
+15 0 001 111
7. Representation of Zero :
Signed magnitude
+0 -0
0 000 000 1 000 000
Signed 1's complement
+0 -0
0 000 000 1 111 111
Signed 2's complement
+0 -0
0 000 000 0 000 000
1 111 111
+ 1
1 0 000 000
= 0 000 000
discard the carry
So in signed 2's complement notation there is just one zero and there is no positive or negative zero.
Because of this reason signed 2's complement is preferred for binary arithmetic.
8. Arithmetic Substraction :
The subtraction can be easily done using the 2's complement by taking the 2's complement of the
subtractend (inclusive of sign bit) and then adding the two numbers.
Ex. Solve (20) - (12) in binary using 7 bit register.
Sol. Representation for
for 20 : 0 010 100
for 12 : 0 001 100
2's complement of subtractend is
1 110 100
Adding the two numbers
0 010 100
1 110 100
1 0 001 000
discard the carry out
9. Overflow :
An overflow is said to have occurred when the sum of two n digit numbers occupies n + 1 digits. An
overflow is a problem in digital computers because the width of registers is finite. A result that contains n + 1
bits cannot be accommodated in a register with a standard length of n bits.
An overflow condition can be detected by observing the carry into the sign bit position and the carry out
of the sign bit position. If these two carries are not equal, an over flow condition is produced. This is indicates
in the examples. If the two carries are applied to an exclusive OR gate, an overflow will be detected when the
output of the gate is equal to 1.
Ex. Add the following numbers in 8 bit register in signed 2's complement notation.
i) Carries: 0 1
+65 0 1000001
+70 0 1000110
+135 1 0000111
This is a negative number - 131 which is obviously a wrong result. This has occurred because of overflow.
ii) Carries: 1 1
By representing numbers in decimal (or BCD) we are wasting a considerable amount of storage space
since the number of bits needed to store a decimal number in a binary code is greater than the number of bits
needed for its equivalent binary representation.
Ex. 24 in BCD will be represented as 0010 0100
Sol. It needs 8 bit register with 8 flip-flops 24 in binary will be represented as 11 000. It needs 5 flip-flops.
However there are some advantages in the use of decimal representation because computer input and
output data are generated by people who use the decimal system. It can be used at places where the amount
of computer arithmetic is less than the amount of input/output of data. Examples : Calculators, business data
processing.
The arithmetic in decimal can also be performed in signed 9's complement and 10's complement
representation.
0 1432 0 02
Mantissa integer Exponent
Normalization
A floating-point numbers said to be normalized if the most significant digit of the mantissa is non zero.
for example, the decimal number 320 is normalized but 0032 is not.
Regardless of the assumed position of radix point in the mantissa, the number is normalized only if its
leftmost digit is non zero.
for example, the 8-bit binary number 00100100 is not normalized because of the two leading 0's
The number can be normalized by shifting two positions to the left to obtain 10010000. The two shifts multiply
the number by 21 = 4.
To keep the same value for the floating point number, the exponent must be subtracted by 2.
Ex: A floating point binary number -1001.101 in a 16 bit register can be represented in normalised form
(assuming 10 bits for mantissa and 6 bits for exponent).
Sol:
1 100100000 0 00101
Mantissa(fraction) Exponent
A zero cannot be normalized as all the digits in mantissa and exponent have to be zero.
Arithmetic operations with floating-point numbers are more complex and take longer time.
Objective Questions
1. The binary code for the word BOY in ASCII-7 (Haxa) is
(a) 42 4F 59
(b) 4B 50 59
(c) 24 F4 95
(d) 4A 4F 59
2. In an eight bit register - 14 can be represented as (signed magnitude representation).
(a) 0 0001110
(b) 1 1110000
(c) 1 0001110
(d) 1 1101001
3. In an 7 bit signed 2's complement representation + 25 will be represented
as
(a) 0 011001
(b) 1 011001
(c) 0 110010
(d) 1 110010
4. Find 1's and 2's complement of 000000
(a) 111111, 100000
(b) 000000, 000000
(c) 111111, 000000
(d) 011111, 111111
5. 2's complement of 11001100 is
(a) 01010100
(b) 00110011
(c) 01000100
(d) 00110100
6. 9's complement of 629 is
(a) 370
(b) 371
(c) 361
(d) 325
7. Addition of + 50 and - 55 in 8 bit register using 2's complement will be
(a) 0 0000101
(b) 1 1111011
(c) 1 1111010
(d) None of the above
8. Addition of + 25 and - 12 in 6 bit register using 1's complement will be
(a) 0 01101
(b) 1 100010
(c) 1 01101
(d) None of the above
9. Result of 20 - 11 in binary using 7 bit register will be
(a) 0 001001
(b) 1 001001
(c) 1 110110
(d) 0 001101
10. Complement representation preferred to signed magnitude representation because
(a) Representation of zero is easy
(b) Less number of control decisions and circuits
(c) Both (a) & (b)
(d)None of the above
11. If carry into the sign bit position and carry out of the sign bit position are not equal then
(a) Result is negative
(b) Overflow condition
(c) Both a < b
(d) None of the above
-15
12. Minimum number of bits required to represent exponent of 101 x 2 will be
(a) 5 bit (b) 4 bit
(c) 8 bit (d) 7 bit
30
13. Minimum number of bits required to represent exponent of 11 x 2 will be
(a) 5 bit (b) 6 bit
(c) 7 bit (d) 8 bit
SOLUTIONS
Ans. 1. (a) In ASCII-7
B = 100 0010 = (42)16
O = 100 1111 = (4F)16
Y = 101 1001 = (59)16
Ans. 2. (b) (14)10 = (1110)2 in eight bit, first is for sign bit and 7 bit for magnitude
(- 14)10 = 1 0001110
Ans. 3. (a) (25)10 = (11001)2
+ sign => sign bit = 0
(+ 25)10 = 0 011001
Ans. 4. (c)
1's complement of 000000 = 111111
2's complement = 111 111
+ 1
1 000 000
discard the carry out = 000 000
Ans. 5. (d) 2's complement of 11001100
= 0011 0011
+ 1
0 0110100
Ans. 6. (a) 9's complement of 629 is
9 9 9
- 6 2 9
3 7 0
Ans. 7. (b) (+ 50) + (- 55) = - 05
(5)10 = (101)2
in 8 bit = 0 0000101
- 5 = 1 1111010
+ 1
= 1 1111011
Ans. 8. (a) (+ 25) + (- 12) = + 13
(13)10 = (1101)2
in 6 bit register = 0 01101
Ans. 9. (a) (20) - (11) = + 9
(9)10 = (1001)2
in 7 bit register = 0 001001
Ans. 12. (a) (15)10 = (1111)2
So 4 bit required by adding one bit for sign. 5 bit required to represent (- 15).
Ans. 13. (b) (30)10 = (11110)2
5 bit + 1 bit sign = 6 bit.