You are on page 1of 64

Chapter Two

Computer Programming
Programming language
Programming language
The terms computer programs, software programs, or just programs
are the instructions that tells the computer what to do. Computer requires
programs to function, and a computer programs does nothing unless its
instructions are executed by a CPU.
Computer programming (often shortened to programming or coding)
is the process of writing, testing, debugging/troubleshooting, and
maintaining the source code of computer programs.
Computer programs (also known as source code) are often written by
professionals known as Computer Programmers (simply programmers).
Source code is written in one of programming languages.
• A programming language is an artificial language that can be used to
control the behaviour of a machine, particularly a computer.
Programming languages, like natural language (such as Amharic), are
defined by syntactic and semantic rules which describe their structure
and meaning respectively.

• Many programming languages have some form of written


specification of their syntax and semantics; some are defined only by
an official implementation.
• In general, programming languages allow humans to communicate instructions to machines.

• Programming languages can be divided in to two major categories: low-level and high-level
languages.

• Low-level languages

• Computers only understand one language and that is binary language or the language of 1s and 0s.
Binary language is also known as machine language, one of low-level languages.

• Assembly language correspondences symbolic instructions and executable machine codes and was
created to use letters (called mnemonics) to each machine language instructions to make it easier to
remember or write.

• For example:

ADD A, B – adds two numbers in memory location A and B


• However, no matter how close assembly language is to machine code,
computers still cannot understand it. The assembly language must be
translated to machine code by a separate program called assembler.
• High-level language: - writing a program in assembly languages is
easier as compared to machine languages. But still assembly language
has its own drawbacks, which is machine dependent. So, we need
other type of programming languages which are not machine
dependent and more flexible. These languages are called high-level
languages.
Advantages of high-level languages: -
• Easier to learn and understand (Looks like English)

• Require less time to write and easier to debug errors.

• Can be used on different machines with little modifications.

• E.g. C++, Java, Fortran, c#, python, etc are also the most modern
programming languages
• Language translators

• Depending on the language, the translator for high level languages is


either a compiler or an interpreter. However, code written using assembly
language is translated to machine language by a program called assembler.

• Interpreter: - is a language translator that converts each high-level


language into machine language and executes immediately, statement by
statement. Although an interpreter slows down the execution speed of a
program somewhat, it does not require extra steps to compile and link like
a compiler.
• Compiler: - is a language translator that converts the entire program of
a high-level language into machine language before the computer
executes the program. The programming instructions of a high-level
language are called source code. The compiler translates source code
into machine language, which in this case is called the object code.
Flow Charts and Algorithm Development
• In computer programming terms, an algorithm is a designed solution
to solve the problem. It is the sequence of steps to be performed for
the problem to be solved. To design an algorithm for specific problem
we first break down the problem into simpler and manageable tasks.
This approach is said to be top-down approach. The algorithm that we
select must be:
• simple and powerful,

• There must be no ambiguity in any instruction

• The description of the algorithm must be finite. Algorithm cannot be open ended

• Correct: easy to maintain and correct.

• Efficient: it does not take too much space and time

• Once an algorithm is designed, it is coded in a programming language and


computer executes the program. There are different ways of describing an
algorithm. These are narrative (or verbal text), flowchart, pseudo code and so on
Narrative Algorithm
It is an algorithm written in the form of sentences of human language
text such as English. This descriptive notation is suitable for short
algorithms, for long notations are less effective to us
Example 1: Algorithm to add two numbers.
Step 1: start
Step 2: Read two numbers n1 and n2.
Step 3: sum = n1 + n2
Step 4: Print sum
Step 5: Stop
• Example 2: Write a C++ algorithm to determine if a student is pass or fail based on the grades.
Grades are the average of total marks obtained in all the subjects.

• Step 1: start

• Step 2: Read marks (Marks1, Marks2, Marks3, Marks4)

• Step 3: Grade= (Marks1+Marks2+Marks3+Marks4)/4

• Step 4: If (Grade<50) then

• Step 5: Print “Fail”

• Step 6: Else

• Step 7: Print “Pass”

• Step 8: End if

• Step 9: Stop
• Flow chart Diagrams for algorithms

• A flowchart consists of an ordered set of standard symbols (mostly,


geometrical shapes) which represent operations, data flow or
equipment. A program flowchart shows the operations and logical
decisions of a computer program

• The standard flowchart symbols and their meaning are given below.
• Example 1: Draw a flowchart to add two numbers (A and B).
Home Work

• Design an algorithm and flow chart that determines:

