CH 2

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

VARIABLE

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.
CONT….
• A type which is established when the variable is
defined (e.g., integer, real, character). Once
defined, the type of a C++ variable cannot be
changed.
• A value which can be changed by assigning a new
value to the variable. The kind of values a variable
can assume depends on its type. For example, an
integer variable can only take integer values (e.g.,
2, 100, -12).
CONT….

#include<iostream.h>

int main()
{
int workdays;
float workhours, payrate, weeklypay;

workdays = 5;
workhours = 7.5;
payrate = 38.55;
weeklypay = workdays * workhours * payrate;
cout<< "weekly Pay= ";
cout<<weeklypay<<endl;
}
OUTPUT:
weekly Pay= 1445.62
CONT….
Simple Input/output
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: >> for input and << for output.
CONT….

#include<iostream.h>

int main()
{
int a;
cin>>a;
cout<<a;
}
CONT….
• 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.
CONT….
Integer Numbers
An integer variable may be defined to be of type
short, int, or long. The only difference is that an int
uses more or at least the same number of bytes as a
short, and a long uses more or at least the same
number of bytes as an int.
• short age = 20;
• int salary = 65000;
• long price = 4500000;
CONT….

• Real Numbers
A real variable may be defined to be of type float or
double. The latter uses more bytes and therefore
offers a greater range and accuracy for representing
real numbers. For example, on the author’s PC, a
float uses 4 and a double uses 8 bytes.
• float interestRate = 0.06;
• double pi = 3.141592654;
• CHARACTERS
A character variable is defined to be of type char.
A character variable occupies a single byte which
contains the code for the character. This code is a
numeric value and depends on the character coding
system being used (i.e., is machine-dependent).
char ch = 'A';
CONT….

• '\n' // new line


• '\r' // carriage return
• '\t' // horizontal tab
• '\v' // vertical tab
• '\b' // backspace
• '\f' // formfeed
CONT….

• Single and double quotes and the backslash


character can also use the escape notation:
• '\'' // single quote (')
• '\"' // double quote (")
• '\\' // backslash (\)
CONT….

• Strings
A string is a consecutive sequence (i.e., array) of
characters which are terminated by a null
character. A string variable is defined to be of
type char* (i.e., a pointer to character). A
pointer is simply the address of a memory
location.
char *str = "HELLO";
CONT….
• Names
Programming languages use names to refer to
the various entities that make up a program. We
have already seen examples of an important
category of such names (i.e., variable names).
CONT….
• C++ imposes the following rules for creating
valid names (also called identifiers). A name
should consist of one or more characters, each
of which may be a letter (i.e., 'A'-'Z' and 'a'-'z'),
a digit (i.e., '0'-'9'), or an underscore character
('_'), except that the first character may not be
a digit. Upper and lower case letters are
distinct.
CONT….
• salary // valid identifier
• salary2 // valid identifier
• 2salary // invalid identifier (begins
with a digit)
• _salary // valid identifier
• Salary // valid but distinct from
salary
++ keywords
as continue float new signed try

auto default for operator sizeof typedef

break delete friend private static union

case do goto protected struct unsigned

catch double if public switch virtual

char else inline register template void

class enum int return this volatile

const extern long short throw while


• Expressions
C++ provides operators for composing arithmetic,
relational, logical, bitwise, and conditional
expressions. It also provides operators which
produce useful side-effects, such as assignment,
increment, and decrement.
• 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
* Multiplicatio 2 * 3.4 // gives 6.8
n
/ Division 9 / 2.0 // gives 4.5

% Remainder 13 % 3 // gives 1
• Relational Operators
C++ provides six relational operators for comparing
numeric quantities.
Operator Name Example
== Equality 5 == 5 // gives 1
!= Inequality 5! = 5 // gives 0
< Less Than 5 < 5.5 // gives 1
<= Less Than or 5 <= 5 // gives 1
Equal
> Greater Than 5 > 5.5 // gives 0
>= Greater Than or 6.3 >= 5 // gives 1
Equal
• Logical Operators
C++ provides three logical operators for combining
logical expression.
Operator Name Example

! Logical !(5 == 5) // gives 0


Negation
&& Logical 5 < 6 && 6 < 7 // gives 1
And
|| Logical Or 5 < 6 || 6 < 5 // gives 1
• Bitwise Operators
C++ provides six bitwise operators for manipulating
the individual bits in an integer quantity.
Operator Name Example

~ Bitwise Negation ~'\011' // gives ‘\366'

& Bitwise And '\011' & '\027' // gives '\001'

| Bitwise Or '\011' | '\027' // gives '\037'

^ Bitwise Exclusive '\011' ^ '\027' // gives '\036'


Or
<< Bitwise Left Shift '\011' << 2 // gives '\044'

>> Bitwise Right Shift '\011' >> 2 // gives '\002'


How the bits are calculated.
Example Octal Value Bit Sequence
x 011 0 0 0 0 1 0 0 1
y 027 0 0 0 1 0 1 1 1
~x 366 1 1 1 1 0 1 1 0
x&y 001 0 0 0 0 0 0 0 1
x|y 037 0 0 0 1 1 1 1 1
x^y 036 0 0 0 1 1 1 1 0
x << 2 044 0 0 1 0 0 1 0 0
x >> 2 002 0 0 0 0 0 0 1 0
• Increment/Decrement Operators
The auto increment (++) and auto decrement (--)
operators provide a convenient way of, respectively,
adding and subtracting 1 from a numeric variable.
• The examples assume the following variable
definition:
• int k = 5;
Increment and decrement operators
Operator Name Example

