Upload
manzoor-khan
View
76
Download
3
Tags:
Embed Size (px)
Citation preview
Computer Programming
Functions, variables and basic input and output
Prof. Dr. Mohammad Haseeb [email protected]
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 argumentsint main(int argc, char* argv[ ])
Gives access to the textof 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 thefunction
Arguments takenby the functionand their types
What the functiondoes
• 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 functionto return the sumof 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 returnNo 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’ ratherthan ‘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 valueinvert 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 numberfrom +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 thatthe variable is of typefloat
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 floatfloat operation performed
1 / 5result = 0int operation performed
1.0 / 5result = 0.2float 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 insidefunction calcXcord
Only known insidefunction 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 casee.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.5Y0Line1 = 2.0gradline2 = -0.5Y0Line2 = 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.5Ycept1 = 2.0grad2 = -0.5Ycept2 = 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 variableint 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 earlierin 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-processorinstruction
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 initTempprints 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 charWill hold a single character
Program execution pauses until user presses enter
This isn’t necessary whenrunning a program in debug modein 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 sayingPress any key to continue . . .Console closes after user presses a key
This isn’t necessary whenrunning a program in debug modein 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 ofsame 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 toknow which version of library functions