Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Computer Programming

Computer programming (often shortened to programming or coding), sometimes considered a branch of applied mathematics, is the process of writing, testing, debugging, and maintaining the source code of computer programs using computer programming language to perform a specified task by the computer. The purpose of programming is to create a program that exhibits a certain desired behavior (customization).
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Computer Programming

Computer programming (often shortened to programming or coding), sometimes considered a branch of applied mathematics, is the process of writing, testing, debugging, and maintaining the source code of computer programs using computer programming language to perform a specified task by the computer. The purpose of programming is to create a program that exhibits a certain desired behavior (customization).
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Computer programming is a way of giving computers instructions about what they should do next.

These instructions are


known as code, and computer programmers write code to solve problems or perform a task. The end goal of computer
programming is to create something: that could mean anything from a web page, or a piece of software, or even just a pretty
picture. It is why computer programming is often described as a mix between art and science; it’s technical and analytical, yet
creative at the same time.

Computer Programming

Computer programming (often shortened to programming or coding), sometimes considered a branch of applied
mathematics, is the process of writing, testing, debugging, and maintaining the source code of computer programs using
computer programming language to perform a specified task by the computer. The purpose of programming is to create a
program that exhibits a certain desired behavior (customization).

A computer program is a detailed, step-by-step set of instructions that are executed by a computer to perform a specific
task or solve a specific problem. It sequences the tasks a user wants to be done and produces the results of output needed.
The set of rules or instructions that tells the computer what to perform is done or written through a variety of programming
languages.

A programmer is a person who designs a program. It converts problem solutions into instructions for the computer.
The programmer designs the program decides which of the programs or set of instructions to use and tests the program to
see if it is working as designed.

A programming language is a set of words, symbols, and codes that enable humans to communicate with computers.
There is a lot of programming languages that exist today. Some of it has its standards in writing. Some examples are C, C++,
C#, Java, and Perl. The process of creating program code often requires expertise in program algorithm, design, and logic. Just
like human languages, programming languages also follow grammar called syntax. Certain basic program code elements are
common for all programming languages. The most important basic elements for programming languages are Programming
Environment, Data Types, Variables, Keywords, Logical and Arithmetical Operators, If else conditions, Loops, Numbers,
Characters and Arrays, Functions, and Input and Output Operations.

An algorithm is a sequence of unambiguous, finite, and ordered instructions to be followed to solve a problem. Usually
implements a program algorithm. The instruction sequence itself must be finite, not the number of steps taken. The programs
are usually divided into smaller parts (modules) so that the algorithm complexity of each of the parties is less than the full
program, which helps the development of the program. According to Niklaus Wirth, a program consists of algorithms and
data structure. Various techniques have been proposed for the program whose goal is to improve the process of creating and
maintaining software.

Programming Languages

A programming language is an artificial language that can be used to control the behavior of a machine, particularly a
computer. Programming languages are used to facilitate communication about the task of organizing and manipulating
information, and to express algorithms precisely. There are two kinds of programming languages which are low-level
programming language and high-level programming language. Low-level programming language is consisting of First
Generation and Second Generation. High-level programming language is consisting of Third, Fourth, and Fifth Generation
languages.

Low-Level Programming Languages

Low-level programming languages are so named because they are closer to machine language than to human language;
that is, it is easier for the machine (computer) to understand them than it is for humans. The lowest level of language par
excellence is the machine code. This was followed by the assembly language, as when programming in assembler is working
with the memory registers of the computer directly.

Low-level programming languages are sometimes divided into two categories which are the first generation and
second generation.

1. First Generation or Machine Language is a language system that is executed directly by a computer processing unit.
The program is represented by 1s and 0s. Machine language may be regarded as an extremely hardware-dependent
programming language.
2. Second Generation or sometimes called Assembly Language. Instead of using 1s and 0s, assembly language uses
mnemonic codes. Mnemonic codes are abbreviations that are easy to remember. Each type of computer has its very own
assembly language.

High-Level Programming Languages

High-level programming languages feature is to express algorithms in a way human does, rather than executing like
machines. The limitation of the high-level language is that it requires some programming skills to perform the logical sequence
of instructions. The very high-level languages were created so that users could solve this common problem of data processing
easier and faster. The main advantage of high-level languages over low-level languages is that they are easier to read, write,
and maintain. Programs written in a high-level language must be translated into machine language by a compiler or
interpreter.

High-level programming languages are sometimes divided into three categories: third generation, fourth generation,
and fifth generation.

