Chapter 1

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 78

Basic computer programming II

INSY 2031
Introduction to programming
 A program is a set of instructions that tell the computer to do.

 Programming is the process of creating a set of instructions that tell a computer how
to perform a task.

 Programming can be done using a variety of computer "languages," such as SQL,


Java, Python, and C++.

 Computer programming (often shortened to programming or coding) is the


process of writing, testing, debugging/troubleshooting, and maintaining the source
code of computer programs
05/11/2024 Compiled by Demeke A. 2
Structure of C++ Program
A C++ program has the // My first program in C++
following structure #include<iostream>
[Comments] Using namespace std;
[Preprocessor directives] int main()
[The main function] {
[Starting of main function] Cout<<“Hello World”;
[Body of function] Return 0;
[Return the function] }
[End of the function]

05/11/2024 Compiled by Demeke A. 3


• The program has been structured in different lines in order to be more
readable, but in C++, we do not have strict rules on how to separate
instructions in different lines. For example, instead of

We could have written:

In C++, the separation between statements is specified with an ending semicolon (;)

05/11/2024 Compiled by Demeke A. 4


#include <iostream>
Lines beginning with a hash sign (#) are directives for the preprocessor.

In this case the directive #include <iostream> tells the preprocessor to

include the iostream standard file.

#include is a preprocessor directive that tells the preprocessor

to include header files in the program

This specific file (iostream) includes the declarations of the basic standard

input-output library in C++


05/11/2024 Compiled by Demeke A. 5
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.

The word main is followed in the code by a pair of parentheses (()). That is
because it is a function declaration

Right after these parentheses we can find the body of the main function enclosed
in braces ({}).

05/11/2024 Compiled by Demeke A. 6


cout << "Hello World!";

cout represents the standard output stream in C++

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

Notice that the statement ends with a semicolon character (;)

05/11/2024 Compiled by Demeke A. 7


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.

05/11/2024 Compiled by Demeke A. 8


Comments

A comment is a piece of descriptive text which explains some aspect of a


program.

Program comments are totally ignored by the compiler and are only intended
for human readers.

C++ provides two types of comment delimiters:


Anything after // (until the end of the line on which it appears) is
considered a comment
Anything enclosed by the pair /* and */ is considered a comment
05/11/2024 Compiled by Demeke A. 9
Input/ Output Statements

The most common way in which a program communicates


with the outside world is through simple, character-oriented
Input/ Output (IO) operations.

C++ provides two useful operators for this purpose


 >> (extraction) for input and
 << (insertion) for output
05/11/2024 Compiled by Demeke A. 10
Keywords (reserved words)

Reserved/Key words have a unique meaning within a C++ program

Special meaning to the compiler.

These symbols, the reserved words, must not be used for any other
purposes

All reserved words are in lower-case letters

Example:- bool, case, break, auto, catch, char, delete, int, void, if, ….,
float etc…
05/11/2024 Compiled by Demeke A. 11
Identifiers

An identifier is name associated with a function or data object and used
to refer to that function or data object. An identifier must:
Start with a letter or underscore
Consist only of letters, the digits 0-9, or the underscore symbol _
Not be a reserved word

For the purposes of C++ identifiers, the underscore symbol, _, is


considered to be a letter.
05/11/2024 Compiled by Demeke A. 12
Variables

A variable is a symbolic name for a memory location in which data can be stored

and subsequently recalled.

Variables are used for holding data values so that they can be utilized in various

computations in a program.

All variables have two important attributes:

A type, which is, established when the variable is defined (e.g., integer, float,

character)

A value, which can be changed by assigning a new value to the variable


05/11/2024 Compiled by Demeke A. 13
Variable Declaration
 Declaring a variable means defining (creating) a variable

 You create or define a variable by stating its type, followed by one or more spaces, followed by
the variable name and a semicolon.

 The variable name can be virtually any combination of letters, but cannot contain spaces and
the first character must be a letter or an underscore

Example:-

int myAge;

 Variables must be declared before used!

 Case sensitive
05/11/2024 Compiled by Demeke A. 14
Creating More Than One Variable at a Time
 You can create more than one variable of the same type in one statement by writing the
type and then the variable names, separated by commas.

 For example:

 int myAge, myWeight; // two int variables

 long area, width, length; // three longs

 myAge and myWeight are each declared as integer variables.

 The second line declares three individual long variables named area, width, and length.

 However keep in mind that you cannot mix types in one definition statement

05/11/2024 Compiled by Demeke A. 15


Variable initialization
You assign a value to a variable by using the assignment operator (=)

Thus, you would assign 5 to Width by writing


 int Width;
 Width = 5;

You can combine these steps and initialize Width when you define it by writing
 int width = 5;

Just as you can define more than one variable at a time, you can initialize more than one

variable at creation. For example:

// create two int variables and initialize them


 int width = 5, length = 7;

05/11/2024 Compiled by Demeke A. 16


Basic Data Types

When you define a variable in C++, you must tell the compiler what kind of variable
it is: an integer, a character, or what

Several data types are built into C++.

Basic (fundamental) data types in C++ can be conveniently divided into numeric and
character types

Numeric variables can further be divided into integer variables and floating-point
variables

Integer variables will hold only integers whereas floating number variables can
accommodate real numbers.
05/11/2024 Compiled by Demeke A. 17
C++ data types and their ranges

Type Size Values/ranges


unsigned short int 2 bytes 0 to 65,535
short int(signed short int) 2 bytes -32,768 to 32,767

unsigned long int 4 bytes 0 to 4,294,967,295


long int(signed long int) 4 bytes -2,147,483,648 to 2,147,483,647

int 2 bytes -32,768 to 32,767


unsigned int 2 bytes 0 to 65,535
signed int 2 bytes -32,768 to 32,767
Char 1 byte 256 character values
Float 4 bytes 3.4e-38 to 3.4e38
Double 8 bytes 1.7e-308 to 1.7e308
long double 10 bytes 1.2e-4932 to 1.2e4932

05/11/2024 Compiled by Demeke A. 18


Type String
used to represent textual information
string constants must be enclosed in double quotation marks eg.
“Hello world!”
empty string “”
new line char or string “\n”
“the word \”hello\”” (puts quotes around “hello” )
The following program reads the four different data type inputs and
outputs listed on the above. The following program reads the four
different data type inputs and outputs listed on the above

05/11/2024 Compiled by Demeke A. 22


.

05/11/2024 Compiled by Demeke A. 23


Defining Constants
Constants are expressions with a fixed value.

There are two simple ways in C++ to define constants


Using #define preprocessor. # # define identifier value

const type variable = value;


Using const keyword

Q? write a c++ program that calculate the area of a circle.


given Pi=3.14

05/11/2024 Compiled by Demeke A. 24


Operators
 An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations.

 Operators are symbols that perform operations on variables and values

 C++ is rich in built-in operators and provide the following types of operators

 Assignment Operators

 Arithmetic Operators

 Relational and equality operators

 Logical operators

 Conditional operator

 Bitwise Operators
05/11/2024 Compiled by Demeke A. 25
Assignment Operators (=)
The assignment operator assigns a value to a variable.
a = 5;
This statement assigns the integer value 5 to the variable a
 Compound assignment

05/11/2024 Compiled by Demeke A. 26


Arithmetic Operators

C++ provides five basic arithmetic operators


Operator Name Example
+ Addition 12 + 4.9 // gives 16.9
- Subtraction 3.98 - 4 // gives -0.02
* Multiplication 2 * 3.4 // gives 6.8
/ Division 9 / 2.0 // gives 4.5
% Remainder 13 % 3 //gives 1
Arithmetic operators.

Modulo is the operation that gives the remainder of a division of two values.
For example, if we write:

05/11/2024 Compiled by Demeke A. 27


Increment and decrement (++, --)

the increase operator (++) and the decrease operator (--) increase or
reduce by one the value stored in a variable c++;
c+=1;
c=c+1;
They are equivalent to +=1 and to -=1, respectively

This operator 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++)

