0% found this document useful (0 votes)
69 views9 pages

Chapter 2

Uploaded by

samuelmeresa19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views9 pages

Chapter 2

Uploaded by

samuelmeresa19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

1

Chapter 2
Fundamental of C++ Programing
2.1. Basics of programing
We know that, the computer can perform a variety of tasks, but not by its own. An instruction is
to be given to a computer for performing even a simple task. A computer program or just a program is a
sequence of instructions, written to perform a specified task with a computer. Computer programing is
the process of developing and implementing various sets of instructions to enable a computer to do a
certain task. The people who write programs are called programmers. Programmers use a variety of
special languages, called programming languages, to communicate with the computer. Some popular
programming languages are C++, Visual Basic, C#, and Java. In this course, you will use the C++
programming language.

Just as human beings communicate with each other through the use of languages such as
Amharic, English, Spanish and Chinese, programmers use a variety of programming languages to
communicate with the computer. In the next sections, you will follow the progression of programming
languages from machine languages to assembly languages, and then to high-level languages.

Machine Languages

Within a computer, all data is represented by microscopic electronic switches that can be either
off or on. The off switch is designated by a 0, and the on switch is designated by a 1. Because computers
can understand only these on and off switches, the first programmers had to write the program
instructions using nothing but combinations of 0s and 1s; for example, a program might contain the
instruction 00101 10001 10000. Instructions written in 0s and 1s are called machine language or machine
code. The machine languages (each type of machine has its own language) represent the only way to
communicate directly with the computer. As you can imagine, programming in machine language is very
tedious and error-prone and requires highly trained programmers.

Assembly Languages

Slightly more advanced programming languages are called assembly languages. The assembly
languages simplify the programmer’s job by allowing the programmer to use mnemonics in place of the
0s and 1s in the program. Mnemonics are memory aids—in this case, alphabetic abbreviations for
instructions. For example, most assembly languages use the mnemonic ADD to represent an add
operation and the mnemonic MUL to represent a multiply operation. An example of an instruction written
in an assembly language is ADD bx, ax. Programs written in an assembly language require an assembler,
which also is a program, to convert the assembly instructions into machine code—the 0s and 1s the
computer can understand. Although it is much easier to write programs in assembly language than in
machine language, programming in assembly language still is tedious and requires highly trained
programmers. Programs written in assembly language are machine specific and usually must be rewritten
in a different assembly language to run on a different computer.

Introduction to Computing ECEg-2033


2

High-Level Languages

High-level languages represent the next major development in programming languages. High-
level languages are a vast improvement over machine and assembly languages, because they allow the
programmer to use instructions that more closely resemble the English language. An example of an
instruction written in a high-level language is grossPay = hours * rate. In addition, high-level languages are
more machine independent than machine and assembly languages. As a result, programs written in a high
level language can be used on many different types of computers. Programs written in a high-level
language usually require a compiler, which also is a program, to convert the English-like instructions into
the 0s and 1s the computer can understand. Some high-level languages also offer an additional program
called an interpreter. Unlike a compiler, which translates all of a program’s high-level instructions before
running the program, an interpreter translates the instructions line by line as the program is running.

Like their predecessors, the first high-level languages were used to create procedure-oriented
programs. When writing a procedure-oriented program, the programmer concentrates on the major tasks
that the program needs to perform. A payroll program, for example, typically performs several major
tasks, such as inputting the employee data, calculating the gross pay, calculating the taxes, calculating the
net pay, and outputting a paycheck. The programmer must instruct the computer every step of the way,
from the start of the task to its completion. In a procedure-oriented program, the programmer determines
and controls the order in which the computer processes the instructions. In other words, the programmer
must determine not only the proper instructions to give the computer, but the correct sequence of those
instructions as well. Examples of high-level languages used to create procedure-oriented programs
include COBOL (Common Business Oriented Language), BASIC (Beginner’s All-Purpose Symbolic
Instruction Code), and C.