1. Third Generation Language (3GL) or High-Level Language transformed programming in the early 1960s. It is the first
to use the true English language which is much easier to use compared to other low-level languages. If assembler is used by
the assembly language, third-generation languages use the translator to convert the program into a machine language. The
third generation languages are portable, the object code created for one type of system can be translated to another different
type of system. Some examples are FORTRAN, COBOL, Basic, Pascal, C, C++, and Java.

2. Fourth Generation Language (4GL) or Very High-Level Language is closer to human languages than a typical high-
level programming language. It further simplifies the third- generation languages (3GL) because there is a reduction in the
number of instructional statements. One hundred (100) lines of instructions in 3GLs can be reduced to five (5) to twenty (20)
lines of instructions in 4GLs. More 4GLs are used to access databases such as database queries, report generators, data
manipulation, analysis and reporting, web development, and general-purpose languages. 4GLs are more user-friendly
because of the use of icons, graphical interfaces, and the use of English-like words and phrases. Some examples are Visual
Basic and other Visual environments.

3. Fifth Generation Language or Natural Language has a closer resemblance to the English language. It has the capability
to translate human instructions into code that a computer understands. If it gets confused with the user’s instructions, it asks
for further explanations. Fifth generation languages are based on solving problems using constraints given to the program,
rather than using an algorithm written by a programmer. This way, the programmer only needs to worry about what
problems need to be solved and what conditions need to be met, without worrying about how to implement a routine or
algorithm to solve them. Fifth generation languages are used mainly in artificial intelligence and neural networks.

Procedural and Non-Procedural Languages

Procedural Languages

Programming languages that are considered procedural uses a series of instructions or statements which are sequential
from the beginning to the end. This means that the execution of instructions is line by line and it is terminated after the last
instruction. Examples of procedural languages are BASIC, COBOL, Pascal, FORTRAN, C, and PL/1.

Non-Procedural Languages

Non-procedural languages are considered object- oriented programming languages. They are event-driven which
means that a programmer selects an event that needs to occur before the instruction or statements is executed. It is different
from procedural language since statements are not executed line per line instead a series of instructions are executed as a
whole when an event occurs. Examples of events are click, double click, drag and drop, mouse over, and other events.
Examples of non- procedural languages are Visual Basic, C++, Java, and Delphi.

Programming Life Cycle

Non-procedural languages are considered object- oriented programming langA computer is a problem-solving tool.
Once it is properly provided with a valid program, the computer becomes self-operational, that is, it requires no human
intervention during processing. To use this tool effectively, the programmer usually has to perform the following set of well-
defined steps:ages. They are event-driven which means that a programmer selects an event that needs to occur before the
instruction or statements is executed. It is different from procedural language since statements are not executed line per line
instead a series of instructions are executed as a whole when an event occurs. Examples of events are click, double click, drag
and drop, mouse over, and other events. Examples of non- procedural languages are Visual Basic, C++, Java, and Delphi.

1. Identifying the problem. It is the first step in creating a program. It involves determining the requirements of the
program to be able to come up with a suitable programming solution.

2. Planning the Solution. There are two ways of planning the solution to a problem, they are drawing a flowchart and
writing pseudocode. The flowchart is a graphical representation of the step-by-step instruction to be done in a program while
pseudocode is listing down the set of instructions to be used in the program. These two approaches are not executable in a
programming language.

3. Coding the Program. Code the program with the use of a chosen programming language. If human language follows
grammar in writing and speaking, programming languages have their own set of rules to follow, this is called syntax.
Violation of the rule set by the programming language used in a certain program will produce an error called syntax error.
One of the common causes of syntax error is a misspelling.

4. Testing the Program. After coding the program, it is important to test if it is running. If it runs properly, then it is free
from a syntax error, however, there will be instances that it does not meet the requirements of the program. Testing the
program involves three phases:

1. Desk checking is the phase when the programmer just mentally traces or checks the logic of the program to
make sure that it's error-free.

2. Translation is the phase when the programming language uses a translator to ensure that the programmer did
not violate any language rules by the chosen programming language. This program translates the program line by line
to locate any syntax error.

3. Debugging means detecting, locating, and correcting bugs. In programming, error or mistakes are called bugs.
In debugging phase, the programmer runs the program and uses dummy data or test data. Then, the programmer
checks the flow of the program if its logic is error-free and if it meets the requirements of the specified program.

4. Documentation. In this step, the programmer makes a detailed description of how the program was created. It
contains a brief narrative process undergone by the program, from the identification of the problem, planning of the
solution through flowcharting and pseudocode, coding of the program up to the testing results. Codes used for the
program are also included in this documentation as a reference for the next programmer who will upgrade the designed
program.

