[go: up one dir, main page]

0% found this document useful (0 votes)
46 views47 pages

Chapter 4&5

The document discusses the basics of C++ programming including memory, variables, identifiers, comments, and operators. It explains that memory is divided into bytes that can store binary digits, and variables are allocated memory locations with symbolic names. It also covers different types of operators in C++ like assignment, arithmetic, compound assignment, and increment/decrement operators. The last section introduces control structures like the if statement for conditional execution.

Uploaded by

girmay gebray
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)
46 views47 pages

Chapter 4&5

The document discusses the basics of C++ programming including memory, variables, identifiers, comments, and operators. It explains that memory is divided into bytes that can store binary digits, and variables are allocated memory locations with symbolic names. It also covers different types of operators in C++ like assignment, arithmetic, compound assignment, and increment/decrement operators. The last section introduces control structures like the if statement for conditional execution.

Uploaded by

girmay gebray
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/ 47

Chapter Four

Introduction to C++
Basics of C++ Programming
Memory
 A computer provides a Random Access Memory
(RAM) for storing executable program code as
well as the data the program manipulates.
 This memory can be thought of as a contiguous
sequence of bits, each of which is capable of
storing a binary digit (0 or 1).
 Typically, the memory is also divided into groups
of 8 consecutive bits (called bytes).
 The bytes are sequentially addressed. Therefore
each byte can be uniquely identified by its
address
Cont.

Figure Bits and bytes in memory.


 TheC++ compiler generates executable code
which maps data entities to memory locations.
For example, the variable definition
int salary = 65000;
Causes the compiler to allocate a few bytes to
represent salary.
Variables

 In computer programming, a variable is a


storage location and an associated symbolic
name (an identifier) which contains some
known or unknown quantity or information, a
value.
 The variable name is the usual way to
reference the stored value
Identifiers

 An identifier is a name that identifies (that is,


labels the identity of) either a unique object
or a unique class of objects.
 A valid identifier is a sequence of one or more
letters, digits or underscore characters (_).
Neither spaces nor punctuation marks or
symbols can be part of an identifier.
 Only letters, digits and single underscore
characters are valid. In addition, variable
identifiers always have to begin with a letter.
They can also begin with an underline
character (_ ),
 Another rule that you have to consider when
inventing your own identifiers is that they
cannot match any keyword of the C++
language nor your compiler's specific ones,
which are reserved keywords.
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
Very important: 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.

salary // valid identifier


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

Probably the best way to start learning a


programming language is by writing a program.
Therefore, here is our first program:
// my first program in C++ Hello World!
#include<iostream.h>
#include<conio.h>
void main ()
{
cout << "Hello World! \n ";
getch();
}
Comments
 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
/* block
comment */
 // 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 behavior of the program.