More advanced high-level languages can be used to create object-oriented programs in addition
to procedure-oriented ones. Different from a procedure-oriented program, which focuses on the
individual tasks the program must perform, an object-oriented program requires the programmer to focus
on the objects that the program can use to accomplish its goal. The objects can take on many different
forms. For example, programs written for the Windows environment typically use objects such as check
boxes, list boxes, and buttons. A payroll program, on the other hand, might utilize objects found in the
real world, such as a time card object, an employee object, or a check object. Because each object is
viewed as an independent unit, an object can be used in more than one program, usually with little or no
modification. The ability to use an object for more than one purpose enables code-reuse, which saves
programming time and money—an advantage that contributes to the popularity of object-oriented
programming. Examples of high-level languages that can be used to create both procedure-oriented and
object-oriented programs include C++, Visual Basic, Java, and C#.

2.2. Algorithm and Flow chart


Algorithm is a finite sequence of explicit and unambiguous steps required to solve the given
problem. When the required input values are provided, it produces an output and then terminates. The
steps may repeat or require decisions as per the requirement. The same problem can be solved with
different methods. So for solving the same problem different algorithm may be accomplished. In this
algorithms, the steps, time, space and efforts may vary more or less. Users writes algorithm in his or her
own language. So it cannot be executed on computer.

Introduction to Computing ECEg-2033


3

Properties of algorithm

1. The steps used in algorithm must be unambiguous and precisely defined.


2. The uncertainty about the instruction to be executed next, should be avoided.
3. The steps used in algorithm should be finite and the algorithm should be terminated,
that is it cannot be open-ended.
4. The execution of the algorithm should conclude after a finite number of steps.
5. The algorithm must be general enough to deal with any situation.

Example: let’s write an algorithm to calculate the average of 3 numbers.

Step 1. Start
Step 2. Read three numbers as A, B and C
Step 3. Add A, B and C and store their sum on D
Step 4. Divide D by 3 and store result on E
Step 5. Display E
Step 6. Stop

Flowcharts

A pictorial representation of an algorithm is called a Flowchart. In flowchart, the steps in the


algorithm are represented in the form of different shapes of boxes and the logical flow is indicated by
interconnecting arrows. The boxes are used to represent different operations and the arrows are used to
represent the sequence of operations. Since this is a visual way of algorithm representation, it helps the
programmer in understanding the logic of the program. The general procedure to solve the problem is
outlined by the flowchart. It is always not necessary to include all the steps in detail. There are rules and
standards for drawing flowcharts, prescribed by American National Standard Institute (ANSI). Some
standard symbols which are frequently required in the flowcharts are shown below.

Symbol Symbol name Description


Flow lines are used to connect
Flow lines symbols used in flowchart and
indicate direction of flow.
This is used to represent the
Terminal (START / STOP)
start and end of the flowchart.
It represent information which
Input / output the system reads as input or
sends as output.
Any process is represented by
this symbol. For example
Processing
arithmetic operation, data
movement
This symbol is used to check any
condition or take decision for
Decision
which there are two answers,
Yes (True) or No (False).
It is used to connect or join flow
Connector
lines.

Introduction to Computing ECEg-2033


4

Guideline for preparing flowcharts

1. The flowchart should be neat and easy to follow so that it will be clearly understood.
2. A logical start and end must be given to the flowchart.
3. The flowchart should include necessary steps in logical order.
4. The only two directions L2R or T2B are allowed for a procedure in a flowchart.
5. The only one flow line should come out from a process symbol.
6. The decision making symbol have only one incoming flow line. However, it may have two or three
out-going flow lines.
7. The terminate symbol, that is, start and stop/end symbols should have only one flow-line.
8. The symbol should contain the information (process data or text) clearly to carry out the required
action.
9. The number of flow-lines can be reduced using connector symbol. The connector are mainly
required in complex flowcharts.
10. The intersected flow-lines should be avoided. This makes the flowchart effective and represent
communication clearly.
11. The correctness of the flowchart can be tested by passing the test data through it. It becomes the
validity test of the flowchart.

2.3. Basics of C++


Properly written C++ programs have a particular structure. The syntax must be correct, or the
compiler will generate error messages and not produce executable machine language. This section
introduces C++ by providing some simple example programs and associated fundamental concepts. Most
of the concepts presented in this chapter are valid in many other programming languages as well. The
code written below is one of the simplest C++ programs that prints the word “hello world” to the screen.

#include<iostream.h>
void main()
{
cout<<”Hello world”<<endl;
}
 #include <iostream.h>