Algorithm

An algorithm is a list of instructions for carrying out some process step by step. Algorithms executed by a computer can
combine millions of elementary steps, such as additions and subtractions, into a complicated mathematical calculation. If an
algorithm is devised for a process, it can usually be done so in many different ways. Some properties of the algorithm are:

• Finiteness. There is an exact number of statements to be executed and has its ending.

• Absence of Ambiguity. Statements are clearly described and defined.

• Sequence of Execution. The sequence of statements is done from top to bottom.

• Input and Output. Unknown values must be identified and exact output must be defined.

• Effectiveness. The solution to the problem must be correct. • Scope of Definition. Identify the scope of the problem.

Pseudocode

Pseudocode specifies the steps of the algorithm using the language of control structure. It is a compact and informal
high- level description of a computer programming algorithm that uses the structural conventions of some programming
language but is intended for human reading rather than machine reading.
Flowchart

A flowchart is a graphical or visual representation of the algorithm of the program. It was introduced by Frank Gilberth
in 1921, and they were called “Process Flow Chart”.

A flowchart is a diagram representing the logical sequence in which a combination of steps or operations is to be
performed. It consists of labeled geometrical symbols that are interconnected to provide a pictorial representation of a data
processing procedure. It also can be used to depict the hardware associated with a computer information system.

Types of Flowcharts

The flowchart can be categorized into four main types.

1. Document Flowchart. It shows controls over a document flow through a system, such as a payroll information,
internal memos, and office mail. The flowchart shows how document passes from one part of the company to another. It does
contain minimal details.

2. System Flowchart. It shows controls on how the entire system works by demonstrating how data flows and what
decisions are made to control it. A system flowchart combines all the resources with the related processes.

3. Data Flowchart. It shows controls over a data-flow system. It illustrates how data passes through a system. It tracks
the origin and end of data. It is more concerned with the movement of data more than how data is processed.

4. Program Flowchart. It shows controls over how a program works within a system. These flowcharts show any and
all- user interaction pathways. Program charts are large and complex.

Flowchart Symbols

Actual program statements are written inside the appropriate symbols. Flowchart symbols conform to the International
Organization for Standardization (ISO) and American National Standard Institute.

1. Input/Output Symbol (Parallelogram). It represents an instruction to an input or an output device.

2. Processing Symbol (Rectangle). It is used to represent a group of program instructions that perform a processing
function of the program.

3. Decision Symbol (Diamond). It denotes a point in the program where more than one path can be taken. It is also
used to document points in the program where, based upon variable conditions, a branch to alternative paths is possible. The
particular path that is chosen depends on the answer to a question or the result of a test that is inserted in the symbol.

4. Preparation Symbol (Hexagon). It is used to represent an instruction or group of instructions that will alter, or modify
a program’s course of execution. It is commonly used to specify operations such as control, index register, initialization, switch
setting, and in indicating loops.

5. Terminal Symbol (Oval). It is used to designate the beginning and the end of a program, or a point of interruption.
It can also be used elsewhere in the flowchart for specifying error conditions, such as parity error checks or detection of invalid
characters.

6. Predefined Process Symbol (Rectangle with Two Vertical Bars). It is a specialized process symbol that represents a
named operation or programmed step not explicitly detailed in the program flowchart. As a subroutine symbol, it can be used
when a procedure needs to be repeated several times.

7. On-page Connector (Small Circle). It is a non-processing symbol that is used to connect one part of a flowchart to
another without drawing flow lines. It denotes an entry or an exit from another part of the flowchart and is also used to change
the reading sequence of a flowchart on the same page. On-page connectors conserve space by keeping related blocks near one
another, reducing the number of flow lines in complex programs, and eliminating cross lines from taking place. It also aids in
developing a clearer, better organized, and more simplified flowchart.

8. Off-page Connector (Small Pentagon). It is used instead of the on-page connector to designate entry to or exit from
a page when a flowchart requires more than one page. It is commonly used in complex flowcharts which often require a
detailed diagram extending over several pages.
9. Flow Lines (Horizontal/Vertical Lines). It is used to show the reading order or sequence in which flowchart symbols
are to be read.

10. Flow Direction Indicators (Arrowheads). It is used to show the direction of processing or data flow. It is added to
flow lines if a flowchart appears confusing in its layout.

Illustrative Problems on Simple Logic Flow

