Local Media5611721699851897771
Local Media5611721699851897771
PREFACE
                                                                                ii
         Activity: What Do You Already Know About?
Pre-Assessment Test
                                                                             iii
                             TABLE OF CONTENTS
Preface                                                                 ii
Pre-Assessment Test                                                     iii
Unit 1. Programming Concepts                                            1
            A.   Software                                               1
            B.   Programmers                                            1
            C.   Hardware                                               2
            D.   Problem Solving                                        2
            E.   Elements of Programming                                4
            F.   Programming Paradigms                                  5
                                                                            v
UNIT 1. PROGRAMMING CONCEPTS
       Learning Objectives
       At the end of the unit, I am able to:
            1. define software and hardware;
            2. identify types of programmers;
            3. explain the steps of problem solving;
            4. identify the elements of programming; and
            5. classify the programming paradigms.
A. SOFTWARE
        A software is a collection of codes that instructs the computer on what it
will do. Another term for software is computer program. For complicated or large
programs, say, the NEUST enrolment system, the program is consists of two sets
of codes, the first are codes that instruct the computer and the second set is
consists of codes which contain data. The lists of instructions are called program
codes and the process of typing these codes into a computer is called program
coding or simply coding.
B. PROGRAMMERS
   The people who write program codes are called programmers. Programmers
are classified as:
   1. SYSTEM PROGRAMMERS
               These are the people who create and maintain programs which are
      involved in the computer’s basic operating functions like operating systems,
      utilities and device drivers.
   2. APPLICATION PROGRAMMERS
             They are the ones who create and maintain programs that have
      specific functions such as Point Of Sale (POS) programs that calculate and
      generate the payroll report of a certain company, and others.
                                                                                 1
       TYPES OF APPLICATION PROGRAMMERS
         • DATABASE APPLICATION PROGRAMMERS
         • WEB APPLICATION PROGRAMMERS
         • GAME DEVELOPERS
         • MICRO DEVICES PROGRAMMERS
C. HARDWARE
      The physical components of a computer system is called hardware. It may
be consisted of the CPU, the keyboard, the LCD screen and other peripherals like
mouse, printer, webcam, etc. These are the tangible parts of the computer system
which you can touch.
D. PROBLEM SOLVING
       Just like when writing a term paper, the first step in creating an effective
program is proper thought and preparation. Planning for the final output is very
important so as to have the solution that you are picturing in your mind for a
particular problem.
STEPS IN PROGRAMMING
       The following figure illustrates the steps that a programmer should follow in
creating C++ programs:
PLANNING
                                                        DOCUMENTATION
                        ANALYSIS
DESIGN
DEVELOPMENT
                                                               TESTING &
                                                              DEBUGGING
                                                                                  2
1. PLANNING
       The planning stage revolves around the determination of the requirements,
then setting the processes by which these goals are to be achieved.
2. ANALYSIS
        In the analysis stage, you must determine the precise objectives     that
you want to achieve to create a solution to the presented problem. The material
that the program generates is called OUTPUT. A FILE, which is stored by name,
is a collection of information. A file may contain data, a program or some other
document.
        After deciding what the output will be, you should determine the information
that is needed to achieve your objectives. These data that the program requires to
produce the desired results are called INPUT.
       Next will be to decide what will be the major steps required for processing
the input to produce the output. A PROCESS is a mechanism for converting input
to output.
3. DESIGN
      After analyzing the problem, we use this analysis to design a solution. You
can use modeling tools to guide you in designing a solution to the problem.
Examples of such tools are flowcharts and algorithms.
4. DEVELOPMENT
       In this step, you translate the design into a program. Writing computer
instructions using any of the available programming languages is called CODING.
These computer instructions or simply statements are called CODES.
5. TESTING AND DEBUGGING
       Testing the problem’s solution on the computer overlaps with the design
and development phases. Testing is done so that all the computer errors or simply
called BUGS will be eliminated or corrected and the process of correcting errors is
referred to as DEBUGGING.
DOCUMENTATION
       Documentation means that you have to create materials that will generally
describe all the things you did in the whole process of developing a project or a
program. All the steps in programming require documenting for the purpose of
reference.
                                                                                  3
E. ELEMENTS OF PROGRAMMING
       Almost all the programs are designed to solve problems. The design team
is presented with the problem first and using these requirements, they will consider
several methods on how to reach the final output, utilizing the following elements
of programming:
   1. INPUT
   4. OUTPUT
              The manipulated data will be extracted from the program and sent
       back to the user. The extracted data is referred to as OUTPUT.
   5. CONDITIONAL EXECUTION
             Data can also be manipulated using conditional execution or
       BRANCHING. There may be codes that require comparison first before
       execution.
   6. LOOPS
F. PROGRAMMING PARADIGMS
       Programming paradigms are the styles of programming that a programmer
uses to come up with the output out of a project or problem.
   1. PROCEDURAL
   2. MODULAR
             Modular paradigm is when you turn a huge program into small ones
      with simpler codes.
   3. DATA ABSTRACTION
            The data abstraction paradigm is hiding the attributes of the data
      making it appear more compound than more primitive.
   4. OBJECT-ORIENTED PROGRAMMING
             A programming methodology that represents concepts as “objects”
      that have specific attributes and methods.
                                                                               5
Seat No.: ____________________________             Rating: ________________
Name: ______________________________               Date: _________________
                            Seatwork No. 1
ENCIRCLE THE LETTER OF THE CORRECT ANSWER.
1. It is a set of instructions in a computer.
          a. program                           c. hardware
          b. computer                          d. programmer
2. It is the data that the program requires to produce the desired results.
          a. output                            c. input
          b. process                           d. storage
3. It is the process of typing codes into a computer.
          a. testing                           c. design
          b. analysis                          d. coding
