Programming chapter 2
Programming chapter 2
Dec 2025
Page 1
Computer programming for Engineers Programming
Dec 2025
compiler. They simply do nothing. Their purpose is only to allow the programmer to insert notes or
descriptions embedded within the source code. C++ supports two ways to insert comments:
The first of them, known as single line comment, discards everything from where the pair of slash signs (//)
is found up to the end of that same line. The second one, known as block comment, discards everything
between the /* characters and the first appearance of the */ characters, with the possibility of including more
than one line.
Page 2
Computer programming for Engineers Programming
Dec 2025
The function body in C++ program is enclosed between two flower brackets (curly braces). The opening
flower bracket ({ ) marks the beginning of a function. What is contained within these braces is what the
function does when it is executed.
Fifth line cout << "Hello World!"; function body
This line is a C++ statement. A statement is a simple or compound expression that can actually produce
some effect. cout represents the standard output stream in C++, and the meaning of the entire statement is to
insert a sequence of characters (in this case the Hello World sequence of characters) into the standard output
stream (which usually is the screen).
Sixth line return 0; Return
The return statement causes the main function to finish (terminate). return may be followed by a return code
(in our example is followed by the return code 0). A return code of 0 for the main function is generally
interpreted as the program worked as expected without any errors during its execution. This is the most
usual way to end a C++ console program.
Seventh line } function end
The end of a function body is marked by the closing flower bracket (closing brace}). When the compiler
gets bracket it is replaced by the statement return 0;
The above example program has been structured in different lines in order to be more readable, but in C++,
we do not have strict rules on how to separate instructions in different lines. For example, we could write
the above program as:
int main () { cout << "Hello World!"; return 0; }
All in just one line and this would have had exactly the same meaning as the previous code. In C++, the
separation between statements is specified with an ending semicolon (;) at the end of each one, so the
separation in different code lines does not matter at all for this purpose. We can write many statements per
line or write a single statement that takes many code lines. The division of code in different lines serves only
to make it more legible and schematic for the humans that may read it. Let us add an additional instruction
to our first program:
#include <iostream.h>
int main ()
{
cout << "Hello World! ";
cout << "I'm a C++ program";
return 0;
}
In this case, we performed two insertions into cout in two different statements. Once again, the separation in
different lines of code has been done just to give greater readability to the program, since main could have
been perfectly valid defined this way:
int main () { cout << " Hello World! "; cout << " I'm a C++ program "; return 0; }
We were also free to divide the code into more lines if we considered it more convenient:
int main ()
{
cout <<
"Hello World!";
cout
<< "I'm a C++ program";
return 0;
}
And the result would again have been exactly the same as in the previous examples.
Preprocessor directives (those that begin by #) are out of this general rule since they are not statements.
They are lines read and processed by the preprocessor and do not produce any code by themselves.
Preprocessor directives must be specified in their own line and do not have to end with a semicolon (;).
I/O streams
Using the standard input and output library, we will be able to interact with the user by printing messages on
the screen and getting the user's input from the keyboard. C++ uses a convenient abstraction called streams
to perform input and output operations in sequential media such as the screen or the keyboard. A stream is
an object where a program can either insert or extract characters to/from it. The standard C++ library
includes the header file iostream, where the standard input and output stream objects are declared.
Standard Output (cout): By default, the standard output of a program is the screen, and the C++ stream
object defined to access it is cout. cout is used in conjunction with the insertion operator, which is written as
<< (two "less than" signs).
Page 4
Computer programming for Engineers Programming
Dec 2025
even though we had written them in two different insertions into cout. In order to perform a line break on
the output we must explicitly insert a new-line character into cout. In C++ a new-line character can be
specified as \n (backslash, n):
cout << "First sentence.\n ";
Page 5
Computer programming for Engineers Programming
Dec 2025
cin can only process the input from the keyboard once the Enter key has been pressed. Therefore, even if
you request a single character, the extraction from cin will not process the input until the user presses Enter
after the character has been introduced.
You must always consider the type of the variable that you are using as a container with cin extractions. If
you request an integer you will get an integer, if you request a character you will get a character and if you
request a string of characters you will get a string of characters.
You can also use cin to request more than one datum input from the user:
cin >> a >> b;
is equivalent to:
cin >> a;
cin >> b;
In both cases the user must give two data, one for variable a and another one for variable b that may be
separated by any valid blank separator: a space, a tab character or a newline.
Page 6
Computer programming for Engineers Programming
Dec 2025
Debugging
A mistake in a program is called a bug. For this reason, the process of eliminating mistakes in your program
is called debugging. Debugging is the process of correcting errors from the program via testing. There are
three commonly recognized types of bugs or errors, which are known as syntax errors, run-time errors, and
logic errors.
A syntax error is a grammatical mistake in your program; that is, a mistake in the allowed arrangement of
words and punctuations. If you violate one of these rules-for example, by omitting a required punctuation-it
is a syntax error. The compiler will catch syntax errors and output an error message telling you that it has
found the error, where it thinks the error is, and what it thinks the error is. If the compiler says you have a
syntax error, you undoubtedly do. However, the compiler could be incorrect about where and what the error
is.
An error that is not detected until your program is run is called a run-time error. If the computer detects a
run-time error when your program is run, then it will output an error message. The error message may not
be easy to understand, but at least it lets you know that something is wrong. For example, division by zero:
If there is any place(instruction ) which attempts to any number by zero, this error will not be syntax error
instead runtime error.
A mistake in the underlying algorithm for your program is called a logic error. If your program has only
logic errors, it will compile and run without any error message. You have written a valid C++ program, but
you have not written a program that does what you want. The program runs and gives output, but the output
is incorrect. For example, if you were to mistakenly use the multiplication sign in place of the addition sign,
it would be a logic error. Logic errors are the hardest kind of error to locate, because the computer does not
give you any error messages.
Page 7
Computer programming for Engineers Programming
Dec 2025
Identifier refers to the name of variables, functions, arrays classes, etc. created by the programmer. They are
fundamental requirements of any language. Each language has its own rules for naming these identifiers. C+
+ imposes the following rules for creating valid names (identifiers).
Only alphabetic characters, digits and underscores are permitted
The name should start with a letter or an underscore ( _ ) cannot start with a digit.
Names must be all one word (no spaces or hyphens).
Keyword is not permitted.
Upper and lower case letters are distinct. That is, C++ is case sensitive Language.
Example:
Keywords
Keywords are certain words reserved by C++. All keywords have fixed meaning which cannot be changed.
All keywords must be written in lowercase and cannot be used as identifiers. The list of keywords supported
in C++ language is given in Table 2.1.
A variable is an entity whose value can be changed during program execution and is known to the program
by a name. It is the content of a memory location that stores a certain value. A variable can hold only one
value at a time during program execution. Its value can be changed during the execution of the program.
The various components associated with variables are the following:
Data type: char, int, float
Variable name: user view
Binding address: machine view
Value: data stored in memory location
Variable Names
Variable names are identifiers used to name variables. They are the symbolic names assigned to the memory
location. A variable name consists of a sequence of letters and digits. The rules that apply to identifiers
(given above) also apply to variable names.
Data Types
When programming, we store the variables in our computer's memory, but the computer has to know what
kind of data we want to store in them, since it is not going to occupy the same amount of memory to store a
simple number than to store a single letter or a large number, and they are not going to be interpreted the
same way.
The memory in our computers is organized in bytes. A byte is the minimum amount of memory that we can
manage in C++. A byte has 8 bits.
C++ supports a variety of data types and the programmer can choose the type to the needs of the
application. The basic data types in C++ are the following:
Character denoted by char is the data type that holds an integer value corresponding to the
representation of an element of the ASCII character set.
Integer denoted by int is the data type that holds an integer value or whole number.
Real denoted by:
o float is the data type that holds single precision floating point value or real number.
o double is the data type that holds a double precision floating point value or real number.
Boolean denoted by bool is the data type that holds a Boolean value of true or false.
Page 9
Computer programming for Engineers Programming
Dec 2025
Page 10
Computer programming for Engineers Programming
Dec 2025
Page 11
Computer programming for Engineers Programming
Dec 2025
Variable Declaration/Definition
A declaration of a variable is a statement that gives information about the variables to the C++ compiler. A
variable must be defined before using it in a program. It reserves memory required for data storage and
associates it with a symbolic name. The syntax for defining a variable is:
int a;
float mynumber;
Are valid declarations of variables. The first one declares a variable of type int with the identifier a. The
second one declares a variable of type float with the identifier mynumber. Once declared, variables a and
mynumber can be used within the rest of their scope in the program.
If you need to declare several variables of the same type and you want to save some writing work you can
declare all of them in the same line separating the identifiers with commas. For example:
int a, b, c;
declares three variables (a, b and c) of type int and has exactly the same meaning as if we had written:
int a;
int b;
int c;
Initialization of variables
In C++, a variable can be assigned with a value during its definition or during the execution of the program.
The assignment operator (=) used in both cases. The syntax for variable initialization during its definition:
For example, if we want to declare an int variable called a initialized with a value of 0 at the moment in
which it is declared, we could write:
int a = 0;
Page 12
Computer programming for Engineers Programming
Dec 2025
When multiple variables are being declared in a single statement, initialization is carried out in the following
way:
Data type variable name1 = value1, variable name2 = value2,…, variable nameN = valueN;
Example:
int i=10,j=5,k=8;
Operators are symbols that tell the computer to perform certain mathematical or logical manipulation. An
operator is a symbol that operates on one or more expressions, producing a value that can be assigned to a
variable. C++ provides many built-in operators for composing expressions. An expression, by the way, is
any computation which yields a value. It is a combination of variables, constants and operators written
according to the syntax of the language. The several C++ operators can be classified in to:
% Remainder 13 % 3 // gives 1
Page 13
Computer programming for Engineers Programming
Dec 2025
Except for remainder (%) all other arithmetic operators can accept a mix of integer and real operands.
Generally, if both operands are integers then the result will be an integer. However, if one or both of the
operands are reals then the result will be a real (or double to be exact).
When both operands of the division operator (/) are integers then the division is performed as an integer
division and not the normal division we are used to. Integer division always results in an integer outcome
(i.e., the result is always rounded down).
For example:
9/2 // gives 4, not 4.5!
It is possible for the outcome of an arithmetic operation to be too large for storing in a designated variable.
This situation is called an overflow. The outcome of an overflow is machine-dependent and therefore
undefined. It is illegal to divide a number by zero. This results in a run-time division-by-zero failure, which
typically causes the program to terminate.
2. Relational Operators
A relational operator is used to make comparison between two expressions. C++ provides six relational
operators for comparing numeric quantities (Table 2.4). Relational operators usually evaluate to 1
(representing the true outcome) or 0 (representing the false outcome). The operands of a relational
operator must evaluate to a number.
Operator Name Example
Page 14
Computer programming for Engineers Programming
Dec 2025
3. Logical Operators
Logical operators connect two or more relational expressions into one or reverse the logic. C++ provides
three logical operators, summarized in Table 2.5, for combining logical expressions. Like the relational
operators, logical operators evaluate to 1 or 0.
Operator Name Example
1
C++ provides library functions (e.g., strcmp) for the lexicographic comparison of string.
Page 15
Computer programming for Engineers Programming
Dec 2025
The assignment operator has a number of variants, obtained by combining it with the arithmetic operators
(Table 2.6).
= n = 25
+= n + = 25 n = n + 25
-= n - = 25 n = n - 25
*= n * = 25 n = n * 25
/= n / = 25 n = n / 25
%= n %= 25 n = n % 25
Page 16
Computer programming for Engineers Programming
Dec 2025
The auto increment (++) and auto decrement (--) operators provide a convenient way of, respectively, adding
and subtracting 1 from a numeric variable. These are summarized in Table 2.7. The examples assume the
following variable definition:
int k = 5;
Page 17
Computer programming for Engineers Programming
Dec 2025
Operator Precedence
The order in which operators are evaluated in an expression is significant and is determined by precedence
rules. These rules divide the C++ operators into a number of precedence levels (see Table 2.8). Operators in
higher levels take precedence over operators in lower levels.
() Parentheses
[] array subscript
++ Unary post increment left to right
-- unary post decrement
* multiplication left to right
/ division
% modulus
+ addition left to right
- subtraction
< relational less than relational less left to right
< than or equal to relational greater
=> than relational greater than or
>= equal to
== relational is equal to relational is
!= not equal to
= assignment right to left
+= addition assignment
-= subtraction assignment
*= multiplication assignment
/= division assignment
%= modulus assignment
Table 2.8: Operator Precedence Levels
For example, in
a == b + c * d
c * d is evaluated first because * has a higher precedence than + and ==. The result is then added to b because
+ has a higher precedence than ==, and then == is evaluated. Precedence rules can be overridden using
brackets. For example, rewriting the above expression as
a == (b + c) * d
causes + to be evaluated before *.
Page 18
Computer programming for Engineers Programming
Dec 2025
Operators with the same precedence level are evaluated in the order specified by the last column of Table
2.8.
For example, in
a = b += c
the evaluation order is right to left, so first b += c is evaluated, followed by a = b.
Page 19