0% found this document useful (0 votes)
5 views19 pages

Programming chapter 2

Chapter Two of the document introduces C++ programming, highlighting its evolution from machine language to higher-level languages like FORTRAN and C++. It covers the structure of a C++ program, including comments, preprocessor directives, functions, and input/output operations using streams. Additionally, it discusses debugging, basic elements of C++, including identifiers and keywords, as well as variables and data types.

Uploaded by

abrish2005
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
0% found this document useful (0 votes)
5 views19 pages

Programming chapter 2

Chapter Two of the document introduces C++ programming, highlighting its evolution from machine language to higher-level languages like FORTRAN and C++. It covers the structure of a C++ program, including comments, preprocessor directives, functions, and input/output operations using streams. Additionally, it discusses debugging, basic elements of C++, including identifiers and keywords, as well as variables and data types.

Uploaded by

abrish2005
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 19

Computer programming for Engineers Programming

Dec 2025

Chapter Two C++ Basics


Introduction
In the early days of computing, programs were written in machine language, which consists of the primitive
instructions that can be executed directly by the machine. Machine language programs are difficult to
understand, mostly because the structure of machine language reflects the design of the hardware rather than
the needs of programmers. In the mid-1950s, a group of programmers had an idea that profoundly changed
the nature of computing. In 1955, the initial version of FORTRAN (whose name is an abbreviation of
formula translation), which was the first example of a higher level programming language produced. Since
that time, many new programming languages have been invented, such as COBOL, BASIC, PASCAL, C,
C++, C#, JAVA etc.
C++ began as an expanded version of C. The C++ extensions were first invented by Bjarne Stroustrup in
1979 at Bell Laboratories in Murray Hill, New Jersey. He initially called the new language "C with
Classes." However, in 1983 the name was changed to C++. C++ allows programmers to comprehend and
manage larger, more complex programs because it includes Object Oriented features.
C++ is a high-level language: when you write a program in it, the short hands are sufficiently expressive
that you don’t need to worry about the details of processor instructions.
2.1. Structure of C++ program
Probably the best way to start learning a programming language is by writing a program. Therefore, here is
our first program:
This program is one of the simplest programs
// my first program in
C++ that can be written in C++, but it already
#include <iostream.h>
contains the fundamental components that
int main ()
{ every C++ program has. We are going to
cout << "Hello World!";
look line by line at the code we have just
return 0;
} written:

First line // my first program in C++ comment