In creating a program flowchart, follow the step of the programming life cycle. In identifying the problem, from the
problem identify the given data, data that are specified or implied in the problem, input, data that will come from the program
user, required, data to be processed or computed, and output, data that will be displayed on the screen. Also, data in the
flowchart should be indicated using variables, which are the storage of data in a computer program. Take note, lowercase
letters used as the variable is different from uppercase letters. Data that are not stored in variables cannot be displayed on the
output screen.

CPROGRAMING

C is a successor of Basic Combined Programming Language' (BCPL) called B language which was introduced around
the early 1970s. C was invented to write an operating system called UNIX. The C language was originally designed to support
procedure-oriented programming. It was subsequently extended to C++ to support object-oriented programming (OOP). The
symbol ++ in C++ indicates that it is an extension of C. Today C is the most widely used and popular System Programming
Language. Most of the state-of-the-art software has been implemented using C.

C Language

C programming is a general-purpose, procedural, imperative computer programming language developed in 1972 by


Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system. The language was formalized in
1988 by the American National Standard Institute (ANSI).

C is an imperative language designed to compile relatively straightforwardly, which provides low-level memory access.
With the gradual increase in the program's popularity, the language and its compiler have become available on a wide range
of platforms, from embedded microcontrollers to supercomputers. With the introduction of the K&R C language, a new
edition of C published in 1978 by Brian Kernighan and Denis Ritchie, several features have been included in the C language.
Some of these features are Standard I/O (Input/Output) Library, long int - data type, unsigned int - data type, and Compound
assignment operators.

During the late 1980s, C was started to be used for various mainframe computers, micro, and minicomputers, which
began to get famous. Gradually C got its superset - i.e., C++, which has added features, but it's developed from C with all its
initial concepts. In the beginning, C was used for developing system applications, such as Database Systems, Language
Interpreters, Compilers and Assemblers, Operating Systems, Network Drivers, and Word Processors. But since it become the
most widely used computer language, other systems and programming languages are written in C such as Linux Operating
System, PHP, and MySQL.

C language has become popular because it is one of the early programming languages and still the best programming
language to learn quickly. C language is also reliable, simple, and easy to use. It is also a structured language and modern
programming concepts are based on C. C can also be compiled on a variety of computer platforms. Also, universities around
the world preferred to add C programming to their courseware.

C language has a lot of features found in modern programming languages. C is a robust language with a rich set of
built-in functions and operators. Programs written in C are efficient and fast. C is highly portable which means programs
once written in C can be run on other machines with minor or no modification. C is a collection of C library functions and
programmers can also create their own function and add it to the C library. Lastly, C is easily extensible.

C Language has a lot of advantages over modern programming languages. The most important is C is the building
block for many other programming languages. Second, programs written in C are highly portable. Third, several standard
functions are there (like in-built) that can be used to develop programs. Fourth, C programs are collections of C library
functions, and it's also easy to add functions to the C library. And the last one is that the modular structure of the C program
makes code debugging, maintenance, and testing easier.

Although there are a lot of advantages in using the C language in designing programs, disadvantages can also be seen
in utilizing it. First, C does not provide Object Oriented Programming (OOP) concepts. Second, there are no concepts of
Namespace in C. Third, C does not provide binding or wrapping up of data in a single unit. And lastly, C does not provide
Constructor and Destructor.

Because of these disadvantages, C displays some limitations during the programming process. First, the C program is
difficult to debug. Second, C allows a lot of freedom in writing code, and that is why programmers can put an empty line or
white space anywhere in the program. And because there is no fixed place to start or end the line, so it isn't easy to read and
understand the program. Third, C compilers can only identify errors or compile-time errors and are incapable of handling
exceptions which are run-time errors. Fourth, C does not provide data protection. Fifth, it also doesn't feature the reusability
of source code extensively. And last, it does not provide strict data type checking, such an example is when an integer value
can be passed for the floating datatype.

Comment Line

