Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 54

Variables, data types,

identifier, operator
cin, cout

OOP, IT, NUR 3/10/2008 1


Recall

/// / This is my first C ++ program


// / It prints a line of text
# include <iostream>
int main ( )
{
std:: cout << “ My first C ++ program ” << std::
endl;
return 0 ;
}
OOP, IT, NUR 3/10/2008 2
Recall(cont.)
structure of the C ++ Program and C+ + features
Above program demonstrates several important features of C+
+ language. The structure of the program above is as
follows:-
// This is my first C++ program
//It prints a line of text
are comments in C++ language.
# include <iostream>
is a preprocessor directive. It tells the preprocessor to include
the contents of iostream header file in the program before
compilation. This file is required for input output statements.

OOP, IT, NUR 3/10/2008 3


Recall(cont.)

main Function
int main()
is a function. C++ program is a collection of functions. Every
program in C++ begins executing at the function main().
Every C++ program has exactly one main function and a
collection of other functions. A function is the main
entity where all of the functionality of a program is
defined. A function takes some input, processes it
according to the some code written in the function body
and produces an output which can be either sent to the
user or can be used by other functions.
OOP, IT, NUR 3/10/2008 4
Recall(cont.)

Keyword int in int main()


 specifies the return type of a function. int specifies that
the function main returns an integer value.
 Brackets () after main signify that main is a function.
Every function should be followed by a pair of brackets.
The purpose of brackets is to pass the parameters list to
the functions. Parameters are the number and type of
arguments (inputs) which a function takes.

OOP, IT, NUR 3/10/2008 5


Recall(cont.)

 Opening brace ( { ) and closing brace ( } ) mark the


beginning and end of a function. Anything which is inside
the braces is the body of that function.
In our example, the function body consists of only two
statements,
{
std::cout << “My first C++ program. \n”;
return 0;
}

OOP, IT, NUR 3/10/2008 6


Recall(cont.)

Statement
 std::cout << “My first C++ program ” << std::endl;
The above line is a statement in C++. A statement must always
terminate with a semicolon (;) otherwise it causes a syntax error.
This statement introduces two new features of C++ language, cout
and << operator. W hen this statement is executed, it sends the
string between the quotation marks to the standard output stream
object – cout. cout is a predefined object in C++ and the standard
output stream is normally the screen.
The purpose of standard output stream object is to print the output on
the device to which it is connected. Normally, the output device is
screen but it can be programmed to output to any other device such
as a printer. The following diagram illustrated the concept of cout.

OOP, IT, NUR 3/10/2008 7


Recall(cont.)
 We used std:: before cout. This is required when we use
# include <iostream> .
 It specifies that we are using a name (cout) which
belongs to namespace std. Namespace is a new concept
introduced by ANSI C++ which defines the scope of
identifiers which are used in the program. std is the
namespace where C++ standard libraries are defined.
 Operator << is the insertion stream operator. It sends
contents of variable on its right to the object on its left. In
our case, right operand is the string “My first C++
program” and left operand is cout object. So it sends the
string to the cout object and cout object then displays it
on the output screen.
OOP, IT, NUR 3/10/2008 8
Recall(cont.)
 endl is the line feed operator in C++. It acts as a stream manipulator
whose purpose is to feed the whole line and then point the cursor to the
beginning of the next line. W e can use \n (\n is an escape sequence)
instead of endl for the same purpose. Then the code would be
 std::cout << “My first C++ program \n”;
R eturn Statement
 Last line in the body of our first program is return 0;
 The keyword return is a special statement which is used to exit a function
and return a value. This statement exits the function main indicating its
completion and returns the value 0 to the operating system indicating
that the program successfully ran to completion. return statement is
included at the end of every main function.

OOP, IT, NUR 3/10/2008 9


Recall(cont.)

OUTP U T
W hen this program is run, it prints the following output
 My first C++ program
For programs to do exciting things, they should be written,
compiled and then run on a computer using a compile or
IDE.
You have just run your first C++ program and have
understood many important features of C++.

