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

Chapter 2 Basic Program Elements Part 2

1. The document discusses basic programming elements such as input/output statements, operators, and expressions in C++. 2. It describes the standard input and output streams cin and cout which are used to take input from the keyboard and display output to the screen respectively. 3. The different types of operators covered include assignment, arithmetic, increment/decrement, relational, and logical operators. Examples are given to demonstrate how to use each operator.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Chapter 2 Basic Program Elements Part 2

1. The document discusses basic programming elements such as input/output statements, operators, and expressions in C++. 2. It describes the standard input and output streams cin and cout which are used to take input from the keyboard and display output to the screen respectively. 3. The different types of operators covered include assignment, arithmetic, increment/decrement, relational, and logical operators. Examples are given to demonstrate how to use each operator.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 54

DFC 20113

PROGRAMMING
FUNDAMENTALS

Department : Information and Communication Technology


Politeknik Balik Pulau
CLO

Upon completion of
this course, students
should be able to:
CLO1 - Implement CLO2 - Show simple
programming programs by developing
element and code to solve problems in a
articulate how they computer using C++
are used to achieve programming language.
a working program. ( P2, PLO 3 )
( C3, PLO 2 )
CHAPTER 2
BASIC PROGRAM
ELEMENTS
LESSON LEARNING OUTCOMES

1 Identify the syntax used for


input and output

Design, implement, test and debug


2 program using data types.
Outline :

2.3 Describe input output statements


2.4 Explain operators and expression
INPUT OUTPUT STATEMENTS
BASIC INPUT/OUTPUT
 C++ Programming uses a convenient abstraction
called streams to perform input and output operations in
sequential media such as the screen, the keyboard or a file
 A stream is an entity where a program can either insert or
extract characters to or from sequential media
 The streams are a source or destination of characters, and
that these characters are provided or accepted sequentially
 The standard library defines a handful of stream objects that
can be used to access what are considered the standard
sources and destinations of characters by the environment
where the program runs :

stream Description
cin Standard input stream
cout Standard output stream
STANDARD OUTPUT (cout)
 On most program environments, the standard
output by default is the screen, and the C++
stream object defined to access it is cout
 Format / Syntax:
cout<<item1<<item2<<item3;

 Header File Needed :


<iostream>
using namespace std;
STANDARD OUTPUT (cout)
i) Definition
cout is the Standard Output Stream
OBJECT.
<< is the Stream Insertion
Operator.
STANDARD OUTPUT (cout)
ii) Getting Out Fixed Numeric Information
 Example1 :
cout<<250;
Generate an output of 250
 
 Example2:
cout <<1<<2<<3<<4;
Generate an output of 1234
STANDARD OUTPUT (cout)

iii)Getting Out Fixed Character Information


 Example 1:
cout<<”Hello”;
Generate an output of Hello

 Example 2:
cout<<”Polytechnic Malaysia”;
Generate an output of Polytechnic Malaysia
STANDARD OUTPUT (cout)
iv) Getting Out Variable Information
 
 Example 1:
char VariableName[4]=”Ali”; //Declare Variable
cout<<VariableName; //Getting out variable information

 
 Example 2:
int Nombor=99; //Declare Variable
cout<<Nombor; //Getting out variable information
 
STANDARD OUTPUT (cin)
i) Definition
cin is the Standard Input Stream
OBJECT.
>> is the Stream Insertion
Operator.
STANDARD INPUT (cin)
1. Format:
cin>>item1;

2. Header File Needed :


<iostream>
Using namespace std;

 3. Rules :
i) only one character is read at a time.
STANDARD INPUT (cin)
Example 1:
#include <iostream> User type : abu
using namespace std;  Output :a
void main ( )  
User type : 79
{ Output :7
char Name;

cin>>Name;  
‘ \ 0’
cout<<Name;
} char : Name
STANDARD INPUT (cin)
Example 2 :
#include <iostream> User type : abu
Using namespace std; Output : abu
 void main ( )  
{ User type : 79
char Name [20]; cin>>Name;
Output : 79
cout<<Name;
}
PROBLEM WITH cin WHEN READING string
 White space (Blanks, tabs, new lines and form
feed) are ignored by cin using >> operator and
left it in the keyboard buffer
 Example :