This line is a preprocessing directive. All preprocessing directives within C++ source code begin
with a # symbol. This one directs the preprocessor to add some predefined source code to our existing
source code before the compiler begins to process it. This process is done automatically and is invisible to
us. Here we want to use some parts of the iostream library, a collection precompiled C++ code that C++
programs (like ours) can use. The iostream library contains routines that handle input and output (I/O)
that include functions such as printing to the display, getting user input from the keyboard, and dealing
with files. Two items used in Listing 2.1 (simple.cpp), cout and endl, are not part of the C++ language itself.
These items, along with many other things related to input and output, were developed in C++, compiled,
and stored in the iostream library. The compiler needs to be aware of these iostream items so it can
compile our program. The #include directive specifies a file, called a header, that contains the
specifications for the library code. The compiler checks how we use cout and endl within our code against
the specifications in the <iostream> header to ensure that we are using the library code correctly. Most
of the programs we write use this #include <iostream.h> directive, and some programs we will write in
the future will #include other headers as well.

Introduction to Computing ECEg-2033


5

 void main()
This specifies the real beginning of our program. Here we are declaring a function named main.
All C++ programs must contain this function to be executable. Details about the meaning of void and the
parentheses will appear in later chapters.
 {
The opening curly brace marks the beginning of the body of a function. The body of a function
contains the statements the function is to execute.
 cout<<”Hello world”<<endl;
The body of our main function contains only one statement. This statement directs the executing
program to print the message “Hello world” on the screen. A statement is the fundamental unit of
execution in a C++ program. Functions contain statements that the compiler translates into executable
machine language instructions. C++ has a variety of different kinds of statements, and the chapters that
follow explore these various kinds of statements. All statements in C++ end with a semicolon (;).
 }
The closing curly brace marks the end of the body of a function. Both the open curly brace and
close curly brace are required for every function definition.

Note which lines in the program end with a semicolon (;) and which do not. Do not put a semicolon after
the #include preprocessor directive. Do not put a semicolon on the line containing main, and do not put
semicolons after the curly braces.
2.4. Values and variables
In this sections we explore some building blocks that are used to develop C++ programs. We
experiment with the following concepts: numeric values, variables, declarations, assignment, identifiers
and reserved words.

Integer values: - C++ supports a number of numeric and non-numeric values. In particular, C++
programs can use integer values. In C++ source code, integers may not contain commas. This means we
must write the number two thousand, four hundred sixty-eight as 2468, not 2,468. In mathematics,
integers are unbounded; said another way, the set of mathematical integers is infinite. In C++ the range
of integers is limited because all computers have a finite amount of memory. The exact range of integers
supported depends on the computer system and particular C++ compiler. C++ on most 32-bit computer
systems can represent integers in the range -2,147,483,648 to +2,147,483,647. What happens if you
exceed the range of C++ integers?
Identifiers: - The name of a variable (or other item you might define in a program) is called an identifier.
A C++ identifier must start with either a letter or the underscore symbol, and all the rest of the characters
must be letters, digits, or the underscore symbol. For example, the following are all valid identifiers:
x x1 x_1 _abc ABC123z7 sum RATE count data2 bigBonus
All the names shown are legal and would be accepted by the compiler, but the first five are poor choices
for identifiers because they are not descriptive of the identifier’s use. None of the following are legal
identifiers, and all would be rejected by the compiler:
12 3X %change data-1 myfirst.c PROG.CPP
The first three are not allowed because they do not start with a letter or an underscore. The remaining
three are not identifiers because they contain symbols other than letters, digits, and the underscore
symbol. Although it is legal to start an identifier with an underscore, you should avoid doing so, because
identifiers starting with an underscore are informally reserved for system identifiers and standard
libraries. C++ is a case-sensitive language; that is, it distinguishes between uppercase and lowercase

Introduction to Computing ECEg-2033


6