OOP, IT, NUR 3/10/2008 10


Assignment 1:C++ basic Programming

 Square and cube programming

# include <iostream.h>
int square (int);
int cube (int);

int main()
{
cout <<“27 squared is”
<< square(27) << endl;
cout<<“27 cubed is”
<< cube(27) <<endl;
return 0;
}

OOP, IT, NUR 3/10/2008 11


Assignment 1:C++ basic Pragramming(
cont)
int square (int n) // function declaration
{
return n*n;
}
int cube (int n)
{
return n* square(n);
}
Results: 27 squared is 729
27 cubed is 19683

OOP, IT, NUR 3/10/2008 12


Variables and identifier
Varibale: a variable as a portion of memory to store a determined value. In
c++ all varibales must be declared before they are used. Futhermore,
variables must be used in a manner consistent with their associated type.
It is a location in memory, referenced by an identifer, in which a data
value that can be changed is stored.
Variables are a way of reserving memory to hold some data and assign
names to them so that we don't have to remember the numbers like
46735 and instead we can use the memory location by simply referring to
the variable. Every variable is mapped to a unique memory address. For
example, we have 3 variable v1, v2, v3. They may be assigned the
memory addresses 32000, 12456, 67893 respectively. It specifies that
there are three variables v1, v2, v3 (named by programmer) and have
assigned the memory locations 32000, 12456 and 67893. These memory
locations are not their values. The values of the variables are what you
assign to them. You can assign value 86 to v1, 32.45 to v2 and 'a' to v3.

OOP, IT, NUR 3/10/2008 13


Variables and
identifier(cont.)
 Declaring and defining variables
A variable in C++ must be declared (the type of variable) and
defined (values assigned to a variable) before it can be used
in a program. Following shows how to declare a variable.
 DATA TYP E S
Every variable in C++ can store a value. However, the type of
value which the variable can store has to be specified by the
programmer. C++ supports the following inbuilt data types:-
int (to store integer values), float (to store decimal values)
and char (to store characters), bool (to store Boolean value
either 0 or 1) and void (signifies absence of information).

OOP, IT, NUR 3/10/2008 14


Variables and
identifier(cont.)
 integer data type
Integer (int) variables are used to store integer values like 34, 68704 etc. To declare a
variable of type integer, type keyword int followed by the name of the variable.
You can give any name to a variable but there are certain constraints, they are
specified in Identifiers section. For example, the statement
 int sum; declares that sum is a variable of type int. You can assign a value to it
now or later. In order to assign values along with declaration use the assignment
operator (=).
 int sum = 25; assigns value 25 to variable sum.
There are three types of integer variables in C++, short, int and long int. All of them store values
of type integer but the size of values they can store increases from short to long int. This is
because of the size occupied by them in memory of the computer. The size which they can
take is dependent on type of computer and varies. More is the size, more the value they can
hold. For example, int variable has 2 or 4 bytes reserved in memory so it can hold 2 32=
65536 values. Variables can be signed or unsigned depending they store only positive values
or both positive and negative values. And short, variable has 2 bytes. Long int variable has 4
bytes.

OOP, IT, NUR 3/10/2008 15


Variables and identifier(cont.)
f loat data type
To store decimal values, you use float data type. Floating point data types comes in
three sizes, namely float, double and long double. The difference is in the length
of value and amount of precision which they can take and it increases from float
to long double. For example, statement
float average = 2.34; declares a variable average which is of type float and has the
initial value 2.34
C h aracter data type
A variable of type char stores one character. It size of a variable of type char is
typically 1 byte. The statement
 char name = 'c'; declares a variable of type char (can hold characters) and has the
initial values as character c. Note that value has to be under single quotes.
Boolean
 A variable of type bool can store either value true or false and is mostly used in
comparisons and logical operations. W hen converted to integer, true is any non
zero value and false corresponds to zero.

OOP, IT, NUR 3/10/2008 16


