Computer Programming 1: Ma. Rhodora R. Gallo Instructor
Computer Programming 1: Ma. Rhodora R. Gallo Instructor
Computer Programming 1: Ma. Rhodora R. Gallo Instructor
COMPUTER PROGRAMMING 1
PART 1.
INTRODUCTION TO PROGRAMMING
Company
LOGO INTRODUCTION TO PROGRAMMING
Programming
(or Computer Programming) is the process of
designing, writing, testing, debugging, and maintaining
the source code of computer programs.
This source code is written in one or more programming
languages.
The purpose of programming is to create a set of
instruction that computers can use to perform specific
operations or to exhibit desired behaviors.
The process of writing source code often requires
expertise in many different subjects, including
knowledge of the application domain, specialized
algorithms and formal logic.
Company
LOGO INTRODUCTION TO PROGRAMMING
Programming Language
It is an artificial language designed to communicate
instructions to a machine, particularly a computer.
Programming languages can be used to create
programs that control the behavior of a machine and/or
to express algorithms precisely.
The description of a programming language usually
splits into the two components of syntax (form) and
semantics (meaning)
Company
LOGO INTRODUCTION TO PROGRAMMING
Program
It is a collection of a set of instructions or operations which
are organized so that they are executed or carried out in a
systematic manner.
An organized list of instructions that, when executed,
causes the computer to behave in a predetermined
manner.
Without programs, computers are useless.
A program is like a recipe. It contains a list of
ingredients(called variables) and a list of directions(called
statements) that tell the computer what to do with the
variables. The variables can represent numeric data, text,
or graphical images.
Company
LOGO INTRODUCTION TO PROGRAMMING
Elements of a Program
All programming languages have some primitive building
blocks for the description of data and the processes or
transformations applied to them (like the addition of two
numbers or the selection of an item from a collection).
These primitives are defined by syntactic and semantic
rules which describe their structure and meaning
respectively.
SYNTAX - refers to the notation used to write things
SEMANTICS - refers to the meaning of languages, as
opposed to their form (syntax).
Company
LOGO INTRODUCTION TO PROGRAMMING
Elements of a Program
There are several elements which
programming languages, and programs written in
them, typically contain. These elements are found in
all languages.
Variables
Assignments
Conditionals
Statements
Control Flow Constructs (Loops)
Functions
Company
LOGO INTRODUCTION TO PROGRAMMING
Basic Steps in Writing a Program
Specify the problem
Analyse and break down into series of steps towards
solution, (i.e., design a pseudocode (English
instructions), an algorithm or a flowchart)
Write the source code in the computer language
Compile the program
Run your program and see if it makes the computer do
what you wanted
If not, fix or “debug” the program, and compile and run it
again.
Company
LOGO INTRODUCTION TO PROGRAMMING
Pseudocode
It is an artificial and informal language that helps
programmers develops algorithms.
Pseudocode is very similar to everyday English.
Example:
Pseudocode that reads two numbers, compute the sum of two numbers
then display the result:
Input first number
Input second number
Calculate the sum by adding the first and second number
Print Sum
Company
LOGO INTRODUCTION TO PROGRAMMING
Algorithm
A list of instructions for carrying out some process step
by step.
Procedure or formula for solving a problem
A sequence of precise instructions that leads to a
solution
Some approximately equivalent words are recipe,
methods, directions, procedures and routine
Computer programs are algorithms written in a language
designed such that the algorithm can be executed on a
computer.
Company
LOGO INTRODUCTION TO PROGRAMMING
Algorithm
Example:
Algorithm that reads two numbers, compute the sum of
two numbers then display the result:
Step 1: Start
Step 2: Input First Number
Step 3: Input Second Number
Step 4: Calculate Sum=First Number + Second Number
Step 5: Output Sum
Step 6: End
Company
LOGO INTRODUCTION TO PROGRAMMING
Flowchart
It is a graphical representation of an algorithm
It is drawn using certain special-purpose symbols
connected by arrows called flow lines.
Company
LOGO INTRODUCTION TO PROGRAMMING
Basic Flowchart Symbols and Descriptions
The terminator is used to show where your flow
begins or ends. (Oval)
Flow Lines
(Arrow)
ALGORITHM
Step 1: Start
Step 2: Input First Number
Step 3: Input Second Number
Step 4: Calculate Sum=First Number +
Second Number
Step 5: Output Sum
Step 6: End
Company
LOGO INTRODUCTION TO PROGRAMMING
Pseudocode, Algorithm and Flowchart that reads two numbers, compute
the sum of two numbers then display the result:
PSEUDOCODE FLOWCHART
Input first number
Start
Input second number
Calculate the sum by adding the
first and second number Read First
Number
Print Sum
Read Second
ALGORITHM Number
Step 1: Start
Step 2: Input First Number
Calculate Sum=First Number +
Step 3: Input Second Number Second Number
Step 4: Calculate Sum=First Number +
Second Number
Step 5: Output Sum Print Sum
Step 6: End
End
Company
LOGO INTRODUCTION TO PROGRAMMING
Pseudocode, Algorithm and Flowchart that reads the midterm and final grade,
calculate the average of two numbers then display the result. If the result of average
is greater than or equal to 75 print the text PASSED, else, end the program:
PSEUDOCODE
Input midterm grade
Input final grade
Calculate the average
Print Average
If average is greater than or equal to 75
print PASSED
ALGORITHM
Step 1: Start
Step 2: Input Midterm Grade
Step 3: Input Final Grade
Step 4: Calculate Average
Step 5: Print Average
Step 6: If Average>=75 print PASSED
Step 7: End
Company
LOGO INTRODUCTION TO PROGRAMMING
Pseudocode, Algorithm and Flowchart that reads the midterm and final grade,
calculate the average of two numbers then display the result. If the result of
average is greater than or equal to 75, print the text PASSED, else, end the
program: FLOWCHART
Start
Read Midterm
Grade Yes
Average>=75 Print PASSED
Read Final
Grade
No
Print Average
Company
LOGO
PART 2.
INTRODUCTION TO C++ PROGRAMMING LANGUAGE
Company
LOGO INTRODUCTION TO C++ PROGRAMMING LANGUAGE
PART 3.
STRUCTURE OF C++ PROGRAM
Company
LOGO STRUCTURE OF C++ PROGRAM
int main()
{
cout<<””;
system(“Pause”);
return EXIT_SUCCESS;
}
Company
LOGO STRUCTURE OF C++ PROGRAM
Probably the best way to start learning a programming language is by
writing a program.
First program: Output:
//my first program in C++ Hello World!
#include <iostream>
using namespace std;
int main()
{
cout<< “Hello World!”;
system(“Pause”);
return EXIT_SUCCESS;
}
Company
LOGO STRUCTURE OF C++ PROGRAM
int main ()
• This line corresponds to the beginning of the definition
of the main function.
• The main function is the point by where all C++
programs start their execution, independently of its
location within the source code.
• It does not matter whether there are other functions with
other names defined before or after it - the instructions
contained within this function's definition will always be
the first ones to be executed in any C++ program.
Company
LOGO STRUCTURE OF C++ PROGRAM
PART 4.
VARIABLE DECLARATION
Company
LOGO VARIABLE DECLARATION
Variables
• A portion of memory to store a determined value
• If you declare a variable in C++, you ask the operating
system for a piece of memory. You (can) give this piece
of memory a name and you can store something in that
piece of memory (for later use).
• The name of a variable is called an identifier. You can
give a variable any name you want, as long as it is a
valid identifier.
Company
LOGO VARIABLE DECLARATION
Valid Identifier
A valid identifier is a sequence of one or more letter, digits or
underscores and the identifier must begin with letter. (It is
not possible to start an identifier with a number). It is also not
possible to use punctuation marks, symbols or spaces in an
identifier. Compiler specific keywords or external identifiers
usually begin with an underscore. (It is possible to use an
underscore at the beginning of your identifier, but it is not
recommended)
The C++ language is a “case sensitive” language. This
means that an identifier with capital letters is not the same
as with normal letters.
Company
LOGO VARIABLE DECLARATION
Valid Identifier
For example: myvar, Myvar, MyVar and MYVAR are four
different variable identifiers.
The C++ language also uses a set of names that are
reserved. It is not allowed to use these keywords as variable
identifiers (variable names)
Company
LOGO VARIABLE DECLARATION
C++ Fundamental Data Types:
Name Description Size* Range*
Char Character or small integer 1 byte signed: -128 to 127
unsigned: 0 to 255
short in (short) Short Integer 2 bytes signed: -32768 to 32767
unsigned: 0 to 65535
Int Integer 4 bytes signed: -2147483648 to
214748367
unsigned: 0 to 4294967295
Long int (long) Long Integer 4 bytes signed: -2147483648 to
214748367
unsigned: 0 to 4294967295
Bool Boolean value. It can take one 1 byte true or false
of two values: true or false
Float Floating point number 4 bytes +/-3.4e +/- 38 (~7 digits)
Double Double precision floating point 8 bytes +/- 1.7e +/- 308 (~15 digits)
number
long double Long double precision floating 8 bytes +/- 1.7e +/- 308 (~15 digits)
Company
LOGO VARIABLE DECLARATION
Example:
int num1;
float average;
Company
LOGO VARIABLE DECLARATION
• Global Variable
Global variables are defined outside of all the functions,
usually on top of the program. The global variables will
hold their value throughout the lifetime of your program.
A global variable can be accessed by any function. That
is, a global variable is available for use throughout your
entire program after its declaration. Following is the
example using global and local variables:
Company
LOGO VARIABLE DECLARATION
#include <iostream>
using namespace std;
//Global variable declaration:
int g;
int main()
{
//Local variable declaration:
int a, b;
//actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
Company
LOGO VARIABLE DECLARATION
• Local Variables
Variables that are declared inside a function or block are
local variables.
They can be used only by statements that are inside that
int main()
{
//Local variable declaration:
int a, b;
int c;
//actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
Company
LOGO
PART 5.
BASIC INPUT/OUTPUT
Company
LOGO BASIC INPUT/OUTPUT
• Using the standard input and output library, the program
will be able to interact with the user by printing messages
on the screen and getting the user's input from the
keyboard.
• C++ uses a convenient abstraction called streams to
perform input and output operations in sequential media
such as the screen or the keyboard. A stream is an object
where a program can either insert or extract characters
to/from it.
• The standard C++ library includes the header file
iostream, where the standard inputnd output stream
objects are declared.
Company
LOGO BASIC INPUT/OUTPUT
• The << operator inserts the data that follows it into the stream preceding it.
In the examples above it inserted the constant string Output sentence, the
numerical constant 120 and variable x into the standard output stream
cout.
• Notice the sentence in the first instruction is enclosed between double
quotes (“) because it is a constant string of character. Whenever we want to
use constant strings of characters we must enclose them between double
quotes (“) so that they can be clearly distinguished from variable names.
Company
LOGO BASIC INPUT/OUTPUT
• The insertion operator (<<) may be used more than once in a single
statement:
cout<< “Hello I am ” <<age<< “ years old and my zipcode is: ” <<zipcode;
• If we assume the age variable to contain the value 24 and the zipcode
variable to contain 065, the output of the previous statement would be:
Hello I am 24 years old and my zipcode is: 065
Company
LOGO BASIC INPUT/OUTPUT
will be shown on the screen one following the other without any line
break between them:
Output:
First sentence.
Second Sentence.
Third sentence.
Company
LOGO BASIC INPUT/OUTPUT
int main()
{
int i;
cout << “Please enter an integer value:
cin>> i;
cout << “The value you entered is”<<i;
cout<<”and its double is” <<i*2<< “\n”;
return 0;
}
Output:
Please enter an integer value: 202
The value you entered is 202 and its double is 404
Company
LOGO
PART 6.
CONSTANTS
Company
LOGO CONSTANTS
LITERALS
Literals are used to express particular values within the
source code of a program. For example, when we wrote:
a=5
the 5 in this piece of code was a literal constant.
Integer Numerals
1776
707
-273
3.14159 //3.14159
6.02e23 //6.02 x 10^23
1.6e-19 //1.60 x 10^-19
3.0 //3.0
Company
LOGO CONSTANTS
Character and string literals
There also exist non-numerical constants, like:
'z'
'p'
“Hello World”
“How do you do”
Boolean Literals
There are only two valid Boolean values: true and
false. These can be expressed in C++ as values of
type bool by using the Boolean literals true and false.
Company
LOGO CONSTANTS
DEFINED CONSTANTS
You can define your own names for constants that you use
very often without having to resort to memory consuming
variable, simple by using the #define preprocessor directive.
Its format is:
#define identifier value
For example:
#define PI 3.14159
int main()
{
double r = 5.0;
double circumference;
circumference=2*PI*r;
cout<<circumference;
return 0;
}
The #define directive is not a C++ statement but a directive for the
preprocessor; therefore it assumes the entire line as the directive and does
not require a semicolon (;) at its end.
Company
LOGO CONSTANTS
DECLARED CONSTANTS (const)
With the const prefix you can declare constants with a specific type in
the same way as you would do with a variable:
For example:
const int pathwidth=100
Company
LOGO
PART 7.
OPERATORS IN C++
Company
LOGO OPERATORS IN C++
ASSIGNMENT
The assignment operator assigns a value to a variable.
a = 5;
ASSIGNMENT
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Company
LOGO OPERATORS IN C++
RELATIONAL AND EQUALITY OPERATORS
Here are some examples:
(7==5) //evaluates to false
(5>4) //evaluates to true
(3!=2) //evaluates to true
(6>=6) //evaluates to true
(5<5) //evaluates to false
Instead of using only numeric constants, we can use any valid expression,
including variables. Suppose that a=2, b=3 and c=6
(a==5) //evaluates to false since a is not equal to 5
(a*b>=c) //evaluates to true since (2*3>=6) is true.
(b+4>a*c) //evaluates to false since (3+4>2*6) is false.
((b=2)==a) //evaluates to true
Company
LOGO OPERATORS IN C++
LOGICAL OPERATORS
&& OPERATOR
The logical operators && and || are used when evaluating two
expressions to obtain a single relational result. The operator &&
corresponds with Boolean logical operation AND. This operation results
true if both its two operands are true, and false otherwise. The
following panel shows the result of operator && evaluating the expression
a && b:
A B a && b
True True True
True False False
False True False
False False False
Company
LOGO OPERATORS IN C++
LOGICAL OPERATORS
|| OPERATOR
The operator || corresponds with Boolean logical operation OR.
This operation results true if either one of its operands is true,
thus being false only when both operands are false themselves.
Here are the possible results of a||b:
A B a || b
True True True
True False True
False True True
False False False
((5==5)&&(3>6)) //evaluates to false (true && false)
((5==5)||(3>6)) //evaluates to true (true || false)
Company
LOGO
PART 8.
CONTROL STRUCTURES
Company
LOGO CONTROL STRUCTURES
if (condition) statement
For example, the following code fragment prints x is 100 only if the value
stored in the x variable is indeed 100:
if (x==100)
cout<< “x is 100”;
Company
LOGO CONTROL STRUCTURES
If we want more than a single statement to be executed in case that
the condition is true, we can specify a block using braces { }:
if (x==100)
{
cout<< “x is ”;
cout<< x;
}
if (x==1){
cout<< “x is 1”;
}
else if (x==2){
cout<< “x is 2”;
}
else {
cout<< “value of x unknown”;
}
Company
LOGO CONTROL STRUCTURES
ITERATION STRUCTURES (LOOPS)
Loops has a purpose to repeat a statement a certain number of
times or while a condition is fulfilled.
int main()
{
int n;
cout<< “Enter the starting number:”;
cin>> n;
while (n>0) {
cout<<n<<”,”;
--n;
}
cout<< “FIRE!\n”;
return 0;
Company
LOGO CONTROL STRUCTURES
THE DO-WHILE LOOP
Syntax: Example:
do statement while (condition); //number echoer
#include <iostream>
Its functionality is exactly the using namespace std;
same as the while loop,
int main()
except that condition in the {
do-while loop is evaluated unsigned long n;
after the execution of
do {
statement instead of before,
cout<< “Enter number (0 to end):”;
granting at least one cin>> n;
execution of statement even cout<< “You entered:” <<n<< “\n”;
if condition is never fulfilled. } while (n != 0);
return 0;
}
Company
LOGO CONTROL STRUCTURES
THE FOR LOOP
Syntax: for (initialization; condition; increase) statement;
int main()
{
for (int x=3; x>0; x--) {
cout<<x<<”,”;
}
cout<< “FIRE!\n”;
return 0;
Company
LOGO CONTROL STRUCTURES
JUMP STATEMENTS Example:
The break statement //break loop example
#include <iostream>
Using break we can leave a using namespace std;
loop even if the condition for
its end is not fulfilled. It can int main()
{
be used to end an infinite int n;
loop, or to force it to end for (n=10; n>0; n--)
before its natural end. {
cout<<n<<“,”;
For example, we are if (n==3)
going to stop the count {
down before its natural end cout<< “countdown aborted!”;
break;
(maybe because of an
}
engine check failure?): }
return 0;
}
Company
LOGO CONTROL STRUCTURES
The continue statement Example
//continue loop example
The continue statement #include <iostream>
causes the program to skip using namespace std;
the rest of the loop in the
current iteration as if the int main()
{
end of the statement block for (int n=10; n>0; n--) {
had been reached, causing if (n==5) continue;
it to jump to the start of the cout<< n << “ , ”;
}
following iteration. cout<< “FIRE!\n”;
For example, we are return 0;
going to skip the number 5 }
in the countdown:
Company
LOGO CONTROL STRUCTURES
The goto statement
goto allows to make an absolute jump to another point in the
program. You should use this feature with caution since its
execution causes an unconditional jump ignoring any type of
nesting limitations.