letters in the spelling of identifiers. Hence, the following are three distinct identifiers and could be used
to name three distinct variables:
rate RATE Rate
However, it is not a good idea to use two such variants in the same program, since that might be confusing.
Although it is not required by C++, variables are usually spelled with their first letter in lowercase. The
predefined identifiers, such as main, cin, cout and so forth, must be spelled in all lowercase letters. The
convention that is now becoming universal in object-oriented programming is to spell variable names with
a mix of upper- and lowercase letters (and digits), to always start a variable name with a lowercase letter,
and to indicate “word” boundaries with an uppercase letter, as illustrated by the following variable names:
topSpeed, bankRate1, bankRate2, timeOfArrival
A C++ identifier can be of any length, although some compilers will ignore all characters after some (large)
specified number of initial characters.
Keyword or reserved word: - There is a special class of identifiers, called keywords or reserved
words, which have a predefined meaning in C++ and cannot be used as names for variables or anything
else. Some predefined words, such as cin and cout , are not keywords. These predefined words are not
part of the core C++ language, and you are allowed to redefine them. Although these predefined words
are not keywords, they are defined in libraries required by the C++ language standard. Needless to say,
using a predefined identifier for anything other than its standard meaning can be confusing and dangerous
and thus should be avoided. The safest and easiest practice is to treat all predefined identifiers as if they
were keywords. A complete list of keywords is given below.

Variables: - In algebra, variables are used to represent numbers. The same is true in C++, except C++
variables also can represent values other than numbers. Every variable in a C++ program must be declared
before it is used. When you declare a variable you are telling the compiler—and, ultimately, the
computer—what kind of data you will be storing in the variable. For example, the following are two
definitions that might occur in a C++ program:
int numberOfBeans;
double oneWeight, totalWeight;
The first defines the variable numberOfBeans so that it can hold a value of type int, that is, a whole
number. The name int is an abbreviation for “integer.” The type int is one of the types for whole numbers.
The second definition declares oneWeight and totalWeight to be variables of type double, which is one of
the types for numbers with a decimal point (known as floating-point numbers). As illustrated here, when
there is more than one variable in a definition, the variables are separated by commas.

Introduction to Computing ECEg-2033


7