4. They are the individuals who write program codes.
          a. designers                         c. users
          b. librarians                        d. programmers
5. It is the material that the program generates.
          a. output                            c. input
          b. process                           d. storage
6. It refers to the computer itself and other equipment such as keyboard, mouse,
monitor, central processing unit (CPU) and printer.
          a. program                           c. hardware
          b. computer                          d. programmer
7. It is a collection of information.
          a. file                              c. data
          b. computer                          d. requirements
8. It is a mechanism for converting input to output.
          a. output                            c. input
          b. process                           d. storage
9. It is another name for EXECUTES (as in executing a program).
          a. runs                              c. codes
          b. debugs                            d. tests
10. Complete name of your instructor.
__________________________________________________________
                                                                                   6
Seat No.: ____________________________   Rating: ________________
Name: ______________________________     Date: _________________
                          Seatwork No. 2
ENUMERATE THE FOLLOWING:
A. PROGRAMMING PARADIGMS
  1.
  2.
  3.
  4.
B. ELEMENTS OF PROGRAMMING
   5.
   6.
   7.
   8.
   9.
   10.
   11.
C. TYPES OF PROGRAMMERS
   12.
   13.
D. STEPS IN PROGRAMMING
   14.
   15.
   16.
   17.
   18.
                                                                    7
UNIT 2. NUMBER SYSTEMS
       Learning Objectives
       At the end of the unit, I am able to:
             1. develop knowledge about th different number systems; and
             2. convert values into different number systems.
       The Decimal Number System is the most common out of all the number
systems because it is used in our everyday living. Since it is using 10 digits,
therefore, it has a base of 10. The BINARY Number System uses only two digits,
0 and 1, so it has a base of 2. HEXADECIMAL means 16. The HEXADECIMAL
Number System uses 16 digits, so the base is also 16.
B. CONVERSIONS
        Any particular number system can be converted to another number system
by following the steps in conversion.
   1. BINARY NUMBER TO DECIMAL NUMBER CONVERSION
   STEPS:
      a. Write the Binary number downwards.
      b. Multiply each digit with the corresponding binary weights starting with
         UNITS from the bottom.
      c. Add the products. The sum is the corresponding decimal number.
                                                                                 8
Example No. 1. CONVERT 1110102 TO DECIMAL.
                                                                                    9
Example No. 1. CONVERT 8210 TO BINARY.
Solution:
                                                                         10
3. HEXADECIMAL NUMBER TO BINARY NUMBER CONVERSION
       To convert Hexadecimal number to Binary, the TABLE OF
     EQUIVALENCES should be used.
                          TABLE OF EQUIVALENCES
                    HEXADECIMAL       BINARY     DECIMAL
                           0            0000          0
                           1            0001          1
                           2            0010          2
                           3            0011          3
                           4            0100          4
                           5            0101          5
                           6            0110          6
                           7            0111          7
                           8            1000          8
                           9            1001          9
                           A            1010         10
                           B            1011         11
                           C            1100         12
                           D            1101         13
                           E            1110         14
                           F            1111         15
STEPS:
     a. Write the digits of the hexadecimal number separately.
     b. Using the Table of Equivalences, write the corresponding binary
        equivalent under each digit.
     c. Cross-out the unnecessary zeroes. The UNNECESSARY ZEROES
        can be found at the leftmost digit.
     d. Write the binary digits as a string.
                                                                    11
Example No. 1. CONVERT 14316 TO BINARY.
Solution:
      14316 =       _101000011_2
1 4 3
Solution:
   STEPS:
            a. Group the digits of the binary number from the last digit by 4’s.
            b. If the last group is less than 4 digits, add zeros to the left to make it
               4. Ex. 11, add 2 zeroes to make it 0011. All the groups should have
               4 digits.
            c. From the Table of Equivalences, write below the corresponding
               hexadecimal number equivalent of each group.
            d. Write the hexadecimal digits as a string.
                                                                                     12
Example No. 1. CONVERT 1011001012 TO HEXADECIMAL.
Solution:
      1011001012 =      _165_16
                101100101
        0 0 01 0 1 1 0 0 1 0 1
            1     6      5
      1011001012 =      _165_16
Solution:
                                                        13
Example No. 1. CONVERT 34B16 TO DECIMAL.
Solution:
      34B16 =        __843__10
      3      x 162 =         768
      4      x 161 =           64
      B = 11 x 160 =          11
                           --------
                             843
                                                                                   14
Example No. 1. CONVERT 19510 TO HEXADECIMAL.
Solution:
      19510 =     __C3__16
      16 |_195_
      16 |__12_    r     3
             0     r     12 = C
                                                15
Seat No.: ____________________________     Rating: ________________
Name: ______________________________       Date: _________________
                         Seatwork No. 3
DO THE FOLLOWING CONVERSIONS:
   1. 11210 = ___________2     2. 5910 = ___________2
                                                                      16
Seat No.: ____________________________     Rating: ________________
Name: ______________________________       Date: _________________
                         Seatwork No. 4
DO THE FOLLOWING CONVERSIONS:
1. 10E16 = _________2          2. 9A16 = _________2
                                                                      17
UNIT 3. PROGRAMMING LANGUAGES
      Learning Objectives
      At the end of the unit, I am able to:
            1. Understand the history of programming languages;
            2. Identify the type of high-level programming;
            3. Understand the control structures; and
            4. Create a flowchart.
