SlideShare a Scribd company logo
1 of 35
2.0 BASIC PROGRAM ELEMENTS
Initialize variable
• When declaring a regular local variable, its value is by default
undetermined. But you may want a variable to store a concrete value at
the same moment that it is declared.
• In order to do that, you can initialize the variable.
• There are two ways to do this in C++:
• The first one, known as c-like, is done by appending an equal sign followed
by the value to which the variable will be initialized:
type identifier = initial_value ;
• For example, if we want to declare an int variable called a initialized with a
value of 0 at the moment in which it is declared, we could write:
int a = 0;
Initialize variable
• The other way to initialize variables, known as constructor
initialization, is done by enclosing the initial value between
parentheses (()):
type identifier (initial_value) ;
• For example:
int a (0);
• Both ways of initializing variables are valid and equivalent
in C++.
Example of program
// initialization of variables
#include <iostream>
using namespace std;
int main ()
{
int a=5; // initial value = 5
int b(2); // initial value = 2
int result; // initial value undetermined
a = a + 3;
result = a - b;
cout << result;
return 0;
}
Output:
6
Identifier scope:local, global
• All the variables that we intend to use in a
program must have been declared with its type
specifier in an earlier
• point in the code, like we did in the previous code
at the beginning of the body of the function main
when we declared that a, b, and result were of
type int.
• A variable can be either of local or global scope.
• A local variable is one declared within the body of
a function or a block.
• A global variable is a variable declared in the
main body of the source code, outside all
functions.
• Global variables can be referred from
anywhere in the code, even inside functions,
whenever it is after its declaration.
Example of program:
#include<iostream>
using namesopace std;
int num1,num2;
char name;
int main()
{
float total;
cout<<“First number is:”;
cin>>num1;
cout<<“Second number is:”;
cin>>num2;
total=num1+NUM2;
cout<<“TOTAL OF TWO NUMBERS IS:”<<total;
return 0;
}
Global Variable
Local Variable
keyword
• Keywords (also called reserved words)
– Reserved words in the C++ language for specific use.
– Must be used as they are defined in the programming
language
– Keywords that identify language entities such as
statements, data types, language attributes, etc.
– Have special meaning to the compiler, cannot be used as
identifiers (variable, function name)
– Should be typed in lowercase.
– Example: const, double, int, main,
void,printf, while, for, else (etc..)
• Cannot be used as identifiers or variable
namesKeywords common to the
C and C++ programming
languages
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
C++ only keywords
asm bool catch class const_cast
delete dynamic_cast explicit false friend
inline mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw true
try typeid typename using virtual
wchar_t
Data Types
• we store the variables in our computer's memory, but the computer
has to know what kind of data we want to store in them,
• The memory in our computers is organized in bytes. A byte is the
minimum amount of memory that we can manage in C++.
• A byte can store a relatively small amount of data: one single
character or a small integer
• (generally an integer between 0 and 255).
• In addition, the computer can manipulate more complex data types
that come from grouping several bytes, such as long numbers or
non-integer numbers.
• Next you have a summary of the basic fundamental data types in
C++, as well as the range of values that can be represented with
each one:
Data Type C++
keyword
Syntax Bit
Width
Example
value
Range
integer int int no1,no2; 32 -1 ,1,34000 -32768-32767
long integer long long amount; 64 1000000 -4294967296 to
4294967296
short
integer
short short totalweight; 16 127 -127-128
unsigned
integer
unsigned unsigned sum; 32 200 0 to 65535
character char char name; 8 ‘z’ 0 to 255
floating
point
float float amount; 32 20.00 Approximately 6
digits of
precision
double
floting point
double double totalweight; 64 100.85321 Approximately
12 digits of
precision
boolean bool bool found; N/A True/false True/false
Input and output statement
• Input/output statement operation is fundamental to any programming language.
• In c++ cin and cout are used to input data and to output the data.
cin>> is used to get data from keyboard
cout<< is used to send the output to the screen.
• Preprocessor directive #include<iostream> must be used in order to handle
the input cin>> and output cout<< statement.
• The other type of input is gets(variableName) and
cin.getline(variablename,length).
• The gets(variableName) should be handle by preprocessor directive
#include<stdio>
• While cin.getline(variablename,length) should be handle by
preprocessor directive #include<string>
Example of input statement
Task Usage/sample input data
To input numeric data type int num1;
float num2;
cin>>num1>>num2; //input 10 5.5
To input 2 character data types char letter, symbol;
cin>>letter>>symbol; //input A #
To input sequence of characters (string) char custName[50];
gets(custName);
char custName[50];
cin.getline(custName,50);
Example of output statement
Task Usage/sample input data
To display labels
Enter 2 number:
cout<<“Enter 2 numbers”;
To display result from an arithmetic
expression
cout<<5*2;
cout<<sum/count;
To display label Total is: and a value stored
in variable total. Complete output is
Total is:10
int total=10;
cout<<“Total is:”<<total;
To display formatted output and
predefined symbol,
endl n
cout<<“n”;
cout<<endl;
Operator and Expression
Operator
• An operator is a symbol that causes the compiler to take an
action
• Operators act an operands and in c++ all operands are
expressions.
• In c++ there are several different categories of operators.
These categories are:
a) Arithmetic operator
b) Assignment operator
c) Increment and Decrement operator
d) Relational operator
e) Logical operator
Arithmetic Operator
Operator Meaning Example
+ addition X+y
- subtraction X-y
* multiplication X*y
/ division X/y
% modulo X%y
Compound Assignment
• 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:
Compound Assignment
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);
Assignment Opertaor
• C++ has several assignment operators. The most
commonly used assignment operator is :
=
• Assignment operator using = has the general form:
identifier = expression
• Where identifier generally represent variable and
expression represent constant, a variable or a more
complex expression.
Assignment Statement
• An assignment statement is used to place a value into another
variable coded directly within the program.
• In other words, the variable gets the value initially assigned to it in
the program (hard-coded) and not from the value keyed in by the
user.
• Example:
quantity=20;
price=5.50;
amount=basic_pay+overtime;
Another example:
counter ++; or also can written as counter=counter + 1;
sum=sum+num; or also can writen as sum+=num;
Increment and decrement operator
• increase operator (++) and the decrease operator (--)
• increase operator (++) increase by one the value stored in a variable.
• the decrease operator (--) reduce by one the value stored in a variable.
• They are equivalent to +=1 and to -=1, respectively.
• c++;
• c+=1;
• c=c+1;
• The three of them increase by one the value of c.
• A characteristic of this operator is that it can be used both
as a prefix and as a suffix.
• That means that it can be written either before the variable
identifier (++a) or after it (a++).
• Although in simple expressions like a++ or ++a both have
exactly the same meaning.
• increase operator is used as a prefix (++a) the value is
increased before the result of the expression is evaluated.
• Used suffix (a++) the value stored in a is increased after
being evaluated and therefore the value stored before the
increase operation is evaluated in the outer expression.
Example 1
B=3;
A=++B;
// A contains 4, B contains 4
Example 2
B=3;
A=B++;
// A contains 3, B contains 4
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.
RELATIONAL OPERATOR
• Relational operators (>, <, >=, <=)(==, !=, )
• In order to evaluate a comparison between two
expressions we can use the relational
• The result of a relational operation is a Boolean
value that can only be true or false, according to
its Boolean result.
• We may want to compare two expressions, for
example, to know if they are equal or if one is
greater than the other is.
• Here is a list of the relational operators that can be used in C++:
• > Greater than
• < Less than
• >= Greater than or equal to
• <= Less than or equal to
• == Equal to
• != Not equal to
• Here there are some examples:
(7 == 5) // evaluates to false.
(5 > 4) // evaluates to true.
(3 != 2) // evaluates to true.
(6 >= 6) // evaluates to true.
(5 < 5) / / evaluates to false.
• Of course, instead of using only numeric constants, we
can use any valid expression, including variables.
Suppose that:
a=2, b=3 and c=6,
(a == 5) // evaluates to false since a is not equal to 5.
(a*b >= c) // evaluates to true since (2*3 >= 6) is true.
(b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false.
((b=2) == a) // evaluates to true.
• Be careful! The operator = (one equal sign) is not the
same as the operator == (two equal signs).
• The first one is an assignment operator (=) is assigns
the value at its right to the variable at its left.
• (==) is the equality operator that compares whether
both expressions in the two sides of it are equal to
each other.
• Thus, in the last expression ((b=2) == a), we first
assigned the value 2 to b and then we compared it to a,
that also stores the value 2, so the result of the
operation is true.
LOGICAL OPERATOR
• Logical operators ( !, &&, || )
• The Operator ! is the C++ operator to perform the Boolean operation NOT.
• It has only one operand, located at its right, and the only thing that it does is
to inverse the value of it, producing false if its operand is true and true if its
operand is false.
• Basically, it returns the opposite Boolean value of evaluating its operand. For
example:
!(5 == 5) // evaluates to false because the expression at its right
(5 == 5) is true.
!(6 <= 4) // evaluates to true because (6 <= 4) would be false.
!true // evaluates to false
!false // evaluates to true.
• The logical operators && and || are used when evaluating two
expressions to obtain a single relational result.
• The operator && corresponds with Boolean logical operation AND.
This operation results true if both its two operands are true, and
false otherwise.
• The following panel shows the result of operator && evaluating the
expression a && b:
• && OPERATOR
a b a && b
true true true
true false false
false true false
false false false
• The operator || corresponds with Boolean logical operation OR.
This operation results true if either one of its two operands is true,
thus being false only when both operands are false themselves.
• Here are the possible results of a|| b:
|| OPERATOR
a b a || b
true true true
true false true
false true true
false false false
• For example:
( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ).
( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).
Precedence of operators
• When writing complex expressions with
several operands, we may have some doubts
about which operand is evaluated first and
which later.
• For example, in this expression:
a = 5 + 7 % 2
• a = 5 + (7 % 2) // with a result of 6, or
• a = (5 + 7) % 2 // with a result of 0
• The correct answer is the first of the two
expressions, with a result of 6.
• There is an established order with the priority
of each operator, and not only the arithmetic
ones (those whose preference come from
mathematics) but for all the operators which
can appear in C++.
• From greatest to lowest priority, the priority
order is as follows:
• ++, --
• !, +, -
• *, /, %
• +, -
• <, <=, >=, >
• ==
• !=
• &&
• ||
• =
EXPRESSION
• Anything that evaluates to a value is an
expression in c++.
• This expression is said to return a value.
• Thus, 3+2 return a value of 5 and so is an
expression.
• All expression are statement
Example:
x=a+b+c;
Num1+num2;

More Related Content

What's hot

C++ Overview
C++ OverviewC++ Overview
C++ Overview
kelleyc3
 

What's hot (20)

C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
Getting Started with C++
Getting Started with C++Getting Started with C++
Getting Started with C++
 
c++
 c++  c++
c++
 
(2) cpp imperative programming
(2) cpp imperative programming(2) cpp imperative programming
(2) cpp imperative programming
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cpp
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
C++ Overview
C++ OverviewC++ Overview
C++ Overview
 
C++ for beginners
C++ for beginnersC++ for beginners
C++ for beginners
 
Basic concept of c++
Basic concept of c++Basic concept of c++
Basic concept of c++
 
C introduction by thooyavan
C introduction by  thooyavanC introduction by  thooyavan
C introduction by thooyavan
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
 
C++ ch2
C++ ch2C++ ch2
C++ ch2
 
C++ book
C++ bookC++ book
C++ book
 
Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1
 
C++ Programming Language Training in Ambala ! Batra Computer Centre
C++ Programming Language Training in Ambala ! Batra Computer CentreC++ Programming Language Training in Ambala ! Batra Computer Centre
C++ Programming Language Training in Ambala ! Batra Computer Centre
 
C++ Ch3
C++ Ch3C++ Ch3
C++ Ch3
 

Similar to POLITEKNIK MALAYSIA

Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variables
Tony Apreku
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
Ralph Weber
 
C++ programming
C++ programmingC++ programming
C++ programming
Anshul Mahale
 
INTRODUCTION TO C++.pptx
INTRODUCTION TO C++.pptxINTRODUCTION TO C++.pptx
INTRODUCTION TO C++.pptx
MamataAnilgod
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
Hattori Sidek
 

Similar to POLITEKNIK MALAYSIA (20)

#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
 
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit DubeyMCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variables
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
 
C++
C++C++
C++
 
C programming language
C programming languageC programming language
C programming language
 
programming week 2.ppt
programming week 2.pptprogramming week 2.ppt
programming week 2.ppt
 
1-19 CPP Slides 2022-02-28 18_22_ 05.pdf
1-19 CPP Slides 2022-02-28 18_22_ 05.pdf1-19 CPP Slides 2022-02-28 18_22_ 05.pdf
1-19 CPP Slides 2022-02-28 18_22_ 05.pdf
 
C Language Part 1
C Language Part 1C Language Part 1
C Language Part 1
 
C++ programming
C++ programmingC++ programming
C++ programming
 
INTRODUCTION TO C++.pptx
INTRODUCTION TO C++.pptxINTRODUCTION TO C++.pptx
INTRODUCTION TO C++.pptx
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
C programming tutorial for Beginner
C programming tutorial for BeginnerC programming tutorial for Beginner
C programming tutorial for Beginner
 
Programming using c++ tool
Programming using c++ toolProgramming using c++ tool
Programming using c++ tool
 
Pc module1
Pc module1Pc module1
Pc module1
 
C-PPT.pdf
C-PPT.pdfC-PPT.pdf
C-PPT.pdf
 
C program
C programC program
C program
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
 

More from Aiman Hud

More from Aiman Hud (20)

POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 

Recently uploaded

Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 

Recently uploaded (20)

Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 

POLITEKNIK MALAYSIA

  • 1. 2.0 BASIC PROGRAM ELEMENTS
  • 2. Initialize variable • When declaring a regular local variable, its value is by default undetermined. But you may want a variable to store a concrete value at the same moment that it is declared. • In order to do that, you can initialize the variable. • There are two ways to do this in C++: • The first one, known as c-like, is done by appending an equal sign followed by the value to which the variable will be initialized: type identifier = initial_value ; • For example, if we want to declare an int variable called a initialized with a value of 0 at the moment in which it is declared, we could write: int a = 0;
  • 3. Initialize variable • The other way to initialize variables, known as constructor initialization, is done by enclosing the initial value between parentheses (()): type identifier (initial_value) ; • For example: int a (0); • Both ways of initializing variables are valid and equivalent in C++.
  • 4. Example of program // initialization of variables #include <iostream> using namespace std; int main () { int a=5; // initial value = 5 int b(2); // initial value = 2 int result; // initial value undetermined a = a + 3; result = a - b; cout << result; return 0; } Output: 6
  • 5. Identifier scope:local, global • All the variables that we intend to use in a program must have been declared with its type specifier in an earlier • point in the code, like we did in the previous code at the beginning of the body of the function main when we declared that a, b, and result were of type int. • A variable can be either of local or global scope. • A local variable is one declared within the body of a function or a block.
  • 6. • A global variable is a variable declared in the main body of the source code, outside all functions. • Global variables can be referred from anywhere in the code, even inside functions, whenever it is after its declaration.
  • 7. Example of program: #include<iostream> using namesopace std; int num1,num2; char name; int main() { float total; cout<<“First number is:”; cin>>num1; cout<<“Second number is:”; cin>>num2; total=num1+NUM2; cout<<“TOTAL OF TWO NUMBERS IS:”<<total; return 0; } Global Variable Local Variable
  • 8. keyword • Keywords (also called reserved words) – Reserved words in the C++ language for specific use. – Must be used as they are defined in the programming language – Keywords that identify language entities such as statements, data types, language attributes, etc. – Have special meaning to the compiler, cannot be used as identifiers (variable, function name) – Should be typed in lowercase. – Example: const, double, int, main, void,printf, while, for, else (etc..)
  • 9. • Cannot be used as identifiers or variable namesKeywords common to the C and C++ programming languages auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while C++ only keywords asm bool catch class const_cast delete dynamic_cast explicit false friend inline mutable namespace new operator private protected public reinterpret_cast static_cast template this throw true try typeid typename using virtual wchar_t
  • 10. Data Types • we store the variables in our computer's memory, but the computer has to know what kind of data we want to store in them, • The memory in our computers is organized in bytes. A byte is the minimum amount of memory that we can manage in C++. • A byte can store a relatively small amount of data: one single character or a small integer • (generally an integer between 0 and 255). • In addition, the computer can manipulate more complex data types that come from grouping several bytes, such as long numbers or non-integer numbers. • Next you have a summary of the basic fundamental data types in C++, as well as the range of values that can be represented with each one:
  • 11. Data Type C++ keyword Syntax Bit Width Example value Range integer int int no1,no2; 32 -1 ,1,34000 -32768-32767 long integer long long amount; 64 1000000 -4294967296 to 4294967296 short integer short short totalweight; 16 127 -127-128 unsigned integer unsigned unsigned sum; 32 200 0 to 65535 character char char name; 8 ‘z’ 0 to 255 floating point float float amount; 32 20.00 Approximately 6 digits of precision double floting point double double totalweight; 64 100.85321 Approximately 12 digits of precision boolean bool bool found; N/A True/false True/false
  • 12. Input and output statement • Input/output statement operation is fundamental to any programming language. • In c++ cin and cout are used to input data and to output the data. cin>> is used to get data from keyboard cout<< is used to send the output to the screen. • Preprocessor directive #include<iostream> must be used in order to handle the input cin>> and output cout<< statement. • The other type of input is gets(variableName) and cin.getline(variablename,length). • The gets(variableName) should be handle by preprocessor directive #include<stdio> • While cin.getline(variablename,length) should be handle by preprocessor directive #include<string>
  • 13. Example of input statement Task Usage/sample input data To input numeric data type int num1; float num2; cin>>num1>>num2; //input 10 5.5 To input 2 character data types char letter, symbol; cin>>letter>>symbol; //input A # To input sequence of characters (string) char custName[50]; gets(custName); char custName[50]; cin.getline(custName,50);
  • 14. Example of output statement Task Usage/sample input data To display labels Enter 2 number: cout<<“Enter 2 numbers”; To display result from an arithmetic expression cout<<5*2; cout<<sum/count; To display label Total is: and a value stored in variable total. Complete output is Total is:10 int total=10; cout<<“Total is:”<<total; To display formatted output and predefined symbol, endl n cout<<“n”; cout<<endl;
  • 15. Operator and Expression Operator • An operator is a symbol that causes the compiler to take an action • Operators act an operands and in c++ all operands are expressions. • In c++ there are several different categories of operators. These categories are: a) Arithmetic operator b) Assignment operator c) Increment and Decrement operator d) Relational operator e) Logical operator
  • 16. Arithmetic Operator Operator Meaning Example + addition X+y - subtraction X-y * multiplication X*y / division X/y % modulo X%y
  • 17. Compound Assignment • 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:
  • 18. Compound Assignment 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);
  • 19. Assignment Opertaor • C++ has several assignment operators. The most commonly used assignment operator is : = • Assignment operator using = has the general form: identifier = expression • Where identifier generally represent variable and expression represent constant, a variable or a more complex expression.
  • 20. Assignment Statement • An assignment statement is used to place a value into another variable coded directly within the program. • In other words, the variable gets the value initially assigned to it in the program (hard-coded) and not from the value keyed in by the user. • Example: quantity=20; price=5.50; amount=basic_pay+overtime; Another example: counter ++; or also can written as counter=counter + 1; sum=sum+num; or also can writen as sum+=num;
  • 21. Increment and decrement operator • increase operator (++) and the decrease operator (--) • increase operator (++) increase by one the value stored in a variable. • the decrease operator (--) reduce by one the value stored in a variable. • They are equivalent to +=1 and to -=1, respectively. • c++; • c+=1; • c=c+1; • The three of them increase by one the value of c.
  • 22. • A characteristic of this operator is that it can be used both as a prefix and as a suffix. • That means that it can be written either before the variable identifier (++a) or after it (a++). • Although in simple expressions like a++ or ++a both have exactly the same meaning. • increase operator is used as a prefix (++a) the value is increased before the result of the expression is evaluated. • Used suffix (a++) the value stored in a is increased after being evaluated and therefore the value stored before the increase operation is evaluated in the outer expression.
  • 23. Example 1 B=3; A=++B; // A contains 4, B contains 4 Example 2 B=3; A=B++; // A contains 3, B contains 4 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.
  • 24. RELATIONAL OPERATOR • Relational operators (>, <, >=, <=)(==, !=, ) • In order to evaluate a comparison between two expressions we can use the relational • The result of a relational operation is a Boolean value that can only be true or false, according to its Boolean result. • We may want to compare two expressions, for example, to know if they are equal or if one is greater than the other is.
  • 25. • Here is a list of the relational operators that can be used in C++: • > Greater than • < Less than • >= Greater than or equal to • <= Less than or equal to • == Equal to • != Not equal to • Here there are some examples: (7 == 5) // evaluates to false. (5 > 4) // evaluates to true. (3 != 2) // evaluates to true. (6 >= 6) // evaluates to true. (5 < 5) / / evaluates to false.
  • 26. • Of course, instead of using only numeric constants, we can use any valid expression, including variables. Suppose that: a=2, b=3 and c=6, (a == 5) // evaluates to false since a is not equal to 5. (a*b >= c) // evaluates to true since (2*3 >= 6) is true. (b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false. ((b=2) == a) // evaluates to true.
  • 27. • Be careful! The operator = (one equal sign) is not the same as the operator == (two equal signs). • The first one is an assignment operator (=) is assigns the value at its right to the variable at its left. • (==) is the equality operator that compares whether both expressions in the two sides of it are equal to each other. • Thus, in the last expression ((b=2) == a), we first assigned the value 2 to b and then we compared it to a, that also stores the value 2, so the result of the operation is true.
  • 28. LOGICAL OPERATOR • Logical operators ( !, &&, || ) • The Operator ! is the C++ operator to perform the Boolean operation NOT. • It has only one operand, located at its right, and the only thing that it does is to inverse the value of it, producing false if its operand is true and true if its operand is false. • Basically, it returns the opposite Boolean value of evaluating its operand. For example: !(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true. !(6 <= 4) // evaluates to true because (6 <= 4) would be false. !true // evaluates to false !false // evaluates to true.
  • 29. • The logical operators && and || are used when evaluating two expressions to obtain a single relational result. • The operator && corresponds with Boolean logical operation AND. This operation results true if both its two operands are true, and false otherwise. • The following panel shows the result of operator && evaluating the expression a && b: • && OPERATOR a b a && b true true true true false false false true false false false false
  • 30. • The operator || corresponds with Boolean logical operation OR. This operation results true if either one of its two operands is true, thus being false only when both operands are false themselves. • Here are the possible results of a|| b: || OPERATOR a b a || b true true true true false true false true true false false false • For example: ( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ). ( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).
  • 31. Precedence of operators • When writing complex expressions with several operands, we may have some doubts about which operand is evaluated first and which later. • For example, in this expression: a = 5 + 7 % 2
  • 32. • a = 5 + (7 % 2) // with a result of 6, or • a = (5 + 7) % 2 // with a result of 0
  • 33. • The correct answer is the first of the two expressions, with a result of 6. • There is an established order with the priority of each operator, and not only the arithmetic ones (those whose preference come from mathematics) but for all the operators which can appear in C++. • From greatest to lowest priority, the priority order is as follows:
  • 34. • ++, -- • !, +, - • *, /, % • +, - • <, <=, >=, > • == • != • && • || • =
  • 35. EXPRESSION • Anything that evaluates to a value is an expression in c++. • This expression is said to return a value. • Thus, 3+2 return a value of 5 and so is an expression. • All expression are statement Example: x=a+b+c; Num1+num2;