Introduction to C/C++ Day 1 Mark Slater

advertisement
Introduction to C/C++ Day 1
Mark Slater
Overview
1. Code Creation and Compilation
2. Variables
3. Object Declaration and Operators
4. Program Flow in C/C++
What is C++?
●
●
●
C++ is a general purpose object oriented programming
language widely used in the software industry and beyond. It
was developed by Bjarne Stroustrup in 1979 as an
enhancement to the C language ('C with classes')
Though comprised of fairly basic syntax and conventions, it is
incredibly powerful, especially with the addition of the
'standard libraries'. Anything you can think of to do on a
computer can be (but not necessarily should be!) done in C++
C++ has been adopted as the standard for most coding tasks in
modern Particle Physics and so it's well worth getting to know!
1. Code Creation and Compilation
Writing and Compiling Code
As already stated, C++ code can be written using any text editor,
but to create the actual programs requires a compiler that creates
the machine-readable code
#include <iostream>
int main()
{
// Read and print three
// floating point numbers
std::cout << "Give 3 nums" << std::endl;
float a, b, c;
std::cin >> a >> b >> c;
std::cout << "Your gave... ";
std::cout << a << ", " << b << ", " << c
<< std::endl;
return 0;
}
Compiled Code
Raw Code
Executable
Additional Libs
The Hello World Program (Ex. 1)
To demonstrate this process, you will create the ubiquitous 'Hello
World' program:
1. Create a directory to put your code in
2. Copy the code here into a text editor
3. Save the file as 'ex1.cpp'
4. Run the GCC compiler
5. Execute the program!
#include <iostream>
int main()
{
// This is a comment
/* This is a
Multiline comment */
std::cout << “Hello World!\n”;
}
return 0;
>
>
>
>
cd ~
mkdir cppex1
cd cppex1
emacs & #(or vim)
> ls
ex1.cpp
> g++ -o ex1 ex1.cpp
> ./ex1
Hello World!
>
Basic Syntax of a C/C++ Program
Before we start looking in more detail at C++ coding, we will just
cover the basic syntax of program you've just written
Preprocessor directive. In this
case, including other code
The braces indicate blocks of
code, in this case a function
#include <iostream>
A function definition
(see later!)
int main()
{
// This is a comment
/* This is a
Multiline comment */
std::cout << “Hello World!\n”;
}
return 0;
Every statement in C/C++ must be ended
with a semi-colon. This is a frequent cause
of compiler errors so watch out!
It is good practise to add
comments to your code –
these are ignored by the
compiler but help you
explain what you're
trying to do, both to
other people and
yourself a few months
on!
2. Variables
Introducing Variables
The first topic we will cover is variables
Variables can be considered as 'labels' to objects or areas in
memory
They are declared by specifying the object type which can be one
of the built-in basic types, e.g.:
➔
➔
➔
➔
➔
A boolean (true/false) – 'bool'
Integer number – 'int'
Floating point number – 'float'
Double precision number – 'double'
Single Character/0-255 number – 'char'
Note that numerical variables
can also be 'signed' (default)
or 'unsigned'
Or alternatively, a user-defined type (like classes)
Variables in Action (1)
Memory Locations
#include <iostream>
int main()
{
double a;
double b;
double c;
a = 43;
b = 21;
c = a * b;
std::cout << c << std::endl;
return 0;
}
43
903
21
To show you how variables
work, we'll now go over a basic
program that simply multiplies
two numbers together
It may seem a little basic at
present, but it will help a lot
when we start dealing with
pointers!
Variables in Action (2)
#include <iostream>
int main()
{
double a;
double b;
double c;
a = 43;
b = 21;
c = a * b;
std::cout << c << std::endl;
return 0;
}
a
c
b
First, the three variables are
declared
Note that all this does is assign
memory locations, NOT actual
values - their initial values are
junk!
Other allocations of memory
will not overwrite these as long
as they are allocated
Variables in Action (3)
#include <iostream>
int main()
{
double a;
double b;
double c;
a = 43;
b = 21;
c = a * b;
std::cout << c << std::endl;
return 0;
}
a
c
b
43
903
21
We now assign values to the 3
variables so they are now
initialised
The value of 'c' is then printed
to the screen using the
Standard Library 'std::cout'
object as before
Variables in Action (4)
#include <iostream>
int main()
{
double a;
double b;
double c;
a = 43;
b = 21;
c = a * b;
std::cout << c << std::endl;
return 0;
}
43
903
21
Zero is returned from the
function and the variables are
removed
Note that, though the memory
is
now
available
for
reallocation, the values are NOT
reset
3. Object Declaration and Operators
Variable Declaration and Object Creation
●
●
The example you've just seen using the basic numeric type 'int' is
an example of 'variable declaration' and the associated creation of
an integer object. In C/C++, before using any variable or method it
must be declared so the compiler knows how to deal with it.In the
basic cases previously, if you removed the 'int x' lines, you would
get a compiler error as it wouldn't know what type the variables
were when it found them later
The declaration of a variable follows the syntax:
<object_type> <variable_name> (<initialisation_parameters>)
●
This will also create an object of the requested type (i.e. assign the
appropriate memory). The important point to remember is:
No matter how complicated or simple it is, any variable is still
referencing an object!
Operators
●
In addition to variable declaration, you have also now met the
idea of operators. C++ is based heavily on the idea of operators
acting on objects. A few examples are:
➔
➔
➔
➔
➔
➔
Multiplication: a * b
Addition: a + b
Increment: a++
Bitwise shift/stream: a << b
Modulus: %
Array: []
Operators have precedence, just like in maths, as
well as associativity (left ↔ right) and arity (# of
operands). For more info, see:
http://cs.smu.ca/~porter/csc/ref/cpp_operators.html
The syntax for this depends on the operator, but a few examples
are:
<object1> <operator> <object2> (e.g. *, +, -)
<object1><operator> (e.g. [], ++)
A More Interactive Program (Ex. 2)
●
To give you a taste of variables in action, you'll now create a
program that asks for two numbers and outputs the product of
them. To do this, you will need to use the 'std::cin' variable as
well as the 'std::cout' variable. std::cout you have already met
in the Hello World program. std::cin works in a similar way but
for input:
➔
➔
●
double b;
std::cin >> b; // Fill the variable 'b' with user input
Don't worry about either of these at present, just know that:
➔
➔
➔
std::cin takes input from the user and parses it to variables
std::cout takes variables and outputs them to the screen
Both can 'chain' operations together using the '<<' and '>>' operators
4. Program Flow
Program Flow
●
●
It would be difficult to do much with the language if a program
was just executed from top to bottom and you couldn't control
what parts of the code were executed
There are a number of ways provided to gain this control over
the program:
➔
➔
➔
●
Conditionals
Loops
Functions
We'll go over each one in turn and at each point, incorporate
them in to the growing 'pp6calculator' package!
Program Flow – Scope (1)
●
●
Before we go into the main ways of controlling program flow,
it's important to understand the idea of scope. This refers to
'blocks of code' that are separated from each other by braces.
You have already encountered one such code block in the
'main' function
Variables declared in one code block will not be visible in an
'outer' block but will be present in an 'inner' block. When the
end of a code block is reached, any local variables declared and
objects created in that block are destroyed – this is termed
going 'out of scope'
Program Flow – Scope (2)
Variables a and b are
declared in the outer
block and assigned values
#include <iostream>
int main()
{
int a, b;
Another variable called 'a' is created (this
doesn't affect the previous one!) in
addition to a 'c' variable
NOTE: This is a very bad idea!!
a = 43;
b = 21;
Values are again assigned to these
new variables and the value of 'c'
printed (88 in this case)
{
int a, c;
a = 12;
c = 88;
}
With the closing brace,
the new variables, a and
c, go out of scope and
are deleted. Hence,
when a is printed, it's
the original value of 43.
std::cout << c << std::endl;
std::cout << a << std::endl;
c = a * b;
}
return 0;
This line will cause the compiler to
crash as, though 'c' was declared in
the inner block, it wasn't in the outer
block and so is not present here
Program Flow - Conditionals
●
Conditionals allows different code blocks to be executed based
on the outcome of a simple test. It uses a number of additional
operators, including:
➔
➔
➔
➔
●
Comparison: ==
Greater/Less than: ><
Greater/Less than or equal to: <=
Not equal to: !=
The general syntax for this is shown here:
➔
➔
➔
➔
➔
The 'if' keyword is used
The condition must evaluate to
true or false
Don't confuse assignment ('=')
with comparison ('==')
if (a == b)
{
// Do something...
}
else
{
// Do something else instead
}
Adding More Functionality (Ex. 3)
●
●
●
We can now control the flow of the program depending on a
comparison. In this exercise, you should add to your previous
program to get the program to ask the user what operation
they want to perform
There should be a choice of addition, subtraction,
multiplication and division. You should use the conditional
('if') operation to decide what the user has asked for and also
check for problems (e.g. divide by zero, user input error)
To check for user input error, you can use the following:
if (!std::cin)
// check if the input 'failed'
Program Flow – Loops (1)
●
Loops are very useful for re-using code – a very important
practise in all code development, not just C++. Loops allow you
to repeat a code block a set number of times or until a
condition is met. The first type of loop we will look at is the
'for' loop which has a syntax:
for ( <initialisation>; <condition>; <loop_process> ) { <code_block> }
●
Some useful points to note are:
➔
➔
➔
➔
➔
for (int i = 0; i < 10; ++i)
{
// Do something 10 times
}
The initialisation step is performed at the start of the loop
The loop continues until the condition evaluates to 'false'
After every loop cycle, the process code is run
Be careful about the position of the semi-colons!
You can use 'break' to terminate a loop and 'continue' to skip to the next
iteration
Program Flow – Loops (2)
●
The other type of loop we will look at is the 'while' loop. This is
somewhat simpler than the for loop as it just loops until a
condition evaluates to 'false'. The syntax is:
while ( <condition> ) { <code_block> }
Some useful points to note are:
➔
➔
➔
int i = 0;
while (i < 10)
{
// Do something 10 times
++i;
}
The evaluation of the condition is done at the beginning of each loop
The loop will continue until the condition is false, so be careful of infinite
loops!
As before, use 'break' to get out of the loop and 'continue' to skip the
iteration
Adding More Functionality (Ex. 3)
●
●
Continuing to add and improve our fledgling pp6calculator,
you should now use a 'while' loop to allow the user to keep
performing operations until they quit. To quit out of the while
loop, check for a specific input (e.g. 'q') and use the 'break'
keyword
You may also need to use the 'continue' keyword when errors
in input are found and also use the following to clear the cin
buffer:
#include <climits>
// defines INT_MAX
std::cin.clear();
std::cin.ignore(INT_MAX, '\n');
// clear the fail flag
// clear the cin buffer
Note that we will introduce 'for' loops later when we add some
statistics based functions
Program Flow – Functions (1)
●
As mentioned before, its good coding practise to reuse as much
code as possible. The main way of doing this in C is through
the use of functions that can then be called in other code
blocks. Just like a variable, a function must be declared before
it can be used:
<return_type> <function_name> ( <arguments> ) { <code_block> }
●
●
After declaration, the function is called by just giving the
function name and the required parameters in brackets. At this
point, the program flow jumps to this function until it hits a
'return' statement or the end of it's scope
An important point to remember is that variables are passed
'by value' – i.e. the object value passed is copied to the new
variable, the object itself is not sent to the function
Program Flow – Functions (2)
Declare and
define a function
that multiplies
two numbers
together and
returns the result
Note that you have
already
encountered a
function: the 'main'
function. This is a
special function
that is where the
program starts, but
it behaves in the
same way
#include <iostream>
double multiply( double a, double b )
{
return a * b;
}
void print( double a )
{
std::cout << “Result: “ << a << std::endl;
}
int main()
{
double a, b, c;
This function
prints the given
number with an
additional
message
a = 43;
b = 21;
c = multiply(a, b);
print(c);
print( multiply(a, c) );
}
return 0;
Note that, the variables here
WILL NOT BE CHANGED as
the values are copied to the
function rather than the
objects themselves
More Complicated Functions (Ex. 5)
●
Now we have a simple system that allows the user to specify
the operation he wants to perform, we can extend these
operations to more complicated functions
Now, try to extract the mathematical operations into their own functions
with appropriate inputs and return values
HOMEWORK
Expand your code to include more complicated maths functions:
➔
➔
➔
➔
Calculate the intercept of a line on the x-axis
Solve a quadratic equation
Calculate the length of 3 and 4 vectors
Calculate the invariant mass of two particles
Note that you will need to add the 'cmath' header to your
program to use the 'sqrt' function
Download