Programming Fundamentals
CSC - 112
Lecture 2
Input and Output Streams
• A data
stream is a sequence of data
- Typically in the form of characters or numbers
• An input stream is data for the program to use
- Typically originates
• at the keyboard
• at a file
• An output stream is the program’s output
- Destination is typically
• the monitor
• a file
‘cout’ stream
• cout is an output stream sending data to the monitor
• The insertion operator "<<" inserts data into cout
• Example:
cout << number_of_bars << " candy bars\n";
- This line sends two items to the monitor
• The value of number_of_bars
• The quoted string of characters " candy bars\n"
- Notice the space before the ‘c’ in candy
- The ‘\n’ causes a new line to be started following the ‘s’ in bars
• A new insertion operator is used for each item of output
Slide 2- 35
Examples
• This produces the same result as the previous sample
cout << number_of_bars ;
cout << " candy bars\n";
• Here arithmetic is performed in the cout statement
cout << "Total cost is $" << (price + tax);
• Quoted strings are enclosed in double quotes ("Walter")
- Don’t use two single quotes (')
• A blank space can also be inserted with
cout << " " ;
Include Directives
• Include Directives add library files to our programs
- To make the definitions of the cin and cout available to
the program:
#include <iostream>
• Using Directives include a collection of defined names
- To make the names cin and cout available to our program:
using namespace std;
Receiving Information from the user
• We can receive input from the user by using the cin (Standard input
stream
Example
int ftemp;
cin>>ftemp;
• causes the program to wait for the user to type in a number.
• The resulting number is placed in the variable ftemp.
• The keyword cin (pronounced “C in”) is an object, predefined in C++ to
correspond to the standard input stream.
• This stream represents data coming from the keyboard
• The >> is the extraction or get from operator.
• It takes the value from the stream object on its left and places it in the
variable on its right.
Reading Data From cin
• Multiple data items are separated by spaces
• Data is not read until the enter key is pressed
- Allows user to make corrections
• Example:
cin >> v1 >> v2 >> v3;
- Requires three space separated values
- User might type
34 45 12 <enter key>
IO flow in a typical program
• Prompt the user for input that is desired
- cout statements provide instructions
cout << "Enter your age: ";
cin >> age;
• Notice the absence of a new line before using cin
• Echo the input by displaying what was read
- Gives the user a chance to verify data
cout << age << " was entered." << endl;
Simplistic View of a Computer
Very Simplistic View of a Computer
Location 0
Location 1
Location 2 Each location is
Location 3 1 byte of memory
CPU Location 4
1 byte = 8 bits
Location 5
Each bit is an electric
impulse carrying 1 or 0.
This simplistic view is enough to explain the basic concepts
of programming to students
5
Value
• The only task a computer can do is arithmetic e.g.
multiplying, dividing, subtracting, etc.
• Therefore, everything in the computer is represented as a
value
- Numbers, letters, characters, etc are all represented as values
• Values could change depending on their nature. For
example
- the temperature today is different from the temperature yesterday
- The number of cars inside Lahore is different then the number of in
cars Islamabad.
Variable
• To store a value inside a computer a
‘variable’ is used.
• A variable is a space in the memory to store
a value.
• This space is reserved until the variable is
required.
Session 2 7
What Makes a Variable
• Variable has three important characteristics:
- Type
• How much memory do a variable need.
- This information is determined by a type.
- Name
• How to differentiate a variable with another variable of the
same type.
- Name refers to the memory location assigned to this variable.
- Value
• What is the value?
- The actual value contained by a variable.
Session 2 8
An Example of a Variable
Type of the variable is integer (written as “int” in C++)
int temperature = 35
A name of the variable
An initial value of the variable
Session 2 9
Example of a Variable
(Memory View)
int temperature = 35
00000000 Location 0
Locations 0 - 3 are collectively 00000000 Location 1
called as ‘temperature’ 00000000 Location 2
00100011 Location 3
Location 4
100011 is the binary equivalent of 35 Location 5
Session 2 10
Changing the Value of Variable
• Lets change the value of ‘temperature’.
temperature = 45902
00000000 Location 0
Locations 0 - 3 are collectively 00000000 Location 1
called as ‘temperature’ 10110011 Location 2
01001110 Location 3
Location 4
Location 5
1011001101001110 is the binary equivalent of 45902
Session 2 11
Variable Capacity
• Among other advantages a ‘type’ determines the
maximum space that can be used by a variable
• The type int is of 4 bytes in C++.
• Therefore, it can hold maximum of
2,147,483,647 value.
• It can also hold values in negative down to
-2,147,483,648.
Session 2 12
Initializing Variables
• Declaring a variable does not give it a value
- Giving a variable its first value is initializing the variable
• Variables are initialized in assignment statements
double mpg; // declare the variable
mpg = 26.3; // initialize the variable
• Declaration and initialization can be combined
using two methods
- Method 1
double mpg = 26.3, area = 0.0 , volume;
- Method 2
double mpg(26.3), area(0.0), volume;
Variable for Real Numbers
• int cannot hold a real value.
• Therefore, a type “double” is used to hold real
values.
• Double takes 8 bytes of memory instead of 4 bytes
of a double.
• Out of the 8 bytes in a double 4 bytes are used to
hold the value before the decimal point and 4
bytes for the value after the decimal point.
Session 2 14
Relative Comparison of int and double
int numPeople = 2;
Reserves 32 bits (4 bytes)
and sets the value stored
in that space to 2. The name
‘numPeople’ is associated with
this space.
double bill = 32.45;
Reserves 64 bits (8 bytes)
and sets the value stored
in that space to 32.45. The name
‘bill’ is associated with
this space.
Session 2 15
Session 2 16
Assignment in C++
• Assignment Statement
- In Mathematics the value x = x + 1 is not
possible why?
- In C++ x = x +1 is possible because “=” is an
assignment operator and not an equality
operator.
- Assignment operator means that the contents of
the right hand side is transferred to the memory
location of the left hand side.
Sessio 2 17
Assignment Statement
x = 5671
5671 is written at the memory location reserved for x
Session 2 18
Constants
• Constants are values which cannot be
modified e.g. the value of Pi
• To declare a constant in C++, we write a
keyword “const” before the variable type.
const double pi = 3.14;
Session 2 19
Reserved Words
• Some names cannot be declared as variable names
because they are reserved words in C++
20
Variables
• You can store your program (algorithm) data into variables (also
called memory locations). In “C++” language there are various
types of variable available.
Variable types
Variable type Keyword used in Size in bits Range
declaration
integer int 32 bits -2147483648 to
2147483647
Short integer short int 16 bits -32768 to 32767
Long integer long int 32 bits -2147483648 to
2147483647
Floating point float 32 bits -1.0x1038 to 1.0x1038
data
Floating point double 64 bits -1.0x10308 to
data (with large 1.0x10308
fraction)
Text type data char 8 bits -128 to 127
Boolean data bool 1 bit 1 or 0
(True or False)
Variable Types
• To use a variable in our code
– First, we must have to declare it, variable are known with its
keywords. “Use the name of keyword” for declaration of a
variable”.
– Example: int number1 = 10;
– Example: float floatData = 20.93;
– Example: long int myData = -10;
– Example: char textData = ‘A’;
– Example: bool boolData = true;
#include <iostream> #include <iostream>
using namespace std; using namespace std;
void main () void main ()
{ {
int number1 = 10; int number1 = 20, number2 = 10;
float floatData = 20.93; }
}
Points to remember in naming the
variables
• The names given to variables (and other
program features) are called identifiers.
• What are the rules for writing identifiers?
• You can use upper- and lowercase letters, and
the digits from 1 to 9.
• You can also use the underscore (_).
• The first character must be a letter or
underscore. (it cannot be a digit)
• No spaces allowed in a variable name
Primitive Data Types
• So far the variable types that we have
studied are primitive data types.
• Primitive data types only have a memory
space for storing values.
27
Type char
• Computers process character data too
• char
- Short for character
- Can be any single character from the keyboard
• To declare a variable of type char:
•
char letter;
char constants
• Character constants are enclosed in single quotes
char letter = 'a';
• Strings of characters, even if only one character
is enclosed in double quotes
- "a" is a string of characters containing one character
- 'a' is a value of type character
Reading Character Data
• cin skips blanks and line breaks looking for data
• The following reads two characters but skips
any space that might be between
char symbol1, symbol2;
cin >> symbol1 >> symbol2;
• User normally separate data items by spaces
J D
• Results are the same if the data is not separated
by spaces
JD
Type bool
• bool is a new addition to C++
- Short for boolean
- Boolean values are either true or false
• To declare a variable of type bool:
bool old_enough;
Manipulator
• Manipulators are instructions to the output
stream that modify the output in various ways
-endl is a manipulator that causes a linefeed to
be inserted into the stream
-cout<<“Sample text”<<endl;
Casting
•Converting a value of one type into another
type
•Manual Casting
• static_cast<double> (intVar)
• e.g int n = static_cast<int>(3.14);
•Automatic Casting
• Automatic conversion of lower order type to higher
order type when two operands of different types are
encountered in the same expression
Practice Question
Calculate a weighted average sum of two numbers x1 and x2 such that x1 has
70% weight.
Write an algorithm, pseudo-code and program for the above problem
Languages Allowed: C, C++