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

What's hot (11)

operator overloading
operator overloadingoperator overloading
operator overloading
Nishant Joshi
 
Lecture5
Lecture5Lecture5
Lecture5
ravifeelings
 
3d7b7 session4 c++
3d7b7 session4 c++3d7b7 session4 c++
3d7b7 session4 c++
Mukund Trivedi
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
Rokonuzzaman Rony
 
Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1
Ali Aminian
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++
Danial Mirza
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi
 
C++
C++C++
C++
Shyam Khant
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Pranali Chaudhari
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
GrejoJoby1
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
harman kaur
 
operator overloading
operator overloadingoperator overloading
operator overloading
Nishant Joshi
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
Rokonuzzaman Rony
 
Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1
Ali Aminian
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++
Danial Mirza
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
GrejoJoby1
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
harman kaur
 

Viewers also liked (8)

Constants and variables in c programming
Constants and variables in c programmingConstants and variables in c programming
Constants and variables in c programming
Chitrank Dixit
 
Chapter1 c programming data types, variables and constants
Chapter1 c programming   data types, variables and constantsChapter1 c programming   data types, variables and constants
Chapter1 c programming data types, variables and constants
vinay arora
 
constants, variables and datatypes in C
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in C
Sahithi Naraparaju
 
Friend functions
Friend functions Friend functions
Friend functions
Megha Singh
 
Friend function & friend class
Friend function & friend classFriend function & friend class
Friend function & friend class
Abhishek Wadhwa
 
Data types
Data typesData types
Data types
Zahid Hussain
 
Data Types and Variables In C Programming
Data Types and Variables In C ProgrammingData Types and Variables In C Programming
Data Types and Variables In C Programming
Kamal Acharya
 
Friends function and_classes
Friends function and_classesFriends function and_classes
Friends function and_classes
asadsardar
 
Constants and variables in c programming
Constants and variables in c programmingConstants and variables in c programming
Constants and variables in c programming
Chitrank Dixit
 
Chapter1 c programming data types, variables and constants
Chapter1 c programming   data types, variables and constantsChapter1 c programming   data types, variables and constants
Chapter1 c programming data types, variables and constants
vinay arora
 
constants, variables and datatypes in C
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in C
Sahithi Naraparaju
 
Friend functions
Friend functions Friend functions
Friend functions
Megha Singh
 
Friend function & friend class
Friend function & friend classFriend function & friend class
Friend function & friend class
Abhishek Wadhwa
 
Data Types and Variables In C Programming
Data Types and Variables In C ProgrammingData Types and Variables In C Programming
Data Types and Variables In C Programming
Kamal Acharya
 
Friends function and_classes
Friends function and_classesFriends function and_classes
Friends function and_classes
asadsardar
 
Ad

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

Basics of cpp
Basics of cppBasics of cpp
Basics of cpp
vinay chauhan
 
Savitch ch 02
Savitch ch 02Savitch ch 02
Savitch ch 02
Terry Yoast
 
Savitch Ch 02
Savitch Ch 02Savitch Ch 02
Savitch Ch 02
Terry Yoast
 
Savitch Ch 02
Savitch Ch 02Savitch Ch 02
Savitch Ch 02
Terry Yoast
 
C++ Tutorial
C++ TutorialC++ Tutorial
C++ Tutorial
freema48
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
Warui Maina
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
AmanuelZewdie4
 
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).pptchapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
harinipradeep15
 
CPP06 - Functions
CPP06 - FunctionsCPP06 - Functions
CPP06 - Functions
Michael Heron
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
Thooyavan Venkatachalam
 
C++
C++C++
C++
VishalMishra313
 
c++ introduction, array, pointers included.pptx
c++ introduction, array, pointers included.pptxc++ introduction, array, pointers included.pptx
c++ introduction, array, pointers included.pptx
fn723290
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
Abdullah Turkistani
 
C++ basics
C++ basicsC++ basics
C++ basics
ndargolis
 
Apclass
ApclassApclass
Apclass
geishaannealagos
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
NUST Stuff
 
