0% found this document useful (0 votes)
64 views

Com Prog

This document provides an outline for a computer programming course. It introduces fundamental programming concepts such as software categories, programming languages, compilers, and errors. It also describes the basics of C++ programming, including writing, compiling, and running a simple program. The outline covers variables and data types, expressions and operators, and basic control structures like if/else statements and switch cases. Students will be assessed based on programming assignments and exams.

Uploaded by

Gel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views

Com Prog

This document provides an outline for a computer programming course. It introduces fundamental programming concepts such as software categories, programming languages, compilers, and errors. It also describes the basics of C++ programming, including writing, compiling, and running a simple program. The outline covers variables and data types, expressions and operators, and basic control structures like if/else statements and switch cases. Students will be assessed based on programming assignments and exams.

Uploaded by

Gel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Agusan del Sur State College of Agriculture and Technology

COLLEGE OF ENGINEERING AND INFORMATION SCIENCES


Bunawan, Agusan del Sur

GE ELEC3

Learning Guide

Bachelor of Science in Agricultural and Biosystems Engineering

JOCELYN O. BALOLOT
Instructor

1st Semester A.Y. 2020-2021


GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 1
GE ELEC3
Computer Programming

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.

Credit Units: 3 units

Number of Hours: 2 hours lecture


3 hours laboratory

Semester Offered: 1st semester

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:

Students Output 60%


Term Exam 40%
100%

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

Title Page No.

Introduction to Programming Language 3


Software Categories
Computer Languages
What is a programming language
Compilers and Linkers
Program Execution and Errors
Pseudocode and Flowchart

Introduction to C++ Programming 8


C++ Definition
History of C and C++
Phases of C++
Integrated Development Environment

Writing, Compiling and Running Your First Program 11


Structure of a C++ program
Comments
Using namespace std
Common input/output functions
main Function
Compiling and Running your program

Variables and Data Types 17


Identifiers
Fundamental data types
Declaration, Initialization of Variables
Introduction to Strings
Literals
Typed Constant Expressions
Preprocessor Definitions

Expressions and Operators 25


Assignment Operators
Arithmetic Operators
Compound Assignment
Increment and Decrement Operators
Relational Operators
Logical Operators
Conditional Ternary operator
Explicit type casting operator
Precedence of Operatoors
Math functions
Basic Input/Ouput

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

A Layered View of the Computer

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.

What is a Programming Language


• A programming language is a set of rules that provides a way of telling a computer what
operations to perform.
• English is a natural language. It has words, symbols and grammatical rules.
• A programming language also has words, symbols and rules of grammar.
• The grammatical rules are called syntax.
• Each programming language has a different set of syntax rules.

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

– Compiler translates source into target (a machine language program)


– Compiler goes away at execution time
– Compiler is itself a machine language program, presumably created by compiling some
other high-level program.

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

An algorithm is a list of instructions, procedures, or formulas used to solve a problem.

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

• An English-like representation of the logical steps it takes to solve a problem.


– pseudo – prefix that means false
– Short English-Like Statements
– Not Standardized
– Proper use of indentation

Flowchart
• A flowchart is a type of diagram that represents an algorithm or process.

• The purpose of a flowchart is to provide people with a common language or reference


point when dealing with a project or process.

• A pictorial representation of the logical steps it takes to solve a problem.


– Uses Standardized Symbols
– Utilize Formula Notation
– Typically Read from Top to Bottom or from Left to Right on a Page

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

Example 3: (Iteration with a while loop)


The pseudocode and flowchart below will display the average of ten numbers from 1 to
10 using a while loop structure.

Pseudocode: Flowchart
Begin

End

Learning Activity #1:


1. Create an algorithm (pseudocode and flowchart) to calculate and display the area of a
circle with the entered diameter of the circle.
2. Create an algorithm for a program that will allow the user to enter two numbers and will
display the larger number.
3. Create an algorithm for a program that will display the even numbers from 0 to 10.

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.

History of C and C++

▪ 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.

Languages that were developed before C++ programming language:

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

Basics of a Typical C++ Environment


• C++ Systems
o Program-development environment
o Language
o C++ Standard Library
• C++ program names extensions
o .cpp
o .cxx
o .cc
o .c

Phases of C++ Programs:


1. Edit
2. Preprocess
3. Compile
4. Link
5. Load
6. Execute

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

• To install Dev-C++ just double click the file:

• Follow the instruction in the installation process

GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 10
WRITING, COMPILING AND RUNNING YOUR FIRST C++ PROGRAM

Structure of a C++ program


The best way to learn a programming language is by writing programs. Typically, the first program
beginners write is a program called "Hello World", which simply prints "Hello World" to your
computer screen. Although it is very simple, it contains all the fundamental components C++
programs have:

