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

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++
C++C++
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
 

What's hot (11)

operator overloading
operator overloadingoperator overloading
operator overloading
 
Lecture5
Lecture5Lecture5
Lecture5
 
3d7b7 session4 c++
3d7b7 session4 c++3d7b7 session4 c++
3d7b7 session4 c++
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
 
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
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
C++
C++C++
C++
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
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
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
 

Viewers also liked

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 constantsvinay arora
 
constants, variables and datatypes in C
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in CSahithi 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_classesasadsardar
 

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
 
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
 
constants, variables and datatypes in C
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in C
 
Friend functions
Friend functions Friend functions
Friend functions
 
Friend function & friend class
Friend function & friend classFriend function & friend class
Friend function & friend class
 
Data types
Data typesData types
Data types
 
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
 
Friends function and_classes
Friends function and_classesFriends function and_classes
Friends function and_classes
 

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

C language
C languageC language
C language
Robo India
 
C
CC
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
sameermhr345
 
Object Oriented Technologies
Object Oriented TechnologiesObject Oriented Technologies
Object Oriented Technologies
Umesh Nikam
 
Basic Elements of C++
Basic Elements of C++Basic Elements of C++
Basic Elements of C++
Jason J Pulikkottil
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
Rasan Samarasinghe
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
Nico Ludwig
 
Prog1-L2.pptx
Prog1-L2.pptxProg1-L2.pptx
Prog1-L2.pptx
valerie5142000
 
c-programming
c-programmingc-programming
c-programming
Zulhazmi Harith
 
Cs1123 4 variables_constants
Cs1123 4 variables_constantsCs1123 4 variables_constants
Cs1123 4 variables_constantsTAlha MAlik
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
Sangharsh agarwal
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
msharshitha03s
 
Function
FunctionFunction
Function
Saniati
 
C programming
C programmingC programming
C programming
Harshit Varshney
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
SaraswathiTAsstProfI
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
imtiazalijoono
 
Presentation c++
Presentation c++Presentation c++
Presentation c++
JosephAlex21
 
PythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdfPythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdf
data2businessinsight
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
UdhayaKumar175069
 

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

C language
C languageC language
C language
 
C
CC
C
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
 
Object Oriented Technologies
Object Oriented TechnologiesObject Oriented Technologies
Object Oriented Technologies
 
Basic Elements of C++
Basic Elements of C++Basic Elements of C++
Basic Elements of C++
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
Prog1-L2.pptx
Prog1-L2.pptxProg1-L2.pptx
Prog1-L2.pptx
 
c-programming
c-programmingc-programming
c-programming
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
 
Cs1123 4 variables_constants
Cs1123 4 variables_constantsCs1123 4 variables_constants
Cs1123 4 variables_constants
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 
Function
FunctionFunction
Function
 
C programming
C programmingC programming
C programming
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
Presentation c++
Presentation c++Presentation c++
Presentation c++
 
PythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdfPythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdf
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
 

More from 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
 
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
 

More from Manzoor ALam (6)

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

Recently uploaded

Astronomy Update- Curiosity’s exploration of Mars _ Local Briefs _ leadertele...
Astronomy Update- Curiosity’s exploration of Mars _ Local Briefs _ leadertele...Astronomy Update- Curiosity’s exploration of Mars _ Local Briefs _ leadertele...
Astronomy Update- Curiosity’s exploration of Mars _ Local Briefs _ leadertele...
NathanBaughman3
 
Structures and textures of metamorphic rocks
Structures and textures of metamorphic rocksStructures and textures of metamorphic rocks
Structures and textures of metamorphic rocks
kumarmathi863
 
GBSN - Biochemistry (Unit 5) Chemistry of Lipids
GBSN - Biochemistry (Unit 5) Chemistry of LipidsGBSN - Biochemistry (Unit 5) Chemistry of Lipids
GBSN - Biochemistry (Unit 5) Chemistry of Lipids
Areesha Ahmad
 
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Sérgio Sacani
 
