SlideShare a Scribd company logo
Computer Programming
Functions, variables and
basic input and output
Prof. Dr. Mohammad Haseeb Zafar
haseeb@uetpeshawar.edu.pk
Today’s lecture
• Introduction to functions
• Naming and typing of functions and variables
• Declaration and assignment of values to variables
• Declaration of functions
• Basic input and output
Functions
• Functions do stuff
– Some come packaged with C and C++ in libraries.
• Need to instruct the Compiler to include the libraries (see last
week’s lecture)
• Means you only use the libraries you need
• Smaller executable program.
– Others you write yourself.
• Need to define and declare in your program
• Functions are called and return values
main
• At the heart of a C/C++ program is a function called main.
– The first instruction executed in the program is the first
instruction in main
– Unless there has been an exit instruction, the last
instruction executed in the program is the last instruction
in main.
• The last instruction is generally a command to return an integer
value to the operating system
• main can take arguments
int main(int argc, char* argv[ ])
Gives access to the text
of the command line arguments
Number of
command line
arguments
What’s this? Aarggh! It’s a pointer!
Maths functions
• To use functions such as…
sin()
asin()
log()
exp()
pow()
sqrt()
• …must include the Math library
– Before main, use the preprocessor command
#include <math.h>
This is a C library
Declaring a function
int FindProduct (int a, int b)
{
}
return a * b;
Leave the function by returning a value
Type of the value
returned by the function
Name of the
function
Arguments taken
by the function
and their types
What the function
does
• The arguments are like the inputs
• you can have as many as you like
• you must define the type and give a name for each
• The return is like the output (only one)
Suggest a function
to return the sum
of two floats
Organising programs
• Enormously long functions are
– hard to follow
– hard to debug and maintain
• Some actions get repeated or used at different times
• Big programs should be made up of small functions
– Functions can call other functions
– Functions representing common actions can be called
from different points in the program
– Different people can develop different functions within one
program using a common, defined interface
– Functions with meaningful names make code easier to
read and maintain
• Functions don’t have to return values or have arguments
void functions
For example…
void DoSomething (void)
{
cout << “Hello” << endl;
}
• Useful just for organising different actions
Nothing to return
No arguments
Can we return more than one value?
• Sort of…
• We can pass addresses (memory locations) to a function
– Function places values at those locations
– Upon return from the function, those locations can be
looked at to retrieve the values
– This is known passing by reference (rather than passing
by value)
• To do this, we make use of pointers or references
– Some people get scared by pointers
– Don’t panic! We’ll come back to them later…
Declaring variables
• Each variable must have a type
• If an initial value is not assigned in the code, there is no
telling what its value will be when it is first used!
– Some compilers will warn you that a variable is being
used it has been assigned a value… but don’t rely on it!
int i = 0;
Assigning values to variables
• It makes sense to assign initial values as 0… (safe)
• …for full flexibility of the program, assign values of inputs to
the program from keyboard inputs or text files…
• …and, generally, avoid using ‘magic numbers’
– Special values written into source code are hard to
maintain (what if you want to change the value?)
double circum = 0.0, radius r = 0.0;
cin >> radius;
circum = 2 * 3.14159 * radius;
– If you want to use a constant, define it
#define PI 3.14159
double circum = 0.0, radius = 0.0;
cin >> radius;
circum = 2 * PI * radius;
We’ll come back to this later
Input values set at
‘run time’ rather
than ‘compile time’
Storage of values: int
• An int is stored like this
– Bit number: 7 6 5 4 3 2 1 0
– Value: 1 1 0 0 0 0 1 1
– Why muck about with inverting values (‘twos
compliment’)?
• To help with addition
– +61: 0 0 1 1 1 1 0 1
– -61: 1 1 0 0 0 0 1 1
– Sum: 0 0 0 0 0 0 0 0
The sign bit.
Here it means -ve
When sign bit set, to get value
invert the other bits.
Here: 0111100 = 6010
Finally, add 1: result -61
Here, just for example,
using 8 bit word
Largest int
• For an 8 bit word, what are the largest positive and negative
values?
– 0 1 1 1 1 1 1 1 +127
– 1 0 0 0 0 0 0 0 -128
Increasing the ‘value’ of the 8 bit binary number
from +127 gives -128
Storage of values: float
where, for a 64 bit number,
S is the sign bit stored in the most significant bit
E is held as a binary number in the next 11 bits
F is held as a binary number in the remaining 52 bits
that is,
the number is stored in three parts:
– sign
– exponent
– fraction
Fxn ES
.12)1( 1024−
×−=
Largest float or double
• For 32 bit word, for variable of type float
– Max ±3.4x1038
– Min ±1.5x10-45
– Precision 7-8 digits
• For 32 bit word, for variable of type double (64 bits)
– Max ±1.7x10308
– Min ±5.0x10-324
– Precision 15-16 digits
Names of functions or variables
• Give each variable or function a meaningful name
– Frequently, people use variable names like
float a, b, c;
• We would need to look very carefully at our code to find out what
will be stored in the variables and why
• Then we have to remember what we found
– Some people give names like this:
int iCount;
float fInitialTemp, fFinalTemp;
char cLabel;
– Good to use nouns for variables and verbs for functions
• In C and C++, names are case sensitive – avoid confusion!
• You cannot use spaces in names
• Names cannot start with numbers
The f reminds us that
the variable is of type
float
Inside functions: operator precedence
• We can have more than one operator in a single instruction
weightave=(a*3+b*4+c*3)/10;
• How does the compiler evaluate these expressions?
– Left association
– Precedence rules
• Contents of parentheses () are evaluated first…
• …then multiplication * and division / …
• …then addition + and subtraction –
• To avoid getting lost
– put things inside parentheses
– use interim variables
• interim variables have advantage of letting you see values in
debugger (which steps through lines of source code)
• Declare first as an int = 1
• What is the value of result?
result = first / second;
• Get around possible problems by using casting
– Change the type of the variable as used
result = (float)first / second;
Combining different types in an
operation
• Declare result as a float
• Declare first as a float = 1.0
• Declare second as an int = 5
• What is the value of result?
result = first / second;
Contents of first converted to float
float operation performed
1 / 5
result = 0
int operation performed
1.0 / 5
result = 0.2
float operation performed
Scope of variables
• Arguments to a function and variables declared inside a function are local
to that function
float calcXcord(float grad1,float Ycept1,float grad2, float Ycept2)
{
float Xcord;
Xcord=(Ycept2-Ycept1)/(grad1-grad2);
return Xcord;
}
int main(int argc, char* argv[])
{
float gradLine1, gradLine2;
float Y0Line1, Y0Line2;
float Xcoord, Ycoord;
cout<<"input gradient and Y axis value for first line"<<endl;
cin>>gradLine1>>Y0Line1;
cout<<"input gradient and Y axis value for second line"<<endl;
cin>>gradLine2>>Y0Line2;
Xcoord=calcXcord(gradLine1,Y0Line1,gradLine2,Y0Line2);
}
Only known inside
function calcXcord
Only known inside
function main
Local versus global variables
• Variables declared inside a function are local to that function
• Values are passed to and from functions
• Global variables that are known to all functions can be
declared (immediately after header section)
– best avoided as in large programs there is a risk of
modifying them when you didn’t mean to!
– If you must use global variables, a useful convention:
• name local variables with lower case
e.g. count
• name global variables starting with upper case
e.g. MasterCount
• ‘Local’ and ‘global’ scope will be visited again in object
orientation in terms of ‘public’ and ‘private’
What happens when a function is
called?
float calcXcord(float grad1,float Ycept1,float grad2, float Ycept2)
{
float xcord;
xcord=(Ycept2-Ycept1)/(grad1-grad2);
return xcord;
}
int main(int argc, char* argv[])
{
float gradLine1, gradLine2;
float Y0Line1, Y0Line2;
float Xcoord, Ycoord;
cout<<"input gradient and Y axis value for first line"<<endl;
cin>>gradLine1>>Y0Line1;
cout<<"input gradient and Y axis value for second line"<<endl;
cin>>gradLine2>>Y0Line2;
Xcoord=calcXcord(gradLine1,Y0Line1,gradLine2,Y0Line2);
}
Suppose users enters the following:
1.5, 2.0, -0.5, 3.0. Now,
gradline1 = 1.5
Y0Line1 = 2.0
gradline2 = -0.5
Y0Line2 = 3.0
Values 1.5, 2.0, -0.5, 3.0 sent to calcXcord
Values 1.5, 2.0, -0.5, 3.0 received by calcXcord
grad1 = 1.5
Ycept1 = 2.0
grad2 = -0.5
Ycept2 = 3.0
Calculation carried out and 0.5 returned
Xcoord equals the value
returned by calcXcord, i.e. 0.5
Automatic memory allocation
• Variable created at a location in memory automatically when
a function is called
– Memory location freed up when function is exited…
– …except when the variable is declared to be a static
variable
• memory not de-allocated on exit from function
• Next time the function is called, the previous value can be found
int myfunction (int a)
{
int n;
n = a * 10;
return n;
}
Each time myfunction is
called, a and n are created
After the return, a and n are
destroyed
Example of a static variable
int myfunction (int a)
{
static int n=0;
n = n+1;
return n * a;
}
int main( )
{
int i = 2, j;
j = myfunction(i);
cout << "First time: j=" << j << endl;
j = myfunction(i);
cout << "Second time: j=" << j << endl;
}
Here j=2
Here j=4
First time in, n is initially 0
before being incremented;
second time, n is initially what
it was on exit first time, then it
is incremented
Location of function declarations
• Notice that in last fragment of code, calcXcord was
declared before main
float calcXcord(float grad1,float Ycept1,float grad2, float Ycept2)
{
float Xcord;
Xcord=(Ycept2-Ycept1)/(grad1-grad2);
return Xcord;
}
int main(int argc, char* argv[])
{
float gradLine1, gradLine2;
float Y0Line1, Y0Line2;
float Xcoord, Ycoord;
cout<<"input gradient and Y axis value for first line"<<endl;
cin>>gradLine1>>Y0Line1;
cout<<"input gradient and Y axis value for second line"<<endl;
cin>>gradLine2>>Y0Line2;
Xcoord=calcXcord(gradLine1,Y0Line1,gradLine2,Y0Line2);
}
• Compiler must see declaration (of function or variable)
before first use)
calcXcord declared earlier
in source code than first call
• Code looks back-to-front!
•main used first but
declared last
Use of function ‘prototypes’
• In order that the compiler doesn’t complain about the order in
which functions are declared:
– you can put prototypes in the header section of the source
code
• In effect, this is what #include does
– header files (*.h) have function prototypes in them
– #include causes the cited header to be copied by the
compiler pre-processor into the object code
• Allows the compiler to ‘know about’ functions defined in other
source modules
• Most professional code written ‘back-to-front’ (main at end)
# indicates a pre-processor
instruction
Function prototypes: example
#include <iostream>
float calcXcord(float, float, float, float);
float calcYcord(float, float, float);
int main()
{
float gradLine1, gradLine2, Y0Line1, Y0Line2, Xcoord, Ycoord;
char stopchar;
cout<<"Input gradient and Y axis value for first line"<<endl;
cin>>gradLine1>>Y0Line1;
cout<<"Input gradient and Y axis value for second line"<<endl;
cin>>gradLine2>>Y0Line2;
Xcoord=calcXcord(gradLine1,Y0Line1,gradLine2,Y0Line2);
Ycoord=calcYcord(Xcoord,gradLine1,Y0Line1);
cout<< "The coordinates of the point of intersection are: "
<< Xcoord<< ", " << Ycoord << endl << "press a key to end" ;
cin >> stopchar;
return 0;
}
float calcXcord(float grad1,float Ycept1,float grad2, float Ycept2)
{
float Xcord;
Xcord=(Ycept2-Ycept1)/(grad1-grad2);
return Xcord;
}
float calcYcord(float X, float grad, float Ycept)
{
float Ycord;
Ycord=grad*X+Ycept;
return Ycord;
Just quote the argument
types in the prototype
• if these are different between
any two of the prototype,
declaration and use, the
compiler will complain of
‘bad arguments’
Input and output
• C and C++ can read from and send messages to file streams
– These can be files on a hard disk
– In C, stdin and stdout are specific streams related to
the keyboard and screen
– C++ uses cin and cout objects to read from the
keyboard and write to the console (screen)
– To access cin and cout, we need to access the iostream
library
• Put #include <iostream> in the head section of the source
code module.
• The iostream library is not available to C compilers
– More on reading from and writing to files later…
Using the cout stream (i)
• Once we have included the iostream library we can use the <<
operator to direct output to the console.
– << is known as an ‘inserter’ – it inserts whatever follows into cout
cout << initTemp;
Sends the contents of the variable
initTemp to the console window
• We can output more than one variable in a single command to use
the cout stream
cout << initTemp << endl << finalTemp << endl;
prints variable initTemp
prints variable
finalTemp
prints a new line
Using the cout stream (ii)
• We can also use the cout stream to print text to the console.
– At present we will do this using a string literal.
– A string literal is a series of alphanumeric characters contained
within “ ”.
cout << “The initial temperature is “ << initTemp << endl;
prints string literal
prints variable
initTemp prints a new line
A simple module showing use of cout
#include <iostream>
using namespace std;
int main()
{
int initTemp;
int finalTemp;
int tempChange;
initTemp = 12;
finalTemp = 15;
tempChange = finalTemp - initTemp;
cout << "The initial temperature is " << initTemp << endl;
cout << "Final temperature is " << finalTemp << endl;
cout << “Temperature change is " << tempChange << endl;
return 0;
}
Keeping the console window open (i)
• In the preceding code program:
– there are outputs of data using cout.
– the next line is at the end of our program:
return 0;
(Literally, this return a value of 0 from the function main. A return
from main marks the end of the program)
– At the end of the program, the console window will close
and our output will disappear.
– With some compilers, you need to add some code to keep
the console window open.
• One way to do this is to use the cin stream to do this
– The program waits for carriage return to be entered
• Or, use function system(“PAUSE”)
Keeping the console window open (ii)
.
.
.
tempChange=finalTemp - initTemp;
cout << "The initial temperature is " << initTemp << endl;
cout << "Final temperature is " << finalTemp << endl;
cout << “Temperature change is " << tempChange << endl;
char stopchar;
cin >> stopchar;
return 0;
}
Declares a variable
stopchar of type char
Will hold a single
character
Program execution
pauses until user presses
enter
This isn’t necessary when
running a program in debug mode
in Visual C++ Express
Keeping the console window open (iii)
.
.
.
tempChange=finalTemp - initTemp;
cout << "The initial temperature is " << initTemp << endl;
cout << "Final temperature is " << finalTemp << endl;
cout << “Temperature change is " << tempChange << endl;
system(“PAUSE”);
return 0;
}
Message written to console saying
Press any key to continue . . .
Console closes after user presses a key
This isn’t necessary when
running a program in debug mode
in Visual C++ Express
Getting input from the keyboard
• We use the cin object to access input from the keyboard
• Use the >> operator to direct the input to our variables
• >> is an ‘extractor’ – extracts a value from cin and assigns
it to a variable, e.g.
cout << “Please input the initial temperature “;
cin >> initTemp;
cout << “Please input the final temperature “;
cin >> finalTemp;
Getting input from keyboard - example
#include <iostream>
using namespace std;
int main()
{
int initTemp, finalTemp, tempChange;
cout << “Please input the initial temperature “;
cin >> initTemp;
cout << “Please input the final temperature “;
cin >> finalTemp;
tempChange=finalTemp - initTemp;
cout << "The initial temperature is " << initTemp << endl;
cout << "Final temperature is " << finalTemp << endl;
cout << “Temperature change is " << tempChange << endl;
char stopchar;
cin >> stopchar;
return 0;
}
Can put declarations of
same type on same line
Review of structure…
#include <iostream>
using namespace std;
int main( )
{
int initTemp;
int finalTemp;
int tempChange;
initTemp = 12;
finalTemp = 15;
tempChange = finalTemp – initTemp;
return 0;
}
The return 0 marks the end of
main
Header section
• # symbol tells the compiler that it is
a preprocessor command.
• include is the instruction to
the preprocessor.
• The < > symbols tell the
preprocessor to look in the
default directory for .h files.
• namespace enables compiler to
know which version of library
functions