Program: Output:
// my first program in C++ Hello World!
#include <iostream>

int main()
{
std::cout << "Hello World!";
}

Line 1: // my first program in C++


Two slash signs indicate that the rest of the line is a comment inserted by the programmer
but which has no effect on the behavior of the program. Programmers use them to include
short explanations or observations concerning the code or program. In this case, it is a brief
introductory description of the program.

Line 2: #include <iostream>


Lines beginning with a hash sign (#) are directives read and interpreted by what is known
as the preprocessor. They are special lines interpreted before the compilation of the
program itself begins. In this case, the directive #include <iostream>, instructs the
preprocessor to include a section of standard C++ code, known as header iostream, that
allows to perform standard input and output operations, such as writing the output of this
program (Hello World) to the screen.

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.

Function Description Example(s)


iostream Input/output Controls for input and output
cstring Functions for strings Create string variables\compare strings
Memory allocation\numeric string
cstdlib Miscellaneous utilities
conversion\process control
running time\clock\time
ctime Date and time
calculations/conversions

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.

Line 3: A blank line.


Blank lines have no effect on a program. They simply improve readability of the code.

Line 4: int main ()


This line initiates the declaration of a function. Essentially, a function is a group of code
statements which are given a name: in this case, this gives the name "main" to the group
of code statements that follow. Functions will be discussed in detail in a later chapter, but
essentially, their definition is introduced with a succession of a type (int), a name (main)
and a pair of parentheses (()), optionally including parameters.

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.

Lines 5 and 7: { and }


The open brace ({) at line 5 indicates the beginning of main's function definition, and the
closing brace (}) at line 7, indicates its end. Everything between these braces is the
function's body that defines what happens when main is called. All functions use braces to
indicate the beginning and end of their definitions.

Line 6: std::cout << "Hello World!";


This line is a C++ statement. A statement is an expression that can actually produce some
effect. It is the meat of a program, specifying its actual behavior. Statements are executed
in the same order that they appear within a function's body.

This statement has three parts:


• First, std::cout, which identifies the standard character output device (usually, this
is the computer screen).
• Second, the insertion operator (<<), which indicates that what follows is inserted
into std::cout.
• Finally, a sentence within quotes ("Hello world!"), is the content inserted into the
standard output.

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.

C++ supports two ways of commenting code:

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.

Adding comments to a program:


/* my second program in C++
with more comments */

#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

Using namespace std


If you have seen C++ code before, you may have seen cout being used instead of std::cout. Both
name the same object: the first one uses its unqualified name (cout), while the second qualifies it
directly within the namespace std (as std::cout).

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:

using namespace std;

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:

// my second program in C++


#include <iostream>
using namespace std;

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.

Desktop start menu

DevC++
DevC++
icon

3. Once open, click File, New, Source File to create a new file.

4. Type the your


program.

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

Type Hello.cpp here

Click Save

Hello.cpp as your filename

To Run or Execute your program click execute


at the menu bar and you can either:
1. Click Compile
2. ( After compilation process)
Click Run
Or
1. Click Compile & Run

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

Variables and types


Programming is not limited only to printing simple texts on the screen. In order to go a little further
on and to become able to write programs that perform useful tasks that really save us work, we
need to introduce the concept of variables.

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.

We can now define variable as a portion of memory to store a value.

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.

Fundamental data types


Fundamental data types are basic types implemented directly by the language that represent the
basic storage units supported natively by most systems. They can mainly be classified into:

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.

Complete list of fundamental types in C++:

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;

Sample Program to illustrates how variables look like within a program.

// operating with variables Output:

#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;

// print out the result:


cout << result;

// terminate the program:


return 0;
}

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++:

// initialization of variables Output:

#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>):

// my first string Output:


#include <iostream>
#include <string> This is a string
using namespace std;

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:

string mystring = "This is a string";


string mystring ("This is a string");
string mystring {"This is a string"};

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;
}

Output: This is the initial string content


This is a different string content

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,

for example, when we wrote:


a = 5; The 5 in this piece of code was a literal constant.

Literal constants can be classified into:


▪ integer
▪ floating-point
▪ characters
▪ strings
▪ Boolean
▪ pointers, and
▪ user-defined literals.

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.

Floating Point Numerals


They express real values, with decimals and/or exponents. They can include either a decimal
point, an e character or both a decimal point and an e character.

3.14159 // 3.14159
6.02e23 // 6.02 x 10^23
1.6e-19 // 1.6 x 10^-19
3.0 // 3.0

These are four valid numbers with decimals expressed in C++.


