ProgrammingFundamentals 1 Nasreen Kadhim
ProgrammingFundamentals 1 Nasreen Kadhim
College of Science
Computer Science Department
Programming Language
Fundamentals
First Class – First Semester
Morning Undergraduate Study
Dr. Nasreen Jawad Kadhim
Lecture 1
1. INTRODUCTION TO COMPUTERS
Today, computers are an integral part of our lives and are found at offices, homes, schools,
colleges, hotels, shops, etc. This advance in technology has made our lives easy and
comfortable. For instance, we can execute a number of activities using computer based
systems.
great speed. To accomplish its various tasks, the computer is made of different parts, each
serving a particular purpose in conjunction with other parts. Computers work through an
interaction of hardware (refers to the parts of a computer that you can see and touch) and
software (refers to the instructions, or programs, that tell the hardware what to do).
one reason that traditional systems are being replaced rapidly by computer-based systems.
• High accuracy
• User-friendly features
• Portability
and large storage capacity. NASA uses supercomputers to track and control space
explorations.
are desk-sized machines and are used in medium scale applications. For example,
minicomputers, microcomputers are the least powerful, but these are very widely
used and rapidly gaining in popularity. These computers are designed for use by a
single person. Four types of microcomputers exists: Desktop, Notebook, Tablet PC,
and Handheld.
Computer Computer can be defined as an electronic device that accepts data from an
input device, processes it, stores it in a disk and finally displays it on an output device such
as a monitor.
To understand the basic principles of the functioning of the computer refer to the basic
block diagram of a computer as shown in Figure 1. This flow of information holds true for
all types of computers such as Personal Computers, Laptops, Palmtops etc. In other words,
STORAGE
As shown in Figure 1, there are four main building blocks in a computer's functioning─
input, processor, output and memory. The data (data is the name given to facts) is entered
through input devices like the keyboard, disks or mouse. These input devices help convert
data and programs into the language that the computer can process. The data received from
the keyboard is processed by the CPU, i.e. the Central Processing Unit. The CPU controls
and manipulates the data that produce information (information is the meaningful data that
is relevant, accurate, up to date and can be used to make decisions). The CPU is usually
housed within the protective cartridge. The processed data is either stored in the memory
or sent to the output device, as explained in the command given by the user. The memory
unit holds data and program instructions for processing data. Output devices translate the
processed information from the computer into a form that we can understand.
The omputer system consists of both hardware and software. Hardware components are
the various physical components that comprise a computer system, as opposed to the non-
tangible software elements. The software components of a computer system are the data
and the computer programs. Figure 2 illustrates the hardware and software components.
The Central Processing Unit also called Processor. This is the brain or heart of the computer
equipment. The CPU carries out the calculations for the program and controls the other
components of the system. It does the function by organizing circuits into two main units,
The ALU contains circuits that do arithmetic and perform logical operations. The control
The ALU contains logic circuits that perform logic operations as well as arithmetic circuits
that can subtract multiply and divide two numbers. More complex operations such as
finding the square root of a number are done by sequence of their basic operations. The
ALU has storage locations called storage registers for storing numbers used in calculations
and for storing the results of calculations. To perform a calculation or logical operation,
number is transferred from primary storage to storage registers in the ALU. These numbers
are sent to the appropriate arithmetic or logic circuit. The results are sent back to the storage
registers. The results are transferred from the storage registers to primary storage.
The Control Unit (CU) controls the whole computer system via performing the following
functions:
• Activates the appropriate circuits necessary for input and output devices.
The CU contains a temporary storage location called an instruction register for storing the
instruction being executed. It also contains circuit called the instruction decoder –which
analyzes the instruction register and causes it to be executed. The CU executes each
• The next instruction in the program is retrieved for primary storage and stored in
• The decoder sends signals to the ALU, primary storage, I/O devices, and secondary
storage, that cause the actions required by the instructions to be performed. These
steps are repeated for each instruction in the program until all instructions have
been executed.
Figure 3: Block diagram of computer system.
2. Storage Unit
i. Primary Storage
Primary storage is also called internal storage or memory. It is used to store programs and
data currently being processed by CPU. Primary storage circuits need electricity to stay on.
If the power to the computer is turned off, all the circuits will turn off and all data in primary
storage will be lost. When computer is turned back on, the data will not reappear. The data
is lost forever. Because of this characteristics primary storage is called volatile storage.
This type of primary storage is called RANDOM ACCESS MEMORY or RAM. RAM is
the main type of primary storage used with computers and it is volatile. Many computers
have another type of primary storage called ROM –Read Only Memory. ROM is non-
volatile storage. ROM can store preset programs that are always put by computer
manufactures.
• Input area –where the data is stored when it is read into CPU, awaiting processing.
• Working storage –where calculations are performed and data is stored temporarily.
• Output area where the information is stored prior to output. Both the input and
Secondary is nonvolatile. Any data or programs stored in secondary storage stays there,
even with the computer power turned off. Secondary storage is a permanent form of
storage.
Differences between Primary storage and Secondary storage are explained at Table 1.
Internal or main storage. High speed External or auxiliary storage. Low speed
It holds programs and data in current use It holds program or data that will still be used
Input is any data or instructions that are used by a computer. Input devices are hardware
used to translate words, sounds, images, and actions that people understand into a form that
the system unit can process. Some commonly used input devices are: Keyboard, Mouse,
and Scanner.
Output is processed data or information, and typically takes the form suitable for use by
the computer's human operators such as text, graphics, photos, audio, and/or video. Output
devices are any hardware used to provide or to create output. They translate information
that has been processed by the system unit into a form that humans can understand. Some
commonly used output devices are: Monitors (soft copy) and Printers (hard copy).
Lecture 2
Or just software, is the collection of computer programs and related data that provide
instructions telling a computer what to do. The term was coined to contrast the old term
There are two types of software -system software and application/utility software.
to help the user to perform singular or multiple related specific tasks. The programs
written under application software are designed for general purpose and special
Explorer.
• System Software is computer software designed to provide services to other
System software is the ‘background’ software that helps the computer to manage
its internal resources. The most important system software is the operating system.
4. PROGRAMMING LANGUAGES
individual preference. Ideally, the programming language best suited for the immediate
computer to perform specific tasks. The term programming language usually refers to
high-level languages, such as C, C++, C#, and Java. Each language has a unique set of
keywords (words that it understands) and a special syntax for organizing program
instructions.
more complex than the languages the computer actually understands, called machine
languages. Each different type of CPU has its own unique machine language. Lying
between machine languages and high-level languages are languages called assembly
languages. Assembly languages are similar to machine languages, but they are much easier
to program in because they allow a programmer to substitute names for numbers. Machine
(usually abbreviated 4GL). 4GLs are far removed from machine languages and represent
the class of computer languages closest to human languages. Each of the programming
language generations aims to provide a higher level of abstraction of the internal
and versatile. Languages claimed to be 4GL may include support for database
web development.
language based on solving problems using constraints given to the program, rather than
programs, fifth-generation languages are designed to make the computer solve a given
problem without the programmer. This way, the programmer only needs to worry about
what problems need to be solved and what conditions need to be met, without worrying
are used mainly in artificial intelligence research. Prolog, OPS5, and Mercury are
Regardless of what language you use, you eventually need to convert your program into
machine language so that the computer can understand it. There are two ways to do this:
Compiler and interpreter are the internal programs that translate High level language
to Machine language. Compiler takes Entire program as input, program need not be
compiled every time, errors are displayed after entire program is checked, and it is
fast. Whereas interpreter takes Single instruction as input, every time higher level
program is converted into lower level program, errors are displayed for every
Every language has its strengths and weaknesses. For example, Pascal is very good for
and difficult to learn. The choice of which language to use depends on the type of computer
the program is to run on, what sort of program it is, and the expertise of the programmer.
The process of developing a software, according to the desired needs of a user, by following
(PDLC). PDLC includes various set of procedures and activities that are isolated and
sequenced for learning purposes but in real life they overlap and are highly interrelated.
The basic set of procedures that are followed by various organizations in their program
2. Program Design,
3. Coding,
4. Debugging,
5. Testing,
6. Documentation,
7. Maintenance,
This stage is the formal definition of the task. It includes the specification of inputs and
outputs, processing requirements, system constraints, and error handling methods. This
step is very critical for the completion of a satisfactory program. It is impossible to solve a
The programmer should invest a significant portion of his time in problem identification.
If he does not spend enough time at this stage, he may find that his well written program
fails to solve the real problem. This step is the process of becoming familiar with the
problem. It starts when the programmer is assigned a task. This step includes the reviewing
of the design document that was prepared for the program, as well as any system wide
information that would be helpful. The process ends when all the programmer’s questions
have been resolved and the requirements of the program are understood.
2. Program Design
Once the problem has been identified, the next stage is the program design. A computer is
both fast and versatile, but it requires the careful specification of what actions it should
take. For the user, there is seldom an opportunity to allow the computer to make an
undirected decision. Therefore the programmer must decide, prior to writing his program,
exactly which steps the computer should take to solve an identified problem. Such a
functional description of the task is either called an algorithm or results in a diagram called
flowchart.
boxes of various kinds, and their order by connecting them with arrows. Flowcharts are
3. Coding
The third step is the process of transforming the program logic design documents into a
computer language format. This stage translates the program design into computer
instructions. These instructions are the actual program or the software product. During this
step the programmer eliminates all the syntax and formal errors from the program and all
Lecture 3
4. Debugging
This stage is the discovery and correction of programming errors. Few programs run
correctly the first time, so debugging is an important and time consuming stage of software
the programmer intends to do. Validation ensures that the program gives the correct results
There are basically three types of errors that you must contend with when writing computer
programs:
✓ The compiler will detect the error and the program won’t even compile. At this
point, the programmer is unable to form an executable program that a user can run until
✓ A compilation error message often helps programmers debugging the source code for
✓ Compilers aren’t perfect and so can’t catch all errors at compile time.
✓ Run-time error - refers to the period while a computer program is actually executed
data.
✓ Errors that indicate the logic used when coding of the program failed to solve the
5. Testing
This stage is the validation of the program. Testing ensures that the program performs
correctly the required tasks. Program testing and program debugging are closely related.
Testing is essentially a later stage of debugging in which the program is validated by trying
it on a suitable set of cases. Program testing is, however, more than a simple matter of
exercising the program a few times. Exhaustive testing of all possible cases is the best
alternative, but this processes is usually impractical. Formal validation methods exist, but
are only applicable to very simple programs. Thus, program testing requires a choice of
test cases.
There are two goals in preparing a test plan. Firstly, a properly detailed test plan
demonstrates that the program specifications are understood completely. Second, the test
plan is used during the program testing to prove the correctness of the program. During this
step a general approach to the testing of the program is prepared and documented,
indicating the number of tests needed and the purpose of each test.
6. Documentation
This stage is the documentation of the program so that those who use and maintain it, can
stage of software development that is often overlooked. Yet proper documentation is not
only useful in the testing and debugging stages, it is also essential in the maintenance and
redesign stages. A properly documented program can be easily reused when needed; an
undocumented program usually requires so much extra work that the programmer might as
well start from scratch. Among the techniques commonly used in documentation are
flowcharts, comments, memory maps, parameter and definition lists, and program library
with the design, coding, debugging and testing stages of software development. Good
documentation simplifies maintenance and redesign, and makes subsequent tasks simpler.
7. Maintenance
After the programs are developed and documented, it is placed into operation. During the
operation, a program may fail to perform its objective and it might be necessary to add new
developed for previous tasks. Redesign may involve adding new features or meeting new
requirements. Such redesign should proceed through the previously mentioned stages
of program development. The process may also involve making a program meet critical
memory usage is needed, a program can often be reorganized to meet the requirement.
Example 1:
Read two numbers A and B and compute The sum of them and print the result.
Processing:
Program output:
Algorithm:
1- Start
2- Read A, and B
3- Compute the Sum (SUM):
SUM = A+B
4- Print the Sum (SUM)
5- End
Flowchart:
Start
Read A, B
SUM = A+B
Print SUM
End
Lecture 4
6. PROGRAM FLOW
the statements in order until it comes to the end. No choices are made; there is no
repetition.
iteration. So there are three programming language constructs. Figure 6 illustrates these
three types.
Construct a flowchart that finds sum, average and product of three numbers.
Simple sequential flow: Example 2:
Construct a flowchart that finds the area and circumference of a circle where R
(radius) is given.
Flowchart:
Start
Read R
A= PI*R*R
C= 2*PI*R
Print R,
A, C
Stop
Lecture 5
• Some techniques are nicely outlined and easy to follow. They not only solve the
problem, but also give insight into how the solution was reached.
problem changes.
• To be a good problem solver and a good programmer, you must follow good
problem-solving techniques.
1. Analyze the problem and outline the problem and its solution requirements.
3. Implement the algorithm in a programming language, such as C++, and maintain the
problem. You then design the algorithm; write the program instructions in a high-
level language (or code the program); and enter the program into a computer
As illustrated in Figure 8, we are ready to review the steps (Six Steps) required to process
Step 2: Pre-process the source codes according to the preprocessor directives. Preprocessor
directives begin with a hash sign (#), e.g., #include and #define. They indicate that certain
Step 3: Compile the pre-processed source codes into object codes (.obj, .o).
Step 4: Link the compiled object codes with other object codes and the library object codes
✓ Source Program (.cpp): consists of the program statements comprising a C++ or other
program.
✓ Linker: A program that combines the Object Program (.obj) with other programs in the
✓ Loader: A program that loads an Executable Program (.exe) into main memory.
Lecture 6
During compilation, if there are any errors that will be listing by the compiler. The errors
• Syntax error This error occurs due to mistake in writing the syntax of a C++
statement or wrong use of reserved words, improper variable names, using variables
without declaration etc. Examples are: missing semi colon or parenthesis, etc.
Appropriate error message and the statement number will be displayed. You can
see the statement and make correction to the program file, save and recompile it.
• Logical error This error occurs due to the flaw in the logic. This will not be
identified by the compiler. However it can be traced using the debug tool in the
editor. First identify the variable which you suspect creating the error and add them
to watch list. This tool helps in knowing the values taken by the variable at each
step. You can compare the expected value with the actual value to identify the error.
• Linker error This error occur when the files during linking are missing or misspelt.
• Runtime error This error occurs if the program encounters division by zero,
accessing a null pointer etc. during execution of the program.
Comments
/* ...... */
These are called comments. Comments are NOT executable and are ignored by the
compiler; but they provide useful explanation and documentation to your readers. There
1. Multi-line Comment: begins with /* and ends with */. It may span more
line.
Preprocessor directives
#include <iostream>
<iostream>" tells the preprocessor to include the "iostream" header file to support
the default namespace used in this program. The names cout and endl, which is used in
this program, belong to the std namespace. These two lines shall be present in all our
programs.
Main function
defines the so-called main() function. The main() function is the entry point of program
"cout" refers to the standard output (or Console OUTput). The symbol << is called the
stream insertion operator (or put-to operator), which is used to put the string "hello, world"
to the console. "endl" denotes the END-of-Line or newline, which is put to the console
return 0;
terminates the main() function and returns a value of 0 to the operating system.
Typically, return value of 0 signals normal termination; whereas value of non-zero (usually
1) signals abnormal termination. This line is optional. C++ compiler will implicitly insert
a "return 0;" to the end of the main() function.
Lecture 7
8. Programming Methodologies
Two popular approaches to programming design are:
problem is then analyzed, and a solution is obtained to solve the sub- problem. The
solutions to all of the sub-problems are then combined to solve the overall problem. The
see Figure 9. The structured-design approach is also known as Top-down design or Bottom-
up design.
(c)
Figure 9: Structured
Programming
8.2 Control Structures in structured design (within C++): An Introduction
The programs in C++ executes its statements one by one from beginning to end. There
are different approaches that can be used to solve same problems. The format of
program should be such that it is easy to trace the flow of execution of statements. By
making the flow of execution traceable, it is easy to develop accurate, error-free and
maintainable code. As the statements are executed, their execution may vary depending
upon the circumstances. The programs not only store data but also perform
manipulative tasks and to perform such tasks C++ has provided tools which help in
performing repetitive tasks and other manipulative actions(decision making). The tools
comes in the form of Control Structures. So Control Structures in C++ tells about
the order in which the statements are executed and helps to perform manipulative,
whether a condition is met or conditions. Within C++; if, if..else, ... or switch.
As the name suggests they alter the sequential execution of the statements of program
depending upon the condition. Branching Statements are included in this control
• if statement.
• if-else statement.
• switch statement.
• goto statement.
Except goto statement which is unconditional branching statement, all the other ones
Lecture 8
if Statement
an ability to make decisions like what part of code to execute thus controlling the
follows:
if (test-expression) statement;
As mentioned in the syntax of the statement, the test expression is always mentioned in
parentheses. In this statement if the test-expression is true then the statement which is
followed immediately is executed. If the test-expression is false then the control will
transfer to the next statement following the if construct. Multiple statements can also
if-else Statement
This statement is quite similar to if-statement, this statement also specify what happens
when the condition is not satisfied by providing else as an alternative statement. If you
1
want to perform some action even if the test-expression fails i.e. condition is false then
As mentioned in syntax of the if-else statement, if the test expression is true then
statement 1 is executed else statement 2 is executed if the test expression fails. The else
In an if-else statement only the code associated with if or the code associated with else
is executed, never both. The following figure explains the flow of if-else statement:
In the above example if the condition fails then else part of the program executes and
if the condition is true then first part i.e. if part is executed. Similar to if-statement, if-
2
Nested if else Statement
As the name suggests this statement contains multiple if-else statements which are used
in multi-way decisions that arise when there are multiple conditions and different
actions are required depending upon the conditions. The syntax of Nested if-else
statement is as follows:
As the above flowchart explains, if the test-expression1 i.e. decision1 is true, the whole
chain is terminated. The chain will only continue if the test-expression1 or decision1
fails, similar is the case for decision2 and so on. In nested if-else statements, the else
3
Lecture 9
switch Statement
construct which allows you to choose different statements depending upon the
conditions. This switch statement successfully tests the expression against the integer
or character constant and when there is a match, the statement associated with the
It causes exit from the switch structure after the case statements are executed. If the
break statement is not mentioned then the control will transfer to the next case
statement. When the condition in case is true the corresponding statement will get
executed. The default part is optional in the switch statement, if none of the case is true
then default statement is executed. The syntax and flow of switch-statement are
switch(test-expression) {
::
4
switch vs if-else
• switch can only test the expression for equality whereas if-else can
if-else can handle range of values whereas switch case can have single
value.
if-else statements can handle floating point values apart from integer and
character.
5
A switch statement is more efficient than nested if-else statement A switch statement
can only work for equality comparisons. A switch statement can also be nested.
With the help of Loops, a section of code can be executed repeatedly until a termination
condition is met. Loops or the looping statements are also called iteration statements.
• for loop.
• while loop.
• do-while loop.
There are four elements in the looping structure that control its execution. These
for the looping structure. This expression is executed only once in the
• Test Expression: As the name suggests this element test the condition
which decides whether the loop body will be executed or not. If the
condition is false the loop gets terminated else the loop statements get
executed. for-loop and while-loop are entry controlled loops where the
controlled loop.
6
• Loop Body: The body of the loop contains the statements which are
controlled loop the body of the loop is executed after the test expression
whereas in the exit controlled loop the body of the loop gets executed
while-loop
what if the number of iterations to be performed are not known in advance, while-loop
can be used in such a case. The statements inside the while loop keeps on executing
7
while-loop evaluates the test-expression before entering into the loop. while-loop can
also be infinite loop, only if the loop variable is not updated inside the body. while-loop
can also be empty loop, only if it contains a null statement in its body.
Lecture 10
do-while loop
evaluated after the loop-body gets executed. Whereas the for-loop and while-loop is
evaluated at the top of the loop, do-while is evaluated at the bottom of the loop. This
least once, even if the test-expression is false. The syntax of do-while loop is as follows:
8
First the statement inside the body of the loop is executed and then the test expression
int i=0;
do
{
cout<<i<<endl;
i++;
}
while (i<5);
selection routine, where the menu is displayed at least once and then depending upon
for-loop
9
The for-loop is used where a statement is executed a fixed number of times. Compound
statements can also be used in the body of for loop. The syntax of for-loop is as follows
body of for-loop; }
10
• The initialization expression step is executed first, and only once.
executed. If it is false, the body of the loop does not execute and flow of control
• After the body of the for loop executes, the update statement is executed to
• The condition is now evaluated again. If it is true, the loop executes and the
11