#include <iostream>
using namespace std; 
void main ( )
{
char Name [5]; u t
tp
cin>>Name;
ou
cout<<Name;
}

User type : abu mohd


Output : abu
PROBLEM WITH cin WHEN READING string
 Numeric value can be read as character, but
each digit is read as a separate character.

 This problem can be solve using cin.getline or


gets( ).
 
 cin is the Standard Input Stream Object
 
 >> is the Stream Extraction Operator.

 Multiple input cin>>item1>>item2;


USING gets( );
 Use to read string, it will read white
space( space , form feed ….) and will stop until
reach ENTER, then will convert ENTER to null
terminator (\0) and save.

 ‘gets’ will read CRLF (produce by Enter) and


convert to null terminator and save.

 Header file needed : cstdio (Standard C++only )

Example : char name[20]; User type : Ali Bin Mohd


gets (name); output : Ali Bin Mohd
cout<<name;
 
SOLUTION
 Must clean after using cin .
#include <iostream>
#include <cstdio>
using namespace std;
 
void main ( )
{
int Number;
char Name[10];
char address[20];
 
cin>>Number; // If user key in : 46 ‘enter’
gets(address); //clear white space (enter, space,…)
 
cout<<Number; //Screen output : 46
gets(Name); //If user key in : John Tan
cout<<Name; // Screen output :John Tan
}
OPERATORS AND EXPRESSION
LESSON LEARNING OUTCOMES
1 Define operator

2 Explain the types of operators

3 Identify the syntax for each operator


with example

4 Differentiate the assignment and equality operator


Use input output statements.

5 Write expression using operators

6 Describe operators precedence

Solve expression according to the operators


7 and expression
DEFINITION of OPERATOR
 A symbols that help us to perform specific
mathematical and logical computations on
operands
 Description : Operators are symbols which act on
variables or other entities that are called operands
and perform mathematical or logical operations to
modify their values and produce results accordingly
 An operator operates the operands
 Example :
c = a + b;
Symbol ‘+’ is the operator known as addition operator and ‘a’
and ‘b’ are operands.
The addition operator tells the compiler to add both of the
operands ‘a’ and ‘b’
TYPES of OPERATOR
 5 types of operators :
i) Assignment operators
ii) Arithmetic operators
iii)Increment and Decrement operators
iv)Relational operators
v) Logical operators
1) ASSIGNMENT OPERATORS

 Example of assignment operators :

“=” : This is the simplest assignment operator. This operator is used to assign the
value on the right to the variable on the left.
For example : a = 10; b = 20; ch = 'y';

“+=” : This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the
current value of the variable on left to the value on right and then assigns the result to
the variable on the left.
Example : (a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11

“-=” : This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts
the value on right from the current value of the variable on left and then assigns the
result to the variable on the left.
Example : (a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2
1) ASSIGNMENT OPERATORS

 Assignment operators are used to assign value to a


variable.

 The left side operand of the assignment operator is a


variable and right side operand of the assignment
operator is a value.

 The value on the right side must be of the same


data-type of variable on the left side otherwise the
compiler will raise an error.
2) ARITHMETIC OPERATOR

 The five arithmetical operations are:


Ope ra tion Symbol
Add +
Subtract -
Multiply *
Divide /
Modulus %
 Operations of addition, subtraction, multiplication and division
correspond literally to their respective mathematical operators
 The last one, modulus operator represented by a percentage
sign (%),and it gives the remainder of a division of two values
Example 1 :

//This program demonstrate the