Nutraceutical market, scope and growth: Herbal drug technology
Nutraceutical market, scope and growth: Herbal drug technologyNutraceutical market, scope and growth: Herbal drug technology
Nutraceutical market, scope and growth: Herbal drug technology
Lokesh Patil
 
In silico drugs analogue design: novobiocin analogues.pptx
In silico drugs analogue design: novobiocin analogues.pptxIn silico drugs analogue design: novobiocin analogues.pptx
In silico drugs analogue design: novobiocin analogues.pptx
AlaminAfendy1
 
in vitro propagation of plants lecture note.pptx
in vitro propagation of plants lecture note.pptxin vitro propagation of plants lecture note.pptx
in vitro propagation of plants lecture note.pptx
yusufzako14
 
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
Scintica Instrumentation
 
Leaf Initiation, Growth and Differentiation.pdf
Leaf Initiation, Growth and Differentiation.pdfLeaf Initiation, Growth and Differentiation.pdf
Leaf Initiation, Growth and Differentiation.pdf
RenuJangid3
 
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...
Sérgio Sacani
 
Unveiling the Energy Potential of Marshmallow Deposits.pdf
Unveiling the Energy Potential of Marshmallow Deposits.pdfUnveiling the Energy Potential of Marshmallow Deposits.pdf
Unveiling the Energy Potential of Marshmallow Deposits.pdf
Erdal Coalmaker
 
role of pramana in research.pptx in science
role of pramana in research.pptx in sciencerole of pramana in research.pptx in science
role of pramana in research.pptx in science
sonaliswain16
 
Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...
Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...
Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...
muralinath2
 
Cancer cell metabolism: special Reference to Lactate Pathway
Cancer cell metabolism: special Reference to Lactate PathwayCancer cell metabolism: special Reference to Lactate Pathway
Cancer cell metabolism: special Reference to Lactate Pathway
AADYARAJPANDEY1
 
What is greenhouse gasses and how many gasses are there to affect the Earth.
What is greenhouse gasses and how many gasses are there to affect the Earth.What is greenhouse gasses and how many gasses are there to affect the Earth.
What is greenhouse gasses and how many gasses are there to affect the Earth.
moosaasad1975
 
Hemostasis_importance& clinical significance.pptx
Hemostasis_importance& clinical significance.pptxHemostasis_importance& clinical significance.pptx
Hemostasis_importance& clinical significance.pptx
muralinath2
 
4. An Overview of Sugarcane White Leaf Disease in Vietnam.pdf
4. An Overview of Sugarcane White Leaf Disease in Vietnam.pdf4. An Overview of Sugarcane White Leaf Disease in Vietnam.pdf
4. An Overview of Sugarcane White Leaf Disease in Vietnam.pdf
ssuserbfdca9
 
PRESENTATION ABOUT PRINCIPLE OF COSMATIC EVALUATION
PRESENTATION ABOUT PRINCIPLE OF COSMATIC EVALUATIONPRESENTATION ABOUT PRINCIPLE OF COSMATIC EVALUATION
PRESENTATION ABOUT PRINCIPLE OF COSMATIC EVALUATION
ChetanK57
 
Richard's entangled aventures in wonderland
Richard's entangled aventures in wonderlandRichard's entangled aventures in wonderland
Richard's entangled aventures in wonderland
Richard Gill
 
The ASGCT Annual Meeting was packed with exciting progress in the field advan...
The ASGCT Annual Meeting was packed with exciting progress in the field advan...The ASGCT Annual Meeting was packed with exciting progress in the field advan...
The ASGCT Annual Meeting was packed with exciting progress in the field advan...
Health Advances
 

Recently uploaded (20)

Astronomy Update- Curiosity’s exploration of Mars _ Local Briefs _ leadertele...
Astronomy Update- Curiosity’s exploration of Mars _ Local Briefs _ leadertele...Astronomy Update- Curiosity’s exploration of Mars _ Local Briefs _ leadertele...
Astronomy Update- Curiosity’s exploration of Mars _ Local Briefs _ leadertele...
 
