Problem Solving Using Computer: CDS101Module IIIISERBPR/CDS
Problem Solving Using Computer: CDS101Module IIIISERBPR/CDS
Problem Solving Using Computer: CDS101Module IIIISERBPR/CDS
1. Problem Definition
A clearly defined problem is already half the solution. Computer programming
requires us to define the problem first before we even try to create a solution.
2. Problem Analysis:
Analyzing the problem require us to identify the following:
Input(s) to the problem, their form and the input media to be used
Output(s) expected from the problem, their form and the output media to be
used
Special constraints or conditions (if any)
Any formulas or equations to be used
i.e. A =T/N
4. Coding:
Coding is the real job of programmer. The algorithm to solve a problem which is
described by pseudo-code or flow chart is converted into actual programming
CDS101Module IIIISERBPR/CDS
So testing is the process of checking the program for its correct functionality by
executing the program with some input data set and observing the output of the
program.
7. Documentation:
From the start of the problem solving to the end of the implementation of the
program, all the tasks should be documented i.e. kept for future reference. It is also
the important part of the problem solving or program development. Documentation
may be of two types
User manual is the documentation prepared for the end-user of the program
that guides the user how to operate the program.
CDS101Module IIIISERBPR/CDS
Algorithm
–An algorithm is a clear and unambiguous specification of the steps needed to solve
a problem. It may be expressed in either:
A pseudocode is:
Example of Algorithm:
Pseudocode Specification:
1. Input N
2. Input N marks: m1, m2, m3,..... mN
CDS101Module IIIISERBPR/CDS
Flow-Chart:
start/stop
Oval symbol (or termination symbol) indicates the beginning or end of a program, or
a section of code
read/print
processing statement
calculation
CDS101Module IIIISERBPR/CDS
condition check
direction of flow
connectors
Entry or exit points are used to attach the one flowchart to another
Another Example: Pseudo code and flow chart for calculation of grade of students
print “A”
else
print “B”
else
print “C”
else
print “D”
else
print “F”
Another Example:
The algorithm sums all the even numbers between 1 and 20 inclusive and then
displays the
CDS101Module IIIISERBPR/CDS
sum. It uses a repeat loop and contains a null else within the repeat loop.
is easier to read
more closely follows a standard, this is not the the case with pseudocode
easier to understand than pseudocode
History of C
CDS101Module IIIISERBPR/CDS
C is one of the most widely used programming languages of all time and there are
very few computer architectures for which a C compiler does not exist. C has greatly
influenced many other popular programming languages, most notably C++, which
began as an extension to C. The origin of C is closely tied to the development of the
Unix operating system, originally implemented in assembly language on a PDP-7 by
Ritchie and Thompson, incorporating several ideas from colleagues. Eventually they
decided to port the operating system to a PDP-11. B's inability to take advantage of
some of the PDP-11's features, notably byte addressability, led to the development
of an early version of C.
The original PDP-11 version of the Unix system was developed in assembly
language. By 1973, with the addition of struct types, the C language had become
powerful enough that most of the Unix kernel was rewritten in C. This was one of the
first operating system kernels implemented in a language other than assembly.
(Earlier instances include the Multics system (written in PL/I), and MCP (Master
Control Program) for the Burroughs B5000 written in ALGOL in 1961.) In 1978, Brian
Kernighan and Dennis Ritchie published the first edition of The C Programming
Language. This book, known to C programmers as "K&R", served for many years as
an informal specification of the language. The version of C that it describes is
commonly referred to as K&R C. The second edition of the book covers the later
ANSI C standard
The C – Preprocessor
The preprocessor is a program that processes the source code before it passes
through the compiler. It operates under the control of preprocessor command line or
directives. Preprossor directives are placed in the source program before the main
line. Before the source code passes through the compiler, it is examined by
preprocessor. After taking appropriate actions as directed by preprocessor, the
source program is handed over to the compiler.
The syntax of pre-processor directives begin with the symbol # and do not require
semi colon (;) at the end. The pre-processor directives can be divided into three
categories.
main()
printf(“Welcome to C programming.\n”);
} /*End of program */
Analysis:
Any things between /* and */ is treated as comments in C. These are for only
programmer references . Comments are escaped by C compiler during compilation
of program.
#include<stdio.h>
stdio.h is an input output header file which contains the input/output and file handling
functions which are used in C programs. The required header file should be included
using #include preprocessor directive.
main():
C programs are made of functions. main() is a special function which should be there
in each c program. Each C program starts executing from main() function. As
program cannot have many starting points, C program should have main function
once and only once. main() may call other function to perform the given task.
printf()
printf is an output function which has been defined in stdio.h file. What ever is put
inside the function printf between two double quotes is printed on the screen
New lines: Note that printf never puts new line automatically. To put new line we
require to put ‘\n’ between double quotes inside ‘printf’ function.
CDS101Module IIIISERBPR/CDS
Eg
printf(“Welcome to ”);
printf(“C programming”);
Welcome to
C programming.
The statement:
is a single statement.
Macro Substitution:
CDS101Module IIIISERBPR/CDS
A simple macro:
example:
#define PI 3.14159
#define TRUE 1
#define CITY “Kathmandu”
#define TWO_PI 2*(22/7)
#define BLANK_LINE printf(“\n”);
#define INCREMENT ++
#define START {
#define END }
etc.
Arguemented macro :
Example:
CDS101Module IIIISERBPR/CDS
Area = PI*SQUARE(radius);
Which is equivalent to :
Nesting macro:
We can use one pre-defined macro to define new macro. This is called nesting of
macro definition.
Example:
#define PI 3.14159
Given the definition of macro MAX(a,b) , We can use nested call of macro to
fine maximum of three numbers a,b,c as: MAX(a,MAX(a,b))
To define multiple lines we can use \ character at the end of each line:
Undifining a Macro:
#undef IDENTIFIER
it is useful when to restrict the definition only to a particular part of the program.
CDS101Module IIIISERBPR/CDS
A file which contains the pre-defined macros and functions can be included in our
source program using #include directive. If we include pre-written file in our source
program we need not to rewrite the functions and macro which are defined in that
file.
When #include<filename> is used, the file inside < > is searched in the
standard directory and included in the source program where it is written. If
file is not find an error is reported.
When #include “filename” is used , the file inside “ ” is searched first in the
current directory and then standard directory included in the source program
where it is written.
Consider a file named test.c which includes the definition of functions for square and
cube and macro to find the maximum of two numbers , and constant PI.
/* test.c */
#define PI 3.14
#define MAX(x,y) ( ( (x) > (y) ) ? (x) : (y) )
Now we have to write a program that uses functions and macros defined in test.c.
the source program is as:
/*source.c */
#include<stdio.h>
#include “test.c”
CDS101Module IIIISERBPR/CDS
void main()
{
int x =10, y=20;
printf(“\nThe square of %d is %d” , x, square(x));
printf(“\nThe cube of %d is %d “, x, cube(x));
printf(“\n The larger no is %d.”, MAX(a,b));
}
Elements Of C Program
The Structure of a C Program #
All C programs will consist of at least one function, but we can write a C programs
that have several functions body . The only function that has to be present is the
function main. For more advanced programs the main function will act as a
controling function calling other functions in their turn to do the dirty work! The main
function is the first function that is called when your program executes. So main is
the starting of execution of program.
preprocessor directives
main()
function1()
function2()
... etc
Note the use of the bracket set () and {}: () are used in conjunction with function
names whereas {} are used with the C statements that are associated with that
function and used for statements block. A semicolon (;) is used to terminate C
statements. C is a free format language and long statements can be continued,
without truncation, onto the next line. The semicolon informs the C compiler that the
end of the statement has been reached. Free format also means that you can add as
many spaces as you like to improve the look of your programs. A very common
mistake made by everyone, who is new to the C programming language, is to miss
off the semicolon. The C compiler will concatenate the various lines of the program
together and then tries to understand them - which it will not be able to do. The error
message produced by the compiler will relate to a line of program which could be
some distance from the initial mistake.
Constants/ Literals #
Like a variable, a constant is a data storage location used by our program. Unlike a
variable, the value stored in a constant can't be changed during program execution.
C has two types of constants, each with its own specific uses.
Integer Constants are sequences of digits. There are three types of integers
namely decimal ,octal and hexadecimal .
e.g.
Real Constants are the numbers with fractional parts and optional leading + or –
symbol.
In addition C supports some special backslash character constants that are used in
outputfunctions.
For example: ‘\n’ for newline, ‘\t’ for tab, ‘\b’ for back space, ‘\”’ for double quote ‘\\’
for \ and so on.
main()
{
printf(“\nIntegers: ”);
printf(“%d, %d , %d”, 32767, 32767+1, 32767+10);
printf(“\nLong integers: ”);
printf(“%ld, %ld, %ld “, 32767, 32767+1, 32767+10);
printf(“\nUnsigned integers: ”);
printf(“%u,%u,%u”, 32767, 32767+1, 32767+10);
printf(“\nReal constants:”);
printf(“%f, %f, %f”, 3.4, 9.9e3, -1.2e-6);
printf(“\nCharacter :%c “,’A’);
printf(“\nA string :%s “, “C programming”);
return 0;
}
output
Character: A
A String: C programming
CDS101Module IIIISERBPR/CDS
All the types of above constants can be classified in to two main categories.
1. Literal Constants
2. Symbolic Constants.
Literal Constants
A literal constant is a value that is typed directly into the source code wherever it is
needed. Here are two examples:
The 20 and the 0.28 are literal constants. The preceding statements store these
values in the variables count and tax_rate. Note that one of these constants contains
a decimal point, whereas the other does not. The presence or absence of the
decimal point distinguishes floating-point constants from integer constants.
123.456
0.019
100.
Note that the third constant, 100., is written with a decimal point even though it's an
integer (that is, it has no fractional part). The decimal point causes the C compiler to
treat the constant as a double- precision value. Without the decimal point, it is
treated as an integer constant.
A constant starting with any digit other than 0 is interpreted as a decimal integer (that
is, the standard base-10 number system). Decimal constants can contain the digits 0
through 9 and a leading minus or plus sign. (Without a leading minus or plus, a
constant is assumed to be positive.)
e.g.
123
-670
8965 etc.
A constant starting with the digit 0 is interpreted as an octal integer (the base-8
number system). Octal constants can contain the digits 0 through 7 and a leading
minus or plus sign.
Symbolic Constants
need the constant's value in our program, we use its name as we would use a
variable name. The actual value of the symbolic constant needs to be entered only
once, when it is first defined.
Symbolic constants have two significant advantages over literal constants, as the
following example shows. Suppose that we're writing a program that performs a
variety of geometrical calculations. The program frequently needs the value ,,
(3.14159) for its calculations.For example, to calculate the circumference and area of
a circle with a known radius, we could write
If, however, we define a symbolic constant with the name PI and the value 3.14, we
could write
circumference = PI * (2 * radius);
area = PI * (radius)*(radius);
The resulting code is clearer. Rather than puzzling over what the value 3.14 is for,
we can see immediately that the constant PI is being used.
C has two methods for defining a symbolic constant: the #define directive and the
const keyword. The #define directive is one of C's preprocessor directives which is
used as follows:
This creates a constant named CONSTNAME with the value of literal. literal
represents a literal constant(i.e.value for constant). CONSTNAME follows the same
rules described for variable names. By convention, the names of symbolic constants
are uppercase. This makes them easy to distinguish from variable names, which by
convention are lowercase. For the previous example, the required #define directive
would be
#define PI 3.14159
CDS101Module IIIISERBPR/CDS
Note that #define lines don't end with a semicolon (;). #defines can be placed
anywhere in our source code, but they are in effect only for the portions of the source
code that follow the #define directive. Most commonly, programmers group all
#defines together, near the beginning of the file and before the start of main().
The precise action of the #define directive is to instruct the compiler as follows: "In
the source code, replace CONSTNAME with literal." Note that #define doesn't
replace instances of its target that occur as parts of longer names, within double
quotes, or as part of a program comment. For example, in the following code, the
instances of PI in the second and third lines would not get changed:
#define PI 3.14159
/* You have defined a constant for PI. */
#define PIPETTE 100
The second way to define a symbolic constant is with the const keyword. const is a
modifier that can be applied to any variable declaration. A variable declared to be
const can't be modified during program execution-only initialized at the time of
declaration. Here are some examples:
const affects all variables on the declaration line. In the last line, debt and tax_rate
are symbolic constants. If our program tries to modify a const variable, the compiler
generates an error message, as shown here:
Now look at this small program that demonstrates the use of variables and
constants.
main()
{
/* Input data from user */
/* Perform conversions */
return 0;
}
Analysis: This program declares the two types of symbolic constants in lines 5 and
8. In line 5, a constant is used to make the value 454 more understandable. Because
it uses GRAMS_PER_POUND, line 25 is easy to understand. Lines 11 and 12
declare the variables used in the program. Notice the use of descriptive names such
as weight_in_grams. We can tell what this variable is used for. Lines 18 and 20 the
printf() print prompts on-screen. To allow the user to respond to the prompts, lines 19
and 21 use another library function, scanf() which gets input information. Lines 25
and 26 calculate the user's weight in grams and his or her age in the year 2000. To
finish the program, lines 30 and 31 display the results for the user.
Expressions #
CDS101Module IIIISERBPR/CDS
Expressions
Simple Expressions
The simplest C expression consists of a single item: a simple variable, literal constant, or
symbolic constant. Here are four expressions:
Expression Description
20 A literal constant
Rate A variable
A literal constant evaluates to its own value. A symbolic constant evaluates to the value it
was given when we created it using the #define directive. A variable evaluates to the current
value assigned to it by the program.
Complex Expressions
For example:
2 + 8
is an expression consisting of the sub-expressions 2 and 8 and the addition operator +. The
expression 2 + 8 evaluates 10. we can also write C expressions of great complexity:
x = a + 10;
CDS101Module IIIISERBPR/CDS
This statement evaluates the expression a + 10 and assigns the result to x. In addition, the
entire statement x = a + 10 is itself an expression that evaluates to the value of the variable on
the left side of the equal sign.
Thus, we can write statements such as the following, which assigns the value of the
expression
y = x = a + 10;
x = 6 + (y = 4 + 5);
Statements #
Statements
A statement is a complete direction instructing the computer to carry out some task.
In C, statements are usually written one per line, although some statements span
multiple lines. C statements always end with a semicolon (except for preprocessor
directives such as #define and #include.
For example:
x = 2 + 3;
is an assignment statement. It instructs the computer to add 2 and 3 and to assign
the result to the variable x.
The term white space refers to spaces, tabs, and blank lines in the source code. The
C compiler isn't sensitive to white space. When the compiler reads a statement in the
source code, it looks for the characters in the statement and for the terminating
semicolon, but it ignores white space. Thus, the statement
x=2+3;
x = 2 + 3;
x =
2
+
3;
This gives us a great deal of flexibility in formatting our source code. We shouldn't
use formatting like the previous example, however. Statements should be entered
one per line with a standardized scheme for spacing around variables and operators.
The point is to keep our source code readable.
However, the rule that C doesn't care about white space has one exception: Within
literal string constants, tabs and spaces aren't ignored; they are considered part of
the string. A string is a series of characters. Literal string constants are strings that
are enclosed within quotes and interpreted literally by the compiler, space for space.
Although it's extremely bad form, the following is legal:
printf(
"Hello, world!"
);
printf("Hello,
world!");
To break a literal string constant line, you must use the backslash character (\) just
before the break. Thus, the following is legal:
printf("Hello,\
world!");
Null Statements
Compound Statements
{
printf("Hello, ");
printf("world!");
}
In C, a block can be used anywhere a single statement can be used. Note that the
enclosing braces can be positioned in different ways. The following is equivalent to
the preceding
example:
{printf("Hello, ");
printf("world!");}
It's a good idea to place braces on their own lines, making the beginning and end of
blocks clearly visible. Placing braces on their own lines also makes it easier to see
whether we've left one out. But if there are large number of statements inside the
block , it is not possible to place braces in one lines.
Notes:
DO put block braces on their own lines. This makes the code easier to read.
DO line up block braces so that it's easy to find the beginning and end of a
block.
DON'T spread a single statement across multiple lines if there's no need to do
so. Limit statements to one line if possible.