mathematic operation
#include <iostream.h>
void main ( )
{
cout<<2+2<<endl;
cout<<5-2<<endl;
cout<<6/2<<endl;
cout<<10%3<<endl;
}
Output
You will get : 4
3
3
1
( endl = endline, it is a Escape
Sequence Command like “\n” )
Example 2: Using mathematics
operator to form a formula.
//Calculate the average of 3 input value
#include<iostream>
using namespace std;
void main ( )
{
float g1,g2,g3,avg;
cout<<"Please key in the your score for 4 test \n";
cout<<" Test score 1 : ";
cin>>g1;
cout<<" Test score 2 : ";
cin>>g2;
cout<<" Test score 3 : ";
cin>>g3;
avg=(g1+g2+g3)/3;
cout<<"Your average score is "<<avg<<"\a\n";
}
Modulus operator (%)
 Simply generate the remainder that when you
divide 2 integers.
Example :
i) 5 % 3 = 2, 5 divide by 3 remain 2.
ii) 5 % 4= 1
iii) 5 % 5 = 0
 The modulus operator can only used for Integers
and will generate a compiler error if you attempt
to apply it to floating values.
 21.0 % 2 = “Illegal use of floating point error”
because % can only use for integer value.
Division
 Only the divide operator need special attention.
When you divide two integer number, you may get
a floating-point answer, the compiler will give you a
Warning of possible losing of data.

Example :
int answer; //define answer as integer
answer =10/3; // real answer = 3.3333 (floating point)
cout<<answer; // but you will get answer =3
3) PRE-INCREMENT AND PRE-DECREMENT
OPERATORS

 PreIncrement ( + + X )
 PreDecrement ( - - X )
 PostIncrement ( X + + )
 PostDecrement( X - - )
1. + + X is equivalent to X+ 1.
2. - - X is equivalent to X-1.
Example:
 Y = + + x +5, mean X will be increment by
one before added to 5.
 Y = X -- +5 mean Y is equal to X + 5, and
after that the value of X will be decrement
by 1.
Example of program
 //Example for preincrement and predecrement Memory Output :
#include <iostream>    
using namespace std;    
   
void main ( )    
{    
int x=5; ++X=X+1  
int y=10; X = 5+1 X=6
y=++x-5; //Preincrement Y = 6-5 Y=1
cout<<"\nY = "<<y;    
cout<<"\nX = "<<x;    
  Y = X-5
y=x-- -5; //Postdecrement Y = 6 -5 Y=1
cout<<"\nY = "<<y; X--= X-1  
cout<<"\nX = "<<x; X= 6-1 X=5
   
y=x++-5; //Postincrement Y = X-5  
cout<<"\nY ="<<y; Y = 5-5  Y = 0
cout<<"\nX ="<<x; X++ = X+1  
} X = 5+1 X=6
COMPOUND ASSIGNMENT EXPRESSIONS

 Increment and decrement operators abbreviate


certain kinds of assignments.
 For example, the combined assignment :
n += 8;
has the same effect as the simple assignment

n=n+8;
It simply adds 8 to n
Example 2
#include >iostream>
using namespace std;
 
// Tests combined operators:
void main ( )
{
 
int n = 44;
n +=9; //n= n+9
cout<<n<< endl;
n –=5 ; //n=n-5
cout <<n<< endl;
n *= 2; //n=n*2
cout <<n<< endl;
return 0;
}
Output

53
48
96
 
The statement n += 9 adds 9 to n, the
statement n - =5 substract 5 from n,
n*= 2 multiplies n by 2.
4) RELATIONAL OPERATORS/BOOLEAN OPERATORS

Math Expression in C++


= ==
= !=
> >
>=
< <
<=
1. The test result / Output are either ‘yes’
or ‘no’ iaitu ‘1’ atau ‘0’ sahaja.
RELATIONAL OPERATORS
OPERATOR DESCRIPTION EXAMPLE
== Checks if the values of two operands are equal (A == B) is not true.
or not, if yes then condition becomes true.

!= Checks if the values of two operands are equal (A != B) is true.


or not, if values are not equal then condition
becomes true.

> Checks if the value of left operand is greater (A > B) is not true.
than the value of right operand, if yes then
condition becomes true.

< Checks if the value of left operand is less than (A < B) is true.
the value of right operand, if yes then
condition becomes true.