A. HISTORY
  1. Machine Language
             The first computer programming language ever developed was the
     machine language. The machine language is written with binary digits,
     that is, 0s and 1s. Machine language is the sole programming language
     which is recognized by the computer, though it is very tedious and the
     tendency of making errors is extremely high. Machine language codes can
     only be written by expert low level programmers.
  2. Assembly Language
            The assembly language is a slightly high-level language than the
     machine language. This programming language uses mnemonics.
     Mnemonics are memory aids which are abbreviated alphabetic
     instructions. The programmers developed this language so that they can
     easily understand their programs as compared to the ones they wrote using
     machine language. An assembler is used to convert codes written in
     assembly language into machine language.
  3. High-level Language
            The high-level language is a program written in English words that
     even common people can understand. Most of the programming languages
     today like C language, C++, Java and others are high-level languages. For
     the computer to understand and execute a program written in high-level
     language, it should first be compiled by a compiler program into object code
     and then combined into a single executable program using a linker.
                                                                              18
B. TYPES OF HIGH-LEVEL PROGRAMS
    1. Procedure-oriented programs
              When you say procedure-oriented, the program is focused on its
       step by step process of solving a given problem.
       Examples:
    2. Object-oriented programs
              The object-oriented program focuses on transforming real-life
       objects into its digital representation. Examples of objects in
       programming are text boxes, frames, check boxes, buttons and combo
       boxes.
       Examples:
          C++           Visual Basic        Java
C. CONTROL STRUCTURES
           Control structures are statements which oversee the flow on how a
    program is executed. The program’s logic depends on these control
    structures that is why they are sometimes called OGIC STRUCTURES.
       1. Sequence Structure
       EXAMPLE:
                 Make an algorithm that will show the process by which a
        Grade I student does his daily routine from the time he wakes up to the
        time he goes to school.
                                                                            19
 SOLUTION:
        1.   Wake up early.
        2.   Eat breakfast.
        3.   Brush his teeth.
        4.   Take a shower.
        5.   Put on his uniform.
        6.   Go to school.
2. Selection Structure
      In this structure, the execution of a statement or a block of
statements will be dependent on outcome of comparing the values in an
expression. The selection structure is also called as a DECISION
STRUCTURE.
EXAMPLE:
   From the previous example, make a selection structure in the part
where the Grade I student is putting on his uniform. Every Wednesday
is PE day, so the algorithm include a selection statement that will make
him put on his PE uniform on a Wednesday.
 SOLUTION:
   1. Wake up early.
   2. Eat breakfast.
   3. Brush his teeth.
   4. Take a shower.
   5. If (today is Wednesday)
           Put on his PE uniform
              else
                   Put on his school uniform
       end if
   6. Go to school.
3. Repetition Structure
       The Repetition Structure is sometimes called LOOPING. In this
structure, the statement or block of statements are done again and again
until the result of the comparison expression becomes “FALSE”.
                                                                     20
 EXAMPLE:
        Make the algorithm above show that the process of going to
 school will be repeated 5 times to cover the 5 school days of the week.
SOLUTION:
 1. Repeat 5 times
• Wake up early.
• Eat breakfast.
• Take a shower.
        •   If (today is Wednesday)
             Put on his PE uniform
                else
• Go to school.
end repeat
                                                                     21
D. FLOWCHART
       Flowchart is a guide in creating programs. It uses symbols to show the step
by step process of how you can develop a solution to a certain problem. The table
below lists the commonly used flowcharting symbols and their corresponding
functions.
                                                                                22
EXAMPLE No. 1:
     Create a flowchart that will display “HeLLo WoRLd”.
START
END
SAMPLE OUTPUT:
HeLLo WoRLd_
                                                           23
EXAMPLE No. 2:
Draw a flowchart that will show your name, and age in the monitor.
START
END
SAMPLE OUTPUT:
       In this example, the first print statement (Dayle Xylia F. Florentino) was displayed
on the screen, then a newline was printed, so the cursor transferred to the next
line. The third print statement (16 years old) was displayed on the screen. A
newline was next printed so the cursor appeared on the next line of the last printed
line.
                                                                                        24
EXAMPLE No. 3:
                 My age is: 16
                 You are too young to drink!!!_
        In this flowchart, variable age was first declared. Then, the prompt (My age
is: ) is printed on the monitor. The user entered 16 and the vaue was stored in
variable age. 16 was compared to 18 (is age < 18?). Since the result is yes, the
message (You are too young to drink!!!) was displayed and the cursor remained
after the last printed character.
                                                                                 25
Seat No.: ____________________________         Rating: ________________
Name: ______________________________           Date: _________________
                          Seatwork No. 5
I. ANSWER THE FOLLOWING QUESTIONS.
                                                                          26
Seat No.: ____________________________   Rating: ________________
Name: ______________________________     Date: _________________
Seatwork No. 6
                                                                    27
Seat No.: ____________________________   Rating: ________________
Name: ______________________________     Date: _________________
Seatwork No. 7
                                                                    28
Seat No.: ____________________________   Rating: ________________
Name: ______________________________     Date: _________________
Seatwork No. 8
                                                                    29
Seat No.: ____________________________         Rating: ________________
Name: ______________________________           Date: _________________
                          Seatwork No. 9
     Two numbers will be input values from the user. Create a flowchart
that will compute; then, display the sum of the numbers on the screen.
Show the sample output.
                                                                          30
Seat No.: ____________________________   Rating: ________________
Name: ______________________________     Date: _________________
Seatwork No. 10
                                                                    31
Seat No.: ____________________________   Rating: ________________
Name: ______________________________     Date: _________________
Seatwork No. 11
                                                                    32
UNIT 4. C++ PROGRAMMING
       Learning Objectives
       At the end of the unit, I am able to:
            1. identify the parts of a simple C++ program;
            2. learn about different C++ applications;
            3. create and compile C++ programs;
            4. debug a C++ source code; and
            5. execute a C++ program.
       For the programs that you will be writing in this programming subject, you
will be using C++. C++ is a high-level programming language which uses codes
that are easier for common people to understand.
       Step by step tracing of the code (debugging) is necessary so that you may
