Variables and Operators
Variables and Operators
+
Variables and Operators
Comments
// my first program in C++
Comments are parts of the source code disregarded by the compiler. They simply do nothing. Their
purpose is only to allow the programmer to insert notes or descriptions embedded within the source
code.
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World! "; // prints Hello World!
cout << "Its a C++ program"; // prints I'm a C++ program
return 0;
}
1. _
2. a-z
3. A-Z
4. 0-9 (we cannot start with number but can be
used anywhere after )
The standard reserved keywords
Very important!!
The C++ language is a "case sensitive” language. Thus, for example, the RESULT
variable is not the same as the result variable.
a) 9times
b) Last + name
c) Short - fall
d) float
e) ME 3002
In order to use a variable in C++, we must first declare it specifying which data type
we want it to be.
For example:
Initialization of variables
// initialization of variables
#include <iostream>
using namespace std;
int main ()
{
int a=5; // initial value = 5
int b(2); // initial value = 2 6
int result; // initial value undetermined
a = a + 3;
result = a- b;
cout << result;
return 0;
}
Constant (#define)
Constants are expressions with a fixed value.
You can define your own names for constants by using the #define preprocessor directive .
Its syntax is: #define identifier value
// defined constants: calculate
circumference
#include <iostream>
#define PI 3.14159
using namespace std;
#define PI 3.14159
int main ()
31.4159 {
double r=5.0; // radius
double circle;
circle = 2 * PI * r;
cout << circle;
return 0;
}
Operators
Assignment (=): The assignment operator assigns a value to a variable.
// assignment operator
#include <iostream>
using namespace std;
int main ()
{
int a, b; // a:?, b:?
a = 10; // a:10, b:?
b = 4; // a:10, b:4 a: 4 b:7
a = b; // a:4, b:4
b = 7; // a:4, b:7
cout << "a:";
cout << a;
cout << " b:";
cout << b;
return 0;
}
Arithmetic operators ( +, -,
*, /, % )
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.
#include<iostream> #include<iostream>
using namespace std; using namespace std;
x=5; x=5;
y = x++; y = ++x;
cout <<y; cout <<y;
return 0; return 0;
} }
Relational Operator ( ==, !=, >, <, >=, <= )
In order to evaluate a comparison between two expressions .The result of a relational operation is
a Boolean value that can only be true or false,
Logical operators ( !, &&, || )
The logical operators are often used to combine relational expressions into
more complicated Boolean expressions.
a=5+7%2 ?
Standard Input (cin>>)
// i/o example
#include <iostream>
using namespace std;
int main ()
{
int i;
cout << “enter an value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i*2 << ".\n";
return 0;
}
THANK YOU