More Related Content

PPT
Input and output in C++
PPTX
Library functions in c++
PPT
Operator overloading
PPT
Strings
PPT
Overloading
PPTX
expression in cpp
PPTX
Managing console input and output
PPTX
C++ theory
Input and output in C++
Library functions in c++
Operator overloading
Strings
Overloading
expression in cpp
Managing console input and output
C++ theory

What's hot (11)

PPTX
operator overloading
PPT
Lecture5
PPT
3d7b7 session4 c++
PPTX
Operator Overloading & Type Conversions
PPTX
Learning C++ - Introduction to c++ programming 1
PPTX
Data Type Conversion in C++
PPT
Operator Overloading
PDF
PDF
Operator overloading
PDF
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
PPTX
Basic c++ programs
operator overloading
Lecture5
3d7b7 session4 c++
Operator Overloading & Type Conversions
Learning C++ - Introduction to c++ programming 1
Data Type Conversion in C++
Operator Overloading
Operator overloading
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
Basic c++ programs
Ad

Viewers also liked (8)

PPTX
Constants and variables in c programming
PPT
Chapter1 c programming data types, variables and constants
PPT
constants, variables and datatypes in C
PPTX
Friend functions
PPTX
Friend function & friend class
PPTX
Data types
PPTX
Data Types and Variables In C Programming
PPT
Friends function and_classes
Constants and variables in c programming
Chapter1 c programming data types, variables and constants
constants, variables and datatypes in C
Friend functions
Friend function & friend class
Data types
Data Types and Variables In C Programming
Friends function and_classes
Ad