know precisely where errors are occurring. A debugger is a tool that helps
programmers trace programs and find probable causes of errors. It cannot correct
the errors in your program. It only assists the programmer find errors while in the
process of programming. The graphically based debugger environment is a part of
the Integrated Development Environment (IDE).
                                                                                33
Examples of IDEs that you can use :
     •   for desktops and laptops: Code::Blocks, text editor with GNU compiler;
     •   for Android: cppDroid, cxxDroid, C++ Compiler;
     •   for iOS: cppCode
   1. From the desktop, look for the Code::Blocks icon. Double click the icon.
      (If you cannot find the Code::Blocks icon in the desktop, you can click the
      START button and then look for Code::Blocks and click it).
                                                                              34
   The figure below will be shown in your monitor.
2. Click the File Menu from the Menu bar and then, click New, and proceed
   to clicking Project. You will be presented with a new window like the one
   below.
3. Choose Console Application by double clicking its icon. Your screen will
   now look like this Figure:
                                                                         35
4. Choose C++ and then, click Next.
                                      36
5. Type the title of the project (example, LabEx1) and then, click Next. The
   figure below will be your next screen.
6. Click Finish. You will now be presented with the Code::Blocks Editor
   screen.
                                                                         37
THE Code::Blocks SCREEN
                                                                               38
EXAMPLE OF A SIMPLE C++ PROGRAM
#include <iostream>
#include <cstdlib>
int main()
{
       cout<<”Aloha…”<<endl;
       cout<<”Hello…”<<endl;
       cout<<”Kumusta…”<<endl;
       return EXIT_SUCCESS;
}
#include <iostream>
#include <cstdlib>
       The first two lines are the declaration of libraries. The number sign or hash