This is a comment line. All lines beginning with two slash signs (//) are considered comments and do not
have any effect on the behavior of the program. Comments are parts of the source code disregarded by the

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:

//single line comment

/* double line comment */

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.

Second line #include <iostream.h> preprocessor directive


Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code lines with
expressions but indications for the compiler's preprocessor. This line uses the preprocessor directive
#include to include the contents of the header file iostream.h in the program. iostream.h is a standard C++
header file and contains definitions for input and output and it is included because its functionality is going
to be used later in the program.
You have heard about compilers of C++. But also, there is another program called preprocessor which
always run before the compiler each time one starts the compiler. The function of the preprocessor program
is to look for all lines which begin with the pound symbol (#) throughout the program. And having these
lines of the program, the preprocessor will ‘read in’ or copy the content of the header files specified after
include into the program to make the program ready to be compiled. It is after this time the compiler starts
acting on the program (translating and checking for syntax errors).
N.B: there are a number of header files with their own content and it is possible to include multiple header
files.
Third line int main () function declarator
This line corresponds to the beginning of the definition of the main function. Every C++ program must have
one function with the name main, from where the execution of the program begins. The word main is
followed in the code by a pair of parentheses ( ) which is mandatory.
Fourth line { function begin

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:

// my second program in C++


Program Output
Page 3

Hello World! I'm a C++ program


Computer programming for Engineers Programming
Dec 2025

#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

cout << "Output sentence"; // prints Output sentence on screen


cout << 120; // prints number 120 on screen
cout << x; // prints the content of x on screen
The << operator inserts the data that follows it into the stream preceding it. In the examples above it inserted
the constant string Output sentence, the numerical constant 120 and variable x into the standard output
stream cout. Notice that the sentence in the first instruction is enclosed between double quotes (") because it
is a constant string of characters. Whenever we want to use constant strings of characters we must enclose
them between double quotes (") so that they can be clearly distinguished from variable names. For example,
these two sentences have very different results:
cout << "Hello"; // prints Hello
cout << Hello; // prints the content of Hello variable
The insertion operator (<<) may be used more than once in a single statement:
cout << "Hello, " << "I am " << "a C++ statement";
This last statement would print the message Hello, I am a C++ statement on the screen. The utility of
repeating the insertion operator (<<) is demonstrated when we want to print out a combination of variables
and constants or more than one variable:
cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode;
If we assume the age variable to contain the value 24 and the zipcode variable to contain 90064 the output
of the previous statement would be:
Hello, I am 24 years old and my zipcode is 90064
It is important to notice that cout does not add a line break after its output unless we explicitly indicate it,
therefore, the following statements:
cout << "This is a sentence.";
cout << "This is another sentence.";
Will be shown on the screen one following the other without any line breaks between them:
This is a sentence. This is another sentence.

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

cout << "Second sentence.\nThird sentence.";


This produces the following output:
First sentence.
Second sentence.
Third sentence.
Additionally, to add a new-line, you may also use the endl manipulator. For example:
cout << "First sentence." << endl;
cout << "Second sentence." << endl;
Would print out:
First sentence.
Second sentence.
The endl manipulator produces a newline character, exactly as the insertion of '\n' does.
Standard Input (cin): The standard input device is usually the keyboard. Handling the standard input in C+
+ is done by applying the overloaded operator of extraction (>>) on the cin stream. The operator must be
followed by the variable that will store the data that is going to be extracted from the stream. For example:
int age;
cin >> age;
The first statement declares a variable of type int called age, and the second one waits for an input from cin
(the keyboard) in order to store it in this integer variable.

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.

2.3 Basic elements of C++


Identifiers

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:

salary // valid identifier


salary2 // valid identifier
2salary // invalid identifier (begins with a digit)
_salary // valid identifier
Salary // valid but distinct from salary

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.

asm continue float new signed try

auto default for operator sizeof typedef

break delete friend private static union

case do goto protected struct unsigned

catch double if public switch virtual

char else inline register template void

class enum int return this volatile

const extern long short throw while

Table 2.1 - C++ keywords

Variables and Data types


Page 8
Computer programming for Engineers Programming
Dec 2025

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

The basic data types byte size are as follows:

Page 10
Computer programming for Engineers Programming
Dec 2025

char takes 1 byte double takes 8/10 bytes depending on


int takes 2/4 bytes depending on the the compiler
compiler bool takes 1 byte
float takes 4 bytes

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:

Data type Variable Name;


The variable name can be any valid C++ identifier. The data type can be int, char, float, double etc.
Example:

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:

Data type variable name = value;

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 and expressions

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:

 Arithmetic operators  Assignment operator

 Relational operators  Increment and Decrement operators

 Logical operators  Conditional operators

Table 2.2 Common operators in C++


1. Arithmetic Operators
C++ provides five basic arithmetic operators that are summarized in Table 2.3.
Operator Name Example

+ Addition 12 + 4.9 // gives 16.9

- Subtraction 3.98 - 4 // gives -0.02

* Multiplication 2 * 3.4 // gives 6.8

/ Division 9 / 2.0 // gives 4.5

% Remainder 13 % 3 // gives 1

Table 2.3: Arithmetic Operators

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

== Equality 5==5 // gives 1

!= Inequality 5!=5 // gives 0

< Less Than 5 < 5.5 // gives 1

<= Less Than or Equal 5 <= 5 // gives 1

> Greater Than 5 > 5.5 // gives 0

>= Greater Than or Equal 6.3 >= 5// gives 1

Table 2.4: Relational Operators


For example:

Page 14
Computer programming for Engineers Programming
Dec 2025

65 < 75 // gives 1 or true


Relational operators should not be used for comparing strings1, because this will result in the string addresses
being compared, not the string contents. For example, the expression
"HELLO" < "BYE"
causes the address of "HELLO" to be compared to the address of "BYE". As these addresses are determined
by the compiler (in a machine-dependent manner), the outcome may be 0 or 1, and is therefore not indicative
of the actual check.

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

! Logical Negation !(5 == 5) // gives 0

&& Logical AND 5 < 6 && 6 < 6 // gives 0

|| Logical OR 5 < 6 || 6 < 5 // gives 1

Table 2.5: Logical Operators


 Logical Negation is a unary operator, which negates the logical value of its single operand. If its
operand is nonzero it produces 0, and if it is 0 it produces 1.
 Logical AND produces 0 if one or both of its operands evaluate to 0. Otherwise, it produces 1.
 Logical OR produces 0 if both of its operands evaluate to 0. Otherwise, it produces 1.
Note that we talk of zero and nonzero operands (not 0 and 1). In general, any nonzero value can be used to
represent the logical true, whereas only zero represents the logical false. The following are, therefore, all
valid logical expressions:
!20 // gives 0
10 && 5 // gives 1
10 || 5.5 // gives 1
10 && 0 // gives 0

1
C++ provides library functions (e.g., strcmp) for the lexicographic comparison of string.

Page 15
Computer programming for Engineers Programming
Dec 2025

4. Assignment Operator (=)


The assignment operator is used for storing a value at some memory location (typically denoted by a
variable). When used, its right operand, which may be an arbitrary expression or a constant, is evaluated and
the outcome is stored in the location denoted by its left operand.

The assignment operator has a number of variants, obtained by combining it with the arithmetic operators
(Table 2.6).

Operator Example Equivalent To

= 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

Table 2.6: Assignment operators


An assignment operation is itself an expression whose value is the value stored in its left operand. An
assignment operation can therefore be used as the right operand of another assignment operation. Any
number of assignments can be concatenated in this fashion to form one expression. For example:
int m, n, p;
m = n = p = 100; // means: n = (m = (p = 100));
m = (n = p = 100) + 2; // means: m = (n = (p = 100)) + 2;
This is equally applicable to other forms of assignment. For example:
m = 100;
m += n = p = 10; // means: m = m + (n = p = 10);
5. Increment/Decrement Operators

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;

Operator Name Example

++ Auto Increment (prefix) ++k + 10 // gives 16

++ Auto Increment (postfix) k++ + 10 // gives 15

-- Auto Decrement (prefix) --k + 10 // gives 14

-- Auto Decrement (postfix) k-- + 10 // gives 15

Table 2.7: Increment and Decrement Operators


Both operators can be used in prefix and postfix form. The difference is significant. When used in prefix
form, the operator is first applied and the outcome is then used in the expression. When used in the postfix
form, the expression is evaluated first and then the operator applied. Both operators may be applied to integer
as well as real variables, although in practice real variables are rarely useful in this form.
6. Conditional (Ternary) operator
The conditional (Ternary) operator takes three operands. It has the general form:
operand1 ? operand2 : operand3
First operand1 is evaluated, which is treated as a logical condition. If the result is nonzero then operand2 is
evaluated and its value is the final result. Otherwise, operand3 is evaluated and its value is the final result.
For example:
int m = 1, n = 2;
int min = (m < n ? m : n); // min receives 1
Note that of the second and the third operands of the conditional operator only one is evaluated. Because a
conditional operation is itself an expression, it may be used as an operand of another conditional operation,
that is, conditional expressions may be nested. For example:
int m = 1, n = 2, p =3;
int min = (m < n ? (m < p ? m : p)
: (n < p ? n : p));

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.

Operator Type Associativity

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

You might also like