The comment line is part of the source code disregarded by the compiler and does not have any effect on the behavior
of the program. Its purpose is only to allow the programmer to insert notes or descriptions embedded within the source code.
It can also be used to include short explanations or observations within the source code itself. There are two kinds of ways to
insert comments in a C program. The line comment discards everything from where the pair of slash signs (//) is found up to
the end of that same line. An example is // my first program in C. The block comment on the other hand discards everything
between the /* characters and the first appearance of the */ characters, with the possibility of including more than one line. An
example is /*Juan Dela Cruz BSIE – 2A Collaborative Learning Exercise No. 9 C Programming*/.

Preprocessor Directive

#include<iostream.h> is an example of an include directive and it is called a preprocessor directive. A preprocessor


directive lines always begin with a pound sign (#) and is followed by the name of the header file that is enclosed in angle
brackets, < and >. It tells the compiler to include the header file in the application before compiling the source code. A header
file is a file with extension .h which contains C function declarations and macro definitions to be shared between several
source files. Make sure that all the header file of all the commands used inside the C program is written using the preprocessor
directive at the top of the program.

Namespace

A namespace is not available in a C program but available in a C++ program. It is used to organize different names used
in programs. The using namespace std; in the sample program indicates that every name used in the iostream standard library
file is part of a namespace called std.

Function

A function is a group of related instructions, also called statements, which together perform a particular task. A program
must have one main function, and only one main function. The main function is the starting point for every C++ program. If
there was no main function, the computer would not know where to start the program. If there was more than one main
function, the program would not know whether to start at one or the other.

A function is divided into two parts the function header and the function body. The function header is consisting of a
return type, a function name, and an argument list. The data type int preceding main is the return type, main is the function
name, and the parentheses (), empty but not always, contain the argument list. A function header is always followed by an
open curly brace, which begins the function body. Each of the related instructions, or statements, which belong to the main
function are contained within the body of that function. Each statement inside the function body always ends with a
semicolon. The last statement is a return statement. The function body must contain a return statement unless the return type
is void, in which case the return statement is optional. Then the function body ends with a close curly brace.

“out” refers to the direction in which cout sends a stream of data. A data stream may flow in one of two directions. One
direction is input, cin>>, into the program from an outside source. The other direction is output, cout<<, out from the program
to an outside source.

<< and >> operators are known as the stream insertion operator. If it is <<, it inserts the information immediately to its
right into the data stream. And if it is >>, it inserts the information from the outside source immediately to its right which is
commonly an identifier.

return 0; statement returns a value of zero to the computer’s operating system. It tells the operating system that the
program ended normally.

Translating the Code for the Computer

Computers don’t understand C++ or any programming language. They understand only machine language. Three
programs are used to translate the source code into an executable file that the computer can run. They are the preprocessor,
compiler, and linker program.

The first to execute during the translation process is the preprocessor program. The preprocessor is a program that scans
the source code for preprocessor directives such as include directives. It inserts into the source code all files included by the
include directives.

The second to execute during the translation process is the compiler program. The compiler is another program that
translates the preprocessed source code into corresponding machine language instructions, which are stored in a separate file,
called an object file, having a .obj extension. If there is a syntax error, then the compiler cannot translate the code into machine
language instructions, and instead will tell the programmer the syntax error. It also acts like a spell checker and grammar
checker.

The last to execute during the translation process is the linker program. The linker is a third program that combines the
object file with the necessary parts of the run-time library. While the object file has machine language instructions, the
computer cannot run the object file as a program. C++ also needs to use another code library, called the run-time library, for
common operations. The result is the creation of an executable file with a .exe extension.

Memory and Data Types

Computer programs consist of instructions and data. Data is the information that is the subject of the program.
Computer programs’ instructions and data have to be in the computer’s memory for the program to work. Memory is
used to store and recall information. Information, also called data, comes in different forms. The type of data, whether
numeric, text or something else is referred to as the data type. The data type will affect not only the form in which the
data is stored but also the amount of memory required to store it.

Data Types

The ones and zeros that may be stored at a memory address may represent text and a whole number. Data comes
in many forms and is generally either numeric or textual. Some numeric data uses whole numbers, while others uses
floating- point numbers. There are different data types for each of the many forms of data. The data type chosen will
affect not only the form in which the data is stored but also the amount of memory required to store the data.

Whole Number Data Types

There are several different whole-number data types. The listed sizes and range are typical but may vary
depending on the compiler and operating system. Use sizeof operator to determine through code the size of different
data types on the compiler and operating system.
Unsigned vs. Signed Data Type

Unsigned means the number is always zero or positive, never negative. While signed means the number may be
negative or positive (or zero). If the data type is not specified as signed or unsigned, the data type is presumed to be
signed. Since an unsigned data type means its value is always 0 or positive, never negative, the smallest value of an
unsigned short is, therefore, zero; an unsigned short cannot be negative. By contrast, the smallest value of a short is -
32767, since a signed data type may be negative, positive, or zero.

Size

All C++ data types have a size. A byte is the smallest unit of information that a computer can process, no data type
may be smaller than one byte. Regardless of the size, the number of bytes is always a whole number. The number of
bytes for a data type is the result of a power of 2 since computers use a binary number system. Size of data type matters
in two related aspects: the range of different values that the data type may represent and the amount of memory required
to store the data type.

Range

Range means the highest and lowest value that may be represented by a given data type. The number of different
values that a data type can represent is 2 n , n is the number of bits in the data type. The highest number that an unsigned
data type may represent is 2 n−1 ; n is the number of bits in the data type, and the minus 1 being used because we are starting
at 0, not 1.

Signed data types involve an additional issue. Determine if a decimal number is positive or negative by looking
to see if the number is preceded by a negative sign (-). However, a bit can be only 1 or 0; there is no option for a negative sign
in a binary number. With a signed data type, different numbers must be split evenly between those starting at zero and going
up, and those starting at zero and going down. One of the bits is used to store the sign, positive or negative.

Floating-Point Data Types

Whole numbers work fine for certain information where fractions don’t apply. Whole numbers also work fine for
certain information where fractions do apply but are not important. There are floating-point data types that can be used
when a value to the right of the decimal point is important. The term floating point comes from the fact that there is no
fixed number of digits before and after the decimal point; that is, the decimal point can float. Floating-point numbers
also are sometimes referred to as real numbers. Even with complex codes, a computer can only approximately represent
many floating-point values.

Text Data Types

There are two text data types. The first is char, which stands for character. It is usually is 1 byte, and can represent
any single character, including a letter, a digit, a punctuation mark, or a space. The second text data type is a string. The
string data type may store several characters, including a sentence, or paragraph, or page. The number of bytes required
depends on the number of characters involved.

Unlike char and the other data types, the string type is not a data type built into C++. Instead, it is defined in the
standard library file string, which therefore must be included with an include directive (#include<string.h>) to use the
string data type.

Boolean Data Types

The bool data type has only two possible values, true and false, and its size usually is one byte. The term “bool”
is a shortening of Boolean, which is usually used in connection with Boolean Algebra, named after the British
mathematician, George Boole. It could be regarded as a numeric data type in that zero is seen as false, and one as true.
sizeof Operator

The sizeof operator is followed by parentheses, in which you place a data type. It returns the size in bytes of that
data type.

Expressions

The code sizeof(int) is called an expression. An expression is a code statement that has a value, usually a value
that has to be evaluated when the program runs. The portion of the statement within double quotes, “Size of int is “, is
outputted literary as “Size of int is 4.” There is no need for evaluation. Instead, this is considered a literal string. The
term string refers to the data type, a series of characters, and the term literal refers to the fact that the string is outputted
literary, without evaluation.

Outputting Expression

The expression sizeof(int)is separated by the stream insertion operator (<<) from the literal string “Size of int is ”.
sizeof(int), being encased inside the double quotes, would be treated as a literal string, not an expression, and therefore
would not be evaluated, but instead displayed as is. Since “Size of int is” is a literal string and sizeof(int) is an expression,
they need to be differentiated before being inserted into the output stream. The differentiation is done by placing a
stream insertion operator between the literal string and the expression.

Escape Sequence

The string “\n” following the expression sizeof(int) is also a literal string, so it, too, is separated by a stream
insertion operator from the sizeof(int) expression. A special type of string is called an escape sequence. C++ has many
escape sequences. The “\n” in a string is not displayed literally by cout even though it is encased in double-quotes. The
backslash signals cout that this is an escape sequence.

Variables

When there is a need to refer in code to a particular item of information among perhaps thousands of items of
information, it is done by referring to the name of that information item. Name information by creating a variable. A variable
not only gives a way of referring later to particular information but also reserves the amount of memory necessary to store
that information.

Declaring Variables

The information a program uses while it is running first needs to be stored in memory. There is a need to reserve memory
before storing information there. It is done by declaring a variable. Declaring variables also gives a convenient way of referring
to the reserved memory when needed in the program. By declaring a variable, it refers to the reserved memory by the
variable’s name, which is easier to remember and identify with the stored information than its hexadecimal address.

Syntax of Declaring Variables

It is a must to declare variables before using them. Name is an alias by which you can refer in code to the area of reserved
memory. The variable declaration ends with a semicolon, it tells the compiler that the statement has ended. Declare a variable
either within a function, such as main or above all functions, just below any include directives.

A compiler error will be received if the variable is referred to first before declaring it because the compiler reads the
code from top to bottom. When a variable is declared, then the compiler recognizes further references to the variable name as
referring to the variable that was declared.
Declaring Multiple Variables of the Same Data Type

Several variables of the same data type could be declared in a separate statement. Several variables of the same data
type could also be declared in one statement separated by commas.

The data types qualify all three variables since they appear in the same statement as the data type. The variables must
all be of the same data type to be declared in the same statement.

Naming Variables

Variables have names that are used to identify the variable so you can refer to it in code. It is also known as identifiers.

Limitations on how a variable is named.

• The variable name cannot begin with any character other than a letter of the alphabet (A-Z or a-z) or an underscore
(_). However, the second and following characters of the variable name may be digits, letters, or underscores.

• The variable name cannot contain embedded spaces, such as My Variable, or punctuation marks other than the
underscore character (_).

• The variable name cannot be the same as a word reserved by C++.

• The variable name cannot have the same name as the name of another variable declared in the same scope.

Standard reserved keywords

• asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast,
else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private,
protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw,
true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while

• Alternative representations for some operators: and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_e

• the compiler may also include some additional specific reserved keywords

It is a good idea to give meaningful variable names. Use a variable name that is descriptive of the purpose of the variable.

Scope of A Variable

A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source
code, outside all functions. On the other hand, the local variable is one declared within the body of a function or a block.

Naming Conventions

The naming convention is simply a consistent method of naming variables. Another naming convention is to name a
variable with a prefix, usually all lowercase and consisting of three letters, that indicate its data type, followed by a word with
its first letter capitalized, that suggests its purpose.

The different naming conventions that could be used are Hungarian Notation and Camel Case Notation. The first
naming convention came to be known as “Hungarian Notation” because the prefixes make the variable names look a bit as
though they’re written in some non-English language and because it is originally from Hungary. The Hungarian naming
convention is quite useful it’s one technique among many that helps programmers produce better code faster. The name of
the variable is its type and intended use.

The second naming convention is the Camel Case Notation. It is the practice of writing compound words or phrases in
which the words are joined without spaces and are capitalized within the compound word thus looking like a hump of a
camel.
The Address Operator

Declaring a variable reserves memory. Use the address operator (&) to learn the address of this reserved memory.

The operating system, not the programmer, chooses the address at which to store a variable. The particular address
chosen by the operating system depends on the data type of the variable, how much memory already has been reserved, and
other factors.

Using the Address and sizeof Operators with Variables

Use the sizeof operator to learn the size of different data types. Also, use the sizeof operator to determine the size of
different variables. The parentheses following the sizeof operator refer to a data type or variable name.

The operating system often attempts to place declared variables near each other. However, this is not always possible,
depending on factors such as the size of the variables and memory already reserved. There is no guarantee that two variables
will even be near each other in memory.

Assigning Values to Variables

The purpose of a variable is to store information. After creating a variable, the next logical step is to specify the
information that the variable will store. This is called assigning a value to a variable. A variable can be assigned a value
supplied by the programmer in code. A variable also can be assigned a value by the user, usually via the keyboard, when the
program is running.

Assignment Operator

Use the assignment operator to assign a value to a variable. The assignment operator looks like the equal sign. However,
in C++ the = sign is not used to test for equality; it is used for assignment. In C++ the equal sign is ==, also called the equality
operator. The variable must be declared either before, or at the same time, it is assigned a value, not afterward.

Initialization is when a variable is assigned a value as part of the same statement that declares that variable.

A variable cannot be declared after it is assigned a value.

The value assigned to a variable need not be a literal value.

A value can be assigned to several variables at once.

Also, another value can be assigned again to a variable after it has already been assigned a value because variable means
likely to change or vary.

Assigning a “Compatible” Data Type

The value assigned to a variable must be compatible with the data type of the variable that is the target of the assignment
statement.

The value being assigned need not necessarily be the same data type as the variable to which the value is being assigned.

Overflow and Underflow

Overflow occurs when a variable is assigned a value too large for its range. The value overflows and wraps around to
the data type’s lowest possible value.

The converse of overflow is an underflow. Underflow occurs when a variable is assigned a value too small for its range.
The value underflows and wraps around to the data type’s highest possible value.
Using the cin Operator

Use the cin object to obtain information from standard input, which usually is the keyboard. It is defined in the standard
library file <iostream.h>. The cin object is followed by >>, which is the stream extraction operator. It obtains the input, usually
from the keyboard, and assigns that input to the variable to its right. A cin statement usually is preceded by a cout statement
telling the user what to do. This is called a prompt.

Assigning a “Compatible” Data Type

The value being assigned by the cin operator need not necessarily be the same data type as that of the variable to which
the value is being assigned. The value being assigned by the cin operator must be compatible with the data type of the variable
to which the value is being assigned. There would be no compile error since at the time of compilation there was no attempt
to assign an incompatible value. The error will be known only at run time. The data types in the cin statement may be different.
What is important is that the order of the input matches the order of the data types of the variables in the cin statement.

Inputting Values for Multiple Variables

Instead of having separate prompts and cin statements for each variable, have one cin statement assign values to all three
variables. When using one cin statement to assign values to multiple variables, the user separates each input by one or more
spaces. The space tells the cin object that the user has finished assigning a value to one variable and the next input should be
assigned to the next variable in the cin statement. As before, the user finishes input by choosing the ENTER key.

Inputting Multiple Words into a String

The cin operator will only take the first word of a string. cin object interprets the space between texts as indicating that the
user has finished inputting the value of the variable. The solutions for this involve using either the get or getline method of
the cin object.

Arithmetic Operators

Many computer programs need to perform calculations. Computers, in addition to being able to store vast amounts of
data, also can calculate far more quickly and accurately than a human can.

An operator is a symbol that represents a specific action. Operators used for arithmetic are called arithmetic operators.

% operator, also called the modulus operator, returns the remainder in the division. Arithmetic operators are binary
operators because they operate on two operands, binary being a reference to 2, and operand referring to each of the two values
that are in the arithmetic expression. Note that not all operators are binary. The negative sign or negation is a unary operator
because it operates on only one operand. There are also ternary operators, which operates on 3 operands.

Arithmetic operators work with negative as well as positive numbers, and, except for the modulus operator, floating-
point numbers as well as whole numbers. The addition operator also works with strings as well as with numbers.

The Addition Operator

Combined Assignment and Arithmetic Operator

In Mathematics, a variable cannot equal itself plus another number. In C++ programming, the = operator is not used for
equality but instead for assignment. Another way to express:

total += added;

The compact form of combining arithmetic and assignment operators is not limited to the addition operator. It can also be
used with the other arithmetic operators.

The arithmetic operation has precedence over the assignment operation. The addition is performed before the assignment.
Precedence also arises when more than one arithmetic operator is used in a statement.
Overflow and underflow apply to the results of addition.

Adding Strings

Although addition does involve numeric operands, the addition operator also can be used with string operands. Adding
two strings has the effect of appending the second-string operand to the first-string operand. Appending means adding the
contents of the second string to the end of the first string. While numbers and numbers or strings and strings can be added,
attempting to add a number and a string will cause a compile error.

The Subtraction Operator

The effect of overflow and underflow is the same with the subtraction operator as with the addition operator. Unlike the
addition operator, the subtraction operator will not work with string operands.

The Multiplication Operator

The effect of overflow and underflow is the same with the multiplication operator as with the addition and subtraction
operators. Unlike the addition operator, but like the subtraction operator, the multiplication operator will not work with string
operands.

Precedence Between Arithmetic Operators

The order in which the two arithmetic operations are performed makes a difference. C++ has a rule, called precedence,
for determining which operation is performed first.

C++ also has rules called associativity for determining which operation is performed first when two operators have
equal precedence.

Override the default precedence with parentheses. Expressions in parentheses are done first.

The Division Operators

The division has two operators. The / operator gives the quotient while the % (or modulus operator) gives the remainder.

The Division Operator

Division operator returns the quotient. The value of the quotient depends on whether at least one of the operands is a
floating-point data type. In C++, when both operands are an integer or other whole number data type, then the result is an
integer as well, and the remainder is not part of the quotient.

When at least one of the operands is a floating-point data type, then the result is a floating-point as well.

If the result of the division of two integer variables needs to be float, then cast one of the variables to float. A cast does
not change the data type of the variable, just the data type of the value of the variables during the completion of the operation.
Cast the variable by putting the desired data type in front of it in an expression, and placing either the desired data type or
the variable in parentheses.

The Modulus Operator

Modulus operator also involves division but returns only the remainder. Modulus operator works only with whole
number operands. The result of an attempt to use it with a floating-point operand is undefined. The result often is a compile
error. Whether using the / or the % operator, it cannot divide by zero. The result is an error.
Exponent

C++, unlike some programming languages, does not have an exponent operator. Instead, it has a built-in function named
pow, which is defined in the standard library file math. pow is shorthand for power since with exponents one number is
raised to the power of another. pow function has two arguments. The first argument is the number that is being raised to a
certain power. The second argument is the power the first argument is being raised to.

pow function returns a double data type. Floating-point numbers also can be raised to a power, resulting in another
floating-point number. Whole numbers can be raised to a negative power, which also may result in a floating-point number.

You might also like