Variables and identifier
(cont.)
a=5;
b=2;
a=a+1;
results= a-b;
Each variable needs an identifier that distinguishes it from the
others, for example, in the previous code the variable
identifiers were a, b and result, but we could have called the
variables any names we wanted to invent, as long as they
were valid identifiers.
identifier: A valid identifier is a sequence of one or more letters,
digits or underscore characters (_). It is a name associated
with a function or data object and used to that function of
data

OOP, IT, NUR 3/10/2008 17


Variables and
identifier(cont.)
 Identifiers are the name of functions, variables, classes,
arrays etc. which you create while writing your programs.
Identifiers are just like names in any language. There are
certain rules to name identifiers in C++. They are:-
 Identifiers must contain combinations of digits, characters
and underscore (_).
 Identifier names cannot start with digit.
 Identifier names can contain any combination of characters
as opposed to the restriction of 31 letters in C.

OOP, IT, NUR 3/10/2008 18


Variables and identifier
int a;
float mynumber;
These are two valid declarations of variables. The
first declares a variable type int with the
identifier a; the second , a variable type float
with the identifier mynumber
int a, b, c; (declares three variables)

OOP, IT, NUR 3/10/2008 19


example
// operating with varibales
#include <iostream>
using namespace std;
int main ()
{
//declaring variables:
int a, b;
int result;
//process
a=5;
b=2;
a=a+1;
result=a-b
//print out the result:
cout<< result;
//terminate the program:
return 0;
}
Result:4

OOP, IT, NUR 3/10/2008 20


Initialization of variables
Two ways of initialization
 C-like: done by appending an equal sign
followed by the value
Typ e identifier = initial_value ;
Ex: int a =0;
 Conctructor initialization: done by enclosing the
initial value between parentheses (())
Type identifier (initial_value);
Ex: int a (O);

OOP, IT, NUR 3/10/2008 21


example
//initialization of variabales
#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;
}
Result: 6

OOP, IT, NUR 3/10/2008 22


Data types
int : this int keyword is used to declare integers i.e integers
with 16bits
ex: int var 1;
int var 11=10; //initialization for C++
long: this long keyword is used for declaring longer
numbers, i.e numbers of length 32 bits
float: this keyword float is used to declare floating point
decimal numbers
char: used to declare characters; the size of each character
is 8bits
string: this is not a basic data type with C++. Instead array
of the char data type should be used for a string
variable,
ex: char strvar1

OOP, IT, NUR 3/10/2008 23


Strings: Variables that can store non-numerical
values that are longer than one single character are
known as strings.
A first difference with fundamental data types is that in order to declare and use
objects (variables) of this type we need to include an additional header file in our
source code: <string> and have access to the std namespace .
// my first string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystring= “This is a string”;
cout << mystring;
Return 0;
}
Results: This is a string

OOP, IT, NUR 3/10/2008 24


String (cont)
• String can be intialiased
string mystring = "This is a string";
string mystring ("This is a string");
Example of assigning values
// my first string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystring;
mystring = "This is the initial string content";
cout << mystring << endl;
mystring = "This is a different string content";
cout << mystring << endl;
return 0;
}
Results: This is the initial string content
This is a different string content

OOP, IT, NUR 3/10/2008 25


Constants and literals
• Constant: a value used in a program that does not change; with fixed value
Ex: 12
114.5
“ Go Eagles!”
• Literals: constant values with are written in a program
Ex: a=5
Literal constants can be divided in Integer Numerals, Floating-Point Numerals,
Characters, Strings and Boolean Values.
 Integer numeral: identify integer decimal , octal, hexadecimalvalues
75 // decimal
0113 // octal ( expressing octal number we have to precede it with a 0, zero character)
0x4b // hexadecimal ( to precede it with 0x (zero, x))
(All represent 75)
 floating point numbers: express numbers with decimals and/oor exponents
3.14159 // 3.14159
6.02e23 // 6.02 x 10^23

OOP, IT, NUR 3/10/2008 26


Constants and literals
 Character and string literals: no-numerical
