Com Prog
Com Prog
GE ELEC3
Learning Guide
JOCELYN O. BALOLOT
Instructor
Course Outline
Course Description:
This course is intended for engineering students to have a concrete knowledge on computer
programming as preparation to their embedded system courses. The course covers the use of
general-purpose programming language to solve computing and related problems. This course
teaches the students the programming terms, concepts, pseudocode and flowcharting. The
emphasis is to train students to design, implement, test, and debug programs intended to solve
computing problems using fundamental programming constructs.
General Objectives:
• Understand and learn the programming concepts of C++ programming language.
• Apply elementary techniques involving arithmetic operators and mathematical expressions
in C++ programming.
• Test and debug C++ programs.
• Solve problems using C++ language and library feature.
• Design and code C++ programs, which meet simple to medium requirements.
• Create programs with a function and object-oriented structure.
Course Requirements:
To successfully complete the Computer Programming course, you are required to
perform all the learning and programming activities specified in each unit to the satisfaction of
the instructor. Overall assessment of the outputs will be based on the following:
Semestral Grade:
Middle Term 40%
Final Term 60%
100%
Note:
For further inquiry you can reach this email account [email protected]
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 1
CONTENTS
Control Structures 38
If statement
If else statement
Nested if-else
Switch case statement
Note:
Coverage of this learning guide is until midterm only
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 2
INTRODUCTION TO PROGRAMMING LANGUAGE
Software Categories
• System SW
o Programs written for computer systems
▪ Compilers, operating systems, …
• Application SW
o Programs written for computer users
▪ Word-processors, spreadsheets, & other application packages
Computer Languages:
• Machine Language
– Uses binary code
– Machine-dependent
– Not portable
• Assembly Language
– Uses mnemonics
– Machine-dependent
– Not usually portable
• High-Level Language (HLL)
– Uses English-like language
– Machine independent
– Portable (but must be compiled for different platforms)
– Examples: Pascal, C, C++, Java, Fortran, . . .
Computer Programming
• A computer is a programmable machine. This means it can execute a programmed list of
instructions and respond to new instructions that it is given.
• Computer Programming is the process of developing and implementing various sets of
instructions to enable a computer to do a certain task.
• Programs are written to solve problems or perform tasks on a computer.
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 3
What is a program?
A program is something that is produced using a programming language.
Compiler
– A program that converts another program from some source language (or high-level
programming language / HLL) to machine language (object code).
– Some compilers output assembly language which is then converted to machine language by
a separate assembler.
Source program
– The form in which a computer program, written in some formal programming language, is
written by the programmer.
– Can be compiled automatically into object code or machine code or executed by an
interpreter.
– Pascal source programs have extension ‘.pas’ and java programs have an extension ‘.java’.
Compilation
Object program
– Output from the compiler
– Equivalent machine language translation of the source program
– Files usually have extension ‘.obj’
Executable program
– Output from linker/loader
– Machine language program linked with necessary libraries & other files
– Files usually have extension ‘.exe’
What is a Linker?
– A program that pulls other programs together so that they can run.
– Most programs are very large and consist of several modules.
– Even small programs use existing code provided by the programming environment called
libraries.
– The linker pulls everything together, makes sure that references to other parts of the
program (code) are resolved.
Program Errors
• Syntax Errors:
o Errors in grammar of the language
• Runtime error:
o When there are no syntax errors, but the program can’t complete execution
▪ Divide by zero
▪ Invalid input data
• Logical errors:
o The program completes execution, but delivers incorrect results
o Incorrect usage of parentheses
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 4
Algorithm
Constructing Algorithms:
1. Pseudo-code
2. Flowchart
Pseudocode
• Pseudocode is a computer programming language that resembles plain English that
cannot be compiled or executed, but explains a solution to a problem.
• Pseudocode is an informal way of programming description that does not require any
strict programming language syntax or underlying technology considerations
Flowchart
• A flowchart is a type of diagram that represents an algorithm or process.
Example:
Problem:
Write an algorithm to obtain or get a number from the user, calculate the product
multiplying by it by two and display the product
Pseudo-code: Flowchart:
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 5
Basic Flowchart Symbols:
Input/Output:
• Generalised Input/Output Block;
• Reading data from an input medium or
writing data to an output medium.
• This block should be used in situation
where data is being sent in and out of
the process.
Process:
• Any process step; an operation or
group of operations that cause a
change in value, form or location of the
data.
• This can consist of arithmetic or logical
operators or even more commands
Decision:
• Decision-making or switching type of
operation, usually based on a
comparison, that determines which of
a number of paths should be followed
Terminal:
• Terminal point in a flowchart – stop,
start or break in the line of flow
Flow line:
• sequence of operations and direction
of data flow; arrowheads are
required if linkage is not left-to-right
or top-to-bottom.
• Generally arrowheads are included to
avoid confusion
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 6
Example 2: (Using a selection structure)
Write a pseudocode and a flowchart that will calculate the salary and overtime pay of an
employee based on the input number of hours and rate of an employee. Consider the
40hours work per week and in exceed to that it is already an overtime. The overtime pay
is calculated as 50% more than the regular pay.
Pseudo-code: Flowchart:
Begin
End
Pseudocode: Flowchart
Begin
End
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 7
INTRODUCTION TO C++ PROGRAMMING
What is C++
▪ C++ (pronounced “see plus plus”) is a programming language began as an expanded version
of C programming language.
▪ C++ is a statically-typed, compiled, case-sensitive, free-form, (usually) combined, general
purpose programming language that supports procedural, object-oriented, and generic
programming.
▪ C++ is a middle level language, you will write code that interacts directly with the internal
hardware of the computer.
▪ C++ was initially known as “C with classes, ” and was renamed C++ in 1983. ++ is shorthand
for adding one to variety in programming; therefore C++ roughly means that “one higher
than C.”
▪ History of C
o Evolved from two other programming languages
▪ BCPL and B
• “Typeless” languages
o Dennis Ritchie (Bell Laboratories) in 1972
o Development language of UNIX
o Hardware independent
▪ Portable programs
▪ History of C++
o C++ programming language was developed in 1980 by Bjarne Stroustrup at bell
laboratories of AT&T (American Telephone & Telegraph), located in U.S.A.
o Bjarne Stroustrup is known as the founder of C++ language.
o It was developed for adding a feature of OOP (Object Oriented Programming) in C
without significantly changing the C component.
o C++ programming is "relative" (called a superset) of C, it means any valid C program
is also a valid C++ program.
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 8
C++ programs
▪ Built from pieces called classes and functions
C++
▪ Rich collections of existing classes and functions
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 9
Integrated Development Environment
▪ An integrated development environment (IDE) is a piece of software that contains all
the things you need to develop, compile, link, and debug your programs.
▪ With a typical C++ IDE, you get a code editor that does line numbering and syntax
highlighting.
▪ Many (but not all) IDEs include a C++ compiler and a linker, which the IDE will know
how to interface with, in order to convert your source code into an executable file.
Dev-C++ IDE
• Dev-C++ is a full-featured Integrated Development Environment (IDE) for the C/C++
programming language. As similar IDEs, it offers to the programmer a simple and unified
tool to edit, compile, link, and debug programs.
• It also provides support for the management of the files of a program in “projects”
containing all the elements required to produce a final executable program.
• Dev-C++ is a Free Software distributed under the terms of the GNU General Public License
(GPL). The IDE can be downloaded here:
http://prdownloads.sourceforge.net/dev-cpp/devcpp-4.9.9.2_setup.exe or it will be
provided by your instructor
Dev-C++ Environment
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 10
WRITING, COMPILING AND RUNNING YOUR FIRST C++ PROGRAM
Program: Output:
// my first program in C++ Hello World!
#include <iostream>
int main()
{
std::cout << "Hello World!";
}
As you program in C++, the most common header file you will use is iostream, the
controls for input and output. You can't write information to the screen or collect from the
user without it. In a C++ program, you use the command include followed by the library
name surrounded by carats (<iostream>).
The table below shows more header files that you will use in your programming.
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 11
Mathematical formulas (such as trig and
cmath Math functions
exponents)
array;
Arrays and vectors Needed when creating arrays or vectors
vector
stack Stacks Required for creating stacks
Exception handling Trap exceptions, which helps prevent program
exception
tools crashes.
The function named main is a special function in all C++ programs; it is the function called
when the program is run. The execution of all C++ programs begins with the main function,
regardless of where the function is actually located within the code.
Notice that the statement ends with a semicolon (;). This character marks the end of the
statement, just as the period ends a sentence in English. All C++ statements must end with
a semicolon character. One of the most common syntax errors in C++ is forgetting to end a
statement with a semicolon.
Comments
As noted, comments do not affect the operation of the program; however, they provide an
important tool to document directly within the source code what the program does and how it
operates.
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 12
// line comment
/* block comment */
• The first of them, known as line comment, discards everything from where the pair of
slash signs (//) are found up to the end of that same line.
• The second one, known as block comment, discards everything between the /* characters
and the first appearance of the */ characters, with the possibility of including multiple
lines.
#include <iostream>
int main ()
{
std::cout << "Hello World! "; // prints Hello World!
std::cout << "I'm a C++ program"; // prints I'm a C++ program
}
Output:
Hello World! I'm a C++ program
cout is part of the standard library, and all the elements in the standard C++ library are declared
within what is called a namespace: the namespace std.
The most typical way to introduce visibility of these components is by means of using declarations:
The above declaration allows all elements in the std namespace to be accessed in
an unqualified manner (without the std:: prefix).
The last example can be rewritten to make unqualified uses of cout as:
int main ()
{
cout << "Hello World! ";
cout << "I'm a C++ program";
}
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 13
Compiling and Running your program in DevC++ in your PC
1. Install the IDE DevC++ using the installer:
2. After the Installation, click the icon at your desktop or DevC++ from the start menu to open.
DevC++
DevC++
icon
3. Once open, click File, New, Source File to create a new file.
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 14
5. After typing your program save it, and assign a filename to your program:
Sample filename: Hello.cpp
Click Save
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 15
Output of the program:
Programming Activity#1:
Program Description:
Modify the Hello.cpp program above to display your name and course before the message “Hello
World! I’m a C++ program. Add one blank line after displaying your course. Write only one
additional “cout” statement for the added information.
Possible Output:
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 16
VARIABLES AND DATA TYPES
Let's imagine that you are ask to remember the number 5, and then ask you to also memorize the
number 2 at the same time. You have just stored two different values in your memory (5 and 2).
Now, if you are ask to add 1 to the first number, you should be retaining the numbers 6 (that is
5+1) and 2 in your memory. Then we could, for example, subtract these values and obtain 4 as
result.
The whole process described above is a simile of what a computer can do with two variables. The
same process can be expressed in C++ with the following set of statements:
a = 5;
b = 2;
a = a + 1;
result = a - b;
Obviously, this is a very simple example, since we have only used two small integer values, but
consider that your computer can store millions of numbers like these at the same time and conduct
sophisticated mathematical operations with them.
Each variable needs a name that identifies it and distinguishes it from the others. We could have
called the variables any names we could have come up with, as long as they were valid C++
identifiers.
Identifiers
valid identifier
▪ is a sequence of one or more letters, digits, or underscore characters (_). Spaces,
punctuation marks, and symbols cannot be part of an identifier.
▪ identifiers shall always begin with a letter. They can also begin with an underline
character (_).
▪ in no case can they begin with a digit.
The standard reserved keywords that cannot be used for programmer created identifiers are:
alignas, alignof, and, and_eq, asm, auto, bitand, bitor, bool, break, case,
catch, char, char16_t, char32_t, class, compl, const, constexpr, const_cast,
continue, decltype, default, delete, do, double, dynamic_cast, else, enum,
explicit, export, extern, false, float, for, friend, goto, if, inline, int, long,
mutable, namespace, new, noexcept, not, not_eq, nullptr, operator, or, or_eq,
private, protected, public, register, reinterpret_cast, return, short, signed,
sizeof, static, static_assert, static_cast, struct, switch, template, this,
thread_local, throw, true, try, typedef, typeid, typename, union, unsigned,
using, virtual, void, volatile, wchar_t, while, xor, xor_eq
Note:
The C++ language is a "case sensitive" language. That means that an identifier written in capital letters is not equivalent
to another one with the same name but written in small letters.
Example: the RESULT variable is not the same as the result variable or the Result variable.
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 17
These are three different identifiers identifiying three different variables.
Character types:
o They can represent a single character, such as 'A' or '$'. The most basic type
is char, which is a one-byte character. Other types are also provided for wider
characters.
Numerical integer types:
o They can store a whole number value, such as 7 or 1024. They exist in a variety of
sizes, and can either be signed or unsigned, depending on whether they support
negative values or not.
Floating-point types:
o They can represent real values, such as 3.14 or 0.01, with different levels of
precision, depending on which of the three floating-point types is used.
Boolean type:
o The boolean type, known in C++ as bool, can only represent one of two
states, true or false.
Declaration of variables
C++ is a strongly-typed language, and requires every variable to be declared with its type before its
first use. This informs the compiler the size to reserve in memory for the variable and how to
interpret its value. The syntax to declare a new variable in C++ is straightforward: we simply write
the type followed by the variable name (i.e., its identifier).
For example:
These are two valid declarations of variables. The first one declares a
int a; variable of type int with the identifier a. The second one declares a
float mynumber; variable of type float with the identifier mynumber. Once declared,
the variables a and mynumber can be used within the rest of their
scope in the program.
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 18
If declaring more than one variable of the same For Example:
type, they can all be declared in a single statement int a, b, c;
by separating their identifiers with commas.
This declares three variables (a, b and c), all of them of int a;
type int, and has exactly the same meaning as: int b;
int c;
#include <iostream> 4
using namespace std;
int main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
Initialization of variables
When the variables in the example above are declared, they have an undetermined value until they
are assigned a value for the first time. But it is possible for a variable to have a specific value from
the moment it is declared. This is called the initialization of the variable
there are three ways to initialize variables and they are all equivalent:
1. First method, consists of appending an equal sign followed by the value to which the
variable is initialized:
Syntax:
type identifier = initial_value;
For example, to declare a variable of type int called x and initialize it to a value of
zero from the same moment it is declared, we can write:
int x = 0;
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 19
2. A second method, known as constructor initialization (introduced by the C++ language),
encloses the initial value between parentheses (()):
Syntax:
type identifier (initial_value);
For example:
int x(0);
3. Finally, a third method, known as uniform initialization, similar to the above, but using
curly braces ({}) instead of parentheses:
Syntax:
type identifier {initial_value};
For example:
int x{0};
All three ways of initializing variables are valid and equivalent in C++:
#include <iostream> 6
using namespace std;
int main ()
{
int a=5; // initial value: 5
int b(3); // initial value: 3
int c{2}; // initial value: 2
int result; // initial value
//undetermined
a = a + b;
result = a - c;
cout << result;
return 0;
}
Introduction to strings
One of the major strengths of the C++ language is its rich set of compound types, of which the
fundamental types are mere building blocks.
An example of compound type is the string class. Variables of this type are able to store
sequences of characters, such as words or sentences.
A first difference with fundamental data types is that in order to declare and use objects
(variables) of this type, the program needs to include the header where the type is defined within
the standard library (header <string>):
int main ()
{
string mystring;
mystring = "This is a string";
cout << mystring;
return 0;
}
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 20
• strings can be initialized with any valid string literal, just like numerical type variables
can be initialized to any valid numerical literal. As with fundamental types, all
initialization formats are valid with strings:
Strings can also perform all the other basic operations that fundamental data types can, like
being declared without an initial value and change its value during execution:
// my first string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystring;
mystring = "This is the initial string content";
cout << mystring << endl;
mystring = "This is a different string content";
cout << mystring << endl;
return 0;
}
Note:
Inserting the endl manipulator ends the line (printing a newline character and flushing
the stream).
Literals
Literals
▪ are the most obvious kind of constants. They are used to express particular values
within the source code of a program. We have already used some in previous chapters
to give specific values to variables or to express messages we wanted our programs to
print out,
Integer Numerals
1776
707
-273
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 21
These are numerical constants that identify integer values. Notice that they are not enclosed in
quotes or any other special character; they are a simple succession of digits representing a whole
number in decimal base;
In addition to decimal numbers (those that most of us use every day), C++ allows the use of octal
numbers (base 8) and hexadecimal numbers (base 16) as literal constants. For octal literals, the
digits are preceded with a 0 (zero) character. And for hexadecimal, they are preceded by the
characters 0x (zero, x). For example, the following literal constants are all equivalent to each other:
75 // decimal
0113 // octal
0x4b // hexadecimal
These literal constants have a type, just like variables. By default, integer literals are of type int:
For example:
75 // int
75u // unsigned int
75l // long
75ul // unsigned long
75lu // unsigned long
Note: In all the cases above, the suffix can be specified using either upper or lowercase letters.
3.14159 // 3.14159
6.02e23 // 6.02 x 10^23
1.6e-19 // 1.6 x 10^-19
3.0 // 3.0
4.25 //double
3.14159L // long double
6.02e23f // float
'z'
'p'
"Hello world"
"How do you do?"
▪ The first two expressions represent single-character literals, and the following
two represent string literals composed of several characters.
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 22
▪ Notice that to represent a single character, we enclose it between single quotes
('), and to express a string (which generally consists of more than one character),
we enclose the characters between double quotes (").
Character and string literals can also represent special characters that are difficult or impossible to
express otherwise in the source code of a program, like newline (\n) or tab (\t). These special
characters are all of them preceded by a backslash character (\).
Other literals
Three keyword literals exist in C++: true, false and nullptr:
• true and false are the two possible values for variables of type bool.
• nullptr is the null pointer value.
We can then use these names instead of the literals they were defined to:
int main ()
{
double r=5.0; // radius
double circle;
circle = 2 * pi * r;
cout << circle;
cout << newline;
}
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 23
Preprocessor definitions (#define)
Another mechanism to name constant values is the use of preprocessor definitions. They have
the following form:
After this directive, any occurrence of identifier in the code is interpreted as replacement, where
replacement is any sequence of characters (until the end of the line). This replacement is performed
by the preprocessor, and happens before the program is compiled, thus causing a sort of blind
replacement: the validity of the types or syntax involved is not checked in any way.
For Example:
#include <iostream> Output:
using namespace std;
31.4159
#define PI 3.14159
#define NEWLINE '\n'
int main ()
{
double r=5.0; // radius
double circle;
circle = 2 * PI * r;
cout << circle;
cout << NEWLINE;
Note:
• the #define lines are preprocessor directives, and as such are single-line instructions that -
unlike C++ statements- do not require semicolons (;) at the end;
• the directive extends automatically until the end of the line. If a semicolon is included in
the line, it is part of the replacement sequence and is also included in all replaced
occurrences.
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 24
EXPRESSIONS AND OPERATORS
Operators
Once introduced to variables and constants, we can begin to operate with them by using operators.
Assignment operator(=)
• The assignment operator assigns a value to a variable.
For Example:
x = 5;
This statement assigns the integer value 5 to the variable x. The assignment operation always
takes place from right to left, and never the other way around:
x = y;
This statement assigns to variable x the value contained in variable y. The value of x at the
moment this statement is executed is lost and replaced by the value of y.
For example:
// assignment operator Output:
#include <iostream>
a:4 b:7
using namespace std;
int main ()
{
int a, b; // a:?, b:?
a = 10; // a:10, b:? This program prints on
b = 4; // a:10, b:4 screen the final values
a = b; // a:4, b:4 of a and b (4 and 7,
b = 7; // a:4, b:7 respectively).
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 25
Arithmetic operators ( +, -, *, /, % )
The five arithmetical operations supported by C++ are:
For example:
x = 11 % 3; results in variable x containing the value 2, since
dividing 11 by 3 results in 3, with a remainder of 2.
Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
Compound assignment operators modify the current value of a variable by performing an operation
on it. They are equivalent to assigning the result of an operation to the first operand:
For example:
int main ()
{
int a, b=3;
a = b;
a+=2; // equivalent to a=a+2
cout << a;
}
• It can be used both as a prefix and as a suffix. That means that it can be written either
before the variable name (++x) or after it (x++).
• Although in simple expressions like x++ or ++x, both have exactly the same meaning; in
other expressions in which the result of the increment or decrement operation is
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 26
evaluated, they may have an important difference in their meaning: In the case that the
increase operator is used as a prefix (++x) of the value, the expression evaluates to the final
value of x, once it is already increased.
• On the other hand, in case that it is used as a suffix (x++), the value is also increased, but
the expression evaluates to the value that x had before being increased.
Relational and comparison operators ( ==, !=, >, <, >=, <= )
Two expressions can be compared using relational and equality operators. For example, to know
if two values are equal or if one is greater than the other.
Examples:
• The assignment operator (operator =, with one equal sign) is not the same as the equality
comparison operator (operator ==, with two equal signs);
• the first one (=) assigns the value on the right-hand to the variable on its left, while the
other (==) compares whether the values on both sides of the operator are equal.
• Therefore, in the last expression ((b=2) == a), we first assigned the value 2 to b and
then we compared it to a (that also stores the value 2), yielding true.
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 27
For Example:
The logical operators && and || are used when evaluating two expressions to obtain a single
relational result. The operator && corresponds to the Boolean logical operation AND, which
yields true if both its operands are true, and false otherwise.
The operator || corresponds to the Here are the possible results of a||b:
Boolean logical operation OR, which
yields true if either of its operands
is true, thus being false only when both
operands are false.
For Example:
• When using the logical operators, C++ only evaluates what is necessary from left to
right to come up with the combined relational result, ignoring the rest.
• Therefore, in the last example ((5==5)||(3>6)), C++ evaluates first
whether 5==5 is true, and if so, it never checks whether 3>6 is true or not.
• This is known as short-circuit evaluation, and works like this for these operators:
If condition is true, the entire expression evaluates to result1, and otherwise to result2.
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 28
For example:
// conditional operator Output:
#include <iostream> 7
using namespace std;
Comma operator ( , )
The comma operator (,) is used to separate two or more expressions that are included where only
one expression is expected. When the set of expressions has to be evaluated for a value, only the
right-most expression is considered.
would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end,
variable a would contain the value 5 while variable b would contain value 3.
int i;
float f = 3.14;
i = (int) f;
The previous code converts the floating-point number 3.14 to an integer value (3); the
remainder is lost. Here, the typecasting operator was (int). Another way to do the same thing in
C++ is to use the functional notation preceding the expression to be converted by the type and
enclosing the expression between parentheses:
i = int (f);
sizeof
This operator accepts one parameter, which can be either a type or a variable, and returns the
size in bytes of that type or object:
x = sizeof (char);
Here, x is assigned the value 1, because char is a type with a size of one byte.
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 29
Precedence of operators
A single expression may have multiple operators.
For example:
x = 5 + 7 % 2;
In C++, the above expression always assigns 6 to variable x, because the % operator has a
higher precedence than the + operator, and is always evaluated before. Parts of the expressions
can be enclosed in parenthesis to override this precedence order, or to make explicitly clear the
intended effect. Notice the difference:
From greatest to smallest priority, C++ operators are evaluated in the following order:
Operator(s) Operation(s) Order of evaluation (precedence)
++, -- Unary Evaluated first. Evaluated from left to right
() Parentheses Evaluated next. If the parentheses are nested, the
expression in the innermost pair is evaluated
first. If there are several pairs of parentheses “on
the same level” (not nested), they are evaluated
left to right.
*,/, % Multiplication Evaluated next. If there are several, they are
Division Modulus evaluated left to right.
+ or - Addition Subtraction Evaluated next. If there are several, they are
evaluated left to right.
< > <= >= Relational Comparison operators
== != Equality Equality, inequality
|| && Logical OR, AND
, Sequencing Comma Separator will be evaluated last.
Note:
When an expression has two operators with the same precedence level, grouping determines
which one is evaluated first: either left-to-right or right-to-left.
Example:
Evaluate if each of the following statement is true or false.
1. 1/2 +3 > 4– 2 || 21 - -4 > 30 && 8 < 10;
True || False && True
True || False
Answer: True
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 30
C++ Math functions
• C++ has many functions that allows you to perform mathematical tasks on numbers.
• The C++ <cmath> header file declares a set of functions to perform mathematical
operations such as: sqrt() to calculate the square root, log() to find natural logarithm of
a number etc.
Example:
Output:
Compute Cosine
• Returns the cosine of an angle of x radians.
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 31
exp(x) Returns the value of Ex
expm1(x) Returns ex -1
Create a C++ program that will ask the user to enter the two sides of a right triangle and will
calculate the hypotenuse side and the two acute angles. (For the angles round off your answers
to a whole number, use round() function)
Sample/Possible Output:
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 32
Basic Input/Output
• C++ uses a convenient abstraction called streams to perform input and output operations
in sequential media such as the screen, the keyboard or a file.
• A stream is an entity where a program can either insert or extract characters to/from.
There is no need to know details about the media associated to the stream or any of its
internal specifications. All we need to know is that streams are a source/destination of
characters, and that these characters are provided/accepted sequentially.
The standard library defines a handful of stream objects that can be used to access what are
considered the standard sources and destinations of characters by the environment where the
program runs:
We are going to see in more detail only cout and cin (the standard output and input
streams); cerr and clog are also output streams, so they essentially work like cout, with the
only difference being that they identify streams for specific purposes: error messages and logging;
which, in many cases, in most environment setups, they actually do the exact same thing: they print
on screen, although they can also be individually redirected.
• The << operator inserts the data that follows it into the stream that precedes it. In the
examples above, it inserted the literal string Output sentence, the number 120, and the
value of variable x into the standard output stream cout.
• Notice that the sentence in the first statement is enclosed in double quotes (") because it
is a string literal, while in the last one, x is not. The double quoting is what makes the
difference; when the text is enclosed between them, the text is printed literally; when they
are not, the text is interpreted as the identifier of a variable, and its value is printed instead.
This last statement would print the text This is a single C++ statement. Chaining insertions
is especially useful to mix literals and variables in a single statement:
Assuming the age variable contains the value 24 and the zipcode variable contains 90064, the
output of the previous statement would be:
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 33
What cout does not do automatically is add line breaks at the end, unless instructed to do so.
For example, take the following two statements inserting into cout:
The output would be in a single line, without any line breaks in between.
Something like:
To insert a line break, a new-line character shall be inserted at the exact position the line should
be broken. In C++, a new-line character can be specified as \n (i.e., a backslash character followed
by a lowercase n).
For example:
The endl manipulator produces a newline character, exactly as the insertion of '\n' does.
• The first statement declares a variable of type int called age, and the second extracts
from cin a value to be stored in it.
• This operation makes the program wait for input from cin; generally, this means that the
program will wait for the user to enter some sequence with the keyboard.
• In this case, note that the characters introduced using the keyboard are only transmitted
to the program when the ENTER (or RETURN) key is pressed. Once the statement with the
extraction operation on cin is reached, the program will wait for as long as needed until
some input is introduced.
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 34
The extraction operation on cin uses the type of the variable after the >> operator to determine
how it interprets the characters read from the input;
if it is an integer, the format expected is a series of digits, if a string a sequence of characters,
etc.
Example:
Output:
Extractions on cin can also be chained to request more than one datum in a single statement:
However, cin extraction always considers spaces (whitespaces, tabs, new-line...) as terminating the
value being extracted, and thus extracting a string means to always extract a single word, not a
phrase or an entire sentence.
To get an entire line from cin, there exists a function, called getline, that takes the stream
(cin) as first argument, and the string variable as second.
For example:
Output:
What the program does in the second call is simply replace the previous content with the new
one that is introduced.
The standard behavior that most users expect from a console program is that each time the
program queries the user for input, the user introduces the field, and then presses ENTER (or
RETURN).
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 35
That is to say, input is generally expected to happen in terms of lines on console programs, and this
can be achieved by using getline to obtain input from the user. Therefore, unless you have a strong
reason not to, you should always use getline to get input in your console programs instead of
extracting from cin.
stringstream
The standard header <sstream> defines a type called stringstream that allows a string to be
treated as a stream, and thus allowing extraction or insertion operations from/to strings in the
same way as they are performed on cin and cout. This feature is most useful to convert strings to
numerical values and vice versa.
This declares a string with initialized to a value of "1204", and a variable of type int. Then, the
third line uses this variable to extract from a stringstream constructed from the string. This
piece of code stores the numerical value 1204 in the variable called myint.
Output:
In this example, we acquire numeric values from the standard input indirectly: Instead of extracting
numeric values directly from cin, we get lines from it into a string object (mystr), and then we extract
the values from this string into the variables price and quantity. Once these are numerical values,
arithmetic operations can be performed on them, such as multiplying them to obtain a total price.
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 36
Programming Activity No. 3:
a. Create a C++ program that will count the equivalent number of months, weeks, days and extra
hours from the entered number of hours. (Consider that there are 30 days in a month)
Sample/Possible Output:
----------------------------------------------------------------------------------------------------------------------
Please enter number of hours: 1000 (1000 is the entered value)
b. Create a program that will ask to enter your name (complete name), age and course. Your
program will display the message as shown below:
Sample/Possible Output:
--------------------------------------------------------------------------------------------------------------
Enter your name:
Enter your age:
Enter your course:
My Name is (Complete here) and in ten years time I’m (age +10 here) years old.
Taking up (course appears here).
--------------------------------------------------------------------------------------------------------------------------
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 37
CONTROL STRUCTURES
A simple C++ statement is each of the individual instructions of a program, like the variable
declarations and expressions always end with a semicolon (;), and are executed in the same order
in which they appear in a program.
• This statement may either be a simple C++ statement, -such as a single instruction, terminated
with a semicolon (;) - or a compound statement.
• A compound statement is a group of statements (each of them terminated by its own
semicolon), but all grouped together in a block, enclosed in curly braces: {}:
• The entire block is considered a single statement (composed itself of multiple substatements).
Whenever a generic statement is part of the syntax of a flow control statement, this can either
be a simple statement or a compound statement.
if (condition) statement
If you want to include more than a single statement to be executed when the condition is
fulfilled, these statements shall be enclosed in braces ({}), forming a block:
As usual, indentation and line breaks in the code have no effect, so the above code is
equivalent to:
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 38
if else statement
Selection statements with if can also specify what happens when the condition is not fulfilled, by
using the else keyword to introduce an alternative statement.
where:
- statement1 is executed in case condition is true, and
- in case it is not, statement2 is executed.
For example:
Several if + else structures can be concatenated with the intention of checking a range of values.
For example:
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 39
Example of a nested if/else if structure :
Syntax:
When a case constant is found that matches the switch expression, control of the program passes
to the block of code associated with that case.
In the above pseudocode, suppose the value of n is equal to constant2. The compiler will execute
the block of code associated with the case statement until the end of switch block, or until
the break statement is encountered
The break statement is used to prevent the code running into the next case.
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 40
Example of switch.. case
Output:
Sample/Possible Output:
------------------------------------------------------------------------------------------------------------
Please enter three numbers:
10
15
12
The largest number is: 15
-----------------------------------------------------------------------------------------------------------
b. Create a C++ program using switch case statement to perform the required operations as
specified. Your program allows the user to enter an integer value and select the different
options for a specific operation. A sample user-interaction is shown below:
Sample/Possible Output:
----------------------------------------------------------------------------------------------------------------
Please enter a number: 4
Choices:
[A] or [a] to determine the sign of the entered number
[S] or [s] to display the square and the square root of the entered number
[C} or [c] to display the cube and the cube root of the entered number
[Any letter] display the message “You entered an invalid letter”
GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 41