Similar to 02 functions, variables, basic input and output of c++ (20)

PPTX
C language
PPTX
PPTX
Funtions of c programming. the functions of c helps to clarify all the tops
PPT
Object Oriented Technologies
PDF
Basic Elements of C++
PPTX
Introduction of function in c programming.pptx
PPSX
Esoft Metro Campus - Programming with C++
PDF
(3) cpp procedural programming
PPT
c-programming
PPTX
Review of C programming language.pptx...
PPTX
Intro in understanding to C programming .pptx
PPTX
Intro in understanding to C programming .pptx
PDF
03-Variables, Expressions and Statements (1).pdf
PPT
85ec7 session2 c++
PPTX
Cs1123 4 variables_constants
PPT
270_2_C Functions_Pepper_in C_programming.ppt
PPTX
Introduction Of C++
PPTX
Object oriented programming system with C++
PPTX
Function
C language
Funtions of c programming. the functions of c helps to clarify all the tops
Object Oriented Technologies
Basic Elements of C++
Introduction of function in c programming.pptx
Esoft Metro Campus - Programming with C++
(3) cpp procedural programming
c-programming
Review of C programming language.pptx...
Intro in understanding to C programming .pptx
Intro in understanding to C programming .pptx
03-Variables, Expressions and Statements (1).pdf
85ec7 session2 c++
Cs1123 4 variables_constants
270_2_C Functions_Pepper_in C_programming.ppt
Introduction Of C++
Object oriented programming system with C++
Function