>= Checks if the value of left operand is greater (A >= B) is not true.
than or equal to the value of right operand, if
yes then condition becomes true.

<= Checks if the value of left operand is less than (A <= B) is true.
or equal to the value of right operand, if yes
then condition becomes true.
Program Example 1 :
#include <iostream>
using namespace std;
void main ( )
{
int Number; cout <<”Please
press 5 and enter : ”; cin>>Number;
if ( Number = = 5 )
cout<<”You just press 5! “ else
cout<<”You did not press 5”;
}
 
Output 1

User type: 3
Out :You did not press 5

User type: 5
Out : You just press 5.
Program Example 2 :

#include <iostream>
using namespace std;
void main ( )
{ cout << (3+4)<<”\n”;
cout<<(3>4)<<”\n”;
cout<<(3<4)<<”\n”;
cout<<( ‘j’ >’k’ )<<”\n”;
}
Output 2

Output :

7
0
1
0
5) LOGICAL OPERATORS
Math C++
AND &&
OR ||
NOT !
The test result / Output :
either ‘yes’ or ‘no’ - ‘1’ or ‘0’ only

A B A&&B
0 0 0
0 1 0
1 0 0
1 1 1
Example 1 :

( -6 < 0 ) && (12 > 10)


= 1 && 1
=1

(-6< 0 ) && 12 < 10)


= 1 && 0
=0
DIFFERENCE BETWEEN = (ASSIGNMENT) AND
== (EQUAL TO) OPERATORS

 The “=“ is used to assign the value on the right to the variable
on the left.
 The “==“ operator checks whether the two given operands
are equal or not. If so, it returns true. Otherwise it returns
false
 The differences can be shown in tabular form as follows:

ASSIGNMENT (=) EQUAL TO (==)


It is a relational or comparison
It is an assignment operator.
operator.
It is used for comparing two values.
It is used for assigning the value to
It returns 1 if both the values are
a variable.
equal otherwise returns 0.
Constant term can be placed in the
Constant term cannot be placed on
left hand side.
left hand side.
Example: 1==1 is valid and returns
Example: 1=x; is invalid.
1.
OPERATOR PRECEDENCE
 Definition : OPERATOR PRECEDENCE specifies
the order of operations in expressions that contain
more than one operator
 Operator precedence determines the grouping of
terms in an expression
 The associativity of an operator is a property that
determines how operators of the same precedence
are grouped in the absence of parentheses
 This affects how an expression is evaluated
 Certain operators have higher precedence than
others
 Example the multiplication operator has higher
precedence than the addition operator
OPERATOR PRECEDENCE
No Operator Associate Type

1 []() left to right Highest

2 ++ -- ! right to left Unary

3 * / % left to right Multiplicative


 

4 + - left to right Additive

5 < <= > >= left to right Relational

6 == != left to right Equality

7 && left to right Logical AND

8 || left to right Logical OR


 

9 = += -= *= /= %=|| right to left Assignment


 

10 , left to right Comma


 
OPERATOR PRECEDENCE
a) All operator within parentheses are performed
first. ( )
Example :
10 – ( 5+2 ) = 10 – ( 7 ) = 3

b) Parentheses within parentheses ( ( ) )


Inner parentheses will be performed first, from
inside out.
Example :
10 – ( 8 – ( 1 + 1) ) = 10 – (8-(2)) = 10 – (6) = 4
OPERATOR PRECEDENCE

c) The *, /, % are performed first,


from left to right.
d) The +, - are performed last, from
left to right.
Exa :
4 * 5 – 10 10 - 3 * 3 /3
= 20 – 10 = 10 – 9 / 3
= 10 = 10 – 3
=7
OPERATOR PRECEDENCE
 Example :
#include<iostream>
using namespace std;

int main()
{
int h=1, i=2,j=3,k=4; //initialized variables
int total=0;
total=(h < i + j && k);

cout<<total;

 Output :
OPERATOR PRECEDENCE

 Example :
OPERATOR PRECEDENCE

 Example :

You might also like