Also, note that each definition ends with a semicolon. Every variable must be declared before it
is used; otherwise, variables may be declared anyplace. Of course, they should always be declared in a
location that makes the program easier to read. Typically, variables are declared either just before they
are used or at the start of a block (indicated by an opening brace, { ). Any legal identifier, other than a
reserved word, may be used for a variable name. C++ has basic types for characters, integers, and floating-
point numbers (numbers with a decimal point). Display 1.2 lists the basic C++ types. The commonly used
type for integers is int. The type char is the type for single characters. The type char can be treated as an
integer type, but we do not encourage you to do so. The commonly used type for floating-point numbers
is double, and so you should use double for floating-point numbers unless you have a specific reason to
use one of the other floating-point types. The type bool (short for Boolean) has the values true and false.
It is not an integer type, but to accommodate older code, you can convert back and forth between bool
and any of the integer types.

TYPE NAME MEMORY USED SIZE RANGE PRECISION


short 2 bytes −32,768 to 32,767 Not applicable
−2,147,483,648 to
int 4 bytes Not applicable
2,147,483,647
−2,147,483,648 to
long 4 bytes Not applicable
2,147,483,647
approximately 10–38
float 4 bytes 7 digits
to 1038
approximately
double 8 bytes 15 digits
10–308 to 10308
approximately
long 10 bytes 19 digits
10–4932 to 104932
All ASCII characters
(Can also be used
as an integer type,
char 1 bytes Not applicable
although we do
not recommend
doing so.)
bool 1 bytes true, false Not applicable
Each of the integer types has an unsigned version that includes only nonnegative values. These
types are unsigned short, unsigned int , and unsigned long . Their ranges do not exactly correspond to the
ranges of the positive values of the types short, int, and long , but are likely to be larger (since they use
the same storage as their corresponding types short , int , or long , but need not remember a sign).
The most direct way to change the value of a variable is to use an assignment statement. In C++
the equal sign is used as the assignment operator. An assignment statement always consists of a variable
on the left-hand side of the equal sign and an expression on the right-hand side. An assignment statement
ends with a semicolon. The expression on the right-hand side of the equal sign may be a variable, a
number, or a more complicated expression made up of variables, numbers, operators, and function
invocations. An assignment statement instructs the computer to evaluate (that is, to compute the value
of) the expression on the right-hand side of the equal sign and to set the value of the variable on the left
hand side equal to the value of that expression. The following are examples of C++ assignment statements:
totalWeight = oneWeight * numberOfBeans;
temperature = 98.6;
count = count + 2;

Introduction to Computing ECEg-2033


8

A variable has no meaningful value until a program gives it one. Variable’s that has not been given
a value is said to be uninitialized. The value of an uninitialized variable is determined by whatever pattern
of zeros and ones was left in its memory location by the last program that used that portion of memory.
One way to avoid an uninitialized variable is to initialize variables at the same time they are declared. This
can be done by adding an equal sign and a value, as follows:
int minimumNumber = 3;
double rate = 0.07, time, balance = 0.00;
As a general rule, you cannot store a value of one type in a variable of another type. For example,
most compilers will object to the following:
int intVariable;
intVariable = 2.99;
The problem is a type mismatch. The constant 2.99 is of type double, and the variable intVariable
is of type int. unfortunately, not all compilers will react the same way to the previous assignment
statement. Some will issue an error message, some will give only a warning message, and some compilers
will not object at all. Even if the compiler does allow you to use the previous assignment, it will give
intVariable the int value 2, not the value 3. Since you cannot count on your compiler accepting the
previous assignment, you should not assign a double value to a variable of type int. Even if the compiler
will allow you to mix types in an assignment statement, in most cases you should not. Doing so makes
your program less portable, and it can be confusing.
There are some special cases in which it is permitted to assign a value of one type to a variable of
another type. It is acceptable to assign a value of an integer type, such as int, to a variable of a floating-
point type, such as type double . For example, the following is both legal and acceptable style:
double doubleVariable;
doubleVariable = 2;
The style shown will set the value of the variable named doubleVariable equal to 2.0 .
A backslash, \, preceding a character tells the compiler that the sequence following the backslash
does not have the same meaning as the character appearing by itself. Such a sequence is called an escape
sequence. The sequence is typed in as two characters with no space between the symbols. Several escape
sequences are defined in C++.
SEQUENCE MEANING
\n New line
Carriage return (Positions the cursor at the start of the current line.
\r
You are not likely to use this very much.)
\t (Horizontal) Tab (Advances the cursor to the next tab stop.)
\a Alert (Sounds the alert noise, typically a bell.)
\\ Backslash (Allows you to place a backslash in a quoted expression.)
Single quote (Mostly used to place a single quote inside single
\’
Quotes.)
Double quote (Mostly used to place a double quote inside a quoted
\”
String.)
The following are not as commonly used, but we include them for completeness:
\v Vertical tab
\b Backspace
\f Form feed
\? Question mark

Introduction to Computing ECEg-2033


9

When you initialize a variable inside a declaration, you can mark the variable so that the program
is not allowed to change its value. To do this, place the word const in front of the declaration, as described
here:
const int MAX_TRIES = 3;
const double PI = 3.14159;
As in most other languages, C++ allows you to form expressions using variables, constants, and
the arithmetic operators: + (addition), - (subtraction), * (multiplication), / (division), and % (modulo,
remainder). These expressions can be used anyplace it is legal to use a value of the type produced by the
expression. You can specify the order of operations in an arithmetic expression by inserting parentheses.
If you omit parentheses, the computer will follow rules called precedence rules that determine the order
in which the operations, such as addition and multiplication, are performed. These precedence rules are
similar to rules used in algebra and other mathematics classes.
The ++ in the name of the C++ language comes from the increment operator, ++. The increment operator
adds 1 to the value of a variable. The decrement operator, --, subtracts 1 from the value of a variable.
They are usually used with variables of type int, but they can be used with any numeric type. If n is a
variable of a numeric type, then n++ increases the value of n by 1 and n-- decreases the value of n by 1.
So n++ and n--(when followed by a semicolon) are executable statements.
The expression n++ evaluates to the value of the variable n, and then the value of the variable n
is incremented by 1. If you reverse the order and place the ++ in front of the variable, the order of these
two actions is reversed. The expression ++n first increments the value of the variable n and then returns
this increased value of n. The same is true for decrement operator.
There are two ways to insert comments in a C++ program. In C++, two slashes, //, are used to
indicate the start of a comment. All the text between the // and the end of the line is a comment. The
compiler simply ignores anything that follows // on a line. If you want a comment that covers more than
one line, place a // on each line of the comment. The symbols // do not have a space between them.
Another way to insert comments in a C++ program is to use the symbol pairs /* and */. Text
between these symbols is considered a comment and is ignored by the compiler. Unlike the // comments,
which require an additional // on each line, the /* -to- */ comments can span several lines.

Introduction to Computing ECEg-2033

You might also like