dinoC_ppt.pptx
dinoC_ppt.pptxdinoC_ppt.pptx
dinoC_ppt.pptx
DinobandhuThokdarCST
 
cppt-170218053903.pptxhjkjhjjjjjjjjjjjjjjj
cppt-170218053903.pptxhjkjhjjjjjjjjjjjjjjjcppt-170218053903.pptxhjkjhjjjjjjjjjjjjjjj
cppt-170218053903.pptxhjkjhjjjjjjjjjjjjjjj
supriyaharlapur1
 
Functions
FunctionsFunctions
Functions
Learn By Watch
 
Apclass (2)
Apclass (2)Apclass (2)
Apclass (2)
geishaannealagos
 
C++ Tutorial
C++ TutorialC++ Tutorial
C++ Tutorial
freema48
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
Warui Maina
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
AmanuelZewdie4
 
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).pptchapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
harinipradeep15
 
c++ introduction, array, pointers included.pptx
c++ introduction, array, pointers included.pptxc++ introduction, array, pointers included.pptx
c++ introduction, array, pointers included.pptx
fn723290
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
NUST Stuff
 
cppt-170218053903.pptxhjkjhjjjjjjjjjjjjjjj
cppt-170218053903.pptxhjkjhjjjjjjjjjjjjjjjcppt-170218053903.pptxhjkjhjjjjjjjjjjjjjjj
cppt-170218053903.pptxhjkjhjjjjjjjjjjjjjjj
supriyaharlapur1
 
Ad

More from Manzoor ALam (6)

8085 microprocessor ramesh gaonkar
8085 microprocessor   ramesh gaonkar8085 microprocessor   ramesh gaonkar
8085 microprocessor ramesh gaonkar
Manzoor ALam
 
01 introduction to cpp
01   introduction to cpp01   introduction to cpp
01 introduction to cpp
Manzoor ALam
 
03b loops
03b   loops03b   loops
03b loops
Manzoor ALam
 
03a control structures
03a   control structures03a   control structures
03a control structures
Manzoor ALam
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
Manzoor ALam
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loops
Manzoor ALam
 
8085 microprocessor ramesh gaonkar
8085 microprocessor   ramesh gaonkar8085 microprocessor   ramesh gaonkar
8085 microprocessor ramesh gaonkar
Manzoor ALam
 
01 introduction to cpp
01   introduction to cpp01   introduction to cpp
01 introduction to cpp
Manzoor ALam
 
03a control structures
03a   control structures03a   control structures
03a control structures
Manzoor ALam
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
Manzoor ALam
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loops
Manzoor ALam
 

Recently uploaded (20)

Comparative Layouts Revisited: Design Space, Guidelines, and Future Directions
Comparative Layouts Revisited: Design Space, Guidelines, and Future DirectionsComparative Layouts Revisited: Design Space, Guidelines, and Future Directions
Comparative Layouts Revisited: Design Space, Guidelines, and Future Directions
sehilyi
 
Kim Sandwich Biomes Project Science 10.pptx
Kim Sandwich Biomes Project Science 10.pptxKim Sandwich Biomes Project Science 10.pptx
Kim Sandwich Biomes Project Science 10.pptx
asantos691
 
Aquatic ecosystem and its biomes involved.pdf
Aquatic ecosystem and its biomes involved.pdfAquatic ecosystem and its biomes involved.pdf
Aquatic ecosystem and its biomes involved.pdf
camillemaguid53
 
Primary and Secondary immune modulation.pptx
Primary and Secondary immune modulation.pptxPrimary and Secondary immune modulation.pptx
Primary and Secondary immune modulation.pptx
devikasanalkumar35
 
Microbiome Engineering: Shaping a Sustainable Future.pptx
Microbiome Engineering: Shaping a Sustainable Future.pptxMicrobiome Engineering: Shaping a Sustainable Future.pptx
Microbiome Engineering: Shaping a Sustainable Future.pptx
akshjm123
 
Grammar-Based 
Interactive Visualization of Genomics Data
Grammar-Based 
Interactive Visualization of Genomics DataGrammar-Based 
Interactive Visualization of Genomics Data
Grammar-Based 
Interactive Visualization of Genomics Data
sehilyi
 
