PHYCS 3730/5730
Lab Exercise

Exercise 1.

Write the Hello world program in C++. In a file hello.cc, put the text

#include <iostream>

int main()
{
    // this is a comment!
    cout << "hello world.\n";
    return 0;
}
Compile your code using
g++ -o hello hello.cc
and run it by typing "hello" into your shell.


Exercise 2.

Write a C++ code that requests input from the user and reads in a number from standard input. Specifically, try

int n; 

cout << "enter n: ";
cin >> n;
cout << " your number was " << n << "\n";
Run your code, an try various types of input, including integers, floating point numbers (e.g., 3.14159) and non-numeric strings (e.g., "hi there") Modify your code code so that it (a) prints out the value of n *before* you read it in (this should show that the variable is not initialized to anything useful), and (b) uses a double precision floating point variable ("double") instead of an integer ("int").


Exercise 3.

Write a C++ code that calculates the factorial of an integer by direct multiplication. Start with your code in exercise (2), and modify it so that it gets "n" from the user and prints out n! = 1*2*3*...*(n-1)*n. To do this, use a "for" loop:

...
int i,nfac;

for (i = 0, nfac = 1; i < n; i++) {
 ...
}
and within the curly braces set the variable nfac appropriately.

Note the structure of the for-loop; how can you make the loop infinite? (If your code has an infinite loop you can stop it from running by hitting ^C (CTRL-C)). Modify your code so that it multiplies only the odd intergers up to n.