Computer Programming
Computer Programming
Computer Programming
POLANGUI CAMPUS
Computer and Engineering Studies Department
Course Description :
The course covers the use of general purpose programming language to solve
problems. The emphasis is to train students to design, implement, test and debug
programs intended to solve computing problems using fundamental programming
constructs.
It always leads to a solution and tries to be the most efficient solution we can
think up. It's often a good idea to number the steps, but you don't have to. Instead of
numbered steps, some folks use indentation and write in pseudocode, which is a semi-
programming language used to describe the steps in an algorithm. But, we won't use
that here since simplicity is the main thing. Other folks just use a diagram called a
flowchart, which we will discuss soon.
Definition of Algorithm
Characteristics of an Algorithm
Not all procedures can be called an algorithm. An algorithm should have the following
characteristics −
Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or
phases), and their inputs/outputs should be clear and must lead to only one meaning.
Definition of Flowchart
program. With algorithms, we can easily understand a program. The main purpose of a
flowchart:
Input / Output
Process / Instruction
Decision
Connector / Arrow
The graphics above represent different part of a flowchart. The process in a flowchart
can be expressed through boxes and arrows with different sizes and colors. In a
flowchart, we can easily highlight a certain element and the relationships between each
part.
Now that we have the definitions of algorithm and flowchart, how do we use a flowchart
to represent an algorithm?
Algorithms are mainly used for mathematical and computer programs, whilst flowcharts
can be used to describe all sorts of processes: business, educational, personal and of
course algorithms. So flowcharts are often used as a program planning tool to visually
Algorithm:
Step 1: Initialize X as 0,
Step 2: Increment X by 1,
Step 3: Print X,
Flowchart:
Algorithm:
Step 1: Read temperature in Fahrenheit,
Step 3: Print C,
Flowchart:
Benefits of Flowchart:
As it provides the pictorial representation of the steps; therefore, it simplifies the logic
Because of having easily understandable pictorial logic and steps, it is a better and
Effective Analysis
Once the flow-chart is prepared, it becomes very simple to analyze the problem in an
effective way.
Useful in Coding
The flow-chart also helps in coding process efficiently, as it gives directions on what to
do, when to do, and where to do. It makes the work easier.
Proper Testing
Further, flowchart also helps in finding the error (if any) in program
Applicable Documentation
Last but not the least, a flowchart also helps in preparing the proper document (once the
Conclusion
flowchart.
An algorithm shows you every step of reaching the final solution, while a flowchart
shows you how to carry out the process by connecting each step. An algorithm uses
mainly words to describe the steps while a flowchart uses the help of symbols, shapes
ACTIVITY:
II. Then try to summarize it into 6 Steps. The algorithm must still make sense.
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.
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.
if "1"
print response
"I am case 1"
if "2"
print response
"I am case 2"
4. Use appropriate naming conventions. The human tendency follows the approach
to follow what we see. If a programmer goes through a pseudo code, his approach
will be the same as per it, so the naming must be simple and distinct.
5. Use appropriate sentence casings, such as CamelCase for methods, upper case
for constants and lower case for variables.
6. Elaborate everything which is going to happen in the actual code. Don’t make the
pseudo code abstract.
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.
ACTIVITY:
Create the Algorithm in a pseudo code format for the following problems:
A. How to solve for the sum of two numbers.
B. Converting Dollars to Philippine Pesos.
C. Process in Withdrawing money from the ATM
D. Deterring if the grade is a PASS or a FAIL
Programmable devices have existed at least as far back as 1106 AD, when
the automata of Al-Jazari were programmable, via pegs and cams, to play various
rhythms and drum patterns;] and the 1801 Jacquard loom could produce entirely
different weaves by changing the "program" - a series of pasteboard cards with holes
punched in them.
However, the first computer program is generally dated to 1843, when
mathematician Ada Lovelace published an algorithm to calculate a sequence
of Bernoulli numbers, intended to be carried out by Charles Babbage's Analytical
Engine.
Ada Lovelace, whose notes added to the end of Luigi Menabrea's paper included the
first algorithm designed for processing by an Analytical Engine. She is often recognized
as history's first computer programmer.
Data and instructions were once stored on external punched cards, which were kept in
order and arranged in program decks.
In the 1880s Herman Hollerith invented the concept of storing data in machine-readable
form. Later a control panel (plugboard) added to his 1906 Type I Tabulator allowed it to
be programmed for different jobs, and by the late 1940s, unit record equipment such as
the IBM 602 and IBM 604, were programmed by control panels in a similar way; as
were the first electronic computers. However, with the concept of the stored-program
computers introduced in 1949, both programs and data were stored and manipulated in
the same way in computer memory.
Machine code was the language of early programs, written in the instruction set of the
particular machine, often in binary notation. Assembly languages were soon developed
that let the programmer specify instruction in a text format, (e.g., ADD X, TOTAL), with
abbreviations for each operation code and meaningful names for specifying addresses.
However, because an assembly language is little more than a different notation for a
machine language, any two machines with different instruction sets also have different
assembly languages.
High-level languages made the process of developing a program simpler and more
understandable, and less bound to the underlying hardware. FORTRAN, the first widely
used high-level language to have a functional implementation, came out in 1957[6] and
many other languages were soon developed – in particular, COBOL aimed at
commercial data processing, and Lisp for computer research.
Programs were mostly still entered using punched cards or paper tape. See computer
programming in the punch card era. By the late 1960s, data storage
devices and computer terminals became inexpensive enough that programs could be
created by typing directly into the computers. Text editors were developed that allowed
changes and corrections to be made much more easily than with punched cards.
C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill,
New Jersey, as an enhancement to the C language and originally named C with
Classes but later it was renamed C++ in 1983.
C++ is a superset of C, and that virtually any legal C program is a legal C++ program.
Note − A programming language is said to use static typing when type checking is
performed during compile-time as opposed to run-time.
Learning C++
C++ supports a variety of programming styles. You can write in the style of Fortran, C,
Smalltalk, etc., in any language. Each style can achieve its aims effectively while
maintaining runtime and space efficiency.
Use of C++
C++ is being highly used to write device drivers and other software that rely on direct
manipulation of hardware under realtime constraints.
C++ is widely used for teaching and research because it is clean enough for successful
teaching of basic concepts.
Anyone who has used either an Apple Macintosh or a PC running Windows has
indirectly used C++ because the primary user interfaces of these systems are written in
C++.
Object − Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behaviors - wagging, barking, eating. An object is an
instance of a class.
Instance Variables − Each object has its unique set of instance variables. An
object's state is created by the values assigned to these instance variables.
Live Demo
#include <iostream>
int main() {
return 0;
The C++ language defines several headers, which contain information that is
either necessary or useful to your program. For this program, the
header <iostream> is needed.
The line using namespace std; tells the compiler to use the std namespace.
Namespaces are a relatively recent addition to C++.
The next line '// main() is where program execution begins.' is a single-line
comment available in C++. Single-line comments begin with // and stop at the
end of the line.
The line int main() is the main function where program execution begins.
The next line cout << "Hello World"; causes the message "Hello World" to be
displayed on the screen.
The next line return 0; terminates main( )function and causes it to return the
value 0 to the calling process.
Open a command prompt and go to the directory where you saved the file.
Type 'g++ hello.cpp' and press enter to compile your code. If there are no errors
in your code the command prompt will take you to the next line and would
generate a.out executable file.
You will be able to see ' Hello World ' printed on the window.
$ g++ hello.cpp
$ ./a.out
Hello World
Make sure that g++ is in your path and that you are running it in the directory
containing file hello.cpp.
You can compile C/C++ programs using makefile. For more details, you can check
our 'Makefile Tutorial'.
x = y;
y = y + 1;
add(x, y);
A block is a set of logically connected statements that are surrounded by opening and
closing braces. For example −
{
cout << "Hello World"; // prints Hello World
return 0;
}
C++ does not recognize the end of the line as a terminator. For this reason, it does not
matter where you put a statement in a line. For example −
x = y;
y = y + 1;
add(x, y);
is the same as
x = y; y = y + 1; add(x, y);
C++ Identifiers
A C++ identifier is a name used to identify a variable, function, class, module, or any
other user-defined item. An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters, underscores, and digits (0 to 9).
C++ does not allow punctuation characters such as @, $, and % within identifiers. C++
is a case-sensitive programming language. Thus, Manpowerand manpower are two
different identifiers in C++.
DATA TYPES:
While writing program in any language, you need to use various variables to store
various information. Variables are nothing but reserved memory locations to store
values. This means that when you create a variable you reserve some space in
memory.
You may like to store information of various data types like character, wide character,
integer, floating point, double floating point, boolean etc. Based on the data type of a
variable, the operating system allocates memory and decides what can be stored in the
reserved memory.
Type Keyword
Boolean bool
Character char
Integer int
Valueless void
Several of the basic types can be modified using one or more of these type modifiers −
signed
unsigned
short
long
The following table shows the variable type, how much memory it takes to store the
value in memory, and what is maximum and minimum value which can be stored in
such type of variables.
The size of variables might be different from those shown in the above table,
depending on the compiler and the computer you are using.
VARIABLE TYPES:
1 bool
2 char
3 int
4 float
5 double
6 void
7 wchar_t
C++ also allows to define various other types of variables, which we will
cover in subsequent chapters like Enumeration, Pointer, Array,
Reference, Data structures, and Classes.
Following section will cover how to define, declare and use various types of
variables.
Variable Definition in C++
A variable definition tells the compiler where and how much storage to
create for the variable. A variable definition specifies a data type, and
contains a list of one or more variables of that type as follows −
type variable_list;
Here, type must be a valid C++ data type including char, w_char, int, float,
double, bool or any user-defined object, etc., and variable_list may
consist of one or more identifier names separated by commas. Some valid
declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; both declares and defines the variables i, j and k; which
instructs the compiler to create variables named i, j and k of type int.
A variable declaration is useful when you are using multiple files and you
define your variable in one of the files which will be available at the time of
linking of the program. You will use extern keyword to declare a variable at
any place. Though you can declare a variable multiple times in your C++
program, but it can be defined only once in a file, a function or a block of
code.
Example
Try the following example where a variable has been declared at the top,
but it has been defined inside the main function −
Live Demo
#include <iostream>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main () {
// Variable definition:
int a, b;
int c;
float f;
// actual initialization
a = 10;
b = 20;
c = a + b;
f = 70.0/3.0;
return 0;
When the above code is compiled and executed, it produces the following
result −
30
23.3333
Same concept applies on function declaration where you provide a function
name at the time of its declaration and its actual definition can be given
anywhere else. For example −
// function declaration
int func();
int main() {
// function call
int i = func();
}
// function definition
int func() {
return 0;
}
OPERATORS:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
Arithmetic Operators
There are following arithmetic operators supported by C++ language −
Show Examples
Relational Operators
There are following relational operators supported by C++ language
Show Examples
Logical Operators
There are following logical operators supported by C++ language.
Show Examples
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth
tables for &, |, and ^ are as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows
−
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following
table. Assume variable A holds 60 and variable B holds 13, then −
Show Examples
Assignment Operators
There are following assignment operators supported by C++ language −
Show Examples
1 if statement
2 if...else statement
An ‘if’ statement can be followed by an optional ‘else’ statement, which
executes when the boolean expression is false.
3 switch statement
A ‘switch’ statement allows a variable to be tested for equality against a
list of values.
4 nested if statements
You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’
statement(s).
LOOPS/ ITERATIONS:
There may be a situation, when you need to execute a block of code several
number of times. In general, statements are executed sequentially: The
first statement in a function is executed first, followed by the second, and
so on.
1 while loop
2 for loop
Execute a sequence of statements multiple times and abbreviates the
code that manages the loop variable.
3 do...while loop
Like a ‘while’ statement, except that it tests the condition at the end of
the loop body.
4 nested loops
You can use one or more loop inside any another ‘while’, ‘for’ or
‘do..while’ loop.
1 break statement
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating.
3 goto statement
Transfers control to the labeled statement. Though it is not advised to
use goto statement in your program.
#include <iostream>
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
return 0;
FUNCTIONS:
You can divide up your code into separate functions. How you divide up
your code among different functions is up to you, but logically the division
usually is such that each function performs a specific task.
The C++ standard library provides numerous built-in functions that your
program can call. For example, function strcat() to concatenate two strings,
function memcpy() to copy one memory location to another location and
many more functions.
Defining a Function
The general form of a C++ function definition is as follows −
return_type function_name( parameter list ) {
body of the function
}
Return Type − A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return_type is the
keyword void.
Function Name − This is the actual name of the function. The function name
and the parameter list together constitute the function signature.
Example
Following is the source code for a function called max(). This function takes
two parameters num1 and num2 and return the biggest of both −
// function returning the max between two numbers
return result;
}
Function Declarations
A function declaration tells the compiler about a function name and how to
call the function. The actual body of the function can be defined separately.
For the above defined function max(), following is the function declaration −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is
required, so following is also valid declaration −
int max(int, int);
Calling a Function
While creating a C++ function, you give a definition of what the function
has to do. To use a function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the
called function. A called function performs defined task and when it’s return
statement is executed or when its function-ending closing brace is reached,
it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along
with function name, and if function returns a value, then you can store
returned value. For example −
Live Demo
#include <iostream>
// function declaration
int main () {
int a = 100;
int b = 200;
int ret;
return 0;
int result;
result = num1;
else
result = num2;
return result;
I kept max() function along with main() function and compiled the source
code. While running final executable, it would produce the following result −
Max value is : 200
Function Arguments
If a function is to use arguments, it must declare variables that accept the
values of the arguments. These variables are called the formal
parametersof the function.
The formal parameters behave like other local variables inside the function
and are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed
to a function −
1 Call by Value
This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument.
2 Call by Pointer
This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the actual
argument used in the call. This means that changes made to the
parameter affect the argument.
3 Call by Reference
This method copies the reference of an argument into the formal
parameter. Inside the function, the reference is used to access the actual
argument used in the call. This means that changes made to the
parameter affect the argument.
This is done by using the assignment operator and assigning values for the
arguments in the function definition. If a value for that parameter is not
passed when the function is called, the default given value is used, but if a
value is specified, this default value is ignored and the passed value is used
instead. Consider the following example −
Live Demo
#include <iostream>
int result;
result = a + b;
return (result);
int main () {
int a = 100;
int b = 200;
int result;
result = sum(a);
return 0;
}
When the above code is compiled and executed, it produces the following
result −
Total value is :300
Total value is :120
MIDTERM EXAMINATION
Instruction:
Create the C++ Code Syntax of the Following output (25 points each):
1. 3.
2. 4.
MODULE V. DEBUGGING: