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

Computer Programming C++ Chapter Three

Uploaded by

Cabdilaahi Cali
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)
6 views

Computer Programming C++ Chapter Three

Uploaded by

Cabdilaahi Cali
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/ 96

Haramaya University, Institute of Technology

School of Electrical and Computer Engineering

Chapter 2

Introduction to C++ Programming

June 8, 2024 Computing


Contents
2

 Basics of programming
 Algorithm and flow chart
 Basics of C++
 Variables and assignment
 Declaration and initialization
 Input /output using console
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
2.1 Programming Basics
3

 Objectives

 Define programs and programming languages

 Categorize programming languages and describe what tools they use

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
…Programming Basics
4

 A program
 is a list of instructions, together with any fixed information required to
carry out those instructions
 The process of programming consists of defining those instructions
and that data
 In order to design a program for a computer, you must determine three
basic elements:
 The instructions that must be performed.
 The order in which those instructions are to be performed.
 The fixed data required to perform the instructions.

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Programming Languages
5

 Programming languages are software development environments


(IDE) that consist of

 a set of language primitives (keywords and specified syntax) and

 a translator (assembler, compiler, or interpreter)

 converts source code (written in with programming language primitives) into


object code (binary machine language).

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
…Programming Languages
6

 Low level languages (LLL), which are computer oriented


 used to create programs that have a one-to-one correspondence between their
statements and the machine language statements
 Machine language which are numeric (sequence of ones and zeros) , and
 Assembly language which utilizes mnemonic keywords.
 Assembly language programs are translated into object code by assemblers.
 Eg. ADD D1,D2

 It is machine/platform dependent.
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
…Programming Languages
7

 High level languages (HLL)


 task oriented
 facilitate the coding of algorithms.
 HLLs are designed to make the programming process easier for humans
 Instructions in HLL emphasize the logical structure being used
 The structure of the language aids in the design process.
 It is machine/platform independent.
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Terminologies
8

 Machine independent: Capable of being used on any type of machine (Intel,


Apple, Sun, ...).
 Platform independent: Capable of being used on any type of machine, running
under any operating system (MS windows, unix, linux...)
 Machine/platform dependent: Applicable to only one specific type of
machine/platform.
 Source Code: The program that you write in some language (Java, C, assembly
language).
 Object Code: Machine code version of source code for a particular machine.

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
…Terminologies
9

 Compiler: a program that translates source code into machine code.


 Linker: puts together several object modules and library routines into one executable file.
 Syntax Error: This is a compiler error, indicating that you disobeyed one of the grammar
rules of the language
 You could misspell a keyword, forget a semicolon or closing bracket, use an else without
an if, and many others

 Linker Error: The most common linker error is an unresolved external reference.
 This occurs when a function is called in one module but coded in a different module.
 The linker tries to find the function's implementation code, but it isn't there.
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
…Terminologies
10

 Run-time Error: This is also called an execution error or an exception


 Cause program to terminate, usually with a system-generated message.
 divide by zero and memory violations
 An infinite loop may cause a time-out on shared systems.
 Logic Error: Your program compiles correctly, links without problems, but doesn't
produce correct output.
 Algorithm is: "An effective procedure for solving a problem in a finite number of
steps."
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Features of Algorithms
11

 Sequence (also known as Process)


 Decision (also known as Selection)
 Repetition (also known as Iteration or Looping)

 Sequence
 each step or process in the algorithm is executed in the specified order

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
…Features of Algorithms
12

 The Decision constructs –


 If ... then, If ... then ... else ...
 the outcome of a decision is either true or false, there is no in between and is
 The outcome of the decision is based on some condition that can only result in a
true or false value
 General form of decision
 if proposition then
 Process1
 else
 process2
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
…Features of Algorithms
13
 The Repetition constructs - Repeat and While
 Repetition takes two forms
 the Repeat loop and the While loop.
 The repeat loop is used to iterate or repeat a process or sequence of
processes until some condition becomes true.
 It has the general form:
 Repeat
 Process
 Until proposition
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Start
Find the Sum of Five Number
Count = 0
14
Sum = 0
 English Read value