constants
Ex: ‘z’ //single character constants
‘p’ // single character constant
“Hello world” / string literal
“ How do you do?” // string literal
 Boolean literals: two valid boolean values: true
and false

OOP, IT, NUR 3/10/2008 27


Defined constants
You can define your own names for constants that you
use very often without having to resort to memory-
consuming variables, simply by using the #define
preprocessor directive. Its format is:
#define identifier value
Ex: #define PI 3.14159265
#define NE W L INE’\N’
This defines two new constants: PI and NE W L INE.
Once they are defined, you can use them in the rest
of the code as if they were any other regular
constant, for example:

OOP, IT, NUR 3/10/2008 28


Defined constants
//define constants : calculate circumference
#include <iostream>
Using namespace std;
#define PI 3.14159
int main ()
{
double r=5.0;
//radius
double circle;
circle=2*PI*r;
cout<< circle;
return 0;
}
results: 31.4159

OOP, IT, NUR 3/10/2008 29


Declared constants

With the const prefix you can declare constants


with a specific type in the same way as you
would do with a variable:
const int pathwidt h = 100;
const char tabula tor = '\t';
Here, pathwidth and tabulator are two typed
constants. They are treated just like regular
variables except that their values cannot be
modified after their definition
OOP, IT, NUR 3/10/2008 30
operators
1. Assignment (=) : it assigns a value to a variable
ex: a=5; //this statement assigns the integer value 5 to the variable a. The part at the left of the assignment operator (=) is known as the
lvalue (left value) and the right one as the rvalue (right value). The lvalue has to be a variable whereas the rvalue can be either a
constant, a variable, the result of an operation or any combination of these
For example:
// 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=b // a:4, b:4
b=7 // a:4, b: 7
cout<< “a:”;
cout<<a;
cout<<“b:”;

return 0;
}
Results: a:4 b:7

OOP, IT, NUR 3/10/2008 31


operator
Assignment statement changes the value of a
variable
variable= expression
Examples:
quizScore=10;
pay= hours Worked*payRate;
y=-b+x*slope;

OOP, IT, NUR 3/10/2008 32


Operator(cont.)
2. Arithmetic operators: are mode up of variables, constants operators and parentheses
C++ expressions are similar to algebraic expressions expect they are written on a single line
rather in two dimensions:

in C++ is written as (a+b)/(c-d).


ab
There
cd
are five basic C++ arithmetic operators:

+ Addition

- subtraction

* multiplication

/ Division

% Modulo

OOP, IT, NUR 3/10/2008 33


Operator(cont.)
Modulo operation gives the remainder of a division of two
values,
ex: a=11% 3= 2
int a=10
int b=7
int x;
x=a % b; // result : 3
x= a % 2; // result : 0
x= b % a; // result: 7

OOP, IT, NUR 3/10/2008 34


Operator (cont.)
3. Compound assignment ( +=, -=, *=, /=, %=, >>=, <<=, &=, ^=, I=)

expression Is equivalent to
Value+=increase; Value=value + increase
a - =5; a=a-5;
a / =b a = a/ b;
price *= units + !; price =price* (units +1);
// compound assignment
#include< iostream>
Using namespace std;
Int main ()
{
int a, b=3;
a =b;
a+= 2; // equivalent to a=a+2
Cout<< a;
Return 0;
}
Results: 5

OOP, IT, NUR 3/10/2008 35


homework exercise 1
1. W rite a program that defines the following functioning of operators:
W e have two variables 20 and 30 defined by a and b;
find:
 a+b
 a-b
 a*b
 a/b
 a%b

2. W rite the same program with an additional variable c=40, find;


 d= a+a*b-c;
 e= a*b/c;
 f= (a*(b/c))

OOP, IT, NUR 3/10/2008 36


Operator(cont.)
4. increase and decrease (++, --)
the increase operator (++) and the decrease operator (--)
increase or reduce by one the value stored in a variable. They
are equivalent to +=1 and to -=1, respectively. Thus:
c++;
c+=1;
c=c+1;
are all equivalent in its functionality: the three of
them increase by one the value of c.

