2 Computer Problem Solving (E-next.in)
2 Computer Problem Solving (E-next.in)
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
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 = 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.
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.
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
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)
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.
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
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
operation.The 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 = .
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:
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
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()
{
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 :
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);
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()
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)
}
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 subscripts.For 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);
}
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);
}
}
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.
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++)
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.
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 :
emp.eno refers to the variable employee number
emp.enm refers to the variable employee name
emp.sal 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",&e1.eno);
printf("Enter the employee name\n");
gets(el.enm);
printf("Enter the employee salary\n");
scanf("%f",&e1.sal);
printf(“The values stored are\n");
printf("%d\t%s\t%f",e1 .eno.el .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?
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
... … … …
… … … …
… … … …
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 .
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 :
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.
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 :
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.
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