a) The average of two numbers

b) Factorial of any positive number


Basic Program Structure

• The General Programming Code Structure, Look the Following


Example
The parts of a C++ Program.

• The first line #include<iostream> is inclusion of header files called as


preprocessor directive (statements)
• Hash symbols (#):- 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.
• In this case the directive #include<iostream> tells the preprocessor to
include the iostream standard files.
• include instruction is a preprocessor instruction that directs the
compiler to include a copy of the file specified in the angle brackets “<
>” in the source code.
• iostream: includes the declarations of the basic standard input-output
library in c++ is a library file which have the built-in function for
input and output operations like cin and cout respectively in the
example above.
• Generally, #include<iostream> statement is used to include a library
file, which contains the necessary built-in functions that are used later
in the program for input and output operations.
• using namespace std; :- 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.

• int main():- is a part of every C++ program called “definition of the main
function”. The parentheses “ ( )” after main indicate that main is a program
building block called a function. C++ programs typically consist of one or more
functions. Exactly one function in every program must be named main. C++
programs begin executing at main function. See its structure in figure 1 below.
Structure of function main()
• Function: - is a block of code that performs one or more actions.
• Int:- the int before main is a keyword, that indicates the main
function “returns” an integer (whole number) value.
• A keyword is a word in code (Selected word) that is reserved by C++
for a specific use.
• { and } symbols are caller open brace, and close brace respectively.
• The body of every function begin and end with opening and closing
braces.
• Open brace is used after functions, and loop statements like (if, for,
while. will see in detail next chapters), close brace is used to end up or
to close up the opened terms.
• Cout<< : It is an output statement available in iostream library file, used to display message on
screen.

• The basic form for writing output to the screen is

• Syntax:

• cout<< “the statement to be displayed”; (for displaying message) or

• cout<< “the name of the variable to be displayed”; (for displaying the value of a variable)

• Cout<<var1<<”, “<<var2<<” and “<<var3; //Multiple output. Here the values of the three variables
will be printed where there is a “,” (comma) between the first and the second variables and the “and”
between the second and the third.

• 
• Cin>>: It is an input statement available in iostream library file, used
to accept values of a variable from user/keyboard.
• Syntax:
• cin>>the name of the variable which its’ value is going to be
accepted;
• Cin>>var1>>var2>>var3; //multiple input
• The identifier cin pronounced as ‘c in’ and cout pronounced as ‘c
out’.
• Notice that the statement ends with a semicolon ( ; ). This character is
used to mark the end of the statement and in fact it must be included at
the end of all expression statements in all c++ programs (one of the
most common syntax errors is indeed to forget to include some
semicolon after a statement).
• << and >>: symbols are insertion (put to operator) and extraction
(get from operator) respectively.
• return 0; : The return statement causes the main function “main ()” to
finish (indicates the termination point for main function).
• Comments:
• A comment is a piece of descriptive text which explains some aspect
of a program. Program comments are text totally ignored by the
compiler and are only intended to inform the reader how the source
code is working at any particular point in the program. Comments
should be used to enhance (not to hinder) the readability of a program.
• C++ provides two types of comment delimiters:
• Single line comment: Anything after double forward slash (//).
Comments starts with a double slash symbol and terminate at the end
of line.
• Example: sum=num1+num2; // the program adds two numbers.
• Multiline comment: used for very long (multiple line comments).
Anything enclosed by the pair /* and */ is considered a comment.,
Example
• /* this is an example of c++ program to
illustrate some of its features */
Variables and data types

• In algebra, variables are used to represent numbers. The same is true in


C++, except C++ variables also can represent values other than
numbers. Therefore, we can define a variable as a portion of memory
to store a determined value. Each variable needs an identifier that
distinguishes it from the others.
Identifier is a sequence of
• Letters
• digits
• Underscore characters (_).
• Spaces, punctuation marks and symbols cannot be part of an identifier
• There is no condition that identifier begins with digit
• The first character must be an alphabetic letter (upper or lower case) or
the underscore
• The remaining characters (if any) may be alphabetic characters (upper
or lower case), the underscore, or a digit.
• No other characters (including spaces) are permitted in identifiers.

• A reserved word cannot be used as an identifier

• The standard reserved keywords are:

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

• All of the following words are valid identifiers and so qualify as


variable names: x, x2, total, port_22, and FLAG.

• None of the following words are valid identifiers: sub-total (dash is


not a legal symbol in an identifier), first entry (space is not a legal
symbol in an identifier), 4all (begins with a digit), #2 (pound sign is
not a legal symbol in an identifier), and class (class is a reserved
word).
• The C++ language is a "case sensitive" language. That means that an
identifier written in capital letters is not equivalent to another one with
the same name but written in small letters. Thus, for example, the
RESULT variable is not the same as the result variable or the Result
variable. These are three different variable identifiers.
Data types

• Data Type: a type which is established when the variable is defined.

(e.g. integer, real, character etc). Data type describes the property of

the data and the size of the reserved memory


C++ Fundamental Data Types

• The table below shows the fundamental data types, their meaning, and
their sizes (in bytes):
Data Type Meaning Size (in Bytes)

int Integer 2 or 4

float Floating-point 4

double Double Floating-point 8

char Character 1

wchar_t Wide Character 2

bool Boolean 1

void Empty 0
Declarations of variables

• In order to use a variable in C++, we must first declare it specifying


which data type we want it to be. The syntax to declare a new variable is
to write the specifier of the desired data type (like int, bool, float...)
followed by a valid variable identifier. For example:

Syntax

<datatype> <variable name>;


• int a;
• float mynumber;
• If you are going to declare more than one variable of the same type,
you can declare all of them in a single statement by separating their
identifiers with commas. For example:
• int a, b, c;
• This declares three variables (a, b and c), all of them of type int, and
has exactly the same meaning as:
• int a;
• int b;
• int c;
Declaration of string variables
• Variables that can store non-numerical values that are longer than one
single character are known as strings.
• Synatx
• <datatype><variable name>
• String abre;
Declaration of constants
Syntax

const <data type> <variable name>;

• const int pathwidth = 100;

• Const float pi=3.1415

• Here, pathwidth and pi are two typed constants. They are treated just
like regular variables except that their values cannot be modified after
their definition.
Initialization of variables

• data_type identifier = initial_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;
• String initialization
• string mystring = "This is a string";
• string mystring ("This is a string");
Character
• The char data type is used to represent single characters: letters of the
alphabet (both upper and lower case), digits, punctuation, and control
characters (like newline and tab characters).
• char ch = 'A';
• Standard (double) quotes (") are reserved for strings, which are
composed of characters, but strings and chars are very different. The
following statement would produce a compiler error message:
• ch = "A";
Operators
• Assignment (=)
• The assignment operator assigns a value to a variable.
• a = 5;
• This statement assigns the integer value 5 to the variable a. The part at
the left of the assignment operator (=) is known as the lvalue (left
value) and the right one as the rvalue (right value). The lvalue has to
be a variable whereas the rvalue can be either a constant, a variable,
the result of an operation or any combination of these. The most
important rule when assigning is the right-to-left rule: The assignment
operation always takes place from right to left, and never the other
way:
• a = b;

• This statement assigns to variable a (the lvalue) the value contained in


variable b (the rvalue). The value that was stored until this moment in
a is not considered at all in this operation, and in fact that value is lost.

• Arithmetic operators (+, -, *, /, %)

• The five arithmetical operations supported by the C++ language are:


+ addition
 

- subtraction
 

* multiplication
 

/ division
 

% modulo
 
• Operations of addition, subtraction, multiplication and division
literally correspond with their respective mathematical operators. The
only one that you might not be so used to see is modulo; whose
operator is the percentage sign (%). Modulo is the operation that gives
the remainder of a division of two values. For example, if we write:

• a = 11 % 3; the variable a will contain the value 2, since 2 is the


remainder from dividing 11 between 3.
Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)

• When we want to modify the value of a variable by performing an


operation on the value currently stored in that variable we can use
compound assignment operators:
• expression is equivalent to
• value += increase; value = value + increase;
• a -= 5; a = a - 5;
• a /= b; a = a / b;
• price *= units + 1; price = price * (units + 1); and the same for all
other operators.
Increase and decrease (++, --)

• Shortening even more some expressions, the increase operator (++)


and the decrease operator (--) increase or reduce by one the value
stored in a variable. They are equivalent to +=1 and to -=1,
respectively. Thus:
• B++;
• B+=1;
• B=B+1;
• are all equivalent in its functionality: the three of them increase by one
the value of B.

• A characteristic of this operator is that it can be used both as a prefix and


as a suffix. That means that it can be written either before the variable
identifier (++a) or after it (a++). Although in simple expressions like a++
or ++a both have exactly the same meaning, in other expressions in
which the result of the increase or decrease operation is evaluated as a
value in an outer expression they may have an important difference in
their meaning:
• In the case that the increase operator is used as a prefix (++a) the value
is increased before the result of the expression is evaluated and
therefore the increased value is considered in the outer expression; in
case that it is used as a suffix (a++) the value stored in a is increased
after being evaluated and therefore the value stored before the increase
operation is evaluated in the outer expression. Notice the difference:
• Example 1
• B=3;
• A=++B;
• // A contains 4, B contains 4
Example 2
• B=3;
• A=B++;
• // A contains 3, B contains 4
Relational and equality operators ( ==, !=, >, <, >=, <= )
• In order to evaluate a comparison between two expressions we can use
the relational and equality operators. The result of a relational
operation is a Boolean value that can only be true or false, according
to its Boolean result. We may want to compare two expressions, for
example, to know if they are equal or if one is greater than the other is.
Here is a list of the relational and equality operators that can be used
in C++:
• Here there are some examples:
== Equal to
 

!= Not equal to
 

>  Greater than


 

<  Less than


 

>= Greater than or equal to


 

<= Less than or equal to


 
• (7 == 5) // evaluates to false.
• (5 > 4) // evaluates to true.
• (3 != 2) // evaluates to true.
• (6 >= 6) // evaluates to true.
• (5 < 5) // evaluates to false.
• Of course, instead of using only numeric constants, we can use any
valid expression, including variables. Suppose
• that a=2, b=3 and c=6,
• (a == 5) // evaluates to false since a is not equal to 5.
• (a*b >= c) // evaluates to true since (2*3 >= 6) is true.
• (b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false.
• ((b=2) == a) // evaluates to true.
• Be careful! The operator = (one equal sign) is not the same as the
operator == (two equal signs), the first one is an assignment operator
(assigns the value at its right to the variable at its left) and the other
one (==) is the equality operator that compares whether both
expressions in the two sides of it are equal to each other. Thus, in the
last expression ((b=2) == a), we first assigned the value 2 to b and
then we compared it to a, that also stores the value 2, so the result of
the operation is true.
Logical operators ( !, &&, || )
• The Operator ! is the C++ operator to perform the Boolean operation
NOT, it has only one operand, located at its right, and the only thing
that it does is to inverse the value of 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: !(5 == 5) // evaluates to false because the expression at
its right (5 == 5) is true.
• !(6 <= 4) // evaluates to true because (6 <= 4) would be false.
• !true // evaluates to false
• !false // evaluates to true.
• The logical operators && and || are used when evaluating two
expressions to obtain a single relational result. The operator &&
corresponds with Boolean logical operation AND. This operation
results true if both its two operands are true, and false otherwise. The
following panel shows the result of operator && evaluating the
expression a && b:
• && OPERATOR
•A b a && b
• True true true
• True false false
• false true false
• false false false
• The operator || corresponds with Boolean logical operation OR. This
operation results true if either one of its two operands is true, thus
being false only when both operands are false themselves. Here are the
possible results of a || b:
• || OPERATOR
•A b a || b
• True true true
• True false true
• false true true
• false false false
• For example:
• ( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ).
• ( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).
• Example 1, construct a certain c++ program to calculate area of a circle for
given diameter d, using formula r2 where r=d/2.

#include<iostream>
int main()
{
float a, pi=3.1415; int d, r;
cout<<”enter the diameter of circle\n”;
cin>>d;
r=d / 2;
a= pi * r * r;
cout<< “area of circle is”<<a;
}
• Example 2, write a program that prints the sum, difference, product, quotient,
and remainder of two integers. Initialize the integers with the values 60 and 7.
• #include <iostream>
• int main()
•{
• int m = 60, n = 7;
• cout<< "the integers are " << m << " and " << n <<endl;
• cout<< "their sum is " << (m + n) <<endl;
• cout<< "their difference is " << (m - n) <<endl;
• cout<< "their product is " << (m * n) <<endl;
• cout<< "their quotient is " << (m / n) <<endl;
• cout<< "their remainder is " << (m % n) <<endl;
•}
• Example: Accept two numbers a and b from keyboard and store the result of
summation in c.
• #include <iostream>
• using namespace std;
• int main ()
• {
• int a, b, c;
• cout<<” enter values of a: ”; // prompt (ask) user to give valuer of a on keyboard
• cin>>a; // read first number and assign to a
• cout<<” enter values of b: ”; // prompt (ask) user to give valuer of b on keyboard
• cin>>b; // read second number and assign to b c=a+b;
//add the numbers a and b, store the result in c cout<< “the result
is: ”<<c; //display sum
• return 0; // terminate function main }

You might also like