OOP, IT, NUR 3/10/2008 37


Operator(cont.)
5. Relational and equality operators ( ==, !=, <, >,
>=, <=)
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

OOP, IT, NUR 3/10/2008 38


operator
6. 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:
Co n dit io n ? r esult1 : result2
If condition is true the expression will return
result1, if it is not it will return result2.

OOP, IT, NUR 3/10/2008 39


Operator (cont.)
Conditional Operator?
// conditional operator
#include <iostream>
Using namespace std;
int main ()
{
int a, b, c;
a=2;
b=7;
c= (a>b) ? a: b;
cout<<c;
return 0;
}
Result: 7

In this example a was 2 and b was 7, so the expression being evaluated (a>b) was not true,
thus the first value specified after the question mark was discarded in favor of the
second value (the one after the colon) which was b, with a value of 7.

OOP, IT, NUR 3/10/2008 40


Operator(cont.)
7. Comma operator (, )
The comma operator (,) is used to separate two or
more expressions that are included where only one
expression is expected. When the set of expressions
has to be evaluated for a value, only the rightmost
expression is considered.
For example, the following code:
• a = (b=3, b+2);
Would first assign the value 3 to b, and then assign b+2
to variable a. So, at the end, variable a would
contain the value 5 while variable b would contain
value 3.

OOP, IT, NUR 3/10/2008 41


Basic input/ output
• Until now, the example programs of previous sections
provided very little interaction with the user, if any at all.
Using the standard input and output library, we will be
able to interact with the user by printing messages on
the screen and getting the user's input from the
keyboard.
• C ++ uses a convenient abstraction called streams to
perform input and output operations in sequential
media such as the screen or the keyboard. A stream is
an object where a program can either insert or extract
characters to/from it.
• The standard C++ library includes the header file
iostream, where the standard input and output stream
objects are declared.

OOP, IT, NUR 3/10/2008 42


B asic input/ output
Standard Output (cout)
Cout<< “ output sentences”; // prints o utput sentences on screen
Cout<<120; //pr ints number 120 on sc ree n
Cout<< x; // prints the content of x on screen

cout is used in conjunction with the in serti on oper ator, which is


written as << (two "less than" signs).
The << operator inserts the data that follows it into the stream
preceding it.
Cout<<“Hello”; //prints Hello
Cout<< Hello; // prints the content of Hello variable

Exercise: Print the out put of the statement


Hello, I am 24 years old and my zipcode is 90064
OOP, IT, NUR 3/10/2008 43
Exercise

Print the out put of the statement


Hello, I am 24 years old and my zipcode is
90064
Answer:
Cout<< “Hello, I am” << age<<“years old and
my zipcode is” << zipcode;

OOP, IT, NUR 3/10/2008 44


Basic input/ output
Standard Input (cin)
The standard input device is usually the keyboard. Handling the standard
input in C++ is done by applying the overloaded operator of extraction
(>>) on the cin stream. The operator must be followed by the variable
that will store the data that is going to be extracted from the stream. For
example:

int age;
Cin>> age;
The first statement declares a variable of type int called age, and the second
one waits for an input from cin (the keyboard) in order to store it in this
integer variable.

OOP, IT, NUR 3/10/2008 45


Basic input/ output
 Input streams: an input stream can be viewed as a
continuous stream of characters that are consumed by the
input mechanisms of the program
To use input and output stream in C++ , you must have the
following include statement near the beginning of your
program:
#include iostream.h>
Iostream.h: defines cin which is an istream and cout which is an ostream.cin
is used to bring data into a program. Cout is used to output data from a
program
The input stream can be thought of as a list of input values that are
separated by white-space characters such space,tab

OOP, IT, NUR 3/10/2008 46


Basic input/ output
<< is the output operator in C++. It sends a value to the screen
>> is the extraction operator in C++. It is referred to as get from; it gets the
item form the input stream
The input examples:
cin>> i>>j; // 4 60 : i=4 , j=60 (I, j are int.)
cin >> ch1; // A: ch1=A (character)
cin.get (ch1); // ch1=A,
Input and output of data in a program is like a two-way conversation with the
program prompting the user for each input:

