Programming for Problem Solving
Programming for Problem Solving
Solving
Reference Book –
Unit 1 –
Programming and Problem Solving with C++ by Chip Weems, Nell Dale and Tim Richards, Jones and Bartlett Publishers, Inc, 2022
UNIT – 1 Syllabus
• Introduction to Programming and C++
• Elements of a computer systems
• DOS Commands & Linux environment
• Overview of programming languages
• Introduction to C++ and its features
• Setting up a C++ development environment
• Language Processors
• Object Oriented Programming Paradigm and benefits
• Applications of Object Oriented programming
Introduction to Programming and C++
• What is Programming?
• Programming refers to the process of designing and building an executable set of instructions to accomplish a
specific task on a computer to get the desired result.
• Programming is writing computer code to create a program, to solve a problem.
• A computer is a useful tool for solving a great variety of problems. To make a computer do anything (i.e.
solve a problem), you have to write a computer program. In a computer program you tell a computer, step by
step, exactly what you want it to do. The computer then executes the program, following each step
mechanically, to accomplish the end goal.
• The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.
• Flowchart is a graphical or symbolic representation of an algorithm. It is the diagrammatic representation of
the step-by-step solution to a given problem.
• Program Design consists of the steps a programmer should do before they start coding the program in a
specific language. Proper program design helps other programmers to maintain the program in the future.
How Do We Write a Program?
• A computer is not intelligent. It cannot analyze a problem and come up with a solution. Instead, a human (the
programmer) must analyze the problem, develop a sequence of instructions for solving the problem, and then
communicate it to the computer. What’s the advantage of using a computer if it can’t solve problems? Once we
have written the solution as a sequence of instructions for the computer, the computer can repeat the solution very
quickly and consistently, again and again. The computer frees people from repetitive and boring tasks.
• To write a sequence of instructions for a computer to follow, we must go through a two-phase process: problem
solving and implementation
• Problem-Solving Phase
• Analysis and specification. Understand (define) the problem and what the solution must do.
• General solution (algorithm). Develop a logical sequence of steps that solves the problem.
• Verify. Follow the steps exactly to see if the solution really does solve the problem.
• Implementation Phase
• Concrete solution (program). Translate the algorithm into a programming language.
• Test. Have the computer follow the instructions, then manually check the results. If you find errors, analyze the program and the
algorithm to determine the source of the errors, and then make corrections.
• Maintenance Phase
• Use. Use the program.
• Maintain. Modify the program to meet changing requirements or to correct any errors that show up in using it
• Algorithm:
• In mathematics, computer science, and related subjects, an algorithm is a finite sequence of
steps expressed for solving a problem. An algorithm can be defined as “a process that
performs some sequence of operations in order to solve a given problem”. Algorithms are
used for calculation, data processing, and many other fields.
• Flowchart:
• A Flowchart is a type of diagram (graphical or symbolic) that represents an algorithm or
process. Each step in the process is represented by a different symbol and contains a short
description of the process step. The flow chart symbols are linked together with arrows
showing the process flow direction. A flowchart typically shows the flow of data in a
process, detailing the operations/steps in a pictorial format which is easier to understand
than reading it in a textual format.
• For example, consider that we need to find the sum, average and product of 3 numbers given
by the user.
Algorithm for the given problem is as follows:
Step 1 :- Read X, Y, Z
Step 2 :- Compute Sum (S) as X + Y + Z
Step 3 :- Compute Average (A) as S / 3
Step 4 :- Compute Product (P) as X * Y * Z
Step 5 :- Write (Display) the Sum, Average and Product
• Flowchart for the above problem will look like
• Example: Consider another problem of finding the largest number between A and B
Algorithm for the above problem is as follows: Flowchart for the above algorithm will look like:
Programming Language
• Programming Language is a language used to communicate with the computer by writing
programs.
• Programming language is widely used in the development of operating systems.
• An Operating System (OS) is a software (collection of programs) that controls the various
functions of a computer.
• Also it makes other programs on your computer work. For example, you cannot work with a
word processor program, such as Microsoft Word, if there is no operating system installed on
your computer.
• Windows, Unix, Linux, Solaris, and Mac OS are some of the popular operating systems.
• The same way to run the programs in a particular programming language we need a language
complier.
• You write computer instructions in a computer programming language such as Visual Basic, C#,
C++, or Java. Just as some people speak English and others speak Japanese, programmers write
programs in different languages.
• The instructions you write using a programming language are called program code; when you
write instructions, you are coding the program. Every programming language has rules
governing its word usage and punctuation.
• These rules are called the language‘s syntax. Mistakes in a language‘s usage are syntax errors.
After a computer program is typed using programming language statements and stored in
memory, it must be translated to machine language that represents the millions of on/off circuits
within the computer.
• Your programming language statements are called source code, and the translated machine
language statements are object code.
• The different types of programming languages are as follows :-
• Machine Level Language
• Assembly Level Language
• High – Level Language
• Machine – Level Language:-
• In the computer, all data, whatever its form, is stored and used in binary codes— that is, as
strings of 1s and 0s. Instructions and data are stored together in the computer’s memory
using these binary codes.
• When computers were first developed, the only programming language available was the
primitive instruction set built into each machine, the machine language, or machine code.
• Even though most computers perform the same kinds of operations, their designers choose
different sets of binary codes for each instruction. Thus the machine code for one computer
is not the same as the machine code for another computer.
• Such a program is called an assembler. The name comes from the fact that much of what an
assembler does is to look up the pieces of an instruction in a table to find the corresponding
binary code (such as ADD = 1001), and then assemble these binary coded pieces of the
instruction into a complete machine language instruction.
• The assembler also puts the instructions together in the specified sequence to create a
complete program.
• High – Level Language:-
• Assembly language is a step in the right direction, but it still forces programmers to think in
terms of individual machine instructions.
• Eventually, computer scientists developed high-level programming languages. These
languages are easier to use than assembly languages or machine code because they are
closer to English and other natural languages.
• In computer science, a high-level programming language is a language that is written in
human understandable form.
• It is like simple English text written as a set of commands for the computer. It provides
strong abstraction from the details of a computer.
• High level languages like COBOL, Pascal, Python , Java, C++ and others enable the
programmer to write codes that are more or less independent of a particular type of
computer.
How Does a Computer Run a Program?
• A program called a compiler translates programs written in certain high level languages (for eg.
C++, Java, Visual Basic, and Ada) into machine language. If you write a program in a high-level
language, you can run it on any computer that has the appropriate compiler. This is possible
because most high level languages are standardized, which means that an official description
of the language exists.
• A program in a high-level language is called a source program. To the compiler, a source
program is just input data. It translates the source program into a machine language program
called an object program.
• If there are errors in the program, the compiler instead generates one or more error messages
indicating the nature and location of the errors.
• One benefit of using standardized high-level languages is that they allow you to write portable
(or machine-independent) code.
• As Figure emphasizes, a single C++ program can be used on different machines, whereas a
program written in assembly language or machine language is not portable from one
computer to another. Because each computer has its own machine language, a machine
language program written for computer A will not run on computer B.
It is important to understand that compilation and execution are two distinct processes. During
compilation, the computer runs the compiler program. During execution, the object program is
loaded into the computer’s memory unit, replacing the compiler program. The computer then runs
the object program, doing whatever the program instructs it to do.
What’s Inside the Computer?
• You can learn a programming language, including how to write programs and how to run (execute) these
programs, without knowing much about computers. But if you know something about the parts of a
computer, you can better understand the effect of each instruction in a programming language.
• Most computers have six basic components: the memory unit, the arithmetic/logic unit, the control unit,
input devices, output devices, and auxiliary storage devices. Above FIGURE is a stylized diagram of the
basic components of a computer.
• Central Processing Unit
• CPU stands for Central Processing Unit; it is also known as "the brain of the computer". A CPU
is a primary component of a computer that performs most of the processing and controls the
operation of all components running inside a computer.
• The key components of a CPU are the Control Unit, ALU and Memory. The alignment and
integration of key components are included in the above figure.
• Components of CPU
• Control Unit (CU) – The control unit controls the actions of the other components so that
program instructions are executed in the correct order. A CPU executes instructions by
fetching them from memory, decodes them, and then executes them. So, it plays a vital role
in fetch-decode-execute instructions.
• ALU (Arithmetic Logic Unit) – The arithmetic/logic unit (ALU) performs arithmetic
operations (addition, subtraction, multiplication, and division) and logical operations
(comparing two values).
• Memory Units
• Memory unit is the amount of data that can be stored in the storage unit. This storage capacity is
expressed in terms of Bytes.
• Input Device
• The devices which are used to give input to the computer system are known as input devices.
Data is inputted into the computer system in raw format, which is then translated into a
computer-understandable form using input devices; after that, it is processed using a central
processing unit, which produces output. Eg. Mouse, Keyboard,etc.
• Output Device
• An output device is a hardware device that is used to show the processed results to the user in
the form of text, audio, video, visuals on a computer screen or a printed hard copy on paper.
Different output devices can be connected to computer systems to retrieve the output, based on
the type of output and requirements. Eg. Monitors, Printer, etc.
• Auxiliary Storage Device
• An auxiliary storage device, or secondary storage device, holds coded data for the computer
until we actually want to use the data. Instead of inputting data every time, we can input it once
and have the computer store it onto an auxiliary storage device. Whenever we need to use this
data, we can tell the computer to transfer the data from the auxiliary storage device to its
memory. An auxiliary storage device therefore serves as both an input device and an output
device. Typical auxiliary storage devices are disk drives and flash memory.
MS-DOS Commands
• MS-DOS, or Microsoft Disk Operating System, is a command-line operating system that was widely used before
the advent of modern graphical interfaces. Understanding MS-DOS commands is essential for those who want to
delve into the roots of computing or need to use these commands in specific scenarios.
• In this article, we provide a comprehensive list of MS-DOS commands, offering a complete MS-DOS
command line reference. Whether you’re looking for basic MS-DOS commands or need detailed information
on common MS-DOS commands, this guide will serve as a valuable resource.
Commands Description
CD changes the current directory to the specified folder.
DIR Displays a list of files and subdirectories in a directory.
COPY Copies files from one location to another.
DEL Deletes one or more files.
REN Renames a file or directory.
MKDIR Creates a new directory.
RMDIR Removes an existing directory.
TYPE filename Displays the contents of a text file.
EDIT Opens the MS-DOS text editor for editing a specified file.
DATE Displays or sets the system date.
TIME Displays or sets the system time.
EXIT Exits the MS-DOS command prompt or a batch file.
ECHO Specifies the text to display on the screen.
Linux OS
• What is Linux Operating System?
• The Linux operating system is a set of programs which acts as a link between the computer and the end user.
• The computer programs that allocate the system resources and coordinate all the details of the computer's
internals is called the Operating System or the Kernel.
• Shell − The shell is the utility that processes your requests. When
you type in a command at your terminal, the shell interprets the
command and calls the program that you want.
• Verify Installation
Ensure the specified version of G++ is correctly installed.
$ g++ --version
This command checks which version is currently active.
• -o hello : Specifies the name of the executable file to be created (optional, defaults to a.out).
• ./hello
• ./ : Tells the shell to look for the executable in the current directory.
• hello : The name you specified during compilation (or a.out if you didn’t specify any output
file name).
Language Processor
• Computer programs are generally written in high-level languages (like C++,
Python, and Java). A language processor, or language translator, is a computer
program that convert source code from one programming language to another
language or to machine code (also known as object code). They also find errors
during translation.
• Compilers, interpreters, translate programs written in high-level languages into
machine code that a computer understands and assemblers translate programs
written in low-level or assembly language into machine code. In the compilation
process, there are several stages. To help programmers write error-free code, tools
are available.
• The language processors can be any of the following three types:
• Compiler
• Assembler
• Interpreter
• Compiler
• 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#.
• In a compiler, the source code is translated to object code successfully if it is free of errors.
The compiler specifies the errors at the end of the compilation with line numbers when there
are any errors in the source code. The errors must be removed before the compiler can
successfully recompile the source code again the object program can be executed number of
times without translating it again.
• Assembler
• The Assembler is used to translate the program written in Assembly language into machine
code. The source program is an input of an assembler that contains assembly language
instructions. The output generated by the assembler is the object code or machine code
understandable by the computer. Assembler is basically the 1st interface that is able to
communicate humans with the machine. We need an assembler to fill the gap between
human and machine so that they can communicate with each other. code written in assembly
language is some sort of mnemonics(instructions) like ADD, MUL, MUX, SUB, DIV, MOV
and so on. and the assembler is basically able to convert these mnemonics in binary code.
Here, these mnemonics also depend upon the architecture of the machine.
• For example, the architecture of intel 8085 and intel 8086 are different.
• 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. An interpreter translates one line at a time and then
executes it.
• Example: Perl, Python and Matlab.
Object Oriented Programming Paradigm
• Programmers write instructions in various programming languages to perform their
computation tasks such as:
• Machine level Language
• Assembly level Language
• High level Language
2. Machine Independent
A C++ executable is not platform-independent (compiled programs on Linux won’t run on Windows), however, they
are machine-independent. Let us understand this feature of C++ with the help of an example. Suppose you have
written a piece of code that can run on Linux/Windows/Mac OSx which makes the C++ Machine Independent but the
executable file of the C++ cannot run on different operating systems.
3. Simple
It is a simple language in the sense that programs can be broken down into logical units and parts, has rich library
support and has a variety of data types.
4. High-Level Language
C++ is a High-Level Language, unlike C which is a Mid-Level Programming Language. It makes life easier to work
in C++ as it is a high-level language it is closely associated with the human-comprehensible English language.
6. Case-sensitive
It is clear that C++ is a case-sensitive programming language. For example, cin is used to take input from the input
stream. But if the “Cin” won’t work. Other languages like HTML and MySQL are not case-sensitive languages.
7. Compiler Based
C++ is a compiler-based language, unlike Python. That is C++ programs used to be compiled and their executable file
is used to run them. C++ is a relatively faster language than Java and Python.
9. Memory Management
C++ allows us to allocate the memory of a variable or an array in run time. This is known as Dynamic Memory
Allocation. In other programming languages such as Java and Python, the compiler automatically manages the
memories allocated to variables. But this is not the case in C++. In C++, the memory must be de-allocated
dynamically allocated memory manually after it is of no use. The allocation and deallocation of the memory can be
done using the new and delete operators respectively.
A SIMPLE C++ PROGRAM
Before looking at how to write C++ programs consider the following simple example program :
The previous program is the typical program that programmer apprentices write for the first
time, and its result is the printing on screen of the "Hello World!" sentence. It is one of the
simplest programs that can be written in C++, but it already contains the fundamental
components that every C++ program has.
We are going to look line by line at the code we have just written:
// my first program in C++ This is a comment line.
All lines beginning with two slash signs (//) are considered comments and do not have any effect on the
behavior of the program. The programmer can use them to include short explanations or observations
within the source code itself. In this case, the line is a brief description of what our program is.
#include<iostream>
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code lines
with expressions but indications for the compiler's preprocessor. In this case the directive #include tells
the preprocessor to include the iostream standard file. This specific file (iostream) includes the
declarations of the basic standard input-output library in C++, and it is included because its
functionality is going to be used later in the program.
using namespace std;
All the elements of the standard C++ library are declared within what is called a namespace, the
namespace with the name std. So in order to access its functionality we declare with this expression
that we will be using these entities. This line is very frequent in C++ programs that use the standard
library.
int main ()
The int main() defines the entry or the starting point of the C++ program code. Here int is a keyword
that tells us about the integer data type. So when one runs the file on their local computer, the
operating system executes the main () function. Any code that is written to solve a particular question
goes into this main() function which the OS system when calls it, it runs the code.
Mainly we use this way of defining the function in the C++ program. The “int” in the int main() suggests
that the “main()” function would return the integer type as an output to the operating system when
the program is terminated. When the integer value is returned, it means that the program has been
completed. If the return value is 0, it indicates that the program has terminated successfully, while any
value other than 0 indicates an error.
cout << "Hello World!";
This line is a C++ statement. A statement is a simple or compound expression that can actually produce
some effect. In fact, this statement performs the only action that generates a visible effect in our first
program. cout represents the standard output stream in C++, and the meaning of the entire statement
is to insert a sequence of characters (in this case the Hello World sequence of characters) into the
standard output stream (which usually is the screen). cout is declared in the iostream standard file
within the std namespace, so that's why we needed to include that specific file and to declare that we
were going to use this specific namespace earlier in our code. Notice that the statement ends with a
semicolon character (;). This character is used to mark the end of the statement and in fact it must be
included at the end of all expression statements in all C++ programs (one of the most common syntax
errors is indeed to forget to include some semicolon after a statement).
return 0;
The return statement causes the main function to finish. return may be followed by a return code (in
our example is followed by the return code 0). A return code of 0 for the main function is generally
interpreted as the program worked as expected without any errors during its execution. This is the
most usual way to end a C++ console program.