0% found this document useful (0 votes)
58 views

Chapter One C++

The document provides an overview of computer programming concepts including: 1. Programming languages allow humans to communicate instructions to machines and can be divided into low-level and high-level languages. Low-level languages like machine language and assembly language are closer to what computers can understand while high-level languages are easier for humans. 2. Programs are written in programming languages and then translated into machine-readable code using tools like compilers and interpreters. Compilers translate entire programs at once while interpreters translate code line-by-line as it executes. 3. Algorithms are the step-by-step solutions to problems and can be described using different notations like flowcharts and pseudocode to help design

Uploaded by

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

Chapter One C++

The document provides an overview of computer programming concepts including: 1. Programming languages allow humans to communicate instructions to machines and can be divided into low-level and high-level languages. Low-level languages like machine language and assembly language are closer to what computers can understand while high-level languages are easier for humans. 2. Programs are written in programming languages and then translated into machine-readable code using tools like compilers and interpreters. Compilers translate entire programs at once while interpreters translate code line-by-line as it executes. 3. Algorithms are the step-by-step solutions to problems and can be described using different notations like flowcharts and pseudocode to help design

Uploaded by

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

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


Basics of c++
• Structure of c++ programming
// my first program in C++
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
• // my first program in C++
• This is a comment line. All lines beginning with two slash signs (//)
are considered comments and do not have any effect on the behaviour
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.
• #include <iostream>

• Lines beginning with a hash sign (#) are directives for the pre-processor.
This one directs the pre-processor to add some predefined source code
to our existing source code before the compiler begins to process it. In
this case the directive #include <iostream> tells the pre-processor to
include the iostream standard file, which includes the declarations of the
basic standard input-output library in C++. Like printing to the display,
getting user input from the keyboard, and dealing with files.
• 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. The two items our program needs to
display a message on the screen, cout and endl, have longer names: std::cout and
std::endl. This using namespace std directive allows us to omit the std:: prefix
and use their shorter names. This directive is optional, but if we omit it, we must
use the longer names. Listing 2.2 (simple2.cpp) shows how the longer names are
used. The name std stands for “standard,” and the using namespace std line
indicates that some of the names we use in our program are part of the so-called
“standard namespace
• Example2

• For example, Listing 2.2 (simple2.cpp) shows an alternative way of


writing Listing 2.1 (simple.cpp

#include <iostream>

int main() {

std::cout << "This is a simple C++ program!" << std::endl;

}
• int main() {

• This line corresponds to the beginning of the definition of the main


function named with main. All C++ programs must contain this function
to be executable. The main function is the point by where all C++
programs start their execution, independently of its location within the
source code. It does not matter whether there are other functions with
other names defined before or after it – the instructions contained within
this function's definition will always be the first ones to be executed in any
C++ program.
• cout << "Hello World!";
• This line is a 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. 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). cout is
declared in the iostream standard file within the std namespace, so
that's why we needed to include that specific file and to declare that
we were going to use this specific namespace earlier in our code. The
symbols << make up the insertion operator. Notice that the statement
ends with a semicolon character (;). If we miss semi colon there is
syntax error.
• return 0;

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 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.
Comment

• 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:

• Line comment (//)

• 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:

• used for very long (multiple line comments).

• Anything enclosed by the pair /*


and */ is considered a comment.,
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
• 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.

• 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;
// operating with variables
#include <iostream>
using namespace std;
int main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print out the result:
cout << result;
// terminate the program:
return 0;
}
Declaration of string variables
• Variables that can store non-numerical values that are longer than one
single character are known as strings. The C++ language library
provides support for strings through the standard string class. This is
not a fundamental type, but it behaves in a similar way as fundamental
types do in its most basic usage. A first difference with fundamental
data types is that in order to declare and use objects (variables) of this
type we need to include an additional header file in our source code:
<string> and have access to the std namespace (which we already had
in all our previous programs thanks to the using namespace statement).
// my first string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystring = "This is a string";
cout << mystring;
return 0;
}
• Syntax string <identifier>;
Declaration of constants
• You can define your own names for constants that you use very often
without having to resort to memory consuming variables, simply by
using the #define pre-processor directive. Its format is: method 1
• #define identifier value
For example:
#define PI 3.14159
• Method2
Syntax const <data type> <variable name>;
• With the const prefix you can declare constants with a specific type in
the same way as you would do with a variable:
• const int pathwidth = 100;
• const char tabulator = '\t';
• Here, pathwidth and tabulator are two typed constants. They are
treated just like regular variables except that their values cannot be
modified after their definition.
Initialization of variables

• When declaring a regular local variable, its value is by default


undetermined. But you may want a variable to store a concrete value
at the same moment that it is declared. In order to do that, you can
initialize the variable. There are two ways to do this in C++: The first
one, known as c-like, is done by appending an equal sign followed by
the value to which the variable will be initialized:
• 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;
#include <iostream>
using namespace std;
int main ()
{
int a=5; // initial value = 5
int b(2); // initial value = 2
int result; // initial value undetermined
a = a + 3;
result = a - b;
cout << result;
return 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). Most systems support the
American Standard Code for Information Interchange (ASCII)
character set. In C++ source code, characters are enclosed by single
quotes ('), as in
• char ch = 'A';
• Standard (double) quotes (") are reserved for strings, which are
composed of characters, but strings and chars are very different. C++
strings are covered in Section D.7. The following statement would
produce a compiler error message:
• ch = "A";
• since a string cannot be assigned to a character variable. Internally,
chars are stored as integer values, and C++ permits assigning numeric
values to char variables and assigning characters to numeric variables.
The statement ch = 65; assigns a number to a char variable to show
that this perfectly legal. The value 65 is the ASCII code for the
character A. If ch is printed, as in
• ch = 65;
• cout << ch;
• the corresponding character, A, would be printed because ch’s
declared type is char, not int or some other numeric type. Some
characters are non-printable characters. The ASCII chart lists several
common non-printable characters:
• '\n'—the newline character
• '\r'—the carriage return character
• '\b'—the backspace character
• '\a'—the “alert” character (causes a “beep” sound on many systems)
• '\t'—the tab character
• '\f'—the form feed character
• '\0'—the null character
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:
• c++;
• c+=1;
• c=c+1;
• are all equivalent in its functionality: the three of them increase by one the value of
c.
• In the early C compilers, the three previous expressions probably produced
different executable code depending on which one was used. Nowadays, this type
of code optimization is generally done automatically by the compiler, thus the three
expressions should produce exactly the same executable code. 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 ).
• Conditional operator ( ? )
• The conditional operator evaluates an expression returning a value if
that expression is true and a different one if the expression is evaluated
as false. Its format is:
• condition ? result1 : result2
• If condition is true the expression will return result1, if it is not it will
return result2.
• 7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.
• 7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.
• 5>3 ? a : b // returns the value of a, since 5 is greater than 3.
• a>b ? a : b // returns whichever is greater, a or b.
// conditional operator
#include <iostream>
using namespace std;
int main ()
{
int a,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
cout << c;
return 0;
}
7
• In this example a was 2 and b was 7, so the expression being evaluated (a>b) was not true, thus the first value specified
after the question mark was discarded in favor of the second value (the one after the colon) which was b, with a value of 7.
• Comma operator ( , )
• The comma operator (,) is used to separate two or more expressions
that are included where only one expression is expected. When the set
of expressions has to be evaluated for a value, only the rightmost
expression is considered.
• For example, the following code:
• a = (b=3, b+2);
• Input and output
• 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).
• 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.
2. Converting from Decimal to another Base (Division Remainder
Technique)
• ➢ Step 1: Divide the decimal number to be converted by the value of
the new base.
• ➢ Step 2: Record the remainder from step 1 as the rightmost digit
(least significant digit) of the new base number.
• ➢ Step 3: Divide the quotient of the previous divide by the new base.
• ➢ Step 4: Record the remainder from step 3 as the next digit (to the
left)
• ➢ Repeat step 3 & 4, recording remainder from right to left until the
quotient become zero in step 3. Note that the last remainder thus
obtained will be the most significant digit of the new base number
• Binary- to-Octal

• Group the binary digits in triplets (three bits) starting at the binary
point to the right and to the left and convert each of these to its octal
equivalent

• you can add 0’s on the right for fractional part and left for the integral
part, if necessary, to form a complete triplet
Example: Convert the following binary numbers to octal
• Octal-to-Hexadecimal This is equivalent to converting octal-to-binary
and then to-hexadecimal
• Example: convert (1076)8 to hexadecimal

You might also like