05/11/2024 Compiled by Demeke A. 28


.

a++ or ++a both have exactly the same meaning

a prefix (++a) the value is increased before

a suffix (a++) the value stored in a is increased after being evaluated

In Example 1, B is increased before its value is copied to A. While in Example 2, the
value of B is copied to A and then B is increased

05/11/2024 Compiled by Demeke A. 29


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

05/11/2024 Compiled by Demeke A. 30


Logical operators ( !, &&, || )

 The Operator ! is the C++ operator to perform the Boolean operation NOT
 producing false if its operand is true and true if its operand is false
 The operator && corresponds with Boolean logical operation AND
 This operation results true if both its two operands are true, and false otherwise
 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

a b !a A&&b a || b
True True False True True
True False False False True
False True True False True
false False True False False

05/11/2024 Compiled by Demeke A. 31


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

Example:-
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.

05/11/2024 Compiled by Demeke A. 32


Bitwise Operators
 Bitwise AND (&) takes two numbers as operands and does AND on every bit of two numbers.
 The result of AND is 1 only if both bits are 1.

 Bitwise OR ( | ) takes two numbers as operands and does OR on every bit of two numbers.
 The result of OR is 1 if any of the two bits is 1.

 Bitwise XOR (^ ) takes two numbers as operands and does XOR on every bit of two numbers.
 The result of XOR is 1 if the two bits are different.

 Left shift (<<) takes two numbers, left shifts the bits of the first operand, the second operand decides the number
