Advanced Introduction to C++, Scientific Computing and Machine Learning




Claudius Gros, WS 2019/20

Institut für theoretische Physik
Goethe-University Frankfurt a.M.

C++ : A First Glance


programming languages

compiled


integrated development environments (IDE)

scripting


computing environments

compilation and execution

g++ : Gnu C++ compiler

a first program

a trivial C++ source example

#include <iostream>
using namespace std;

int main() 
  {                        
  cout << "Hello World!" << endl;
  return 0;
  }

commenting the code is the first duty of every programmer


Copy Copy to clipboad
Downlaod Download
// helloWorld.cpp
// a program that prints the immortal saying "hello world"

#include <iostream>          // include utilities for input and output
using namespace std;         // we will be using functions from the 
                             // standard C++ libary

int main()                   // entry point
  {                          // starting a scope
  cout << "Hello World!" << endl;
  return 0;
  }                         // ending a scope

a pretty complicated program

Copy Copy to clipboad
Downlaod Download
#include <iostream>
using namespace std;

int main() 
{                    // some people like to align { and }
  int inputVar = 0;  // defining an integer variable
  do                 // entering a loop
    {               
    cout << "Enter a number (-1 = quit): ";  // prompting the prompt
    if (!(cin >> inputVar))                  // continue while inputing
      {          
      cout << "You entered a non-numeric. Exiting..." << endl;
      break;         // break the loop for wrong inputs
      }
    if (inputVar != -1) 
      {             // not necessary:: only one command after if (..)
      cout << "You entered " << inputVar << endl;
      }
    } while (inputVar != -1);   // termination condition of the do .. while loop
  cout << "All done." << endl;
  return 0;
}

example: strings

Copy Copy to clipboad
Downlaod Download
#include <iostream>
using namespace std;

int main() {
  string str1 = "To be or not to be, that is the question";
  string str2 = "only ";
  string str3 = str1.substr(6, 12);
//                    // endl == end of line
  cout << "str1        :: " << str1 << endl; 
  cout << "str2        :: " << str2 << endl; 
  cout << "str3        :: " << str3 << endl; 
  cout << "str2 + str3 :: " << str2+str3 << endl;
//
  cout << "str1 (again)         :: " << str1 << endl;
  str1.insert(32, str2);
  cout << "str1 (after insert)  :: " << str1 << endl;
  str1.replace(str1.find("to be", 0), 5, "to jump");
  cout << "str1 (after replace) :: " << str1 << endl;
  str1.erase(9, 4);
  cout << "str1 (after erase)   :: " << str1 << endl;
//        
  for (int i = 0; i < str3.length(); i++) // accessing the length
    cout << str3[i]; 
  cout << endl;
//           
  cout << "str3 (again)         :: " << str3 << endl;
  cout << "str3.length()        :: " << str3.length() << endl;
  str3.clear();
  cout << "str3 (after clear)   :: " << str3 << endl;
}

example: functions and scopes

Copy Copy to clipboad
Downlaod Download
#include <iostream>   /* another way for comments */
#include <stdlib.h>   /* srand, rand */
#include <time.h>     /* for the time */
using namespace std;

int a = 18;      // global variables
int b = 6;       // scope: global

// ================== //
// ================== //

int  f_1(int a, int b) {return a - b;} // from function arguments: call by value
int  f_2()             {return a + b;} // from global scope
void f_3(int &x);                      // forward declaration with call be reference

// ================== //
// ================== //

int main() {
  cout << "a (initial):: " << a << endl;
  cout << "b (initial):: " << b << endl;
  cout << endl;
  int b = 0;                  // overrides global definition
  int c,d;
  c = f_1(b, a);
  d = f_2();
  cout << "a (end)        :: " << a << endl;
  cout << "b (end)        :: " << b << endl;
  cout << "c (local  b-a) :: " << c << endl;
  cout << "d (global a+b) :: " << d << endl;
//
  srand( (unsigned)time( NULL ) );  // initializing the random number
                                    // generator with a random seed
//
  cout << endl;
  int z = 444;
  cout << "z (before calling f_3) :: " << z << endl;
  f_3(z);
  cout << "z (after  calling f_3) :: " << z << endl;
}

// ================== //
// ================== //

void f_3(int &x){ x=rand() % 10;}   // backward function definition

example: input and output

Copy Copy to clipboad
Downlaod Download
// file firstIO.cpp
// basic input and output streams
#include <iostream>
#include <fstream>
using namespace std;

// ================== //
// ================== //
 
void printSomething(ofstream &localIOstream)  // passing arguments by reference
{
  localIOstream << "\n";
  localIOstream << "printing something from the function \"";
  localIOstream << __FUNCTION__ << "\"\n";
}

// ================== //
// ================== //

int main () {
  ofstream myIOstream;              // declare output file stream 
  myIOstream.open ("example.txt");  // open output stream myIOstream
  myIOstream << "Writing a line with an escape character (\\n) \n";
  myIOstream << "for line breaks" << endl;
  printSomething(myIOstream);
  myIOstream.close();
//
  return 0;
}

output formatting

Copy Copy to clipboad
Downlaod Download
#include <iostream>
#include <stdio.h>       // for printf
#include <cstdlib>       // for atof
using namespace std;

int main(int argLength, char* argValues[])   // parsing command line arguments
{                          
  printf("number of input arguments: %3d\n",argLength);
  for(int i = 0; i < argLength; i++)
  cout << "argValues[" << i << "] = " << argValues[i] << endl;

//
  double inputDouble  = atof(argValues[1]);    // casting string to double
  int    inputInteger = (int)inputDouble;      // casting double to integer
//
  printf("\n");
  printf("floating-point %10.3f  number\n",inputDouble);
  printf("   exponential %10.3e  number\n",inputDouble);
  printf("   fixed-width %10s  string\n"  ,argValues[2]);
  printf("   fixed-width %10d  integer\n" ,inputInteger);
//          problems with strings
  string ss = "a C++ string can only be printed with printf()\n";
  string tt = "if turned previously into a C-string by .c_str()\n";
  printf("\n");
  printf("%s%s",ss.c_str(),tt.c_str());
//
  return 0;
}  // end of main()

user@pc:~$ ./a.out 3345.345 hello
number of input arguments:   3
argValues[0] = ./a.out
argValues[1] = 3345.345
argValues[2] = hello

floating-point   3345.345  number
   exponential  3.345e+03  number
   fixed-width      hello  string
   fixed-width       3345  integer

a C++ string can only be printed with printf()
if turned previously into a C-string by .c_str()