Morphological and biochemical characterization in Rice
Morphological and biochemical characterization in RiceMorphological and biochemical characterization in Rice
Morphological and biochemical characterization in Rice
AbhishekChauhan911496
 
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy TextsCloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
sehilyi
 
To study the factors on which the self-inductance of the coil depends by obse...
To study the factors on which the self-inductance of the coil depends by obse...To study the factors on which the self-inductance of the coil depends by obse...
To study the factors on which the self-inductance of the coil depends by obse...
crazycompetitor000
 
instrument of surgery help for the practical
instrument of surgery help for the practicalinstrument of surgery help for the practical
instrument of surgery help for the practical
radialcarpoulnaris
 
National development you must learn it.pptx
National development you must learn it.pptxNational development you must learn it.pptx
National development you must learn it.pptx
mukherjeechetan56
 
International Journal of Pharmacological Sciences (IJPS)
International Journal of Pharmacological Sciences (IJPS)International Journal of Pharmacological Sciences (IJPS)
International Journal of Pharmacological Sciences (IJPS)
journalijps98
 
Comparative anatomy of brain of different types of vertebrates
Comparative anatomy of brain of different types of vertebratesComparative anatomy of brain of different types of vertebrates
Comparative anatomy of brain of different types of vertebrates
arpanmaji480
 
Driving sustainability: AI adoption framework for the fast fashion industry
Driving sustainability: AI adoption framework for the fast fashion industryDriving sustainability: AI adoption framework for the fast fashion industry
Driving sustainability: AI adoption framework for the fast fashion industry
Selcen Ozturkcan
 
Toward Understanding Representation Methods in Visualization Recommendations ...
Toward Understanding Representation Methods in Visualization Recommendations ...Toward Understanding Representation Methods in Visualization Recommendations ...
Toward Understanding Representation Methods in Visualization Recommendations ...
sehilyi
 
Understanding Visualization Authoring for Genomics Data through User Interviews
Understanding Visualization Authoring for Genomics Data through User InterviewsUnderstanding Visualization Authoring for Genomics Data through User Interviews
Understanding Visualization Authoring for Genomics Data through User Interviews
sehilyi
 
Immunity and its Types.hububhubibkinunubunni
Immunity and its Types.hububhubibkinunubunniImmunity and its Types.hububhubibkinunubunni
Immunity and its Types.hububhubibkinunubunni
Manveer19
 
Dr. James Farley Identifies the Key Root Causes You Must Address to Heal Natu...
Dr. James Farley Identifies the Key Root Causes You Must Address to Heal Natu...Dr. James Farley Identifies the Key Root Causes You Must Address to Heal Natu...
Dr. James Farley Identifies the Key Root Causes You Must Address to Heal Natu...
DrJamesFarley
 
Class 12 biology project on the topic cancer
Class 12 biology project on the topic cancerClass 12 biology project on the topic cancer
Class 12 biology project on the topic cancer
crazycompetitor000
 
Metabolic acidosis and alkalosis ppt.pptx
Metabolic acidosis and alkalosis ppt.pptxMetabolic acidosis and alkalosis ppt.pptx
Metabolic acidosis and alkalosis ppt.pptx
aanchalm373
 
Comparative Layouts Revisited: Design Space, Guidelines, and Future Directions
Comparative Layouts Revisited: Design Space, Guidelines, and Future DirectionsComparative Layouts Revisited: Design Space, Guidelines, and Future Directions
Comparative Layouts Revisited: Design Space, Guidelines, and Future Directions
sehilyi
 
Kim Sandwich Biomes Project Science 10.pptx
Kim Sandwich Biomes Project Science 10.pptxKim Sandwich Biomes Project Science 10.pptx
Kim Sandwich Biomes Project Science 10.pptx
asantos691
 
Aquatic ecosystem and its biomes involved.pdf
Aquatic ecosystem and its biomes involved.pdfAquatic ecosystem and its biomes involved.pdf
Aquatic ecosystem and its biomes involved.pdf
camillemaguid53
 