#include<iostream.h> and
 Lines beginning with a pound sign (#) are
directives for the preprocessor. They are not
regular code lines with expressions but
indications for the compiler's preprocessor.
 #<Iostream.h> is a standard C++ header file and
contains definitions for input and output.
Int main ()

 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.
{
 This brace marks the beginning of the body of
main.
cout << "Hello World\n";
 This line is a statement. A statement is a
computation step which may produce a value.
Cont.

 Theend of a statement is always marked with


a semicolon (;).
 The
last character in this string (\n) is a
newline character.
cout is the standard output stream in C++
(standard output usually means your computer
monitor screen).
The symbol << is an output operator
Cont.

Return 0;
 Return an integer value.
}
This brace marks the end of the body of main.
Let us add an additional instruction to our
first program:
Hello World! I'm a C++ program
// my second program in C++
#include<iostream>

int main ()
{
cout << "Hello World! ";
cout << "I'm a C++ program";
return 0;
}

 In this case, we performed two insertions into cout in


two different statements.
Operators

 Assignment (=)
 Arithmetic operators (+, -, *, /, %)
 Compound assignment (+=, -=, *=, /=)
 Increment and decrement (++, --)
 Relational and equality operators ( ==, !=, >,
<, >=, <= )
 Logical operators ( !, &&, || )
 Conditional operator ( ? )
Assignment (=)

The assignment operator assigns a value to a


variable.
a = 5;
This statement assigns the integer value 5 to the
variable a.
a = b;
Here also assign the value of b into a.
For example, let us have a look at the following code
// assignment operator a:4 b:7
#include<iostream.h>
#include<conio.h>
void main (){
int a, b; // a:?, b:?
a = 10; // a:10, b:?
b = 4; // a:10, b:4
a = b; // a:4, b:4
b = 7; // a:4, b:7
cout << "a:";
cout << a;
cout << " b:";
cout << b;
getch();
}
cont.
The following expression is also valid in C++:
a = b = c = 5;
It assigns 5 to the all the three variables: a, b
and c.
Arithmetic operators (+, -, *, /, %)

 C++ provides five basic arithmetic operators


(+, -, *, /, %).
 Except for remainder (%) all other arithmetic
operators can accept a mix of integer and real
operands. Generally, if both operands are
integers then the result will be an integer.
However, if one or both of the operands are
reals then the result will be a real (or double
to be exact).
Cont.

When both operands of the division operator (/)


are integers then the division is performed as an
integer division and not the normal division we
are used to. Integer division always results in an
integer outcome (i.e., the result is always
rounded down). For example:
9 /2 // gives 4, not 4.5!
Cont.

To obtain a real division when both operands are


integers, you should cast one of the operands to
be real:
 Int cost = 100;
 Int volume = 80;
 Double unitPrice = cost / (double) volume;
// gives 1.25
 The remainder operator (%) expects integers for
both of its operands. It returns the remainder of
integer-dividing the operands. For example 13%3
is calculated by integer dividing 13 by 3 to give an
outcome of 4 and a remainder of 1; the result is
therefore 1. example: a = 11 % 3;
 It is possible for the outcome of an arithmetic
operation to be too large for storing in a
designated variable. This situation is called an
overflow. The outcome of an overflow is machine-
dependent and therefore undefined. For
example:
 unsigned char k = 10 * 92; // overflow: 920 > 255
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:
Cont.

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

Operator Example Equivalent To


= n = 25
+= n += 25 n = n + 25
-= n -= 25 n = n – 25
*= n *= 25 n = n * 25
/= n /= 25 n = n / 25
%= n %= 25 n = n % 25
<<= n <<= 4 n = n << 4
>>= n >>= 4 n = n >> 4
Cont.
5
// compound assignment operators
#include<iostream.h>
#include<conio.h>
void main (){
int a, b=3;
a = b;
a+=2; // equivalent
cout << a; to a=a+2
getch();
}
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.

Example 1 Example 2

B=3; B=3;
A=++B; A=B++;
// A contains 4, // A contains 3,
B contains 4 B contains 4
Chapter Five
Control Structures
 Conditional structure:
The if Statement
 The if keyword is used to execute a statement or
block only if a condition is fulfilled. Its form is:
 if (condition) statement
 Where condition is the expression that is being
evaluated. If this condition is true, statement
is executed. If it is false, statement is ignored
(not executed) and the program continues
right after this conditional structure.
 Forexample, the following code fragment
prints x is 100 only if the value stored in the x
variable is indeed 100:
if (x == 100)
cout << "x is 100";
Cont.
 We can additionally specify what we want to
happen if the condition is not fulfilled by using
the keyword else. Its form used in conjunction
with if is:
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
Cont.
A program that prints out a result as +ve, -ve or 0.
int x=7;
if (x>0){
cout<<x<<“is +ve”;
}
else if (x<0){
cout<<x<<“ is -ve”;
}
else
cout<<x<<“ is Zero”;

return 0;
}
Iteration structures (loops)
 Loops have as purpose to repeat a statement a
certain number of times or while a condition is
fulfilled.
Types of loops
for loop
while loop
do-while loop
The for loop

 Its format is:

for (initialization; condition; increase) statement;

its main function is to repeat statement while


condition remains true.
It works in the following way:

1. initialization is executed. Generally it is an initial value setting for a


counter variable. This is executed only once.

2. condition is checked. If it is true the loop continues, otherwise the loop


ends and statement is skipped (not executed).

3. statement is executed. As usual, it can be either a single statement or a


block enclosed in braces { }.

4. finally, whatever is specified in the increase field is executed and the loop
gets back to step 2.
Here is an example of countdown using a for loop:

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
// countdown using a for loop
#include<iostream.h>
int main ()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}
Jump statements.

 The continue statement


The continue statement causes the program to
skip the rest of the loop in the current iteration
as if the end of the statement block had been
reached, causing it to jump to the start of the
following iteration.
 The break statement
Using break we can leave a loop even if the
condition for its end is not fulfilled.
It can be used to end an infinite loop, or to
force it to end before its natural end.
Using continue statement

0,1,2,3,4,_6,7,8,9,10

// continue statement example


for(int i=0;i<=10; i++){
if (i==5){
continue;
}
cout<<i<<“,”;
}
Using break statement

0,1,2,3,4,
// break statement example
for(int i=0;i<=10; i++){
if (i==5){
continue;
}
cout<<i<<“,”;
}
The while loop

 The while statement (also called while loop)


provides a way of repeating a statement while
a condition holds. It is one of the three flavors
of iteration in C++. The general form of the
while statement is:
while (expression)
statement;
 First expression (called the loop condition) is
evaluated. If the outcome is nonzero then
statement (called the loop body) is executed
and the whole process is repeated. Otherwise,
the loop is terminated.
Cont.

 For example, suppose we wish to display


numbers from 1 to 10. This can be
expressed as:
Using while loop

Output
//while loop 1,2,3,4,5,6,7,8,9,10,
#include<iostream>

using namespace std;


int main(){
int i=1;
while( i <= 10){
cout<<i<<“,”;
i++;
}
return 0;
}
The do-while loop

 The do statement (also called do loop) is


similar to the while statement, except that its
body is executed first and then the loop
condition is examined. The general form of the
do statement is:
do
statement;
while (expression);
Using do-while loop
1,2,3,4,5,6,7,8,9,10,
//do while loop example
#include<iostream>
using namespace std;
int main(){

int i=1;
do {
cout<<i<<“,”;
++i;
}
while (i <=10);

return 0;
}
NEXT

 Nested loop

You might also like