OOP, IT, NUR 3/10/2008 47


Basic input/ output(cont.)
cout<<“Enter the part number:”;
cin>> partNumber;
cout<<“Enter the quantity:”;
cin>>quantity;
cout<<“Enter the unit price:”;
cin>> unitPrice;
cout<<endl;
totalPrice= unitPrice * quantity
cout<<“The total price for”<< quantity
<<“items of part number”<< partNumber<<endl
<<“at $ << setprecision (2)<< unitPrice
<<“each is $”<< totalPrice<<‘.’<< endl
Results: Enter the part number: 4671
Enter the quantity: 10

OOP, IT, NUR 3/10/2008 48


Basic input/ output(cont.)
Example of cin
//i/o example
#include <iostream>
using namespace std;
int main ()
{
int i;
cout<< “please enter an integer value:”;
cin>> i;
cout<<“ the value you entered is”<< i;
cout<<“ and its double is” << i*2<<“.\n”;
return 0;
}
Results: Please enter an integer value: 702
The value you entered is 702 and its double is 1404.

OOP, IT, NUR 3/10/2008 49


Basic input/ output(cont.)
 You can also use cin to request more than one
datum input from the user:
cin >> a >> b;
Equivalent to
cin >> a;
cin>> b;

OOP, IT, NUR 3/10/2008 50


cin and strings
We can use cin to get strings with the extraction operator (>>) as we do with fundamental data type variables:
cin>> mystring;
// cin with strings
#include <iostream>
#include <string>
using namespace std;

int main ()
{
string mystr;
cout << "What's your name? ";
getline (cin, mystr);
cout << "Hello " << mystr << ".\n";
cout << "What is your favorite team? ";
getline (cin, mystr);
cout << "I like " << mystr << " too!\n";
return 0;
}

Notice how in both calls to getline we used the same string identifier (mystr). What the program does in the second call is
simply to replace the previous content by the new one that is introduced

OOP, IT, NUR 3/10/2008 51


stringstream
• The standard header file <sstream> defines a class called stringstream that
allows a string-based object to be treated as a stream. This way we can perform
extraction or insertion operations from/to strings, which is especially useful to
convert strings to numerical values and vice versa. For example, if we want to
extract an integer from a string we can write:
string mystr (“1204”);
int myint;
stringstream(mystr)>> myint;
• This declares a string object with a value of "1204", and an int
object. Then we use stringstream's constructor to construct an
object of this type from the string object. Because we can use
stringstream objects as if they were streams, we can extract an
integer from it as we would have done on cin by applying the
extractor operator (>>) on it followed by a variable of type int.
• After this piece of code, the variable myint will contain the
numerical value 1204.

OOP, IT, NUR 3/10/2008 52


example
//stringstream
#include <iostream>
#include<string>
#include< stream>
Using namespace;

int main ()
{
string mystr;
float price=0;
int quantity=0;

cout << “Enter price:”;


getline (cin, mystr);
stringstream(mystr)>> quantity;

cout<<“Total price:”; << price* quantity<<endl;

return 0;
}
Results: Enter price: 22.25
Enter quantity: 7
Total price: 155.75

OOP, IT, NUR 3/10/2008 53


Example explanation
• In this example, we acquire numeric values from the
standard input indirectly. Instead of extracting numeric
values directly from the standard input, we get lines from
the standard input (cin) into a string object (mystr), and
then we extract the integer values from this string into a
variable of type int (quantity).
• Using this method, instead of direct extractions of integer
values, we have more control over what happens with the
input of numeric values from the user, since we are
separating the process of obtaining input from the user (we
now simply ask for lines) with the interpretation of that
input. Therefore, this method is usually preferred to get
numerical values from the user in all programs that are
intensive in user input.

OOP, IT, NUR 3/10/2008 54

You might also like