More from Manzoor ALam (6)

PDF
8085 microprocessor ramesh gaonkar
PPT
01 introduction to cpp
PPT
03b loops
PPT
03a control structures
PPT
02a fundamental c++ types, arithmetic
PPT
03 conditions loops
8085 microprocessor ramesh gaonkar
01 introduction to cpp
03b loops
03a control structures
02a fundamental c++ types, arithmetic
03 conditions loops

Recently uploaded (20)

PDF
AlphaEarth Foundations and the Satellite Embedding dataset
PPTX
Cell Membrane: Structure, Composition & Functions
PPTX
Protein & Amino Acid Structures Levels of protein structure (primary, seconda...
PDF
HPLC-PPT.docx high performance liquid chromatography
PPTX
microscope-Lecturecjchchchchcuvuvhc.pptx
PDF
CAPERS-LRD-z9:AGas-enshroudedLittleRedDotHostingaBroad-lineActive GalacticNuc...
PDF
diccionario toefl examen de ingles para principiante
PPT
Chemical bonding and molecular structure
PPTX
Derivatives of integument scales, beaks, horns,.pptx
PDF
Biophysics 2.pdffffffffffffffffffffffffff
PPTX
SCIENCE10 Q1 5 WK8 Evidence Supporting Plate Movement.pptx
PPTX
famous lake in india and its disturibution and importance
PDF
. Radiology Case Scenariosssssssssssssss
PPTX
ognitive-behavioral therapy, mindfulness-based approaches, coping skills trai...
PDF
Mastering Bioreactors and Media Sterilization: A Complete Guide to Sterile Fe...
PDF
Phytochemical Investigation of Miliusa longipes.pdf
PPTX
cpcsea ppt.pptxssssssssssssssjjdjdndndddd
PPTX
Comparative Structure of Integument in Vertebrates.pptx
PPTX
The KM-GBF monitoring framework – status & key messages.pptx
PDF
IFIT3 RNA-binding activity primores influenza A viruz infection and translati...
AlphaEarth Foundations and the Satellite Embedding dataset
Cell Membrane: Structure, Composition & Functions
Protein & Amino Acid Structures Levels of protein structure (primary, seconda...
HPLC-PPT.docx high performance liquid chromatography
microscope-Lecturecjchchchchcuvuvhc.pptx
CAPERS-LRD-z9:AGas-enshroudedLittleRedDotHostingaBroad-lineActive GalacticNuc...
diccionario toefl examen de ingles para principiante
Chemical bonding and molecular structure
Derivatives of integument scales, beaks, horns,.pptx
Biophysics 2.pdffffffffffffffffffffffffff
SCIENCE10 Q1 5 WK8 Evidence Supporting Plate Movement.pptx
famous lake in india and its disturibution and importance
. Radiology Case Scenariosssssssssssssss
ognitive-behavioral therapy, mindfulness-based approaches, coping skills trai...
Mastering Bioreactors and Media Sterilization: A Complete Guide to Sterile Fe...
Phytochemical Investigation of Miliusa longipes.pdf
cpcsea ppt.pptxssssssssssssssjjdjdndndddd
Comparative Structure of Integument in Vertebrates.pptx
The KM-GBF monitoring framework – status & key messages.pptx
IFIT3 RNA-binding activity primores influenza A viruz infection and translati...

02 functions, variables, basic input and output of c++

  • 1. Computer Programming Functions, variables and basic input and output Prof. Dr. Mohammad Haseeb Zafar haseeb@uetpeshawar.edu.pk
  • 2. Today’s lecture • Introduction to functions • Naming and typing of functions and variables • Declaration and assignment of values to variables • Declaration of functions • Basic input and output
  • 3. Functions • Functions do stuff – Some come packaged with C and C++ in libraries. • Need to instruct the Compiler to include the libraries (see last week’s lecture) • Means you only use the libraries you need • Smaller executable program. – Others you write yourself. • Need to define and declare in your program • Functions are called and return values
  • 4. main • At the heart of a C/C++ program is a function called main. – The first instruction executed in the program is the first instruction in main – Unless there has been an exit instruction, the last instruction executed in the program is the last instruction in main. • The last instruction is generally a command to return an integer value to the operating system • main can take arguments int main(int argc, char* argv[ ]) Gives access to the text of the command line arguments Number of command line arguments What’s this? Aarggh! It’s a pointer!
  • 5. Maths functions • To use functions such as… sin() asin() log() exp() pow() sqrt() • …must include the Math library – Before main, use the preprocessor command #include <math.h> This is a C library
  • 6. Declaring a function int FindProduct (int a, int b) { } return a * b; Leave the function by returning a value Type of the value returned by the function Name of the function Arguments taken by the function and their types What the function does • The arguments are like the inputs • you can have as many as you like • you must define the type and give a name for each • The return is like the output (only one) Suggest a function to return the sum of two floats
  • 7. Organising programs • Enormously long functions are – hard to follow – hard to debug and maintain • Some actions get repeated or used at different times • Big programs should be made up of small functions – Functions can call other functions – Functions representing common actions can be called from different points in the program – Different people can develop different functions within one program using a common, defined interface – Functions with meaningful names make code easier to read and maintain • Functions don’t have to return values or have arguments
  • 8. void functions For example… void DoSomething (void) { cout << “Hello” << endl; } • Useful just for organising different actions Nothing to return No arguments
  • 9. Can we return more than one value? • Sort of… • We can pass addresses (memory locations) to a function – Function places values at those locations – Upon return from the function, those locations can be looked at to retrieve the values – This is known passing by reference (rather than passing by value) • To do this, we make use of pointers or references – Some people get scared by pointers – Don’t panic! We’ll come back to them later…
  • 10. Declaring variables • Each variable must have a type • If an initial value is not assigned in the code, there is no telling what its value will be when it is first used! – Some compilers will warn you that a variable is being used it has been assigned a value… but don’t rely on it! int i = 0;
  • 11. Assigning values to variables • It makes sense to assign initial values as 0… (safe) • …for full flexibility of the program, assign values of inputs to the program from keyboard inputs or text files… • …and, generally, avoid using ‘magic numbers’ – Special values written into source code are hard to maintain (what if you want to change the value?) double circum = 0.0, radius r = 0.0; cin >> radius; circum = 2 * 3.14159 * radius; – If you want to use a constant, define it #define PI 3.14159 double circum = 0.0, radius = 0.0; cin >> radius; circum = 2 * PI * radius; We’ll come back to this later Input values set at ‘run time’ rather than ‘compile time’
  • 12. Storage of values: int • An int is stored like this – Bit number: 7 6 5 4 3 2 1 0 – Value: 1 1 0 0 0 0 1 1 – Why muck about with inverting values (‘twos compliment’)? • To help with addition – +61: 0 0 1 1 1 1 0 1 – -61: 1 1 0 0 0 0 1 1 – Sum: 0 0 0 0 0 0 0 0 The sign bit. Here it means -ve When sign bit set, to get value invert the other bits. Here: 0111100 = 6010 Finally, add 1: result -61 Here, just for example, using 8 bit word
  • 13. Largest int • For an 8 bit word, what are the largest positive and negative values? – 0 1 1 1 1 1 1 1 +127 – 1 0 0 0 0 0 0 0 -128 Increasing the ‘value’ of the 8 bit binary number from +127 gives -128
  • 14. Storage of values: float where, for a 64 bit number, S is the sign bit stored in the most significant bit E is held as a binary number in the next 11 bits F is held as a binary number in the remaining 52 bits that is, the number is stored in three parts: – sign – exponent – fraction Fxn ES .12)1( 1024− ×−=
  • 15. Largest float or double • For 32 bit word, for variable of type float – Max ±3.4x1038 – Min ±1.5x10-45 – Precision 7-8 digits • For 32 bit word, for variable of type double (64 bits) – Max ±1.7x10308 – Min ±5.0x10-324 – Precision 15-16 digits
  • 16. Names of functions or variables • Give each variable or function a meaningful name – Frequently, people use variable names like float a, b, c; • We would need to look very carefully at our code to find out what will be stored in the variables and why • Then we have to remember what we found – Some people give names like this: int iCount; float fInitialTemp, fFinalTemp; char cLabel; – Good to use nouns for variables and verbs for functions • In C and C++, names are case sensitive – avoid confusion! • You cannot use spaces in names • Names cannot start with numbers The f reminds us that the variable is of type float
  • 17. Inside functions: operator precedence • We can have more than one operator in a single instruction weightave=(a*3+b*4+c*3)/10; • How does the compiler evaluate these expressions? – Left association – Precedence rules • Contents of parentheses () are evaluated first… • …then multiplication * and division / … • …then addition + and subtraction – • To avoid getting lost – put things inside parentheses – use interim variables • interim variables have advantage of letting you see values in debugger (which steps through lines of source code)
  • 18. • Declare first as an int = 1 • What is the value of result? result = first / second; • Get around possible problems by using casting – Change the type of the variable as used result = (float)first / second; Combining different types in an operation • Declare result as a float • Declare first as a float = 1.0 • Declare second as an int = 5 • What is the value of result? result = first / second; Contents of first converted to float float operation performed 1 / 5 result = 0 int operation performed 1.0 / 5 result = 0.2 float operation performed
  • 19. Scope of variables • Arguments to a function and variables declared inside a function are local to that function float calcXcord(float grad1,float Ycept1,float grad2, float Ycept2) { float Xcord; Xcord=(Ycept2-Ycept1)/(grad1-grad2); return Xcord; } int main(int argc, char* argv[]) { float gradLine1, gradLine2; float Y0Line1, Y0Line2; float Xcoord, Ycoord; cout<<"input gradient and Y axis value for first line"<<endl; cin>>gradLine1>>Y0Line1; cout<<"input gradient and Y axis value for second line"<<endl; cin>>gradLine2>>Y0Line2; Xcoord=calcXcord(gradLine1,Y0Line1,gradLine2,Y0Line2); } Only known inside function calcXcord Only known inside function main
  • 20. Local versus global variables • Variables declared inside a function are local to that function • Values are passed to and from functions • Global variables that are known to all functions can be declared (immediately after header section) – best avoided as in large programs there is a risk of modifying them when you didn’t mean to! – If you must use global variables, a useful convention: • name local variables with lower case e.g. count • name global variables starting with upper case e.g. MasterCount • ‘Local’ and ‘global’ scope will be visited again in object orientation in terms of ‘public’ and ‘private’
  • 21. What happens when a function is called? float calcXcord(float grad1,float Ycept1,float grad2, float Ycept2) { float xcord; xcord=(Ycept2-Ycept1)/(grad1-grad2); return xcord; } int main(int argc, char* argv[]) { float gradLine1, gradLine2; float Y0Line1, Y0Line2; float Xcoord, Ycoord; cout<<"input gradient and Y axis value for first line"<<endl; cin>>gradLine1>>Y0Line1; cout<<"input gradient and Y axis value for second line"<<endl; cin>>gradLine2>>Y0Line2; Xcoord=calcXcord(gradLine1,Y0Line1,gradLine2,Y0Line2); } Suppose users enters the following: 1.5, 2.0, -0.5, 3.0. Now, gradline1 = 1.5 Y0Line1 = 2.0 gradline2 = -0.5 Y0Line2 = 3.0 Values 1.5, 2.0, -0.5, 3.0 sent to calcXcord Values 1.5, 2.0, -0.5, 3.0 received by calcXcord grad1 = 1.5 Ycept1 = 2.0 grad2 = -0.5 Ycept2 = 3.0 Calculation carried out and 0.5 returned Xcoord equals the value returned by calcXcord, i.e. 0.5
  • 22. Automatic memory allocation • Variable created at a location in memory automatically when a function is called – Memory location freed up when function is exited… – …except when the variable is declared to be a static variable • memory not de-allocated on exit from function • Next time the function is called, the previous value can be found int myfunction (int a) { int n; n = a * 10; return n; } Each time myfunction is called, a and n are created After the return, a and n are destroyed
  • 23. Example of a static variable int myfunction (int a) { static int n=0; n = n+1; return n * a; } int main( ) { int i = 2, j; j = myfunction(i); cout << "First time: j=" << j << endl; j = myfunction(i); cout << "Second time: j=" << j << endl; } Here j=2 Here j=4 First time in, n is initially 0 before being incremented; second time, n is initially what it was on exit first time, then it is incremented
  • 24. Location of function declarations • Notice that in last fragment of code, calcXcord was declared before main float calcXcord(float grad1,float Ycept1,float grad2, float Ycept2) { float Xcord; Xcord=(Ycept2-Ycept1)/(grad1-grad2); return Xcord; } int main(int argc, char* argv[]) { float gradLine1, gradLine2; float Y0Line1, Y0Line2; float Xcoord, Ycoord; cout<<"input gradient and Y axis value for first line"<<endl; cin>>gradLine1>>Y0Line1; cout<<"input gradient and Y axis value for second line"<<endl; cin>>gradLine2>>Y0Line2; Xcoord=calcXcord(gradLine1,Y0Line1,gradLine2,Y0Line2); } • Compiler must see declaration (of function or variable) before first use) calcXcord declared earlier in source code than first call • Code looks back-to-front! •main used first but declared last
  • 25. Use of function ‘prototypes’ • In order that the compiler doesn’t complain about the order in which functions are declared: – you can put prototypes in the header section of the source code • In effect, this is what #include does – header files (*.h) have function prototypes in them – #include causes the cited header to be copied by the compiler pre-processor into the object code • Allows the compiler to ‘know about’ functions defined in other source modules • Most professional code written ‘back-to-front’ (main at end) # indicates a pre-processor instruction
  • 26. Function prototypes: example #include <iostream> float calcXcord(float, float, float, float); float calcYcord(float, float, float); int main() { float gradLine1, gradLine2, Y0Line1, Y0Line2, Xcoord, Ycoord; char stopchar; cout<<"Input gradient and Y axis value for first line"<<endl; cin>>gradLine1>>Y0Line1; cout<<"Input gradient and Y axis value for second line"<<endl; cin>>gradLine2>>Y0Line2; Xcoord=calcXcord(gradLine1,Y0Line1,gradLine2,Y0Line2); Ycoord=calcYcord(Xcoord,gradLine1,Y0Line1); cout<< "The coordinates of the point of intersection are: " << Xcoord<< ", " << Ycoord << endl << "press a key to end" ; cin >> stopchar; return 0; } float calcXcord(float grad1,float Ycept1,float grad2, float Ycept2) { float Xcord; Xcord=(Ycept2-Ycept1)/(grad1-grad2); return Xcord; } float calcYcord(float X, float grad, float Ycept) { float Ycord; Ycord=grad*X+Ycept; return Ycord; Just quote the argument types in the prototype • if these are different between any two of the prototype, declaration and use, the compiler will complain of ‘bad arguments’
  • 27. Input and output • C and C++ can read from and send messages to file streams – These can be files on a hard disk – In C, stdin and stdout are specific streams related to the keyboard and screen – C++ uses cin and cout objects to read from the keyboard and write to the console (screen) – To access cin and cout, we need to access the iostream library • Put #include <iostream> in the head section of the source code module. • The iostream library is not available to C compilers – More on reading from and writing to files later…
  • 28. Using the cout stream (i) • Once we have included the iostream library we can use the << operator to direct output to the console. – << is known as an ‘inserter’ – it inserts whatever follows into cout cout << initTemp; Sends the contents of the variable initTemp to the console window • We can output more than one variable in a single command to use the cout stream cout << initTemp << endl << finalTemp << endl; prints variable initTemp prints variable finalTemp prints a new line
  • 29. Using the cout stream (ii) • We can also use the cout stream to print text to the console. – At present we will do this using a string literal. – A string literal is a series of alphanumeric characters contained within “ ”. cout << “The initial temperature is “ << initTemp << endl; prints string literal prints variable initTemp prints a new line
  • 30. A simple module showing use of cout #include <iostream> using namespace std; int main() { int initTemp; int finalTemp; int tempChange; initTemp = 12; finalTemp = 15; tempChange = finalTemp - initTemp; cout << "The initial temperature is " << initTemp << endl; cout << "Final temperature is " << finalTemp << endl; cout << “Temperature change is " << tempChange << endl; return 0; }
  • 31. Keeping the console window open (i) • In the preceding code program: – there are outputs of data using cout. – the next line is at the end of our program: return 0; (Literally, this return a value of 0 from the function main. A return from main marks the end of the program) – At the end of the program, the console window will close and our output will disappear. – With some compilers, you need to add some code to keep the console window open. • One way to do this is to use the cin stream to do this – The program waits for carriage return to be entered • Or, use function system(“PAUSE”)
  • 32. Keeping the console window open (ii) . . . tempChange=finalTemp - initTemp; cout << "The initial temperature is " << initTemp << endl; cout << "Final temperature is " << finalTemp << endl; cout << “Temperature change is " << tempChange << endl; char stopchar; cin >> stopchar; return 0; } Declares a variable stopchar of type char Will hold a single character Program execution pauses until user presses enter This isn’t necessary when running a program in debug mode in Visual C++ Express
  • 33. Keeping the console window open (iii) . . . tempChange=finalTemp - initTemp; cout << "The initial temperature is " << initTemp << endl; cout << "Final temperature is " << finalTemp << endl; cout << “Temperature change is " << tempChange << endl; system(“PAUSE”); return 0; } Message written to console saying Press any key to continue . . . Console closes after user presses a key This isn’t necessary when running a program in debug mode in Visual C++ Express
  • 34. Getting input from the keyboard • We use the cin object to access input from the keyboard • Use the >> operator to direct the input to our variables • >> is an ‘extractor’ – extracts a value from cin and assigns it to a variable, e.g. cout << “Please input the initial temperature “; cin >> initTemp; cout << “Please input the final temperature “; cin >> finalTemp;
  • 35. Getting input from keyboard - example #include <iostream> using namespace std; int main() { int initTemp, finalTemp, tempChange; cout << “Please input the initial temperature “; cin >> initTemp; cout << “Please input the final temperature “; cin >> finalTemp; tempChange=finalTemp - initTemp; cout << "The initial temperature is " << initTemp << endl; cout << "Final temperature is " << finalTemp << endl; cout << “Temperature change is " << tempChange << endl; char stopchar; cin >> stopchar; return 0; } Can put declarations of same type on same line
  • 36. Review of structure… #include <iostream> using namespace std; int main( ) { int initTemp; int finalTemp; int tempChange; initTemp = 12; finalTemp = 15; tempChange = finalTemp – initTemp; return 0; } The return 0 marks the end of main Header section • # symbol tells the compiler that it is a preprocessor command. • include is the instruction to the preprocessor. • The < > symbols tell the preprocessor to look in the default directory for .h files. • namespace enables compiler to know which version of library functions

Editor's Notes

  • #7: Get students to call out ideas. Emphasise that the variable names in the called and calling functions don’t have to be the same
  • #22: Note that the variables in the calling and called functions don’t have the same names The students should look for the form or the structure from the examples