▪ The first number is PI,
▪ the second one is the number of Avogadro,
▪ the third is the electric charge of an electron (an extremely small number) -all of them
approximated-,
▪ and the last one is the number three expressed as a floating-point numeric literal.

4.25 //double
3.14159L // long double
6.02e23f // float

Character and string literals


Character and string literals are enclosed in quotes:

'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 (\).

Here you have a list of the single character escape codes:

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.

bool foo = true;


bool bar = false;
int* p = nullptr;

Typed constant expressions


Sometimes, it is just convenient to give a name to a constant value:

const double pi = 3.1415926;


const char tab = '\t';

We can then use these names instead of the literals they were defined to:

#include <iostream> Output:


using namespace std;
31.4159
const double pi = 3.14159;
const char newline = '\n';

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:

#define identifier replacement

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).

cout << "a:";


cout << a;
cout << " b:";
cout << b;
}

Assignment operations are expressions that can be For Example:


evaluated. That means that the assignment itself has a
y = 2 + (x = 5);
value, and -for fundamental types- this value is the one
assigned in the operation.

In this expression, y is assigned the result of adding 2 and


the value of another assignment expression (which has x = 5;
itself a value of 5). It is roughly equivalent to: y = 2 + x;

With the final result of assigning 7 to y.

The following expression is also valid in C++:


x = y = z = 5;

It assigns 5 to the all three variables: x, y and z; always from right-to-left.

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:

• Operations of addition, subtraction, multiplication and division correspond


literally to their respective mathematical operators.
• The last one, modulo operator, represented by a percentage sign (%), gives the
remainder of a division of two values.

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:

and the same for all other compound assignment operators.

For example:

// compound assignment operators Output:


#include <iostream> 5
using namespace std;

int main ()
{
int a, b=3;
a = b;
a+=2; // equivalent to a=a+2
cout << a;
}

Increment and decrement (++, --)


Some expression can be shortened even more: the increase operator (++) and the decrease
operator (--) increase or reduce by one the value stored in a variable. They are equivalent
to +=1 and to -=1, respectively.
Thus:
++x;
x+=1; are all equivalent in its functionality; the three of them
x=x+1; increase by one the value of x.

• 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.

Notice the difference:

• In Example 1, the value assigned to y is the value of x after being increased.


• While in Example 2, it is the value 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.

The result of such an operation is either true or false (a Boolean value).

The relational operators in C++ are:

Examples:

Suppose that a=2, b=3 and c=6, then:

• 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.

Logical operators ( !, &&, || )


The operator ! is the C++ operator for the Boolean operation NOT. It has only one operand, to its
right, and inverts it, producing false if its operand is true, and true if its operand is false. Basically,
it returns the opposite Boolean value of evaluating its operand.

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 following panel shows the result of


operator && evaluating the
expression a&&b:

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:

Conditional ternary operator ( ? )


The conditional operator evaluates an expression, returning one value if that expression
evaluates to true, and a different one if the expression evaluates as false.
Its syntax is:
condition ? result1 : result2

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;

int main () In this example, a was 2, and b was 7, so


{
int a,b,c; the expression being evaluated (a>b) was
a=2; not true, thus the first value specified
b=7; after the question mark was discarded in
c = (a>b) ? a : b;
favor of the second value (the one after the
cout << c << '\n';
} colon) which was b (with a value of 7).

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.

For example, the following code:


a = (b=3, b+2);

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.

Explicit type casting operator


Type casting operators allow to convert a value of a given type to another type. There are several
ways to do this in C++. The simplest one, which has been inherited from the C language, is to
precede the expression to be converted by the new type enclosed between parentheses (()):

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);

Both ways of casting types are valid in C++.

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.

The value returned by sizeof is a compile-time constant, so it is always determined before


program execution.

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

2. !(8==16/4) ||(20<12/3+20) && (5+4==3*3)


! FALSE || False && True
TRUE || False
Answer = TRUE

Learning Activity #2:


1. 10 - -14 <= 20 && (10>= 20 || 5+6 >= 20) && 12>=25/3
2. ! (20 > 8) && 25!=20 || 5 + 20== 35 - 10;

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.

Max and min functions


• The max (x, y) function can be used to find the highest value of x and y:
• The min(x,y) function can be used to find the lowest value of x and y:

C++ <cmath> Header


• Other functions, such as sqrt (square root), round (rounds a number) and log (natural
logarithm), can be found in the <cmath> header file:

Other Math Functions


A list of other popular Math functions (from the <cmath> library) can be found in the table below:
Function Description

abs(x) Returns the absolute value of x

acos(x) Returns the arccosine of x, in radians

asin(x) Returns the arcsine of x, in radians

atan(x) Returns the arctangent of x, in radians

