Gradcpp Lec1 Nobkgnd
Gradcpp Lec1 Nobkgnd
Lecture 1
W. H. Bell
University of Glasgow
C++ Programming for Physicists Page 1
Lecture Overview
● Introduction
– Foreword
– Programming Methodology
● Basic C/C++ Syntax
– Loops and Conditional Statements
– Functions
– Pointers and Arrays
● Streams
– Standard out, in, and error
– File Streams
C++ Programming for Physicists Page 2
Foreword
● Form a plan of the program needed before
writing any C++.
– Use a flowchart or pseudocode
– Think through the implementation
● A little planning at the beginning can save a lot of
time later on.
– This is especially true of Object Orientated languages,
of which C++ is the worst in this respect.
C++ Programming for Physicists Page 3
Programming Methodology
1.Requirements
2.Design
3.Implementation
4.Documentation
C++ Programming for Physicists Page 4
A first C++ program
PRINT a string
RETURN 0 to the Operating System
http://en.wikipedia.org/wiki/Flow_chart
http://en.wikipedia.org/wiki/Pseudocode
C++ Programming for Physicists Page 5
A first C++ program
/* W. H. Bell
** A very simple C++ program to print one line to
** the standard out
*/
#include <iostream>
using namespace std;
int main() {
cout << "In the beginning..." << endl;
return 0;
}
InTheBeginning.cc
C++ Programming for Physicists Page 6
Compiling C++ on LINUX
● Using the GNU C++ Compiler
g++ -o executable filename.cc
g++ -c file1.cc
g++ -c file2.cc
g++ file1.o file2.o -o executable
● Documentation
– Man pages man g++
– Info pages info gcc
– Web pages http://gcc.gnu.org/onlinedocs/
C++ Programming for Physicists Page 7
Functions
void numFingers(int);
void pickColour(void);
bool quitTime(void);
int main() {
...
numFingers(3);
pickColour();
...
return 0;
}
void numFingers(int) {
...
}
void pickColour(void) {
...
}
Extract from StdioTests.cc
C++ Programming for Physicists Page 8
Logic and Relational Operators
Operator Meaning
! Not
&& And ● Single & and|are bitwise
|| Or
== Equal to operators
!= Not equal to ● A single = is an
< Less than
<= Less than or equal to assignment operator.
> Greater than
>= Greater than or equal to
C++ Programming for Physicists Page 9
Mathematical Operators
Operator Meaning ● Other basic
+ Add
Subtract
mathematical
* Multiply functions can be
/ Divide found in <cmath>
% Modulus and <math.h>
i++ Add 1 to i (after operation)
i += 7 i = i + 7
i Subtract 1 from i (before operation)
>= Greater than or equal to
C++ Programming for Physicists Page 10
Loops
int main() {
do {
...
} while (!quitTime()); // Loop until ready to quit.
return 0;
}
Extract from StdioTests.cc
int main() {
...
for(int i=0;i<4;i++) {
...
}
}
... Extract from Pointers.cc
● Can just use while(){} too.
C++ Programming for Physicists Page 11
Conditional Statements
void numFingers(void) {
int fingers;
...
if(fingers==3) {
cout << "Correct!" << endl;
}
else if(fingers>10 || fingers<0) {
cout << "That is not possible with two hands!"
<< endl;
}
else {
cout << "Wrong. Try again." << endl;
}
} Extract from StdioTests.cc
C++ Programming for Physicists Page 12
Conditional Statements
void pickColour(void) {
char colourFlag;
...
switch (colourFlag) {
case 'y' : cout << "Custard..." << endl; break;
case 'g' : cout << "Green..." << endl; break;
case 'b' : cout << "As..." << endl; break;
case 'r' : cout << "Fast..." << endl; break;
default : cout << "That..." << endl; break;
}
} Extract from StdioTests.cc
● Faster than if, else if, else for some
operations.
C++ Programming for Physicists Page 13
Arrays
● An array is a sequential block of memory, the
size of which depends on the type and the number
of elements.
int arr[4]; int int int int
● Declaring an array causes memory to be assigned
but does not zero elements.
C++ Programming for Physicists Page 14
Pointers
● A pointer points to a memory address
– Initialise with memory address
– Use to access value in memory address
● Unlike a variable declaration pointer declarations
do not cause memory to be assigned
– Uninitialised pointers are null.
C++ Programming for Physicists Page 15
Pointers and Arrays
int main() {
...
int v[] = {1,2,3,4};
int *pv = &v[0];
cout << endl;
for(int i=0;i<4;i++) {
cout << "v[" << i << "]=" << *pv <<
"\t &v[" << i << "]=" << pv << endl;
pv++;
}
} Extract from Pointers.cc
int *pv;
pv = &v[0]; Alternative code
C++ Programming for Physicists Page 16
Pointers and Arrays
● Incrementing the pointer pv causes it to point at
the next memory location
1 2 3 4 Value
0xbfff9dd0 0xbfff9dd4 0xbfff9dd8 0xbfff9ddc Memory Address
pv
● The value stored in the given memory address
can be accessed with *pv
C++ Programming for Physicists Page 17
Pointers and Functions
void fun(int, int *);
int main() {
int np = 1, p = 1;
cout << "Before fun(): np=" << np << " p=" << p << endl;
fun(np, &p);
cout << "After fun(): np=" << np << " p=" << p << endl;
...
}
void fun(int np, int *p) {
np = 2;
*p = 2;
}
Extract from Pointers.cc
C++ Programming for Physicists Page 18
Pointers and Functions
● Passing an array name to a function passes a
pointer to the first element
● Objects passed into functions behave in a similar
way to simple variables in the given example
– If changes made within a function are needed after the
function has executed Pointers or References should
be used.
C++ Programming for Physicists Page 19
Command Line Arguments
int main(int argc, char *argv[]) {
cout << "argc=" << argc
<< " (argc => size of argv array)" << endl;
for(int i=0;i<argc;i++) {
cout << "argv[" << i << "]=" << argv[i] << endl;
}
return 0;
}
Extract from CommandLine.cc
C++ Programming for Physicists Page 21
Output File Streams
#include <fstream>
using namespace std;
void fileWrite(char *filename) {
ofstream file(filename);
for(int i=1;i<=20;i++) {
file << i;
if(i%5==0) {
file << endl;
}
else {
file << " ";
}
}
file.close();
}
Extract from FileIO.cc
C++ Programming for Physicists Page 22
Input File Streams
#include <fstream>
...
void fileRead(char *filename) {
int i;
ifstream file(filename);
if(!file) {
cerr << "Error: could not open " << filename << endl;
}
else {
cout << "Reading file " << filename << endl;
while(!file.eof()) {
file >> i;
cout << i << " ";
if(i%5==0) cout << endl;
}
file.close();
}
} Extract from FileIO.cc
C++ Programming for Physicists Page 23
Make
● A useful tool for building executables and
libraries
● Documentation:
– Man pages man make
– Info pages info make
– Web pages
http://www.gnu.org/software/make/manual/make.html
C++ Programming for Physicists Page 24
Make Files
# W. H. Bell %.o: %.cc
# A Makefile to build FileIO.exe @echo "**"
@echo "** Compiling C++ Source"
CC=g++ @echo "**"
TARGET=FileIO
$(CC) c $(INCFLAGS) $<
OBJECTS=main.o FileIO.o
$(TARGET).exe: $(OBJECTS)
@echo "**" ● Provided the file is called
@echo "** Linking Executable"
@echo "**" Makefile, just type make
$(CC) $(OBJECTS) o $(TARGET).exe
to build
clean:
@rm f *.o *~
● make without any
veryclean: clean
@rm f $(TARGET).exe arguments builds the
default target
C++ Programming for Physicists Page 25
Header Files
● Can contain:
– Predefinition of functions
– Class declarations (next lecture)
– Variable declaration
● Processed during precompilation.
– Precompiler has its own syntax
C++ Programming for Physicists Page 26
Header Files
#ifndef FILE_IO_HH
#define FILE_IO_HH
Prevent multiple declarations void fileWrite(char *filename);
void fileRead(char *filename);
#endif Extract from FileIO.hh
...
#include "FileIO.hh" Must be in the include path
...
int main(int argc, char *argv[]) {
...
fileWrite(argv[1]);
...
} Extract from main.cc
C++ Programming for Physicists Page 27
Building an Executable
main.cc FileIO.cc
1. Precompilation
2. Compilation
main.o FileIO.o
3. Link
FileIO.exe
● When linking with g++, ld is used
● The ld command line depends on which gnu
compiler is used
C++ Programming for Physicists Page 28
Examples and Problems
● Prepare for Friday's tutorial session
– Purchase recommended textbook
– Download session 1 examples and course guide from
http://ppewww.ph.gla.ac.uk/~wbell/graduatecpp/
– Build and test examples
● Tutorial time should be used for consultation
C++ Programming for Physicists Page 29