1. Initialize sum and count to 0
2. Read value (I/O) Sum = sum + value
Count = count + 1
3. Sum = sum + value; Count = count + 1;
4. Is count < 5 Yes
 If Yes go to step 2 Count < 5
 If No print sum No
5. end Print Sum

End
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Algorithm Stating Techniques
15

 There are three different ways of stating algorithms:


1. Step-Form – step-by-step procedure

2. Pseudocode – code like algorithm

3. Flowchart – Graphical design

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Flow Chart
16

 Symbols in flow charts

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Begin

Exercise Input a, b, c
17
 Write an algorithm and draw a flow chart to find the solution of Quadratic Equation
 Begin
 Input a, b, c (coefficients) D = b*b-4*a*c
 Determine the Discriminant D = b2-4ac
 If D > 0 Yes
D>0
 Find the two real roots as
 R1 = (-b-sqrt(D))/(2*a) No
 R2 = (-b+sqrt(D))/(2*a) R1 = (-b-sqrt(D))/(2*a) Yes
 Display both roots (R1 and R2) R1 = (-b+sqrt(D))/(2*a) D=0 R = (-b/(2*a)
 Else if D = 0
Display R1 No
 Find the root as Display R
Display R2 Print no real
 R = -b/(2*a)

 Display the root (R)


solution
 Else
 Display no real root
End
 End
Haramaya University, HiT, School of Electrical and Computer
Engineering Saturday, June 8, 2024
Compile, Link & Run
18

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
2.2 Introduction to C++ Programming
19

Objectives
 Identify and differentiate the various parts of C++ program
 Declare and manipulate variables
 Communicate (I/O) with the console using appropriate syntax and
manipulators
 State the various operator types
 Use operator precedence rules to evaluate expressions
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
2.2.1 Introduction
20

Section Objectives

 List the parts of a C++ program.

 Describe how the parts work together.

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Program Development
21

1. Defining the Problem


 Write the problem in clear language
 Give different condition and see the response
2. Analyzing the problem
 In view of developing an algorithm capable of solving the problem
3. Computing
 Code the algorithm using the editor
 Compile (using the existing C++ compiler)
 Execute

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Example 1
22

Problem
 Printing Hello World! on the screen
output
Hello World!
// My first program in C++
#include<iostream>
Editor using namespace std;
int main()
{
cout<<"Hello World! "; Screen
return 0;
}
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Example 1 (cont’d)
23

Line 1: // My first program in C++

 This is a comment line

 All lines beginning with two slash sign (//) are considered comments

 Do not have any effect on the behavior of the program

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Example 1 (cont’d)
24

Line 2 & 3: #include<iostream>


using namespace std;
 Preprocessor directive, Instruction to compiler
 It tells the compiler to insert a file (here iostream) into your source file
 Iostream is one of the several header files

 Concerned with basic input/output operation

 Contains declaration that are needed by cout identifier and “<<“operator,


cin and identifier and “>>” operator

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Example 1 (cont’d)
25

Line 4: int main()


 Corresponds to the beginning of the main function declaration

 The point where all C++ programs begin execution

 The parenthesis following the word main are the distinguishing feature of a
function

 Every C++ program must contain the main function

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Example 1 (cont’d)
26

 Line 5 and 8: pair of curly braces


{

}
 The body of the function is surrounded by braces

 They delimit a block of program statement

 Every function must have a pair of braces ({ }) around the body of the function

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Example 1 (cont’d)
27

Line 6: cout<<"Hello World! ";


 Does the most important thing in this program

 Itinserts a sequence of characters into the output stream


 cout standard output stream in C++ (usually the screen)

 Notice that the sentence ends with semicolon (;)

 It has the meaning of finishing the instruction

 Must be included after every instruction in your C++ program

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Example 1 (cont’d)
28

 Line 7: return 0;

 The return instruction makes the main() function to finish

 Return the code (in this case 0)

 Most usual way to terminate a program

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Example 2
29

 Add one more instruction output


Hello World! I’m a C++ program
// My second program in C++

#include<iostream>
using namespace std
int main()
{
cout<< " Hello World! ";
cout<< " I’m a C++ program";
return 0; Notice that the second
} output is immediately
after the first one

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Comments
30

 C++ supports two ways of inserting comments


 // line comment
 /* block comment */

 The line comment discards everything from where the pair of slash sign (//) is found
up to the end of the same line

 The block comment discard everything between /* */

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Example 3
31

 With more comments


/* My second program in C++
with more comments */

#include<iostream>>
using namespace std
int main()
{
cout<< " Hello World! "; // displays Hello World!
cout<< " I’m a C++ program"; // displays I’m a C++ program
return 0;
}
output
Hello World! I’m a C++ program

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Software Development Environments
32

 An integrated development environment (IDE) is a software package


that bundles
 An editor (used to write programs),
 A compiler (that translates programs) and
 A run time component
 For example
 Microsoft Visual C++, Dev C++
 Code Block, NetBeans
 Visual Studio

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
2.2.2 Variables, Data Types, Constants
33

Section Objectives

 Declare and define valid variables and constants.

 Assign values to variables and manipulate those values.

 Discuss what is meant by scope of a variable.

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Introduction
34

 Suppose we have two numbers to manipulate

 Memorize the two numbers: say 5 and 2

 Add 1 on the first and memorize the result: 5 + 1 = 6

 Now you have 6 and 2 in your memory

 Subtract the second from the first: 6 – 2 = 4

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Introduction (cont’d)
35

 This same process can be expressed in C++ with the following set of
instruction:
a = 5;
b = 2;
a = a + 1;
result = a - b;
a , b and result are known as variables

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
What is a variable ?
36

 Portion of memory to store a determined value

 Each variable needs an identifier that distinguishes it from others

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Identifiers
37

 A valid C++ identifier


 is a sequence of one or more letter, digit or underscore/underline
 Should begin with letter/underscore

Example
 a, b, result, root, no_of_students, _grade
 Are all valid C++ identifiers
 2students, cout, for
 are not valid C++ identifiers

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Identifiers (cont’d)
38

 Note
1. Identifiers can not match any language keywords nor compiler specific
ones.
 eg. switch, break, for, bool, if, false, class, char, etc…
2. No blank spaces are allowed in identifies
3. The C++ compiler (the language in general) is case sensitive
 eg. RESULT, result, Result
are three different identifiers

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Data Types
39

 When programming, we store variables in our computer memory

 The compiler must know the data type of the variable


 is the variable an integer, float point number, character, boolean

 This is because the size of different data types are not the same

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Built in Data Types
40

Name Bytes Description Range


char 1 Character or integer of 8 bit signed: -128 to 127
length unsigned : 0 to 255
short 2 Integer of 16 bit length signed: -32,768 to 32,767
unsigned: 0 to 65,535
long 4 Integer of 32 bit length signed: -2,147,483,648 to 2,147,483,647
unsigned: 0 to 4,294,967,295
int 2/4 Integer of 16 / 32 bit length See short and long
float 4 Floating Point (FP) number 3.4 x 10-38 to 3.4 x 1038
double 8 Double precision FP number 1.7 x 10-308 to 1.7 x 10308
long double 10 Long double precision FP 1.2 x 10-4932 to 1.2 x104932
number
bool 1 Boolean value true or false
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Built in Data Types….
41

 Character
 They can represent a single character such as ‘A’ or ‘$’.
 The most basic type is char, which is a one-byte character
 Numerical Integer
 They exist in a variety of sizes, and can be either signed or unsigned, depending on whether
they support negative values or not
 Floating-point
 They can represent real values, such as 3.14 or 0.01, with different levels of precision
depending on which of the three floating-point types is used (float, double)
 Boolean
 The Boolean type, known in C++ as bool, can only represent one of two states, true or false

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Declaration of Variables
42

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


data type
Syntax <data type> <identifier>;

eg.
int a; // declares a variable a of type int

float myNumber; // variable of type float


 Once declared, variables a and myNumber can be used within the rest
of their scope in the program.

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Declaration of Variables (cont’d)
43

To declare several variables of the same type


example:
int a, b, c; // declares 3 variables of type int

is the same as
int a;
int b;
int c;

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Declaration of Variables (cont’d)
44

 Integer data types (char, short, long and int) can be signed or
unsigned
 This is according to the range of numbers that we need to represent.
 To specify an integer data type we do it by putting the keyword
signed or unsigned before the data type itself.
Example:
unsigned short numberOfSons;
signed int myAccountBalance;

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Declaration of Variables (cont’d)
45

 By default, if we do not specify signed or unsigned it will be assumed


that the type is signed

int myAccountBalance;
// equivalent as: signed int myAccountBalance;

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Example 4
46

#include<iostream> Output
using namespace std; 6 2 4
int main()
{
int a,b,result; // declaring variables
a = 5;
b = 2; process
a = a+1;
result = a - b;
cout<<a<<" "<<b<<" "<<result<<" "; // print out the result
return 0; // terminate the program
}

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Initialization of Variables
47

 When declaring a local variable, its value is undetermined by default.


 But you may want that a variable stores a concrete value since the
moment in which it is declared.
syntax type identifier = initial_value; or
type identifier (initial_value);

For example
int a = 0; or
int a (0);

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Scope of Variables
48
#include<iostream>
using namespace std;

int Integer; // Global Variables


char aCharacter;
unsigned int numberOfSons;

int main()
{
unsigned short age; // local variables
float aNumber, anotherNumber;

cout<<"Enter Your Age: "; // prompt the user to


// enter his/her age
cin>>age;

return 0;
} Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Scope of Variables (cont’d)
49

 Global Variable
 Can be referred anywhere in the code, within any function, wherever it is
after its declaration
 The global variables will hold their value throughout the lifetime of your
program
 Local Variable
 The scope of local variables is limited to the code level in which they are
declared
 Variables declared inside a function or block are local variables
 Only statements that are inside that function or block of code can use them
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Constants
50

 A constant : is any expression that has a fixed value.

 Can be
 Integers

 Floating-Point Numbers

 Characters

 Strings

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Integers
51

 Decimal (base 10)


eg. 1776, 707, -273

 Octal (base 8)
eg. 032, 067, -042

 Hexadecimal (base 16)


eg 0x12, 0xa2, 0xF2

 Notice that these values are not in quotation


Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Example 5: Integer Constants
52

#include<iostream> Integers
using namespace std;
int main()
75
{
// integers
75
cout<<"Integers\n\n"; 75

//Decimal
cout<<75<<"\n";

// octal
cout<<0113<<"\n";

// hexadecimal
cout<<0x4b<<"\n”
return 0;
}

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Floating Point Numbers
53

eg.
3.14159 // 3.14159 (PI)

6.02e23 // 6.02 x 1023 Avogadro Number

1.6e-19 // 1.6 x 10-19 Electric charge

3.0 // 3.0

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Characters and strings
54

 There also exist non-numerical constants, like:


'z' ,'p' ,"Hello world" , "How do you do?"
 The first two expressions represent single characters,
 the other two represent strings of several characters.
 Note
 single quotes (') are used to represent a single character
 to express a string of more than one character we use double quotes (").
 x and 'x' are two different things
 x refers to variable x, whereas 'x' refers to the character constant 'x'

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Escape Codes
55

 \n newline
 \r carriage return
 \t tabualtion
 \v vertical tabualtion
 \b back space
 \f page feed
 \a alert (beep)
 \’ single Quote
 \” double Quote
 \\ inverted slash

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Escape Codes (cont’d)
56

For example:

1. '\n', '\t', "Left \t Right", "one\ntwo\nthree"

2. "string expressed in \

two lines"

3. "we form" "a single" "string" "of characters"

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Defined constants (using #define)
57

 You can define your own names by using the #define preprocessor directive.
 The syntax is

#define identifier value


For example:
 #define PI 3.14159265
 #define NEWLINE '\n'
Notice that no semicolon at the end
 #define WIDTH 100
This is because it is preprocessor
 You can use the constants directive
 circle = 2 * PI * r;
 cout << NEWLINE;

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Declared Constants (const)
58

 With the const prefix you can declare constants with a specific type
exactly as you would do with a variable:

const int width = 100;

const char tab = '\t';

const zip = 12440;

 In case that the type was not specified (as in the last example) the
compiler assumes that it is type int.
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
2.2.3 Communication through console.
59

Section objectives

 Communicate with the console by performing input and output


operations

 Use I/O manipulators to format the screen output.

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Introduction
60

 The console is the basic interface of computers


 set composed by the keyboard and the screen.
 The keyboard:
 the standard input device
 Supported by cin for input
 cin is assigned to keyboard
 The screen:
 the standard output device.
 Supported by cout for output
 cout is directed to the screen

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Output (cout)
61

 Used in conjunction with the overloaded operator <<


Example.
cout << "Output sentence"; // prints Output sentence
// on screen
cout << 120; // prints number 120 on
// screen
cout << x; // prints the content of
// variable x on screen

 Once again notice that constant strings are enclosed in double


Quotation whereas variables or constants are not
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Output (cout) …
62

 For Example
cout << "Hello"; // prints Hello on screen
cout << Hello; // prints the content of
// Hello variable on screen
 The insertion operator (<<) may be used more than once in a same
sentence:

For Example
cout << "Hello, " << "I am " << "a C++ sentence";
cout << "Hello, I am " << age << " years old and my\ zipcode is " <<
zipcode;
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Input (cin)
63

 For example:
int age;
cin >> age;
 Declares the variable age as an int

 Then waits for an input from cin (keyborad) in order to store it in this
integer variable.

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Input (cin)…
64

 You can also use cin to request more than one datum input from the
user:
cin >> a >> b;

 is equivalent to:
cin >> a;
cin >> b;

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Example 6
65

// input/output example
#include<iostream>
using namespace std;
int main()
{
int i;
cout<<" Enter an integer value ";
cin>>i;
cout<<" The Value you entered is " <<i;
cout<<" and its double is "<<i*2<<endl;
return 0;
}
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
I/O Manipulators
66

 Manipulators are the most common way to control output formatting

 I/O manipulators are in the <iomanip> include file.


#include<iomanip>

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Some I/O Manipulaltors
67

Manipulator (output) Description


endl Write a new line (\n)
setw(n) Sets minimum width on output
eg. cout<<setw(7)<<n<<endl
width(n) Same as setw(n)
left Left justify in output field width
right Right justify in output field width
setfill(ch) Fill field with character ch
eg. Cout<<setw(4)<<setfill(‘0’)<<n;
setprecision(n) Sets the number of digits to be printed to the right decimal point

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Example 7
68

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const float tenth = 0.1;
const float one = 1.0;
const float big = 1234567890.0;
cout << “\n\n\tA. "<< tenth << ", " << one << ", " << big << endl;
cout << “\tB. " <<fixed<<setprecision(3)<<tenth<<", “<<one<<",“
<< big << endl;
cout << “\tC. " << setprecision(20) << tenth << endl;
cout << “\tD. " << setw(8) << setfill('*') << 34 << 45 << endl;
cout << “\tE. " << setw(8) << 34 << setw(8) << 45 << endl;

return 0;
}

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Example 8: cin, cout, getline
69

#include <iostream>
#include <string>
using namespace std;
int main ()
{
string x;
cout << “your name please ”;
getline (cin, x);
cout << “Hello” << x << “\n”;
return 0;
}

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
2.3.4 Operators
70

Section objective

 Define what statements, blocks and expressions are.

 Differentiate the various operator types and use them

 State operator precedence rules and utilize them

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Introduction
71

 Once we have variables and constants we can operate on them


 The operations are
 Assignment
 Arithmetic
 Bitwise
 Relational
 Logical

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Assignment operator (‘=’)
72

Serves to assign a value to a variable


Example
 The statement a = 5; assign value 5 to the variable a

 It is the equal sign (assignment operator) that makes the value on the
right be assigned to the variable on the left

 Left of the “=“ is known as the l- value

 Right of the “=“ is known as the r-value

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Assignment operator (‘=’)…
73

Note :
 l-value must always be a variable
 5 = a; is an error
 r-value can be either
 Constant
 Variable
 The result of operation or
 Combination of them

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Assignment operator (‘=’)…
74

Example
a = 5;
b = a;
c = a + b;
d = a + b * c +5;
 Assignment only takes place from right to left never reverse
Example
 What will be the values of a, b , and c after execution of the following
statements?
int a = 5, b = 3, c = 4; All the values of
a = b = c; a , b and c will
be 4

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Arithmetic Operators
75

Four normal arithmetic operators


 + for addition
 - for Subtraction
 * for multiplication
 / for division
 Work on all data types
 Are analogous to their use in algebra

Example
mean = (num1 + num2) / 2; // arithmetic mean of two numbers

TF = 9/5 * TC + 32; // Celsius to Fahrenheit conversion

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Module Operator (%)
76

 Remainder operator
 Works only on integers
 It finds the remainder when a number is divided by another
Example
 11 % 3 = 2 i.e 11/3 =3 and remainder is 2

int a = 13, b = 4;
int c = a % b; 1
cout<<c;

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Bitwise Operators
77

 Bitwise operators modify the variables considering the bits that


represent the value they store
 In other words, bitwise operations are on the binary representation of
the numbers
Operator Description
& Bitwise AND Bitwise operators
| Bitwise OR supported in C++
~ Bitwise NOT (bit
inversion)
^ Bitwise Exclusive OR
<< Shift Left
>> Shift Right
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Bitwise Operators (cont’d)
78 Output
a & b = 5
Example a | b = 15
int a = 7, b = 13; a ^ b = 10
int c = a & b; a << 2 = 28
int d = a|b; b >> 2 = 3
int e = a ^ b;
int f = a << 2; Let a = 7 and b =13
In binary form
int g = b >> 2; a = 0111(with four bits)
cout<< "\ta & b = " <<c <<endl; b = 1101(with four bits)
cout<< "\ta | b = " <<d <<endl;
cout<< "\ta ^ b = " <<e <<endl; 0111
a & b = 1101
cout<< "\ta << 2 = " <<f <<endl;
0101 5
cout<< "\tb >> 2 = " <<g <<endl;

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Compound Assignment Operators
79

Operator Description Remark


+= add and assign Works on all built in data type
-= subtract and assign Same
*= multiply and assign Same
/= divide and assign Same
%= find remainder and assign Works only on integers
>>= right shift and assign same
<<= Left shift and assign same
|= bitwise OR and assign same
^= bitwise exclusive OR and assign same
&= Bitwise AND and Assign same
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Compound Assignment Operators (cont’d)
80

 These operators are used to combine arithmetic operation with assignment


Example
 a = a + 5; has same operand in both sides

 It means add 5 to the value of variable a and assign the result to a


 Increase the value of a by 5

 We can eliminate the repeated operand from the expression by using


compound assignment operator (+=) as a+=5;

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Compound Assignment Operators (cont’d)
81

Example

 What are the values of a, b, c, d and e after execution of the following


statements
int a = 13, b = 11, c = 5, d = 7, e = 3;
a-= d;
b %= e; a is 6
c +=b; b is 2
d *=e; c is 7
e <<=b; d is 21
e is 12

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Increment and Decrement Operator
82

 (++) increment operator


 ( -- ) decrement operator
 More specialized operator, used to increment or decrement 1
 Used in incrementing or decrementing integer variables

 Example
int count = 3;
count = count + 1; //same as count += 1;

More condensed approach is


++count; // adds 1 to count
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Increment and Decrement Operator (cont’d)
83

 Increment/decrement operator can be used in two ways

 As prefix, meaning the operator precedes the variable (++a/--a) and

 As postfix, meaning the operator follows the variable (a++/a--)

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Increment and Decrement Operator (cont’d)
84

 Simple expressions like a++ and ++a have same meaning


 But when used in expression there is a difference

Example
int a, b = 3;
a = ++b; //assign after incrementing
cout<<a<<“ ”<<b<<“ ”;
output 4 4
int a, b = 3;
a = b++; // increment after assignment
cout<<a<<“ ”<<b<<“ ”;
output 3 4

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Increment and Decrement Operator (cont’d)
85

Note

1. In prefix (a = ++b) the value increases before the expression is


evaluated where as

2. In postfix (a = b++) the value increases after the expression is


evaluated

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Relational Operators (==, !=, >, <, >=, <=)
86

 A relational operator compares two values


 Evaluates a comparison between two expression

 The result of the comparison is either true (1) or false (0)

Example
int a = 2, b = 3, c = 6;
 The result of ((b+4) > a*c) is false (0)
 The result of ((b=2) ==a) is true(1)

 The result of c!=6 is false(0)

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Logical Operators (!, &&, ||)
87

 C++ has two binary logical operators (“or”, “and”) and one unary
logical operator (“not”)
Logical and (&&)
 condition1 && condition2 is true if both the conditions are true, false

otherwise
Example
int a = 2, b = 3, c = 6;
 The result of (a*b == c && 4 < 6) is true (1)
 The result of (b+4 < c && b == 3) is false (0)
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Logical or (||)
88

 condition1 || condition2 is true if either condition or both are true


 Note: if condition1 is true no need to check the next condition (this is

a short circuit evaluation)


Example
int a = 2, b = 3, c = 6;
 The result of (a*b == c || 4 > 6) is true (1)
 The result of (b+4 < c || b == 3) is true (1)
 The result of (b+4 < c || a > b) is false (1)

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Logical not (!)
89

 !condition is true if condition is false

Example

 !((5==5) && (3 > 6)) would return true

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Conditional Operator (?:)
90

Syntax
 Condition?result1:result2
 If condition is true result1 will be executed result2 otherwise
Example
 c = 5>3?a:b; // a will be returned i.e c = a
 c = 7==5?4:3;// 3 will be returned i.e c = 3

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Explicit Type Casting operators
91

int i;
float f = 3.14;
i = (int) f; // or i = int (f)
 i will be 3
 sizeof() : accepts one parameter that can be either a variable type or variable itself
and returns size in bytes
 Example 1 4 2
int a = sizeof(char);
int b = sizeof(double);
int c = sizeof(int)
cout <<a<<“ ” <<b<<“ ”<<c<<“ ”;

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Operator Precedence Table
92

Operator Type Operators Precedence Order


Unary ! , +, - Highest Left to right
++, -- Postfix: Left to
right
Postfix: Right to
left
Multiplicative *, /, % Left to right
Arithmetic
Additive +, - Left to right
Inequality <, >, <=, >= Left to right
Relational
Equality == , != Left to right
and && Left to right
Logical
or || Left to right
Conditional ?: Left to right
Assignment =,School
Haramaya University, HiT, +=, -=, /=, %=and Computer
of Electrical Lowest Left to right
Saturday, June 8, 2024
Engineering
Exercises
93

1. Write the output of the following program.


#include<iostream>
using namespace std;
int main()
{
int x=10,y=20,z=30;
--x;
y=++y;
z=x--;
cout<<”x= ”<<x<<endl;
cout<<”y= ”<<y<<endl;
cout<<”z= ”<<z<<’\n’;
cout<<x+y;
return 0;
}
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Exercises…
94
2. What is the output of the following program
#include<iostream>
using namespace std;
int main(){
int x,y, c=10;
cout<<c++;
x=2*c+1;
cout<<'\n'<<x;
y=--x+1;
cout<<'\n'<<y;
x=c++;
cout<<'\n'<<x;
cout<<'\n'<<c++;
x=2*x++;
cout<<'\n'<<x;
cout<<'\n'<<4+x;
return 0;
} Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Exercises…
95

Develop an algorithm, flowchart and write C++ program for the following problems

3. That finds the equivalent resistance of two resisters connected in


a. Series
b. Parallel and displays the result

4. That converts temperature in degrees Fahrenheit to Celsius, and displays the result.

5. That converts temperature in degrees Celsius to Fahrenheit t, and displays the result

Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering
Exercises…
96

6. Write a program that generates the following table:


1990 135
1991 7290
1992 11300
1993 16200
Use a single cout statement for all output.
7. Write a program that generates the following output:
10
20
19
Use an integer constant for the 10, an arithmetic assignment operator to generate the 20, and a
decrement operator to generate the 19.
Haramaya University, HiT, School of Electrical and Computer Saturday, June 8, 2024
Engineering

You might also like