Structures and textures of metamorphic rocks
Structures and textures of metamorphic rocksStructures and textures of metamorphic rocks
Structures and textures of metamorphic rocks
 
GBSN - Biochemistry (Unit 5) Chemistry of Lipids
GBSN - Biochemistry (Unit 5) Chemistry of LipidsGBSN - Biochemistry (Unit 5) Chemistry of Lipids
GBSN - Biochemistry (Unit 5) Chemistry of Lipids
 
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
 
Nutraceutical market, scope and growth: Herbal drug technology
Nutraceutical market, scope and growth: Herbal drug technologyNutraceutical market, scope and growth: Herbal drug technology
Nutraceutical market, scope and growth: Herbal drug technology
 
In silico drugs analogue design: novobiocin analogues.pptx
In silico drugs analogue design: novobiocin analogues.pptxIn silico drugs analogue design: novobiocin analogues.pptx
In silico drugs analogue design: novobiocin analogues.pptx
 
in vitro propagation of plants lecture note.pptx
in vitro propagation of plants lecture note.pptxin vitro propagation of plants lecture note.pptx
in vitro propagation of plants lecture note.pptx
 
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
 
Leaf Initiation, Growth and Differentiation.pdf
Leaf Initiation, Growth and Differentiation.pdfLeaf Initiation, Growth and Differentiation.pdf
Leaf Initiation, Growth and Differentiation.pdf
 
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...
 
Unveiling the Energy Potential of Marshmallow Deposits.pdf
Unveiling the Energy Potential of Marshmallow Deposits.pdfUnveiling the Energy Potential of Marshmallow Deposits.pdf
Unveiling the Energy Potential of Marshmallow Deposits.pdf
 
role of pramana in research.pptx in science
role of pramana in research.pptx in sciencerole of pramana in research.pptx in science
role of pramana in research.pptx in science
 
Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...
Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...
Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...
 
Cancer cell metabolism: special Reference to Lactate Pathway
Cancer cell metabolism: special Reference to Lactate PathwayCancer cell metabolism: special Reference to Lactate Pathway
Cancer cell metabolism: special Reference to Lactate Pathway
 
What is greenhouse gasses and how many gasses are there to affect the Earth.
What is greenhouse gasses and how many gasses are there to affect the Earth.What is greenhouse gasses and how many gasses are there to affect the Earth.
What is greenhouse gasses and how many gasses are there to affect the Earth.
 
Hemostasis_importance& clinical significance.pptx
Hemostasis_importance& clinical significance.pptxHemostasis_importance& clinical significance.pptx
Hemostasis_importance& clinical significance.pptx
 
4. An Overview of Sugarcane White Leaf Disease in Vietnam.pdf
4. An Overview of Sugarcane White Leaf Disease in Vietnam.pdf4. An Overview of Sugarcane White Leaf Disease in Vietnam.pdf
4. An Overview of Sugarcane White Leaf Disease in Vietnam.pdf
 
PRESENTATION ABOUT PRINCIPLE OF COSMATIC EVALUATION
PRESENTATION ABOUT PRINCIPLE OF COSMATIC EVALUATIONPRESENTATION ABOUT PRINCIPLE OF COSMATIC EVALUATION
PRESENTATION ABOUT PRINCIPLE OF COSMATIC EVALUATION
 
Richard's entangled aventures in wonderland
Richard's entangled aventures in wonderlandRichard's entangled aventures in wonderland
Richard's entangled aventures in wonderland
 
The ASGCT Annual Meeting was packed with exciting progress in the field advan...
The ASGCT Annual Meeting was packed with exciting progress in the field advan...The ASGCT Annual Meeting was packed with exciting progress in the field advan...
The ASGCT Annual Meeting was packed with exciting progress in the field advan...
 

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

  1. Get students to call out ideas. Emphasise that the variable names in the called and calling functions don’t have to be the same
  2. 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