Chpter 3: The Programming Process

You might also like

You are on page 1of 19

CHPTER 3

C++ Programming Basics

The Programming Process

How exactly do we program? (This is an algorithm for programming with C++.)

1. Using a text editor, write the program: The files you create with your editor are called source
files.

2. Save it as a file (.cpp extension)

3. Fix any errors that you might have

4. Compile your program into object code. If there are errors, go back to step 3

5. Run the linker to generate executable code. If there are errors, go back to step 3

6. Run (execute) your program and test it. If there are errors, go back to step 3.

 Source Code: The instructions written in C++. This is the only part that we can understand.
 Compiler: Translates the source code into some intermediate form
 Linker: links our object code with other object codes (libraries) to create our executable
program.
 Run: An executable program, once converted into machine code, is ready to run (execute)
on our computer.

Integrated Development Environment (IDE)

 Has tools to assist the programmer


 Includes the compiler, linker, debugger and editor
 Automates and simplifies the programming process
In practice all steps to compile, link, debug, run are usually invoked by a single command or click
in IDE and the Programmer will not even see the intermediate files generated.

For this course, we will be using the visual studio IDE.

By Ins. Merihun N.
Basic Program Construction

Let us look at a simple code that would print the words Hello World

Let us look various parts of the above program:

 Comment line All lines beginning with two slash signs (//) are considered comments and
do not have any effect on the behavior of the program. The programmer can use them to
include short explanations or observations within the source code itself. In this case, the
line is a brief description of what our program is.
 Lines beginning with a hash sign (#) are preprocessor directives. They are not regular
code lines with expressions but indications for the compiler's preprocessor. In this case the
directive #include<iostream> tells the preprocessor to include the iostream standard
file. This specific file (iostream) includes the declarations of the basic standard input-
output library in C++, and it is included because its functionality is going to be used
later in the program.
 All the elements of the standard C++ library are declared within what is called a
namespace, the namespace with the name std. So in order to access its functionality we
declare with this expression that we will be using these entities.
 This line corresponds to the beginning of the definition of the main function. The main
function is the point by where all C++ programs start their execution, independently of its
location within the source code. It is essential that all C++ programs have a main function.
The word main is followed in the code by a pair of parentheses (()).
Right after these parentheses we can find the body of the main function enclosed in
braces ({}). What is contained within these braces is what the function does when it is
executed.
 C++ statement. A statement is a simple or compound expression that can actually
produce some effect. In fact, this statement performs the only action that generates a
visible effect in our first program. A statement ends with a semicolon character (;). Note
that cout is iostream standard file and is used to display characters in the standard output
stream like the computer monitor.
 The return statement causes the main function to finish. return may be followed by a
return code (in our example is followed by the return code with a value of zero). A return
code of 0 for the main function is generally interpreted as the program worked as expected

By Ins. Merihun N.
without any errors during its execution. This is the most usual way to end a C++ console
program.
 In C++, the semicolon is a statement terminator. That is, each individual statement must
be ended with a semicolon. It indicates the end of one logical entity. For example,
following are three different statements:

The 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, instead of

We could have written:

All in just one line and this would have had exactly the same meaning as the previous code.

Comments are parts of the source code disregarded by the 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 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. We
are going to add comments to our second program:

By Ins. Merihun N.
Variables

While doing programming in any programming language, you need to use various variables to
store various information. Variables are nothing but reserved memory locations to store values.
This means that when you create a variable you reserve some space in memory.

All variables have three important properties:

• Data Type: a type which is established when the variable is defined. You may like to store
information of various data types like character, wide character, integer, floating point,
double floating point, Boolean, etc. Based on the data type of a variable, the operating
system allocates memory and decides what can be stored in the reserved memory.
• Name: a name which will be used to refer to the value in the variable. A unique identifier for
the reserved memory location.
• Value: a value which can be changed by assigning a new value to the variable or initialized
during the variable declaration time.

Built- in Data Types:

C++ offer the programmer a rich assortment of built-in as well as user defined data types.
Following table list down five basic C++ data types:

Several of the basic types can be modified using one or more of these type modifiers: signed, unsigned,
short, long.

By Ins. Merihun N.
Signed integers are either negative or positive. Unsigned integers are always positive. Because
both signed and unsigned integers require the same number of bytes, the largest number (the
magnitude) that can be stored in an unsigned integer is twice as the largest positive number that
can be stored in a signed integer.

Declaring Variables: Variables can be created in a process known as declaration.

Syntax: Data type Variable_Name;

The declaration will instruct the computer to reserve a memory location with the name and size
specified during the declaration. Good variable names indicate the purpose of the variable or they
should be self-descriptive.

E.g. int myAge; //variable used to store my age

Identifiers

A C++ identifier is a name used to identify a variable, function, class, module, or any other userdefined
item.

C++ has strict rules for naming identifiers.

1. You can use upper and lowercase letters, and the digits
2. You can also use the underscore (_).
3. The first character must be a letter or underscore.
4. Identifiers can be as long as you like, but most compilers will only recognize the first few
hundred characters.

By Ins. Merihun N.
5. The compiler distinguishes between upper- and lowercase letters, so identifier “sum” is not the
same as identifier “SUM”.
6. You can‟t use a C++ keyword as an identifier.

The following list shows the reserved words (keyword) in C++. These reserved words may not be
used as constant or variable or any other identifier names.

Here are some examples of acceptable identifiers:

Initializing Variables When a variable is assigned a value at the time of declaration, it is called variable
initialization. This is identical with declaring a variable and then assigning a value to the variable
immediately after declaration.

ƒ The syntax: DataType variable name = initial value;

e.g. int a = 0;

char c = „A‟;

double tax = 0.15;

float pi = 3.14;

Scope of Variables Scope of a variable is the boundary or block in a program where a variable can
be accessed. The boundary or block is identified by the left and right curl braces.

By Ins. Merihun N.
• In C++, we can declare variables anywhere in the source code. But we should declare a
variable before using it no matter where it is written.
• Global variables: are variables that can be referred/accessed anywhere in the code, within
any function, as long as it is declared first. A variable declared before any function
immediately after the include statements are global variables.
• Local Variables: the scope of the local variable is limited to the code level or block within
which they are declared.
Example:
#include<iostream>
usingnamespace std;
int x; // global variable
int main{
while ( int y > 0 ){ // int y is local variable
cout<<” positive”;
}
}

Characters: Characters variables (type char) are typically one byte in size, enough to hold 256
different values. A char can be represented as a small number (0 - 255). Char in C++ are represented
as any value inside a single quote.

E.g.: „x‟, „A‟, „5‟, „a‟, etc.

When the compiler finds such values (characters), it translates back the value to the ASCII values.
E.g. „a‟ has a value 97 in ASCII.

In C++, there are some special characters used for formatting. These are:
\n new line

\t tab

\b backspace etc…

Constants A constant is any expression that has a fixed value. Like variables, constants are data
storage locations in the computer memory. But, constants, unlike variables their content cannot
be changed after the declaration. Constants must be initialized when they are created by the
program, and the programmer can‟t assign a new value to a constant later. E.g.: const int
studentPerClass = 65; const double pi = 3.14;

Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provides the following types of operators

By Ins. Merihun N.
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators

This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other operators one
by one.

1. Arithmetic Operators
There are following arithmetic operators supported by C++ language, Assume variable A holds 10
and variable B holds 20, then

Try the following example to understand all the arithmetic operators available in C++.

Copy and paste the following C++ program in test.cpp file and compile and run this program.

By Ins. Merihun N.
When the above code is compiled and executed, it produces the following result

2. Relational Operators
These operators establish a relationship between operands. Two expressions can be compared
using relational and equality operators. For example, to know if two values are equal or if one is
greater than the other.

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

By Ins. Merihun N.
There are following relational operators supported by C++ language

Assume variable A holds 10 and variable B holds 20, then

Here there are some examples:

Of course, it's not just numeric constants that can be compared, but just any value, including, of course,
variables. Suppose that a=2, b=3 and c=6, then:

3. Assignment Operators

By Ins. Merihun N.
It takes the right-hand side (called rvalue) and copies it into the left-hand side (called lvalue). There
are following assignment operators supported by C++ language

Example:

You must notice that assignment operator is (=) and there is a relational operator, for equivalent (=
=). These two are different from each other, the assignment operator assigns the value to any
variable, whereas equivalent operator is used to compare values, like in if-else conditions,
Example:

4. Logical Operators

By Ins. Merihun N.
They are used to combine two different expressions together. If two statement are connected using
AND operator, the validity of both statements will be considered, but if they are connected using
OR operator, then either one of them must be valid. These operators are mostly used in loops and
in Decision making.

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

The logical operators && and || are used when evaluating two expressions to obtain a single
relational result. The operator && corresponds to the Boolean logical operation AND, which
yields true if both its operands are true, and false otherwise. The following panel shows the result
of operator && evaluating the expression a&&b:

The operator || corresponds to the Boolean logical operation OR, which yields true if either of its
operands is true, thus being false only when both operands are false. Here are the possible results

By Ins. Merihun N.
of a||b:

When using the logical operators, C++ only evaluates what is necessary from left to right to come
up with the combined relational result, ignoring the rest. Therefore, in the last example ((5==5)||
(3>6)), C++ evaluates first whether 5==5 is true, and if so, it never checks whether 3>6 is true or
not. This is known as short-circuit evaluation, and works like this for these operators:

5. Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. The truth tables for &, |, and ^ are
as follows:

Assume if A = 60; and B = 13; now in binary format they will be as follows:

A = 0011 1100

B = 0000 1101

A&B = 0000 1100

A|B = 0011 1101

By Ins. Merihun N.
A^B = 0011 0001

~A = 1100 0011

The Bitwise operators supported by C++ language are listed in the following table. Assume variable
A holds 60 and variable B holds 13, then

6. Other Operators

The following table lists some other operators that C++ supports.

 sizeof ()

sizeof operator returns the size of a variable. For example, sizeof(a), where „a‟ is integer, and
will return 4. The syntax of using sizeof is as follows

 Condition ? X : Y

Conditional operator (?). If Condition is true then it returns value of X otherwise returns value of Y.
The ? is called a ternary operator because it requires three operands and can be used to replace if-
else statements. the syntax:

Example:

By Ins. Merihun N.
Output:

 Comma operator(,)

Comma operator causes a sequence of operations to be performed. The value of the entire comma
expression is the value of the last expression of the comma-separated list.

Example:

Assigns var the value of the rightmost expression, count+1, which is 20.

 Cast

Casting operators convert one data type to another. For example, int(2.2000) would return 2.
Example:

By Ins. Merihun N.
Output:

 &

Pointer operator & returns the address of a variable. For example &a; will give actual address of the
variable. &var will be read as "the address of var".

 *

Indirection Operator *, it is the complement of &. It is a unary operator that returns the value of the
variable located at the address specified by its operand.

Example:

By Ins. Merihun N.
Output:

Operators Precedence in C++


Operator precedence determines the grouping of terms in an expression. This affects how an expression
is evaluated. Certain operators have higher precedence than others; for example, the multiplication
operator has higher precedence than the addition operator.

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.

The list is in order of decreasing precedence.

By Ins. Merihun N.
Exercise
1. Using the above table, evaluate the following expressions

a) 4+7*6/3-5

b) 15/3*34-(5+7)/6

c) ++23/-3+3--

2. Write a program to verify your answer for question 1.

3. what is reminder for 5.0%2 ?

4. what is the maximum length of identifier?

5. what is d/ce b/n variable declaration and initialization ?

6.

By Ins. Merihun N.
6. What is the output of the following program?

By Ins. Merihun N.

You might also like