Bx4002 Unit 2
Bx4002 Unit 2
Department of MCA
BX4002 - Problem Solving and Programming in C
Computer is a dumb machine with expeditious computational speed. It can give quick
results to many of the complex scientific calculations but it can’t perform a task on its
own. A computer needs set of instructions to do some task. This set of instructions is
contained in a computer program. Computer program is basically in binary language
i.e. series of 0s and 1s. A large bunch of programs makes the computer functional
without which the computer would be like a paralyzed machine.
You may think computer as an idiot person who does not know to cook. If you
provide ingredients for cooking Pasta to that idiot person, you cannot expect a
delicious dish. However, if you provide ingredients along with the full step-by-step
recipe of cooking Pasta then you may expect a real Pasta from that idiot person.
Same is the concept with computers, for computers the ingredients are data (might be
an integer, string, images, videos or anything) and the recipe is a program.
1
In my early ages one question always ponders in my mind, how can I create my own
programs? Smaller but effective and my own. Programs like Calculator, Notepad,
Music Player, A Website and many complex as a Remote Administration Tool, Search
Engine etc. I found programming is the only way through which I can create my own
program. Surely you won’t be creating complex and big software’s in few days, with
little or no programming knowledge and experience. But definitely, you can create
different small programs designed for specific tasks.
What is Programming?
1. Expressions
2. Statements
3. Statement Blocks
4. Function Blocks
1. Expressions
2
• Operators can be classified based on the number of operands they perform
their operation on:
• Unary Operators
• Take one operand
• Example: & (address-of operator); see Pointer tutorial
• Binary Operators
• Operate on two operands and are by far the most common
• Examples: +, -, <, =, etc.
• Ternary Operators
• Operate on three operands
• Operators can also be classified based on the kind of function they perform:
• Arithmetic (math) Operators:
• i.e. Operators that perform math
• Examples: +, -, /
• Relational Operators:
• Compare the values of two operands
• Examples: >, <, ==
• Return/resolve to a boolean: true (1) or false(0)
• Logical Operators:
• Combine logical expressions
• Examples: && (AND), || (OR)
• Return/resolve to a boolean: true; false
2. Statements:
3. Statement Blocks:
3
4. Function Blocks:
Pseudo code is a term which is often used in programming and algorithm based fields.
It is a methodology that allows the programmer to represent the implementation of an
algorithm. Simply, we can say that it’s the cooked up representation of an algorithm.
Often at times, algorithms are represented with the help of pseudo codes as they can
be interpreted by programmers no matter what their programming background or
knowledge is. Pseudo code, as the name suggests, is a false code or a representation of
code which can be understood by even a layman with some school level programming
knowledge.
Algorithm: It’s an organized logical sequence of the actions or the approach towards a
particular problem. A programmer implements an algorithm to solve a problem.
Algorithms are expressed using natural verbal but somewhat technical annotations.
4
Pseudo code: It’s simply an implementation of an algorithm in the form of
annotations and informative text written in plain English. It has no syntax like any of
the programming language and thus can’t be compiled or interpreted by the computer.
Advantages of Pseudocode
• Improves the readability of any approach. It’s one of the best approaches to
start implementation of an algorithm.
• Acts as a bridge between the program and the algorithm or flowchart. Also
works as a rough documentation, so the program of one developer can be
understood easily when a pseudo code is written out. In industries, the
approach of documentation is essential. And that’s where a pseudo-code
proves vital.
• The main goal of a pseudo code is to explain what exactly each line of a
program should do, hence making the code construction phase easier for the
programmer.
Example:
3. The way the if-else, for, while loops are indented in a program, indent the
statements likewise, as it helps to comprehend the decision control and
execution mechanism. They also improve the readability to a great extent.
Example:
if "1"
print response
"I am case 1"
if "2"
print response
"I am case 2"
5
7. Use standard programming structures such as ‘if-then’, ‘for’, ‘while’, ‘cases’
the way we use it in programming.
8. Check whether all the sections of a pseudo code is complete, finite and clear to
understand and comprehend.
9. Don’t write the pseudo code in a complete programmatic manner. It is
necessary to be simple to understand even for a layman or client, hence don’t
incorporate too many technical terms.
Flow charts
6
Elements that may be included in a flowchart are a sequence of actions, materials or
services entering or leaving the process (inputs and outputs), decisions that must be
made, people who become involved, time involved at each step, and/or process
measurements.
Materials needed: Sticky notes or cards, a large piece of flipchart paper or newsprint,
and marking pens.
1. Define the process to be diagrammed. Write its title at the top of the work
surface.
2. Discuss and decide on the boundaries of your process: Where or when does
the process start? Where or when does it end? Discuss and decide on the level
of detail to be included in the diagram.
3. Brainstorm the activities that take place. Write each on a card or sticky note.
4. Arrange the activities in proper sequence.
5. When all activities are included and everyone agrees that the sequence is
correct, draw arrows to show the flow of the process.
6. Review the flowchart with others involved in the process (workers,
supervisors, suppliers, customers) to see if they agree that the process is drawn
accurately.
Flowchart Considerations
• Don’t worry about drawing the flowchart the "right way." Ultimately, the right
way is the way that helps those involved understand the process.
• Identify and involve in the flowcharting process all key people involved with
the process. This includes suppliers, customers, and supervisors. Involve them
in the actual flowcharting sessions by interviewing them before the sessions
and/or by showing them the developing flowchart between work sessions and
obtaining their feedback.
• Do not assign a "technical expert" to draw the flowchart. People who actually
perform the process should do it.
Flowchart Examples
7
1. High-Level Flowchart for an Order-Filling Process
2. Detailed Flowchart
One step in the process. The step is written inside the box. Usually, only one
arrow goes out of the box.
8
Decision based on a question. The question is written in the diamond.
More than one arrow goes out of the diamond, each one showing the direction the
process takes for a given answer to the question. (Often the answers are "yes" and
"no.")
Delay or wait
Link to another page or another flowchart. The same symbol on the other
page indicates that the flow continues there.
Input or output
Document
Develop a Flowchart
Use the flowchart template (Excel) to create a graphical representation of the steps in
a process to better understand it and reveal opportunities for improvement.
Programming Languages
What is Language?
9
What is a Programming Language?
i. Machine Language
The advantage of machine language is that it helps the programmer to execute the
programs faster than the high-level programming language.
The advantage of assembly language is that it requires less memory and less
execution time to execute a program.
The main advantage of a high-level language is that it is easy to read, write, and
maintain.
10
High-level programming language includes Python, Java, JavaScript, PHP, C#,
C++, Objective C, Cobol, Perl, Pascal, LISP, FORTRAN, and Swift
programming language.
The advantage of POP language is that it helps programmers to easily track the
program flow and code can be reused in different parts of the program.
The main advantage of object-oriented programming is that OOP is faster and easier
to execute, maintain, modify, as well as debug.
The main advantage of natural language is that it helps users to ask questions in any
subject and directly respond within seconds.
11
A middle-level programming language's advantages are that it supports the features of
high-level programming, it is a user-friendly language, and closely related to machine
language and human language.
As we all know, the programming language makes our life simpler. Currently, all
sectors (like education, hospitals, banks, automobiles, and more ) completely depend
upon the programming language.
There are dozens of programming languages used by the industries. Some most
widely used programming languages are given below -
1. Python
2. Java
3. C
4. C++
5. C#
6. JavaScript
7. R
8. PHP
9. GO
10. Ruby
Compiler
When executing (running), the compiler first parses (or analyzes) all of the language
statements syntactically one after the other and then, in one or more successive stages
or "passes", builds the output code, making sure that statements that refer to other
statements are referred to correctly in the final code. Traditionally, the output of the
compilation has been called object code or sometimes an object module . (Note that
the term "object" here is not related to object-oriented programming.) The object code
is machine code that the processor can execute one instruction at a time.
12
recompiled at the execution platform by a just-in-time compiler. (See also: Java
compiler)
A compiler works with what are sometimes called 3GL and higher-level languages.
An assembler works on programs written using a processor's assembler language.
The language processor that reads the complete source program written in high-level
language as a whole in one go and translates it into an equivalent program in machine
language is called a Compiler. Example: C, C++, C#, Java.
Interpreter :
The translation of a single statement of the source program into machine code is done
by a language processor and executes immediately before moving on to the next line
is called an interpreter. If there is an error in the statement, the interpreter terminates
its translating process at that statement and displays an error message. The interpreter
moves on to the next line for execution only after the removal of the error. An
Interpreter directly executes instructions written in a programming or scripting
language without previously converting them to an object code or machine
code.
13
• An interpreter is a common kind of language processor. Instead of producing
target program as a translation, an interpreter appears to directly execute the
operations specified in the source program on inputs supplied by the user.
• In contrast, an interpreter reads a statement from the input, converts it to an
intermediate code, execute it, then takes the next statement in sequence.
• If an error occurs, an interpreter stops execution and reports it.
· Loader
A loader is a major component of an operating system that ensures all necessary
programs and libraries are loaded, which is essential during the startup phase of
running a program. It places the libraries and programs into the main memory in order
to prepare them for execution. Loading involves reading the contents of the
executable file that contains the instructions of the program and then doing other
preparatory tasks that are required in order to prepare the executable for running, all
of which takes anywhere from a few seconds to minutes depending on the size of the
program that needs to run.
· Linker
• Linker is a computer program that links and merges various object files
together in order to make an executable file. All these files might have been
compiled by separate assembler.
• The major task of a linker is to search and locate referenced module/routines
in a program and to determine the memory location where these codes will be
loaded making the program instruction to have absolute reference.
Linker is a program in a system which helps to link a object modules of program into
a single object file. It performs the process of linking. Linker are also called link
editors. Linking is process of collecting and maintaining piece of code and data into a
single file. Linker also link a particular module into system library. It takes object
modules from assembler as input and forms an executable file as output for loader.
14
Linking is performed at both compile time, when the source code is translated into
machine code and load time, when the program is loaded into memory by the loader.
Linking is performed at the last step in compiling a program.
Source code -> compiler -> Assembler -> Object code -> Linker ->
Executable file -> Loader
The linker copy all library routines used in the program into executable image. As a
result, it require more memory space. As it does not require the presence of library on
the system when it is run . so, it is faster and more portable. No failure chance and
less error chance.
2. Dynamic linking – Dynamic linking is performed during the run time. This linking
is accomplished by placing the name of a shareable library in the executable image.
There is more chances of error and failure chances. It require less memory space as
multiple program can share a single copy of the library.
Here we can perform code sharing. it means we are using a same object a number of
times in the program. Instead of linking same object again and again into the library,
each module share information of a object with other module having same object. The
shared library needed in the linking is stored in virtual memory to save RAM. In this
linking we can also relocate the code for the smooth running of code but all the code
is not relocatable.It fixes the address at run time.
Program execution
Since directions are simply bit patterns, they will be kept in memory. The instruction
pointer register continuously has the memory address of (points to) the next
15
instruction to be executed. so as for the management unit to execute this instruction,
it’s derived into the instruction register. the case is as follows:
Steps 3, 4, and 5 are called an instruction fetch. Notice that steps 3 – 8 constitute a
cycle, the instruction execution cycle. It is shown graphically below.
16
Classification of Programming Language
Each programming language contains a unique set of keywords and syntax, which are
used to create a set of instructions. Thousands of programming languages have been
developed till now, but each language has its specific purpose. These languages vary
in the level of abstraction they provide from the hardware. Some programming
languages provide less or no abstraction while some provide higher abstraction. Based
on the levels of abstraction, they can be classified into two categories:
• Low-level language
• High-level language
The image which is given below describes the abstraction level from hardware. As we
can observe from the below image that the machine language provides no abstraction,
assembly language provides less abstraction whereas high-level language provides a
higher level of abstraction.
Low-level language
17
Machine-level language
The machine-level language is a language that consists of a set of instructions that are
in the binary form 0 or 1. As we know that computers can understand only machine
instructions, which are in binary digits, i.e., 0 and 1, so the instructions given to the
computer can be only in binary codes. Creating a program in a machine-level
language is a very difficult task as it is not easy for the programmers to write the
program in machine instructions. It is error-prone as it is not easy to understand, and
its maintenance is also very high. A machine-level language is not portable as each
computer has its machine instructions, so if we write a program in one computer will
no longer be valid in another computer.
The different processor architectures use different machine codes, for example, a
PowerPC processor contains RISC architecture, which requires different code than
intel x86 processor, which has a CISC architecture.
Assembly Language
The assembly language contains some human-readable commands such as mov, add,
sub, etc. The problems which we were facing in machine-level language are reduced
to some extent by using an extended form of machine-level language known as
assembly language. Since assembly language instructions are written in English
words like mov, add, sub, so it is easier to write and understand.
The assembly language code is not portable because the data is stored in computer
registers, and the computer has to know the different sets of registers.
The assembly code is not faster than machine code because the assembly language
comes above the machine language in the hierarchy, so it means that assembly
language has some abstraction from the hardware while machine language has zero
abstraction.
The following are the differences between machine-level language and assembly
language:
18
It does not require any translator as the In assembly language, the assembler is
machine code is directly executed by the used to convert the assembly code into
computer. machine code.
It is a first-generation programming It is a second-generation programming
language. language.
High-Level Language
When writing a program in a high-level language, then the whole attention needs to
be paid to the logic of the problem.
The following are the differences between low-level language and high-level
language:
19
Structured Programming Concept
• C
• C++
• Java
• C#
• ..etc
On the contrary, in the Assembly languages like Microprocessor 8085, etc, the
statements do not get executed in a structured manner. It allows jump statements like
GOTO. So the program flow might be random.
• Selection Statements
• Sequence Statements
• Iteration Statements
The structured program consists of well structured and separated modules. But the
entry and exit in a Structured program is a single-time event. It means that the
program uses single-entry and single-exit elements. Therefore a structured program is
well maintained, neat and clean program. This is the reason why the Structured
Programming Approach is well accepted in the programming world.
20
Advantages of Structured Programming Approach:
Illustrated Problems:
Algorithm to check whether a given number is Armstrong number or not
An Integer number in which the sum of the cubes of its digits is equal to the number
itself is called Armstrong Number. For example, 153 is an Armstrong number since
1**3 + 5**3 + 3**3 = 153.
(NOTE: 5**3 is nothing but 5*5*5)
Step 1: Start
Step 2: Declare Variable sum, temp, num
Step 3: Read num from User
Step 4: Initialize Variable sum=0 and temp=num
Step 5: Repeat Until num>=0
5.1 sum=sum + cube of last digit i.e
[(num%10)*(num%10)*(num%10)]
5.2 num=num/10
Step 6: IF sum==temp
Print "Armstrong Number"
ELSE
Print "Not Armstrong Number"
Step 7: Stop
21
Pseudocode to find whether number is Armstrong Number or Not:
READ n
temp=n
sum=0
WHILE n>=0
sum=sum+(n%10)*(n%10)*(n%10)
n=n/10
ENDWHILE
IF sum==temp
WRITE "NUMBER IS AN ARMSTRONG NUMBER"
ELSE
WRITE "NUMBER IS NOT AN ARMSTRONG NUMBER"
We first take input from user and store it in variable n. Then we initialize 2 variables
temp to n and sum to 0. We calculate the cube of last digit by this expression
[(n%10)*(n%10)*(n%10)] and add it to value of sum and also divide n by 10. We
repeat the above step until n is greater than or equal to 0. At last, we check whether
sum is equal to temp, if yes Print "Number is Armstrong Number" else print "Number
is Not Armstrong Number".
22
Find factorial of a number
Step 1: Start
Step 2: Declare Variable n, fact, i
Step 3: Read number from User
Step 4: Initialize Variable fact=1 and i=1
Step 5: Repeat Until i<=number
5.1 fact=fact*i
5.2 i=i+1
Step 6: Print fact
Step 7: Stop
Read number
Fact = 1
i=1
WHILE i<=number
Fact=Fact*i
i=i+1
ENDWHILE
WRITE Fact
Explanation
We first take input from user and store that value in variable named “n”. Then we
initialize a variable “Fact” with value 1 (i.e Fact=1) and variable i with value 1(i.e
i=1). Repeat next two steps until i is less than n.
23