sign (#) indicates that the line is a directive for the compiler’s preprocessor.
These libraries should be invoked in your program so that commands that you are
bound to use in your codes will be able to function. The <iostream> contains the
basic input and output commands of C++ while the <cstdlib> includes the
namespace std.
        This line is the main method of your C++ program where all the statements
will be executed by the program and is enclosed by opening ({) and closing (})
braces.
                                                                                 39
cout<<”Aloha…”<<endl;
cout<<”Hello…”<<endl;
cout<<”Kumusta…”<<endl;
        The sixth, seventh and eighth lines are C++ output statements. Every C++
statement should end with a semicolon( ; ). cout is a command which will display
anything inside the quote and unquote marks. It is followed immediately by an
insertion operator (<<) and then, the quote, the literal string or text to be printed,
the unquote and a semicolon. Literal strings are texts which are inside the quote-
unquote symbols and will be displayed as is, or the way the strings are written or
coded. These literal strings will be directed to the standard output stream,
usually, the screen or monitor. The endl command will print a newline to the
output. This means that the cursor will go down the next line of the screen. It is just
like pressing the Enter Key when typing in a text editor.
return EXIT_SUCCESS;
      The ninth line is a statement that causes a main function to end. This
statement is translated as “the program has functioned as expected and is
deemed a success.”
SAMPLE PROBLEM:
      Make a program which will display the names of your schools during
elementary, high school and college years.
#include <iostream>
#include <cstdlib>
int main()
{
        cout<<”San Isidro Central School”;
        cout<<”Central Luzon Polytechnic College”;
        cout<<”Adamson University”;
        return EXIT_SUCCESS;
}
                                                                                    40
2. TEXT EDITOR AND COMMAND LINE INTERFACE
TEXT EDITOR
       Use notepad as your text editor. To open notepad, click Start, then choose
All Programs and Accessories. Then click on Notepad.
       You can now write the source code in the Notepad window. To run the
program that you have encoded using your text editor, you have to use a Compiler
to execute the program.
                                                                              41
COMPILER
       For the compiler, you can install MinGW in your desktop using the following
steps:
4. Click Install.
                                                                               42
             This window will be displayed on your screen.
5. Click Continue.
6. Click Continue.
                                                             43
7. Click x in the MinGW Installation Manager.
9. Click Apply.
                                                44
             The following windows will be displayed on your screen.
                                                                               45
o   Click Enviroment Variables...; you will see
                                                  46
11. Click OK three times.
                            47
Create a source code and compile it on the Command Line Interface
                                                                            48
4. Type cd c:\CPP to change directory to change the directory to CPP so
   that the sorce file will be saved in that directory.
  To run the hello.exe program, type hello.exe or hello or simply type a at the
command prompt.
Output:
     Congrats, you have compiled and run a C++ program by using the
command-line tools.
                                                                                  50
B. C++ Application for iOS Devices
1. CppCode
  2. Upon opening the application, the main screen will appear as described in
     the figure below.
                                                                           51
3. To create a new C++ project, click on More on the upper right hand of the
   screen then choose Project. Next, choose New Project.
                                                                         52
4. After tapping New Project, a new window will appear. Input the file name
   you want in the text field then choose Create C++ Project.
                                                                        53
5. Upon choosing Create C++ Project, the text editor will appear and you can
   now type the C++ code. Please note that for special characters such as
   quotation marks (“ “) and single quotes (‘ ‘), please use the symbols
   interface that is provided with the text editor. Otherwise, you might
   encounter errors.
Coding Area
       Symbols
                                                                Toggle to
       Interface
                                                                hide/show
                                                                keyboard
                                                                            54
6. Once done, tap on the hide keyboard symbol, then tap Save. You will be
   prompted if the save is successful. If there are errors, tap on the editor
   again to enable the keyboard and correct the errors. If there are no errors,
   tap Compile and wait for the prompt that the compilation is successful.
   Then, tap Run. A terminal window will appear with the code’s output.
                                                                            55
Opening Existing Projects
       From the main screen, tap Open then Open project then choose C++ on
the upper right hand corner of the screen. All existing projects will be listed. Then
tap the > symbol found at right of the file that you want open. The text editor that
contains the code will appear.
                                                                                  56
C. APPLICATIONS FOR ANDROID DEVICES
1. Cxxdroid
                                                              57
USING Cxxdroid
                                                                     58
The default and existing codes on    After running or executing the
work area can be replaced by the     program by pressing the play
  desired coding of your own.       button/icon on the lower right of
                                               the screen
                                                                    59
 On the upper right corner, click     On the upper right corner, click
   the folder icon to toggle the    the three dots (Vertical Ellipsis) to
options on how to manipulate the     open another option set such as
              project.              undo, redo, search and go to line.
                                                                     60
Click the three dashes icon found    Appearance of the app such as
  on the upper left corner of the   themes, font size and font styles
 app to display other features of         are customizable.
              the app.
                                                                        61
 Ready made samples of basic           Sharing capability via text
C++ coding are also available in   message, Bluetooth, social media
          this app.                platforms, etc. is also available in
                                                this app.
                                                                          62
2. CppDroid
     Launch the Google Play application in your android device and search for
CppDroid.
      After installing CppDroid, you can see the launch icon of CppDroid in your
screen.
                                                                              63
        Upon opening the application, the main screen will appear as described in
the figure below.
                                                                               64
Creating Project
                                                                            65
Input project name (ex. LabEx1), then click CREATE C++ PROJECT.
                                                                  66
Writing, Compiling and Running a Code
       You can now start your coding in the IDE’s Edior Tab and write codes in
its workspace.
                                                                                 67
       After writing the program, tap on Compile                         (Lightning
Icon) to compile the written code.
       After the compilation is successful, tap on Run and it will execute the
program. The figure presents the output preview:
It can be helpful for you to run and test C/C++ on your device at any time.
                                                                                68
3. C++ Compiler IDE
From Google Play Store, download and Install C++ Compiler IDE.
                                                                       69
Using C++ Compiler IDE
      The main screen will be displayed as defined in the following figure when
the application is opened.
text area
                                                                              70
       To create a new project for C++, click “New” at the bottom on the phone
screen. Now you can start to construct the code. After you have constructed the
code, click “Save” so that project will be stored. If no errors exist, click “Compile”
and wait for the prompt to successfully compile. When you click “Run” the output
of the code will be displayed in the phone’s screen.
                                                                                   71
output
          output
         72
Opening Existing Projects
      From the phone screen, click “Open”, then select the existing file project
you want to view.
select
existing project
click
                                                                                 73
Seat No.: ____________________________         Rating: ________________
Name: ______________________________           Date: _________________
                                                                          74
UNIT 5. IDENTIFIERS, VARIABLES AND CONSTANTS
       Learning Objectives
       At the end of the unit, I am able to:
            1. define and classify identifiers;
            2. use and apply appropriate data types for variables and constants;
            3. name, declare and initialize variables and constants;
            4. use assignment statements and expressions; and
            5. apply mathematical operators in building a program.
A. IDENTIFIERS
       Identifiers are names given to variables and constants. In C++, an
identifier can be a letter or series of letters, numbers or underscore. No other
symbol can be used for valid identifiers. The identifiers should not start with a
number. You cannot use reserved words in C++ as identifiers since they all have
specific functions. The list of reserved words is given below:
                                                                              75
EXAMPLES OF VALID IDENTIFIERS
B. DATA TYPES
       Variables and constants use memory locations to store data and the size of
which will be depending on the data type that these two identifiers will hold. This
is the reason why you cannot use variables and constants unless you have
declared them first. The primitive data types which are built-in in the C++
programming language are listed below with their corresponding size.
        The short, long and the int data type will store integers or whole
numbers with no decimal place values. The float and the double data type will
hold real numbers or numbers with decimal parts. You cannot use the value of a
char data type in mathematical and logical computations. Character values are
enclosed with a pair of apostrophes( ‘ ‘ ). The bool data type will store the
values true or false. The string data type can hold values which are series of
letters, numbers and symbols, or it can hold a null string which is a space inside
the quote-unquote symbols (“ “). The value of a string data type is enclosed with
quote-unquote.
                                                                                76
C. VARIABLES
        Variables are names given to memory locations that you will be utilizing in
order for you to store data. You can change the value of a variable as you go along
in your coding but as mentioned earlier, a variable should be declared first at the
start of the program before you can use it. As for conventionality, if a variable name
you want to use is consisted of two or more words, use small letters to the first
word then capitalize the first letter/s of the succeeding word/s. The variable will
appear like it has humps thus, it is said to be using camel case format.
Examples:
        To declare a variable (so that the computer can allocate memory space for
it), use the following syntax:
data_type variable_name;
Examples::
int x;                     // Declares x as a variable which can only store
                           //whole numbers
float interest_rate;       //Declares interest_rate to be a float variable;
char alias;                //Declares alias as a variable which can only hold
                           // a single character (number, letter or symbol)
       If you are using variables with the same data type, you can declare
individually or together in one declaration statement:
Example:
           short rv;
           short df;                        short rv, df, dx;
           short dx;
                                                                                   77
INITIALIZATION OF VARIABLES
        You can also declare a variable and at the same time put an initial value to
it. To do that, follow this syntax:
Examples:
D. CONSTANTS
       A constant is an identifier which can store unchanging values. The same
thing as in variables, constants should be declared first at the beginning of your
program before you can utilize them. You can declare constants before the main
method of a C++ program like this:
       #define PI 3.1416
       #define LETTER ‘a’
      If you want to declare a constant inside the main method, use the following
syntax:
Examples:
                                                                                 78
E. ASSIGNMENT STATEMENTS AND ASSIGNMENT
EXPRESSIONS
      You can also assign values to your variables using the assignment
operator (=).
                               x = 5 * (3 / 2) + 3 * 2;
                            area = PI * radius * radius;
       Notice that in the assignment statement, the variable is located at the left of
the assignment operator. The right side, however, can be a value, another variable
or an expression. An expression in C++ is a mathematical expression which is
consists of values, variables and operators which evaluates to a single value.
INCREMENT/DECREMENT
       Increment and decrement can also use other numbers aside from 1. If
variable x is incremented by 3, the corresponding statement will be like this.
x = x + 3;
or
x += 3;
y = y – 5;
or
y -= 5;
F. MATHEMATICAL OPERATORS
       C++ also uses mathematical operators the list of which appears in the table
below:
 SYMBOL              NAME                                FUNCTION
     +           Plus(Addition)          Used in getting the sum of numbers
     -        Minus(Subtraction)         Used in getting the difference of numbers
     *       Asterisk(Multiplication)    Used in getting the product of numbers
     /       Slash(Integer division)     Used in getting the quotient of numbers
                                         Used in getting the remainder of the
     %               Modulo
                                         division
ORDER OF PRECEDENCE
                                                                                   80
                 LEVEL                                        OPERATOR/S
I ( )
II * / %
III + -
        The computer will first evaluate the level I operator which is a pair of
parentheses. After all the operators inside the parentheses were evaluated, the
level II operators will be processed next, then followed by the level III operators.
          If the are operators under the same level, evaluate first the operator on the
left of the expression until all of the same-level operators are evaluated.
EXAMPLES:
               1. x = 4324 % 7 – 2 * (15 – 30 / 6) + 84 / 3
                  x = 4324 % 7 – 2 * (15 – 5) + 84 / 3
                  x = 4324 % 7 – 2 * 10 + 84 / 3
                  x = 5 – 2 * 10 + 84 / 3
                  x = 5 – 20 + 84 / 3
                  x = 5 – 20 + 28
                  x = -15 + 28
                  x = 13
              2. x = (28 – 4) * 3 / 8 – 82 % 7
                 x = 24 * 3 / 8 – 82 % 7
                 x = 72 / 8 – 82 % 7
                 x = 9 – 82 % 7
                 x=9-5
                 x=4
                                                                                      81
Seat No.: ____________________________            Rating: ________________
Name: ______________________________              Date: _________________
                         Seatwork No. 12
I. BOX ALL THE VALID IDENTIFIERS.
x C char true_blue
                                                                             82
Seat No.: ____________________________           Rating: ________________
Name: ______________________________             Date: _________________
Seatwork No. 13
2. r = 25 + 50 / 4 – 22 * 15 % 23
                                                                            83
Seat No.: ____________________________           Rating: ________________
Name: ______________________________             Date: _________________
                          Seatwork No. 14
MAKE C++ STATEMENTS THAT WILL DO THE FOLLOWING:
   1. Assign the value of variable z to variable w;
2. Assign the value you will get if you add 5 to variable x to variable y.
                                                                                84
Seat No.: ____________________________   Rating: ________________
Name: ______________________________     Date: _________________
                                                                    85
Seat No.: ____________________________           Rating: ________________
Name: ______________________________             Date: _________________
                                                                            86
UNIT 6. INPUT/ OUTPUT STATEMENTS
        Learning Objectives
        At the end of the unit, I am able to:
             1. create a C++ program using input/output statements.
              cout<<value;
              cout<<variable;
              cout<<”Literal String”;
COMBINATION:
cout<<value<<variable<<”Literal string”;
EXAMPLE:
              cout<<10;
              cout<<age;
              cout<<”Choobahnez”;
       The command endl (pronounced as endline) will print a line break on the
output screen. This is just like pressing the ENTER key. Another way to print a line
break is by using the quote-backslash-n-unquote (“\n”) command. \n will not
function if it is not inside the quote-unquote symbols.
                                                                                    87
B. THE INPUT STATEMENT
       There are times when a program requires user input in order to have data
to manipulate and produce the output it desired. The C++ input stream object is
cin (see in). The cin object is followed by the extraction operator (>>) and the
variable where you want to store the value to be extracted by the cin object. The
extraction operator will stop removing cin object characters once it encounters a
linebreak (when you press the ENTER key) or a space(when you press the
spacebar) or a tab(when you press the TAB key). These are called the
whitespaces in programming. The syntax for the cin statement is:
cin>>variable;
      Before using the cin statement; you should first prompt the user as to what
data should be entered. For example, you want the user to key-in the age of a
person. In the program, you will type:
cin>>age;
        As seen in the output screen, only a blinking cursor will be displayed since
it is waiting for the user to type the age. The problem with this lies on the fact that
if you are not the programmer of this code, you will not have any idea as to what it
is you are supposed to input. The solution for this will be to prompt the user by
using the cout object like this:
                                                                              89
Seat No.: ____________________________          Rating: ________________
Name: ______________________________            Date: _________________
                         Seatwork No. 15
MAKE C++ STATEMENTS THAT WILL DO THE FOLLOWING:
                                                                           90
Seat No.: ____________________________   Rating: ________________
Name: ______________________________     Date: _________________
                                                                    91
UNIT 7. DECISION MAKING
           Learning Objectives
           At the end of the unit, I am able to:
                1. write decision making statements in C++, including an if statement
                   and an if else statement;
                2. use relational and logical operators to make decision in a program;
                   and
                3. write other decision making statements in C++ including nested if
                   else and switch statement.
A. THE if STATEMENT
       The if statement is one of the selection structures that will execute the
statements or block of statements following it when the comparison expression
evaluates to true. However, if the comparison expression evaluates to false, it will
go out of the if structure without doing anything. The if statement syntax is as
follows:
SAMPLE PROBLEM:
        Make a C++ construct that will print the name and age of a person if the age
is less than 10.
       if (age<10)
       {
               cout<<”Juan Dela Cruz”;
               cout<<”The age is “<<age<<endl;
       }
                                                                                   92
B. THE if else STATEMENT
       The if else statement is a selection construct that will execute a statement
or a block of statements when the condition evaluates to true or another series of
instructions when the result of the comparison is false.
START
age
                            print “Enter
                               age:”
get age
                                           Y
                                Is                    print “You can have
                               age                   your driver’s license…”
                               >=                                ;
                               18?
                        N
END
                                                                                 93
      The C++ structure of a simple if else statement is as follows:
                if (comparison expression)
            {
                      statement/s;
                }
                      else
                      {
                             statement/s;
                      }
C. RELATIONAL OPERATORS
     Relational operators are also called comparison operators because they
compare values. The result of of the comparison is a Boolean value, either a
TRUE or a FALSE.
D. BOOLEAN OPERATORS
        Boolean operators in C++ are operators used in Boolean values which
will result to a single Boolean value. They are also called logical operators.
                                                                                 94
   1. The NOT ( ! ) operator negates the value of the Boolean variable.
       In the first example, the value of (1 > 2) is FALSE. Applying the NOT
operator, !(false) will evaluate to TRUE. In the second example, the value of (1 >
0) is TRUE. Applying the NOT operator, !(true) will evaluate to FALSE.
   2. The AND (&&) of the operands in a Boolean comparison will result to true
      if all of the operands that are being compared have true values.
                                                                               95
        3. The OR (||) of the operands in a Boolean comparison will result to true if
           one of the operands that are being compared has a true value.
SAMPLE PROBLEM:
       Two numbers will be input values from the user. Make a C++ program that
will compute and display the sum of the numbers if the first number is in the range
of 5-10. Otherwise, compute and then display the product of the two numbers.
SAMPLE PROGRAM:
#include <iostream>
#include <cstdlib>
int main()
{
   int fnum, snum, sum, product;
    return EXIT_SUCCESS;
}
                                                                                  96
Seat No.: ____________________________      Rating: ________________
Name: ______________________________        Date: _________________
Seatwork No. 16
                                  Solution         Answer
      1. (x+y) > z          _________________   _________________
                                                                       97
Seat No.: ____________________________   Rating: ________________
Name: ______________________________     Date: _________________
Seatwork No. 17
                                                                    98
Seat No.: ____________________________   Rating: ________________
Name: ______________________________     Date: _________________
Seatwork No. 18
                                                                    99
  Seat No.: ____________________________   Rating: ________________
  Name: ______________________________     Date: _________________
                              CHAPTER 7
                                                                      100
           OTHER DECISION MAKING STATEMENTS
       if (comparison expression)
       {
              statement/s;
       }
       else
              if (comparison expression)
              {
                     statement/s;
              }
              else
                     if (comparison expression)
                     {
                            statement/s;
                     }
SAMPLE PROBLEM:
        Make a C++ program that will compute for the average of the grades of a
high school student by getting the average of his grades from first grading period
to the fourth, and display the letter grade using the following conversions: 91 – 100
= ‘A’, 81 – 90 = ‘B’, 71 – 80 = ‘C’, 70 and below = ‘F’. It should print the average of
the grades of the student and his letter grade.
                                                                                   101
FLOWCHART:
START
get grade1
get grade2
get grade3
get grade4
                                    102
                     A
                                                  X
                                                        print “The
                                                        average is: “,
                    is             lgrade = ‘F’                             END
                  ave<=7                                ave
                    0?
                              Y
                                                        print “The letter
                 N                                      grade is “,
                                                        lgrade
                    is             lgrade = ‘C’
                  ave<=8                                  X
                    0?
                              Y
                    is             lgrade = ‘B’
                  ave<=9
                    0?        Y
                 N
              lgrade = ‘A’
                                                                             103
Sample Output 1 (for basic pay of 10000 or less)
SIMPLE COMPUTATION OF AN EMPLOYEE’S NETPAY
Enter your number of hours worked in a month: 100
Enter your rate per hour: 90
Basic Pay =        9000 pesos
Tax @ 5 %          =         400 pesos
NET PAY =          8600 pesos
SOURCE CODE
#include <iostream>
#include <cstdlib>
int main()
{
  int nhw, rpr, tax=0, bp=0, np=0;
bp=nhw*rph;
    if(bp <=10000)
    {
        tax = bp*.05;
    return EXIT_SUCCESS;
}
                                                                    105
Seat No.: ____________________________        Rating: ________________
                         Seatwork No. 19
     Using the nested if else statement, create a c++ program that will
compute for your electricity bill based on the following data:
            20 or less                    ₱5.50/kwh
            21 – 50                       ₱10.00/kwh
            More than 50                  ₱15/kwh
                                                                          106
 Seat No.: ____________________________   Rating: ________________
B. SWITCH STATEMENT
                                                                     107
F. THE switch STATEMENT
          default:
          {
                     statement(s);
          }
      }
SAMPLE PROBLEM 1:
         Write a c++ program that inputs the course code of a student then outputs
his/her course based in the following data:
Good Day!
Choose a course code (I, M, N, E, D, A or C) and i will tell you its equivalent
course description.
Enter your choice now : A
The course code you have chosen is A
The equivalent course description is Architecture.
Thank You!
SOURCE CODE:
#include <iostream>
#include <cstdlib>
int main()
{
   char cc;
  cout<<”Good Day\n”;
  cout<<”Choose a course code (I, M, N, E, D, A, or c) and i will tell you its
         equivalent course description\n”;
  cout<<”Enter your choice now : “;
  cin>>cc;
  switch (cc)
  {
    case ‘I’ : case ‘i’:
    {
             cout<<”The course code you have chosen is “<<cc;
             cout<<”\nThe equivalent course description is Information
                         Technology\n”;
             break;
      }
    case ‘M’ : case ‘m’:
     {
             cout<<”The course code you have chosen is “<<cc;
             cout<<”\nThe equivalent course description is Management\n”;
             break;
     }
                                                                                 109
         case ‘N’ : case ‘n’:
         {
                  cout<<”The course code you have chosen is “<<cc;
                  cout<<”\nThe equivalent course description is Nursing\n”;
                  break;
         }
        case ‘E’ : case ‘e’:
        {
                  cout<<”The course code you have chosen is “<<cc;
                  cout<<”\nThe equivalent course description is Engineering\n”;
                  break;
        }
        case ‘D’ : case ‘d’:
        {
                  cout<<”The course code you have chosen is “<<cc;
                  cout<<”\nThe equivalent course description is Education\n”;
                  break;
        }
        case ‘A’ : case ‘a’:
        {
                  cout<<”The course code you have chosen is “<<cc;
                  cout<<”\nThe equivalent course description is Architecture\n”;
                  break;
        }
        case ‘C’: case ‘c’:
        {
                  cout<<”The course code you have chosen is “<<cc;
                  cout<<”\nThe equivalent course description is Criminology\n”;
                  break;
         }
         default:
         {
                  cout<<”The course code you have chosen is “<<cc;
                  cout<<”\nIt is an INVALID course code.\n”;
           }
    }
    return EXIT_SUCCESS;
}
                                                                                   110
SAMPLE PROBLEM 2:
       Make a C++ program that will create a Q and A using the Switch
statement.
SOURCE CODE:
     #include <iostream>
     #include <cstdlib>
     int main()
     {
       char answer;
         switch(answer)
         {
           case 'a':
            {
               cout<< “WRONG”;
               break;
             }
            case 'b':
             {
               cout<< “WRONG”;
               break;
             }
            case 'c':
            {
                cout<< “CORRECT”;
                break;
             }
            case 'd':
            {
                cout<< “WRONG”;
                break;
             }
            default:
            {
                 cout<<"invalid input";
            }
         }
         return EXIT_SUCCESS;
     }
                                                                                111
SAMPLE PROBLEM 3:
         Using the switch statement create a c++ program that compute your water
bill based on the account classification.
SOURCE CODE:
      #include <iostream>
      #include <cstdlib>
      int main()
      {
          int cnum, prevR, presR, bill;
          switch(cnum)
          {
            case 1:
            {
                              cout<< "RESIDENTIAL";
                              cout<< "Enter the previous reading of your account :";
                              cin>>prevR;
                              cout<< "Enter the present reading of your account :";
                              cin>>presR;
bill=(presR-prevR)*20;
                        break;
               }
              case 2:
              {
                              cout<< "COMMERCIAL";
                              cout<< "Enter the previous reading of your account :";
                              cin>>prevR;
                              cout<< "Enter the present reading of your account :";
                              cin>>presR;
bill=(presR-prevR)*30;
                              break;
                   }
                   default:
                   {
                              cout<<"invalid input";
                   }
          }
          return EXIT_SUCCESS;
      }
                                                                                       112
SAMPLE PROBLEM 4:
      Using switch statement, create a c++ program that provide the four
mathematical operations as choices for computation.
SOURCE CODE:
      #include <iostream>
      #include <cstdlib>
      int main()
      {
          int fn, sn;
          char ch;
          float ans;
          switch(ch)
          {
             case 'A':
             {
                            ans = fn + sn;
                            cout<<ans;
                            break;
               }
               case 'B':
               {
                            ans = fn - sn;
                            cout<<ans;
                            break;
               }
               case 'C':
               {
                            ans = fn * sn;
                            cout<<ans;
                            break;
                }
                case 'D':
                 {
                            ans = fn / sn;
                            cout<<ans;
                            break;
                }
               default:
               {
                            cout<<"invalid input";
               }
          }
              return EXIT_SUCCESS;
      }
                                                                                     113
Seat No.: ____________________________   Rating: ________________
Name: ______________________________     Date: _________________
Seatwork No. 20
                                                                    114
Seat No.: ____________________________   Rating: ________________
Name: ______________________________     Date: _________________
                                                                    115
             Activity: What Did You Learn About?
Post-Assessment Test
Leave a short comment on which topic you enjoyed the most and why?
________________________________________________________________
________________________________________________________________
________________________________________________________________
                                                                          116
                     REFERENCES
https://www.tutorialspoint.com/cplusplus/
http://www.cplusplus.com/doc/tutorial/
http://www.text-editor.org/
https://www.techopedia.com/definition/3912/compiler
https://en.wikipedia.org/wiki/GNU_Compiler_Collection
https://itunes.apple.com/app/cppcode-offline-c-c++-ide/id936694712
http://www.cppcode.info/
https://play.google.com/store/apps/details?id=org.zhiyuan.zhiyuan24
https://www.google.com/url?sa=t&source=web&rct=j&url=https://play.g
oogle.com/store/apps/details%3Fid%3Dname.antonsmirnov.android.cp
pdroid%26hl%3Den%26referrer%3Dutm_source%253Dgoogle%2526u
tm_medium%253Dorganic%2526utm_term%253Dcppdroid%26pcamp
aignid%3DAPPU_1_rbENX5jpCceUr7wPwuqzuAE&ved=2ahUKEwjY8
4Gj68zqAhVHyosBHUL1DBcQ5IQBMAB6BAgPEAM&usg=AOvVaw0h
W7KjCxj0wxFIL1Tq-8ky&cshid=1594733019938
https://play.google.com/store/apps/details?id=ru.iiec.cxxdroid
http://texteditor.org/?fbclid=IwAR0phsV4QRGThctQObygLFgZAmCbH
FA9F04y896a74Bm5RNm8zTzg8ccwJY
http://www.webopedia.com/TER M/s/source_code.html
117