++ Auto Increment ++k + 10 // gives 16


(prefix)

++ Auto Increment k++ + 10 // gives 15


(postfix)

-- Auto Decrement --k + 10 // gives 14


(prefix)

-- Auto Decrement k-- + 10 // gives 15


(postfix)
• ASSIGNMENT OPERATOR
The assignment operator is used for storing a value
at some memory location (typically denoted by a
variable). Its left operand should be an l value, and
its right operand may be an arbitrary expression.
Operator Example Equivalent To
= n = 25
+= n += 25 n = n + 25
-= n -= 25 n = n - 25
*= n *= 25 n = n * 25
/= n /= 25 n = n / 25
%= n %= 25 n = n % 25
&= n &= 0xF2F2 n = n & 0xF2F2
|= n |= 0xF2F2 n = n | 0xF2F2
^= n ^= 0xF2F2 n = n ^ 0xF2F2
<<= n <<= 4 n = n << 4
>>= n >>= 4 n = n >> 4
• Int m, n, p;
• m = n = p = 100; // means: n = (m = (p = 100));
• m = (n = p = 100) + 2;
// means: m = (n = (p = 100)) + 2;

• This is equally applicable to other forms of


assignment. For example:
• m = 100;
• m += n = p = 10; // means: m = m + (n = p = 10);
• Conditional Operator
The conditional operator takes three operands. It
has the general form:
operand1 ? operand2 : operand3
• int m = 1, n = 2;
• int min = (m < n ? m : n); // min receives
• Comma Operator
Multiple expressions can be combined into one
expression using the comma operator. The comma
operator takes two operands.
• int m, n, min;
• int mCount = 0, nCount = 0; //...
• min = (m < n ? mCount++, m : nCount++, n);
• Simple Type Conversion
A value in any of the built-in types we have see so far
can be converted (type-cast) to any of the other types.
For example:
• (int) 3.14 // converts 3.14 to an int to give 3
• (long) 3.14 // converts 3.14 to a long to give 3L
• (double) 2 // converts 2 to a double to give 2.0
• (char) 122 // converts 122 to a char whose code is
122
• (unsigned short) 3.14 // gives 3 as an unsigned short
• Statements
Like many other procedural languages, C++ provides
different forms of statements for different purposes.
Declaration statements are used for defining
variables.
• Simple and Compound Statements
A simple statement is a computation terminated
by a semicolon. Variable definitions and semicolon-
terminated expressions are examples:

• int i; // declaration statement


• ++i;
• double d = 10.5; // declaration statement
• d + 5;
• Multiple statements can be combined into a
compound statement by enclosing them within
braces. For example:
• {
int min, i = 10, j = 20;
min = (i < j ? i : j);
cout << min << '\n’;
}
• a compound statement may contain variable
definitions and defines a scope for them, it is also
called a block.
• The if Statement
It is sometimes desirable to make the execution of
a statement dependent upon a condition being
satisfied. The if statement provides a way of
expressing this, the general form of which is:
if (expression)
statement;
if-else statement
 if (expression)
statement1;
else
statement2;
• The switch Statement
The switch statement provides a way of choosing between a
set of alternatives, based on the value of an expression.
switch (expression) tag
{
labels
case constant1:
statements;
...
case constantn:
statements;
default:
statements;
}
switch (operator)
{
case '+': result = operand1 + operand2;
break;
case '-': result = operand1 - operand2;
break;
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
default: cout << "unknown operator: " << ch << '\n';
break;
}
• The while Statement
The while statement (also called while loop) provides
a way of repeating an statement while a condition
holds. It is one of the three flavors of iteration in C++.
• while (expression)
statement;
i = 1;
sum = 0;
while (i <= n)
sum += i++;
• The do Statement
The do statement (also called do loop) is similar to
the while statement, except that its body is executed
first and then the loop condition is examined.
do
statement;
while (expression);
do {
cin >> n;
cout << n * n << '\n';
} while (n != 0);
• The for Statement
The for statement (also called for loop) is similar to
the while statement, but has two additional
components: an expression which is evaluated only
once before everything else, and an expression
which is evaluated once at the end of each iteration.
• for (expression1; expression2; expression3)
statement;
 sum = 0;
for (i = 1; i <= n; ++i)
sum += i;
• for (int i = 1; i <= n; ++i)
sum += i;
• The continue Statement
The continue statement terminates the current iteration
of a loop and instead jumps to the next iteration. It
applies to the loop immediately enclosing the continue
statement.
• for (i = 0; i < n; ++i)
{
cin >> num;
if (num < 0) continue; // causes a jump to: ++i
// process num here...
}
• The break Statement
A break statement may appear inside a loop (while, do, or
for) or a switch statement. It causes a jump out of these
constructs, and hence terminates them.
• for (i = 0; i < attempts; ++i) {
cout << "Please enter your password: ";
cin >> password;
if (Verify(password))
// check password for correctness
break; // drop out of the loop
cout << "Incorrect!\n";
}
• The goto Statement
The goto statement provides the lowest-level of
jumping. It has the general form:
• goto label;
• The return Statement
• The return statement enables a function to
return a value to its caller. It has the general
form:
• return expression;
THE END

You might also like