Wednesday, 6 February 2013

Simple C++ examples

Computational Physics wiki (UCAM only) / C++ resources /

Simple C++ examples

http://www.inference.phy.cam.ac.uk/teaching/comput/C++/examples/AddTwoNumbers.shtml

What you want What it is called Examples
outputcout AddTwoNumbers.cc
Hello.cc
loopsfor HelloFor.cc
ForStatistics.cc
loops do .. while BiggestInt.cc
loopswhile twoPower.cc (has never-ending loop)
AddWhilePositive.cc
input from usercin HelloIn.cc
RandDemo2.cc
twoPower.cc
function
FunctionFactorial.cc
HexagonValue.cc
RandDemo7.cc
definition #define RandDemo2.cc
pass by reference& SortReference.cc
SortReference2.cc
shared definitions#include (header file) RandDemo2.cc and rand.h
conditional if / else
HelloFor.cc
RandDemo5.cc
? (ternary operator) RandDemo2.cc
switch / case SwitchDemo.cc
CalculatorSwitch.cc
random random() (random integer between 0 and 231
RollDie.cc
RandDemo5.cc
RandDemo6.cc
srandom() (initialize/seed the generator) RandDemo2.cc (seeds using time)
RandDemo5.cc (user-supplied seed)
input from command lineargv, sscanf RandDemo4.cc
convert string to int or long intsscanf RandDemo4.cc
integer arithmetic unsigned int BiggestUnInt.cc
power (xy)pow(x,y) twoPower.cc
bit-shift (1<<i) BiggestUnInt2.cc
Examine memory bit by bit& (bit mask) BitsOut.cc
BiggestUnInt2.cc
input from fileifstream, open, getline, close ReadFile.cc
OpenFile.cc
remember variablesstatic StaticDemo.cc
arraysfloat vector[3] ScalarProduct.cc
char phone[11] CharacterArray.cc
dynamically allocate memory for vectors/ arrays/ matricesint *a, new, delete ArrayDemo1.cc
ArrayDemo2.cc
ArrayDemo3.cc
dynamically allocate double arrays/matricesdouble *a, new, delete ArrayDemo4.cc
useful warnings when compilingmakefile Makefile
Classes class SimpleClass.cc
rejects
RandDemo3.cc
convert between typescast, reinterpret_cast, static_cast CastDemo.cc (not yet finished)

AddTwoNumbers.cc

(← right click this link to download this file)
// AddTwoNumbers.cc
// Computes the sum of two numbers inputed at the keyboard.

#include <iostream>
using namespace std;

int main()
{
  int a, b, total ;
   
   cout << "Input numbers to be added: " << endl;
   cin >> a >> b ;
   total = a + b ;
   cout << "The sum is " << total << endl;
   return 0;
}


David MacKay / Computational Physics wiki (UCAM only) / C++ resources /
David MacKay / python resources /

 

No comments:

Post a Comment