Primary and Secondary immune modulation.pptx
Primary and Secondary immune modulation.pptxPrimary and Secondary immune modulation.pptx
Primary and Secondary immune modulation.pptx
devikasanalkumar35
 
Microbiome Engineering: Shaping a Sustainable Future.pptx
Microbiome Engineering: Shaping a Sustainable Future.pptxMicrobiome Engineering: Shaping a Sustainable Future.pptx
Microbiome Engineering: Shaping a Sustainable Future.pptx
akshjm123
 
Grammar-Based 
Interactive Visualization of Genomics Data
Grammar-Based 
Interactive Visualization of Genomics DataGrammar-Based 
Interactive Visualization of Genomics Data
Grammar-Based 
Interactive Visualization of Genomics Data
sehilyi
 
Morphological and biochemical characterization in Rice
Morphological and biochemical characterization in RiceMorphological and biochemical characterization in Rice
Morphological and biochemical characterization in Rice
AbhishekChauhan911496
 
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy TextsCloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
sehilyi
 
To study the factors on which the self-inductance of the coil depends by obse...
To study the factors on which the self-inductance of the coil depends by obse...To study the factors on which the self-inductance of the coil depends by obse...
To study the factors on which the self-inductance of the coil depends by obse...
crazycompetitor000
 
instrument of surgery help for the practical
instrument of surgery help for the practicalinstrument of surgery help for the practical
instrument of surgery help for the practical
radialcarpoulnaris
 
National development you must learn it.pptx
National development you must learn it.pptxNational development you must learn it.pptx
National development you must learn it.pptx
mukherjeechetan56
 
International Journal of Pharmacological Sciences (IJPS)
International Journal of Pharmacological Sciences (IJPS)International Journal of Pharmacological Sciences (IJPS)
International Journal of Pharmacological Sciences (IJPS)
journalijps98
 
Comparative anatomy of brain of different types of vertebrates
Comparative anatomy of brain of different types of vertebratesComparative anatomy of brain of different types of vertebrates
Comparative anatomy of brain of different types of vertebrates
arpanmaji480
 
Driving sustainability: AI adoption framework for the fast fashion industry
Driving sustainability: AI adoption framework for the fast fashion industryDriving sustainability: AI adoption framework for the fast fashion industry
Driving sustainability: AI adoption framework for the fast fashion industry
Selcen Ozturkcan
 
Toward Understanding Representation Methods in Visualization Recommendations ...
Toward Understanding Representation Methods in Visualization Recommendations ...Toward Understanding Representation Methods in Visualization Recommendations ...
Toward Understanding Representation Methods in Visualization Recommendations ...
sehilyi
 
Understanding Visualization Authoring for Genomics Data through User Interviews
Understanding Visualization Authoring for Genomics Data through User InterviewsUnderstanding Visualization Authoring for Genomics Data through User Interviews
Understanding Visualization Authoring for Genomics Data through User Interviews
sehilyi
 
Immunity and its Types.hububhubibkinunubunni
Immunity and its Types.hububhubibkinunubunniImmunity and its Types.hububhubibkinunubunni
Immunity and its Types.hububhubibkinunubunni
Manveer19
 
Dr. James Farley Identifies the Key Root Causes You Must Address to Heal Natu...
Dr. James Farley Identifies the Key Root Causes You Must Address to Heal Natu...Dr. James Farley Identifies the Key Root Causes You Must Address to Heal Natu...
Dr. James Farley Identifies the Key Root Causes You Must Address to Heal Natu...
DrJamesFarley
 
Class 12 biology project on the topic cancer
Class 12 biology project on the topic cancerClass 12 biology project on the topic cancer
Class 12 biology project on the topic cancer
crazycompetitor000
 
Metabolic acidosis and alkalosis ppt.pptx
Metabolic acidosis and alkalosis ppt.pptxMetabolic acidosis and alkalosis ppt.pptx
Metabolic acidosis and alkalosis ppt.pptx
aanchalm373
 

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

  • 1. Computer Programming Functions, variables and basic input and output Prof. Dr. Mohammad Haseeb Zafar [email protected]
  • 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