of places to shift.

 Right shift (>>) takes two numbers, right shifts the bits of the first operand, the second operand decides the
number of places to shift.

 Bitwise NOT (~ ) takes one number and inverts all bits of it

05/11/2024 Compiled by Demeke A. 34


.

#include <iostream>
int main()
{
unsigned int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)

cout<< "a&b = “ << a & b;


Output
cout<< "a|b = " << a | b;

cout<< "a^b = " << a ^ b;


a&b = 1
a|b = 13
cout<< "~a = "<< a = ~a;
a^b = 12
cout<< "b<<1 = " << b << 1; ~a = 250
cout<< "b>>1 = " << b >> 1; b<<1 = 18
return 0;
b>>1 = 4
05/11/2024 Compiled by Demeke A. 35
}
Precedence of operators

When writing complex expressions with several operands,


 we may have some doubts about which operand is evaluated first and
which later
Example:-
a = 5+7 % 2

05/11/2024 Compiled by Demeke A. 36


Precedence of operators
Category Operator Associativity

Postfix () [] -> . ++ - - Left to right


Unary ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right


Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= Right to left
^= |=

05/11/2024 Compiled by Demeke A. 37


Precedence of operators

When writing complex expressions with several operands,

 we may have some doubts about which operand is evaluated first and
which later

Exercise: find the value of A based on precedence rule.


int c = 20 - 5 % 4 * 2 + 3 /2*3 ;
cout<<c<<endl;

05/11/2024 Compiled by Demeke A. 38


05/11/2024 Compiled by Demeke A. 39
Quiz
• Write a C++ program that display the sum of two numbers

• Write a C++ program that print the area of a circle given diameter=6

• Evaluate

int c = 10 * 5 % 4 * 2 + 3 /2*3%2;
cout<<c<<endl;

05/11/2024 Compiled by Demeke A. 40


Control Statements

05/11/2024 Compiled by Demeke A. 41


Control Statements
 A control statement is a statement that determines whether other statements will be
executed.

 Control statements are elements in the source code that control the flow of program
execution.

 A running program spends all of its time executing statements

 The order in which statements are executed is called flow control

 Flow control in a program is typically sequential, from one statement to the next

 Flow control is an important consideration because it determines what is executed during


a run and what is not
.

• .

C++ control
Statement

Selection Iteration Jump


Statement Statement Statement

For loop Do while loop Continue goto


If---Else Switch

Break
While loop

05/11/2024 Compiled by Demeke A. 43


Conditional Statements
The IF statement works by checking the expression to see whether a condition is met

and returns a value based on the output obtained.

 If statements are logical blocks used within programming.

 They're conditional statements that tell a computer what to do with certain

information.
 the general form is: if (expression)
statement;

 First expression is evaluated. If the outcome is nonzero (true) then statement is

executed. Otherwise, nothing happens


05/11/2024 Compiled by Demeke A. 44
The if …..else

We can additionally specify what we want to happen if the condition is

not fulfilled by using the keyword else


Example 1:-
Syntax :if (condition) if (x == 100)
statement1; cout << "x is 100";
else
else cout << "x is not 100";
statement2;

05/11/2024 Compiled by Demeke A. 45


Nested if and if-else-if ladder statements