cbrt(x) Returns the cube root of x

ceil(x) Returns the value of x rounded up to its nearest integer

cos(x) Returns the cosine of x, in radians

cosh(x) Returns the hyperbolic cosine of x, in 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

fabs(x) Returns the absolute value of a floating x

fdim(x, y) Returns the positive difference between x and y

floor(x) Returns the value of x rounded down to its nearest integer

hypot(x, y) Returns sqrt(x2 +y2) without intermediate overflow or underflow

fma(x, y, z) Returns x*y+z without losing precision

fmax(x, y) Returns the highest value of a floating x and y

fmin(x, y) Returns the lowest value of a floating x and y

fmod(x, y) Returns the floating point remainder of x/y

pow(x, y) Returns the value of x to the power of y

sin(x) Returns the sine of x (x is in radians)

sinh(x) Returns the hyperbolic sine of a double value

tan(x) Returns the tangent of an angle

tanh(x) Returns the hyperbolic tangent of a double value

Programming Activity No. 2:

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.

Standard output (cout)


• The standard output by default is the screen, and the C++ stream object defined to access
it is cout.
• cout is used together with the insertion operator, which is written as << (i.e., two "less
than" signs).

• 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.

For example, these two sentences have very different results:

Multiple insertion operations (<<) may be chained in a single statement:

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:

I am 24 years old and my zipcode is 90064

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:

cout << "This is a sentence.";


cout << "This is another sentence.";

The output would be in a single line, without any line breaks in between.
Something like:

This is a sentence.This is another sentence.

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:

This produces the following output:


First sentence.
Second sentence.
Third sentence.

Alternatively, the endl manipulator can also be used to break lines.


For example:

This would print:


First sentence.
Second sentence.

The endl manipulator produces a newline character, exactly as the insertion of '\n' does.

Standard input (cin)


• The standard input by default is the keyboard, and the C++ stream object defined to access
it is cin.
• cin is used together with the extraction operator, which is written as >> (i.e., two "greater
than" signs). This operator is then followed by the variable where the extracted data is
stored.
For example:

• 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:

This is equivalent to:

cin and strings


The extraction operator can be used on cin to get strings of characters in the same way as with
fundamental data types:

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.

For example, in order to extract an integer from a string we can write:

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)

1000 hours is equivalent to:


Month/s: 1
Week/s: 1
Da/ys: 4
Hour/s: 16
--------------------------------------------------------------------------------------------------------------------

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: {}:

{ statement1; statement2; statement3; }

• 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.

Selection statements: if and else


The if keyword is used to execute a statement or block, if, and only if, a condition is fulfilled. Its
syntax is:

if (condition) statement

• Here, condition is the expression that is being evaluated. If this condition is


true, statement is executed. If it is false, statement is not executed (it is simply ignored),
and the program continues right after the entire selection statement.
• For example, the following code fragment prints the message (x is 100), only if the value
stored in the x variable is indeed 100:

- If x is not exactly 100, this statement is ignored, and nothing is printed.

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.

Its syntax is:


if (condition) statement1 else statement2

where:
- statement1 is executed in case condition is true, and
- in case it is not, statement2 is executed.

For example:

This prints x is 100, if indeed x has a value of 100, but if it


does not, and only if it does not, it prints x is not
100 instead.

Several if + else structures can be concatenated with the intention of checking a range of values.

For example:

This prints whether x is positive, negative, or zero by


concatenating two if-else structures. Again, it would have also
been possible to execute more than a single statement per case
by grouping them into blocks enclosed in braces: { }.

If/else Selection Structure (using ternary conditional operator)

• Ternary Conditional Operator (?:)


- Three arguments (condition, value if true, value if false)
• Code could be written:

Nested if/else structure

- One inside another, test for multiple cases


- Once condition is met, other statements skipped

GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 39
Example of a nested if/else if structure :

Switch.. case statement

Switch case statement


- is used when we have multiple conditions and we need to perform different action
based on the condition. When we have multiple conditions and we need to execute a
block of statements when a particular condition is satisfied. In such case either we
can use lengthy if..else-if statement or switch case. The problem with lengthy if..else-
if is that it becomes complex when we have several conditions.
- The switch case is a clean and efficient method of handling such scenarios

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:

Programming Activity No. 4:


a. Create a C++ program that will allow the users to enter three values and will display which one
is the larger number.

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”

Please enter a letter: S


The square of 4 is: 16
The square root of 4 is: 2.
---------------------------------------------------------------------------------------------------------------

GE Elec3 - Computer Programming CEIS-ASSCAT, Bunawan, Agusan del Sur | JOCELYN O. BALOLOT - Instructor 41

You might also like