This document discusses computer programming functions, variables, and basic input/output in C and C++. It covers:
- Defining and calling functions, function parameters and return values.
- Declaring and assigning values to variables of different data types like int, float, and double.
- Using basic input/output functions like cout and cin to display output and get user input.
- The scope of variables and how they work within and outside of functions.
Operator overloading is a technique by which operators used in a programming language are implemented in user-defined types with customized logic that is based on the types of arguments passed.
Operator overloading is a technique by which operators used in a programming language are implemented in user-defined types with customized logic that is based on the types of arguments passed.
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyGrejoJoby1
The slides from the C++ and OOPS Crash Course conducted for ACM DBIT by Grejo Joby.
Learn the concepts of OOPS and C++ Programming in the shortest time with these notes.
This presentation of ROBO INDIA comprises all of the elements that must be known to learn the programming language C.
This ppt also explains all these topics in details.
We welcome all you views and queries. Please write us, we are found at-
website: http://roboindia.com
mail: info@roboindia.com
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyGrejoJoby1
The slides from the C++ and OOPS Crash Course conducted for ACM DBIT by Grejo Joby.
Learn the concepts of OOPS and C++ Programming in the shortest time with these notes.
This presentation of ROBO INDIA comprises all of the elements that must be known to learn the programming language C.
This ppt also explains all these topics in details.
We welcome all you views and queries. Please write us, we are found at-
website: http://roboindia.com
mail: info@roboindia.com
Esoft Metro Campus - Programming with C++
(Template - Virtusa Corporate)
Contents:
Overview of C++ Language
C++ Program Structure
C++ Basic Syntax
Primitive Built-in types in C++
Variable types
typedef Declarations
Enumerated Types
Variable Scope
Constants/Literals
Storage Classes
Operators
Control Constructs
Functions
Math Operations in C++
Arrays
Multi-dimensional Arrays
Strings
C++ Pointers
References
Date and Time
Structures
Basic Input / Output
Classes and Objects
Inheritance
Overloading
Polymorphism
Interfaces
Files and Streams
Exception Handling
Dynamic Memory
Namespaces
Templates
Preprocessor
Multithreading
Check out these exercises: http://de.slideshare.net/nicolayludwig/3-cpp-procedural-programmingexercises
- Procedural Programming
- Predefined and User defined Functions
- Declaration and Definition of Functions
- Procedural and recursive Function Calling
- Namespaces and separated Function Definitions
- A Glimpse of Separated Compilation and Translation Units
Programming Fundamentals Functions in C and typesimtiazalijoono
Programming Fundamentals
Functions in C
Lecture Outline
• Functions
• Function declaration
• Function call
• Function definition
– Passing arguments to function
1) Passing constants
2) Passing variables
– Pass by value
– Returning values from functions
• Preprocessor directives
• Local and external variables
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...Sérgio Sacani
We characterize the earliest galaxy population in the JADES Origins Field (JOF), the deepest
imaging field observed with JWST. We make use of the ancillary Hubble optical images (5 filters
spanning 0.4−0.9µm) and novel JWST images with 14 filters spanning 0.8−5µm, including 7 mediumband filters, and reaching total exposure times of up to 46 hours per filter. We combine all our data
at > 2.3µm to construct an ultradeep image, reaching as deep as ≈ 31.4 AB mag in the stack and
30.3-31.0 AB mag (5σ, r = 0.1” circular aperture) in individual filters. We measure photometric
redshifts and use robust selection criteria to identify a sample of eight galaxy candidates at redshifts
z = 11.5 − 15. These objects show compact half-light radii of R1/2 ∼ 50 − 200pc, stellar masses of
M⋆ ∼ 107−108M⊙, and star-formation rates of SFR ∼ 0.1−1 M⊙ yr−1
. Our search finds no candidates
at 15 < z < 20, placing upper limits at these redshifts. We develop a forward modeling approach to
infer the properties of the evolving luminosity function without binning in redshift or luminosity that
marginalizes over the photometric redshift uncertainty of our candidate galaxies and incorporates the
impact of non-detections. We find a z = 12 luminosity function in good agreement with prior results,
and that the luminosity function normalization and UV luminosity density decline by a factor of ∼ 2.5
from z = 12 to z = 14. We discuss the possible implications of our results in the context of theoretical
models for evolution of the dark matter halo mass function.
Nutraceutical market, scope and growth: Herbal drug technologyLokesh Patil
As consumer awareness of health and wellness rises, the nutraceutical market—which includes goods like functional meals, drinks, and dietary supplements that provide health advantages beyond basic nutrition—is growing significantly. As healthcare expenses rise, the population ages, and people want natural and preventative health solutions more and more, this industry is increasing quickly. Further driving market expansion are product formulation innovations and the use of cutting-edge technology for customized nutrition. With its worldwide reach, the nutraceutical industry is expected to keep growing and provide significant chances for research and investment in a number of categories, including vitamins, minerals, probiotics, and herbal supplements.
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...Scintica Instrumentation
Intravital microscopy (IVM) is a powerful tool utilized to study cellular behavior over time and space in vivo. Much of our understanding of cell biology has been accomplished using various in vitro and ex vivo methods; however, these studies do not necessarily reflect the natural dynamics of biological processes. Unlike traditional cell culture or fixed tissue imaging, IVM allows for the ultra-fast high-resolution imaging of cellular processes over time and space and were studied in its natural environment. Real-time visualization of biological processes in the context of an intact organism helps maintain physiological relevance and provide insights into the progression of disease, response to treatments or developmental processes.
In this webinar we give an overview of advanced applications of the IVM system in preclinical research. IVIM technology is a provider of all-in-one intravital microscopy systems and solutions optimized for in vivo imaging of live animal models at sub-micron resolution. The system’s unique features and user-friendly software enables researchers to probe fast dynamic biological processes such as immune cell tracking, cell-cell interaction as well as vascularization and tumor metastasis with exceptional detail. This webinar will also give an overview of IVM being utilized in drug development, offering a view into the intricate interaction between drugs/nanoparticles and tissues in vivo and allows for the evaluation of therapeutic intervention in a variety of tissues and organs. This interdisciplinary collaboration continues to drive the advancements of novel therapeutic strategies.
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...Sérgio Sacani
Since volcanic activity was first discovered on Io from Voyager images in 1979, changes
on Io’s surface have been monitored from both spacecraft and ground-based telescopes.
Here, we present the highest spatial resolution images of Io ever obtained from a groundbased telescope. These images, acquired by the SHARK-VIS instrument on the Large
Binocular Telescope, show evidence of a major resurfacing event on Io’s trailing hemisphere. When compared to the most recent spacecraft images, the SHARK-VIS images
show that a plume deposit from a powerful eruption at Pillan Patera has covered part
of the long-lived Pele plume deposit. Although this type of resurfacing event may be common on Io, few have been detected due to the rarity of spacecraft visits and the previously low spatial resolution available from Earth-based telescopes. The SHARK-VIS instrument ushers in a new era of high resolution imaging of Io’s surface using adaptive
optics at visible wavelengths.
Cancer cell metabolism: special Reference to Lactate PathwayAADYARAJPANDEY1
Normal Cell Metabolism:
Cellular respiration describes the series of steps that cells use to break down sugar and other chemicals to get the energy we need to function.
Energy is stored in the bonds of glucose and when glucose is broken down, much of that energy is released.
Cell utilize energy in the form of ATP.
The first step of respiration is called glycolysis. In a series of steps, glycolysis breaks glucose into two smaller molecules - a chemical called pyruvate. A small amount of ATP is formed during this process.
Most healthy cells continue the breakdown in a second process, called the Kreb's cycle. The Kreb's cycle allows cells to “burn” the pyruvates made in glycolysis to get more ATP.
The last step in the breakdown of glucose is called oxidative phosphorylation (Ox-Phos).
It takes place in specialized cell structures called mitochondria. This process produces a large amount of ATP. Importantly, cells need oxygen to complete oxidative phosphorylation.
If a cell completes only glycolysis, only 2 molecules of ATP are made per glucose. However, if the cell completes the entire respiration process (glycolysis - Kreb's - oxidative phosphorylation), about 36 molecules of ATP are created, giving it much more energy to use.
IN CANCER CELL:
Unlike healthy cells that "burn" the entire molecule of sugar to capture a large amount of energy as ATP, cancer cells are wasteful.
Cancer cells only partially break down sugar molecules. They overuse the first step of respiration, glycolysis. They frequently do not complete the second step, oxidative phosphorylation.
This results in only 2 molecules of ATP per each glucose molecule instead of the 36 or so ATPs healthy cells gain. As a result, cancer cells need to use a lot more sugar molecules to get enough energy to survive.
Unlike healthy cells that "burn" the entire molecule of sugar to capture a large amount of energy as ATP, cancer cells are wasteful.
Cancer cells only partially break down sugar molecules. They overuse the first step of respiration, glycolysis. They frequently do not complete the second step, oxidative phosphorylation.
This results in only 2 molecules of ATP per each glucose molecule instead of the 36 or so ATPs healthy cells gain. As a result, cancer cells need to use a lot more sugar molecules to get enough energy to survive.
introduction to WARBERG PHENOMENA:
WARBURG EFFECT Usually, cancer cells are highly glycolytic (glucose addiction) and take up more glucose than do normal cells from outside.
Otto Heinrich Warburg (; 8 October 1883 – 1 August 1970) In 1931 was awarded the Nobel Prize in Physiology for his "discovery of the nature and mode of action of the respiratory enzyme.
WARNBURG EFFECT : cancer cells under aerobic (well-oxygenated) conditions to metabolize glucose to lactate (aerobic glycolysis) is known as the Warburg effect. Warburg made the observation that tumor slices consume glucose and secrete lactate at a higher rate than normal tissues.
What is greenhouse gasses and how many gasses are there to affect the Earth.moosaasad1975
What are greenhouse gasses how they affect the earth and its environment what is the future of the environment and earth how the weather and the climate effects.
Richard's entangled aventures in wonderlandRichard Gill
Since the loophole-free Bell experiments of 2020 and the Nobel prizes in physics of 2022, critics of Bell's work have retreated to the fortress of super-determinism. Now, super-determinism is a derogatory word - it just means "determinism". Palmer, Hance and Hossenfelder argue that quantum mechanics and determinism are not incompatible, using a sophisticated mathematical construction based on a subtle thinning of allowed states and measurements in quantum mechanics, such that what is left appears to make Bell's argument fail, without altering the empirical predictions of quantum mechanics. I think however that it is a smoke screen, and the slogan "lost in math" comes to my mind. I will discuss some other recent disproofs of Bell's theorem using the language of causality based on causal graphs. Causal thinking is also central to law and justice. I will mention surprising connections to my work on serial killer nurse cases, in particular the Dutch case of Lucia de Berk and the current UK case of Lucy Letby.
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
Get students to call out ideas. Emphasise that the variable names in the called and calling functions don’t have to be the same
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