• Nested if- if statement inside another if statement


05/11/2024 Compiled by Demeke A. 46


IF …else…if ladder
• If else if statement –
• if (expression)
statement1;
else if (expression)
statement2;
else if (expression)
statement3;
...
else
statement;

 Write a c++ program that display the grade equivalent of your score. Accept your score
from the user using if..else..if statement.
05/11/2024 Compiled by Demeke A. 47
Switch
 The switch statement provides a way of choosing between a set of alternatives, based on the

value of an expression.

 The general form of the switch statement is:


The expression must evaluate to a
switch (expression) {
case constant 1: character or integer value. Floating-
statements; break; point expressions, for example, are not
...
allowed.
case constant n:
statements; break;
default:
statements;
}
05/11/2024 Compiled by Demeke A. 48
There are three important things to know about the switch statement:

The switch differs from the if in that switch can only test for equality,
whereas if can evaluate any type of relational or logical expression.

No two case constants in the same switch can have identical values. Of
course, a switch statement enclosed by an outer switch may have case
constants that are the same.

If character constants are used in the switch statement, they are
automatically converted to integers.
05/11/2024 Compiled by Demeke A. 49
05/11/2024 Compiled by Demeke A. 50
Example:-
 Write a c++ program that display the name of days using switch statement.
1= Monday
2= Tuesday
3= Wednesday
4=Thursday
5=Friday
6=Saturday
7=Sunday
 Write a c++ program that checks whether the character is vowel or consonant
using switch statement.

05/11/2024 Compiled by Demeke A. 51


Iteration structures (loops)
Loops have as purpose to repeat a statement a certain number of times or while a
condition is fulfilled
The while loop

The while statement (also called while loop) provides a way of repeating a
statement while a condition holds

Syntax:- while(Condition )
condition {
evaluated Statement
}
true false

statement

05/11/2024 Compiled by Demeke A. 52


.

• An example of a while statement:


int count = 1;
while (count <= 2)
{
cout<<"Welcome to C++!";
count++;
}
Cout<<“end!”;

• If the condition of a while loop is false initially, the statement is


never executed
• Therefore, the body of a while loop will execute zero or more times

05/11/2024 Compiled by Demeke A. 53


Trace while Loop
Initialize count
int count = 1;
while (count <= 2)
{
cout<<"Welcome to C++!";
count++;
}
Cout <<" End";

05/11/2024 Compiled by Demeke A. 54


Trace while Loop, cont.
(count < =2) is true
int count = 1;
while (count < =2)
{
cout<<"Welcome to C++!";
count++;
}
Cout <<" End";

05/11/2024 Compiled by Demeke A. 55


Trace while Loop, cont.
Print Welcome to C++
int count = 1;
while (count < =2)
{
cout<<"Welcome to C++!";
count++;
}
Cout <<" End";

05/11/2024 Compiled by Demeke A. 56


Trace while Loop, cont.
Increase count by 1
int count = 1; count is 2 now
while (count < =2)
{
cout<<"Welcome to C++!";
count++;
}
Cout <<" End";

05/11/2024 Compiled by Demeke A. 57


Trace while Loop, cont.
(count < =2) is still true since count
int count = 1; is 2
while (count < =2)
{
cout<<"Welcome to C++!";
count++;
}
Cout <<" End";

05/11/2024 Compiled by Demeke A. 58


Trace while Loop, cont.
Print Welcome to C++
int count = 1;
while (count <= 2)
{
cout<<"Welcome to C++!";
count++;
}
Cout <<" End";

05/11/2024 Compiled by Demeke A. 59


Trace while Loop, cont.
Increase count by 1
int count = 1; count is 3 now
while (count < =2)
{
cout<<"Welcome to C++!";
count++;
}
Cout <<" End";

05/11/2024 Compiled by Demeke A. 60


Trace while Loop, cont.
(count <= 2) is false since count is 3
int count = 1; now

while (count < =2)


{
cout<<"Welcome to C++!";
count++;
}
Cout <<" End";

05/11/2024 Compiled by Demeke A. 61


Trace while Loop
The loop exits.
Execute the next statement after the loop.
int count = 1; Print End;
while (count < =2)
{
cout<<"Welcome to C++!";
count++;
}

Cout <<" End";

Q? Write a C++ program that display from 10 to 1 using while loop.

05/11/2024 Compiled by Demeke A. 62


The do-while loop
Syntax

do statement while (condition);

Its functionality is exactly the same as the while loop, except that condition
in the do-while loop is evaluated after the execution of statement instead of
before

Unlike for and while loops, which test the loop condition at the top of the

loop, the do-while loop checks its condition at the bottom of the loop.

This means that a do-while loop always executes at least once


05/11/2024 Compiled by Demeke A. 63
Output:
0123456789

05/11/2024 Compiled by Demeke A. 64


The for loop

The for statement (also called for loop) is similar to the while statement,
except in its syntax

for (initialization; condition; increase) statement;

05/11/2024 Compiled by Demeke A. 65


For loop Example

int num;
for (num = 1 ; num <= 3 ; num ++ )
{
cout << num << “ * IS” << endl;
}
Cout<<“end of the loop”;

05/11/2024 Compiled by Demeke A. 66


.

num ?

int num;

for (num = 1 ; num <= 3 ; num ++ )


{

cout << num << “ * IS” << endl;


}
Cout<<“end of the loop”;

05/11/2024 Compiled by Demeke A. 67


num 1
Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )


{
cout << num << “IS” << endl;
}
Cout<<“end of the loop”;

05/11/2024 Compiled by Demeke A. 68


num 1
Example of Repetition

int num;
true

for ( num = 1 ; num <= 3 ; num++ )


{

cout << num << “IS” << endl;


}
Cout<<“end of the loop”;

05/11/2024 Compiled by Demeke A. 69


num 1
Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )


{

cout << num << “ * IS” << endl;


}
Cout<<“end of the loop”;

05/11/2024 Compiled by Demeke A. 70


num 2
Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )


{

cout << num << “IS” << endl;


}
cout<<“end of the loop”;

05/11/2024 Compiled by Demeke A. 71


num 2
Example of Repetition

int num;
true

for ( num = 1 ; num <= 3 ; num++ )


{
cout << num << “IS” << endl;
}
Cout<<“end of the loop”;

05/11/2024 Compiled by Demeke A. 72


num 2
Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )


{
cout << num << “ * IS” << endl;
}
Cout<<“end of the loop”;

05/11/2024 Compiled by Demeke A. 73


num 3
Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )


{
cout << num << “IS” << endl;
}
Cout<<“end of the loop”;

05/11/2024 Compiled by Demeke A. 74


num 3
Example of Repetition

int num;
true

for ( num = 1 ; num <= 3 ; num++ )


{
cout << num << “IS” << endl;
}
Cout<<“end of the loop”;

05/11/2024 Compiled by Demeke A. 75


num 3
Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )


{
cout << num << “IS” << endl;
}
Cout<<“end of the loop”;

05/11/2024 Compiled by Demeke A. 76


num 4
Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )


{
cout << num << “IS” << endl;
}
Cout<<“end of the loop”;

05/11/2024 Compiled by Demeke A. 77


num 4
Example of Repetition

int num;
false

for ( num = 1 ; num <= 3 ; num++ )


{
cout << num << “IS” << endl;
}
Cout<<“end of the loop”;

05/11/2024 Compiled by Demeke A. 78


num 4
Example of Repetition

int num;
false

for ( num = 1 ; num <= 3 ; num++ )


{
cout << num << “IS” << endl;
}
Cout<<“end of the loop”;

Q? Write a C++ program that display from 10 to 1 using do-while and


for loop.
05/11/2024 Compiled by Demeke A. 79
Nested loops
Loops may be nested, with one loop sitting in the body of another.
The inner loop will be executed in full for every execution of the outer
loop.
Write a c++ program that display the following output
1
12
123
1234
12345

05/11/2024 Compiled by Demeke A. 80


The ‘continue’ Statement

The continue statement terminates the current iteration of a loop and


jumps to the next iteration

It applies to the loop immediately enclosing the continue statement

 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.
05/11/2024 Compiled by Demeke A. 81
The ‘goto’ Statement

The goto statement provides the lowest-level of jumping. It has the


general form:

goto label;

label:

Where label is an identifier which marks the jump destination of goto.

The label should be followed by a colon and appear before a statement


within the same function as the goto statement itself.
05/11/2024 Compiled by Demeke A. 82

You might also like